From philipasmith at blueyonder.co.uk Sun Jun 4 08:43:47 2006 From: philipasmith at blueyonder.co.uk (Philip Smith) Date: Sun, 04 Jun 2006 12:43:47 GMT Subject: Pyrex newbie question Message-ID: <7AAgg.111198$8W1.91569@fe1.news.blueyonder.co.uk> Just starting to use pyrex on windows. Using pyrex version 0.9.3.1.win32 Using Activestate Python 2.4.3.12 Using Mingw compiler When I try to run the pyrex demo it fails with a message: "undefined reference to '_imp__Py_NoneStruct' " Anyone know why? From seberino at spawar.navy.mil Sat Jun 17 14:44:14 2006 From: seberino at spawar.navy.mil (seberino at spawar.navy.mil) Date: 17 Jun 2006 11:44:14 -0700 Subject: PyObject_SetItem(..) *always* requires a Py_INCREF or not? Message-ID: <1150569854.734805.278760@r2g2000cwb.googlegroups.com> I would think everytime you add an item to a list you must increase reference count of that item. http://docs.python.org/api/refcountDetails.html has an example that seems to contradict that.... int set_all(PyObject *target, PyObject *item) { int i, n; n = PyObject_Length(target); if (n < 0) return -1; for (i = 0; i < n; i++) { if (PyObject_SetItem(target, i, item) < 0) return -1; } return 0; } *WHY* don't you need a Py_INCREF(item); in the for loop!?!?!? Thanks! Chris From anton.vredegoor at gmail.com Mon Jun 19 08:57:59 2006 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Mon, 19 Jun 2006 14:57:59 +0200 Subject: [OT] code is data In-Reply-To: <44965f53$0$12743$636a55ce@news.free.fr> References: <44965f53$0$12743$636a55ce@news.free.fr> Message-ID: bruno at modulix wrote: > I still don't get the point. Well, I've got to be careful here, lest I'd be associated with the terr.., eh, the childp..., eh the macro-enablers. The idea is to have a way to transform a Python (.py) module into XML and then do source code manipulations in XML-space using ElementTree. But rest assured, there is no such module, nor will we ever need it for anything. Anton "use cases are for the faint-hearted" From deets at nospam.web.de Wed Jun 14 10:32:22 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 14 Jun 2006 16:32:22 +0200 Subject: Using "external" vars on module load time In-Reply-To: References: Message-ID: <4fakvkF1hf098U1@uni-berlin.de> Marco Aschwanden schrieb: > Marvelous that was the solution I was looking for. > >> I think you should consider a class instead of a module, though. > > What I don't get: Why should I consider using a class? Because sharing state in such a way that several functions need to access some later bound globals cries for a class that gets that very state passed on instantiation. Diez From belred at gmail.com Tue Jun 13 10:49:54 2006 From: belred at gmail.com (Bryan) Date: Tue, 13 Jun 2006 07:49:54 -0700 Subject: numeric/numpy/numarray In-Reply-To: <1150209185.022926.307780@g10g2000cwb.googlegroups.com> References: <1150188484.888977.189510@y43g2000cwc.googlegroups.com> <1150209185.022926.307780@g10g2000cwb.googlegroups.com> Message-ID: Ben Sizer wrote: > Bryan wrote: > >> at the end of that page, it says: >> >> "Numarray is another implementation of an arrayobject for Python written after >> Numeric and before NumPy. Sponsors of numarray have indicated they will be >> moving to NumPy as soon as is feasible for them so that eventually numarray will >> be phased out." >> >> >> on the python wiki >> "NumArray is the current reimplementation of NumPy." >> http://wiki.python.org/moin/NumArray >> >> so, was Numarray written *before* NumPY, or was it a reimplementation of NumPy >> which implies it came *after* NumPy? it seems clear that Numeric is the old one >> and i read is not being worked on anymore. so that leaves Numarray and numpy. >> which of these two should i use? > > Bryan, > > NumPy is the name of both an old package and a new package. I believe > that NumArray came after the first incarnation, but that the new > incarnation of NumPy is the most recent, and is probably the one you > want. > thanks ben, i'll use NumPy then. just wish it was clear and obvious which one to use so i wouldn't have had to ask this question here. bryan From bearophileHUGS at lycos.com Thu Jun 8 13:27:58 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 8 Jun 2006 10:27:58 -0700 Subject: How to generate k+1 length strings from a list of k length strings? In-Reply-To: <1149785331.109164.208340@i39g2000cwa.googlegroups.com> References: <44883789$1_4@news.bluewin.ch> <1149785331.109164.208340@i39g2000cwa.googlegroups.com> Message-ID: <1149787678.865580.34690@i40g2000cwc.googlegroups.com> > I think there can be written more readable code. For my programs I > usually prefer simpler code, that (if possible) even a children can > understand. So I can debug, modify and improve it better & faster. Debugged: I think it can be written more readable code. In this newsgroup sometimes I have tried to post 'clever' code, but for my programs I (if possible) prefer simpler code, that even a child can understand. So I can debug, modify and improve it faster. Sorry, I was tired, bearophile From george.sakkis at gmail.com Fri Jun 23 08:26:35 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 23 Jun 2006 05:26:35 -0700 Subject: Specifing arguments type for a function References: <200606201328.02784.maric@aristote.info> <1150804645.542646.38570@g10g2000cwb.googlegroups.com> <449afb64$0$16558$636a55ce@news.free.fr> <1151020127.152656.26860@m73g2000cwd.googlegroups.com> <9cum92trvgb271b776l2lg4rdfj3ed951g@4ax.com> <1151042100.731065.19510@r2g2000cwb.googlegroups.com> Message-ID: <1151065595.089436.214710@i40g2000cwc.googlegroups.com> Dennis Lee Bieber wrote: > On 22 Jun 2006 22:55:00 -0700, "George Sakkis" > declaimed the following in comp.lang.python: > > > > Ok, I'll try once more: What does __setitem__ have to do with > > **iterability**, not mutability or indexability ? I was commenting on > > Maric's post that although some objects are typically iterable, they > > are often treated as atomic by some/many/most applications (e.g. > > strings). It's not rocket science. > > > And the absence of the setitem would indicate such an object -- it > may be iterable in terms of retrieving subparts, but atomic WRT > modification. > > That, at least, is how I interpreted the introduction of the test... Applications that don't need to treat strings as iterables of characters wouldn't do so even if strings were mutable. Atomicity has to do with whether something is considered to be composite or not, not whether it can be modified. George From steve at holdenweb.com Thu Jun 29 08:29:16 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 29 Jun 2006 13:29:16 +0100 Subject: Import Issue In-Reply-To: <1151566468.352032.24560@j72g2000cwa.googlegroups.com> References: <1151566468.352032.24560@j72g2000cwa.googlegroups.com> Message-ID: praveenkumar.117 at gmail.com wrote: > Hi All, > > What is the difference between > import string > and > from string import * > sholden at bigboy ~/Projects/dbimp $ python Python 2.4.1 (#1, May 27 2005, 18:02:40) [GCC 3.3.3 (cygwin special)] on cygwin Type "help", "copyright", "credits" or "license" for more information. Started with C:/Steve/.pythonrc >>> dirnow = dir() >>> import string >>> print [x for x in dir() if x not in dirnow] ['_[1]', 'dirnow', 'string'] >>> In the above case something in string is accessed as string.something. sholden at bigboy ~/Projects/dbimp $ python Python 2.4.1 (#1, May 27 2005, 18:02:40) [GCC 3.3.3 (cygwin special)] on cygwin Type "help", "copyright", "credits" or "license" for more information. Started with C:/Steve/.pythonrc >>> dirnow = dir() >>> from string import * >>> print [x for x in dir() if x not in dirnow] ['Template', '_[1]', 'ascii_letters', 'ascii_lowercase', 'ascii_uppercase', 'atof', 'atof_error', 'atoi', 'atoi_error', 'atol', 'atol_error', 'capitalize', 'capwords', 'center', 'count', 'digits', 'dirnow', 'expandtabs', 'find', 'hexdigits', 'index', 'index_error', 'join', 'joinfields', 'letters', 'ljust', 'lower', 'lowercase', 'lstrip', 'maketrans', 'octdigits', 'printable', 'punctuation', 'replace', 'rfind', 'rindex', 'rjust', 'rsplit', 'rstrip', 'split', 'splitfields', 'strip', 'swapcase', 'translate', 'upper', 'uppercase', 'whitespace', 'zfill'] >>> In the second case something from string is inserted directly into the current module's namespace, possibly rebinding the name "something" if it already had a value, but you get the convenience of being able to access it as something. Not generally regarded as a good idea unless you know the package and know it has been designed to be used in this way. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From larry.bates at websafe.com Thu Jun 15 15:48:19 2006 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 15 Jun 2006 14:48:19 -0500 Subject: Database read and write In-Reply-To: References: Message-ID: <4491B983.6050403@websafe.com> Stan Cook wrote: > Ok . I know I'm talking ancient history, but some of us are stuck > working with them. Is there anything for python which will ope, read, > and write to a Dbase 3 or 4 file? I really need your assistance on this > one. > > Regards, > > Stan Might want to check out: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/362715 -Larry Bates From flupke at nonexistingdomain.com Sun Jun 25 04:54:18 2006 From: flupke at nonexistingdomain.com (flupke) Date: Sun, 25 Jun 2006 08:54:18 GMT Subject: logging error with RotatingFileHandler Message-ID: <_asng.501715$x64.12701762@phobos.telenet-ops.be> Hi, i'm getting errors with the log module concerning RotatingFileHandler. I'm using Python 2.4.3 on Windows XP SP2. This used to work in previous python versions but since i upgraded to 2.4.3 i get these errors: Traceback (most recent call last): File "C:\Python24\lib\logging\handlers.py", line 71, in emit if self.shouldRollover(record): File "C:\Python24\lib\logging\handlers.py", line 150, in shouldRollover self.stream.seek(0, 2) #due to non-posix-compliant Windows feature ValueError: I/O operation on closed file 2006-06-25 10:35:07,171 INFO firebird 210 Starting up the database Traceback (most recent call last): File "C:\Python24\lib\logging\handlers.py", line 72, in emit self.doRollover() File "C:\Python24\lib\logging\handlers.py", line 134, in doRollover self.handleError(record) NameError: global name 'record' is not defined I use the logging module by loading a config file: import logging import logging.config LOGFILE = r"logconf.ini" Then in the init function of the class # load logger logging.config.fileConfig(LOGFILE) self.log = logging.getLogger('stats') If i have a main class and a class deriving from it, i let the main class instantiate the class by issueing the commands like above and then get automatically get access to it in the deriving classes. If i remove the logfile, it all works until it has to rollover. My config.ini file contains this info: [loggers] keys=root,stats,database [handlers] keys=hand01,hand02 [formatters] keys=form01,form02 [logger_root] level=NOTSET handlers=hand01 qualname=(root) # note - this is used in non-root loggers propagate=1 # note - this is used in non-root loggers channel= parent= [logger_stats] level=DEBUG propagate=0 qualname=stats handlers=hand01,hand02 channel=log02 parent=(root) [logger_database] level=DEBUG propagate=0 qualname=database handlers=hand01,hand02 channel=log03 parent=(root2 [handler_hand01] class=StreamHandler level=DEBUG formatter=form01 args=(sys.stdout,) stream=sys.stdout [handler_hand02] class=handlers.RotatingFileHandler level=NOTSET formatter=form01 filename=stats.log mode=a maxsize=500000 backcount=9 args=('stats.log', 'a', 900000, 5) [formatter_form01] format=%(asctime)s %(levelname)s %(module)s %(lineno)d %(message)s datefmt= [formatter_form02] format=%(asctime)s %(levelname)s %(module)s %(lineno)d %(message)s datefmt= Any idea on why this suddenly doesn't work anymore? Thanks From jo at durchholz.org Wed Jun 14 14:55:40 2006 From: jo at durchholz.org (Joachim Durchholz) Date: Wed, 14 Jun 2006 20:55:40 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: <7zpshbsvjy.fsf@app-1.diku.dk> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> Message-ID: Torben ?gidius Mogensen schrieb: > For example, > if you have to code everything as natural numbers, untyped pure lambda > calculus or S-expressions, there is a good chance that you can get > nonsense past the compiler. Also past peer review and/or debugging runs. And, most importantly, past your own mental review processes. Regards, Jo From larry.bates at websafe.com Mon Jun 19 19:13:36 2006 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 19 Jun 2006 18:13:36 -0500 Subject: Does Running Python modules dump stuff on "C" drive? In-Reply-To: <1150756840.984382.234500@i40g2000cwc.googlegroups.com> References: <1150756840.984382.234500@i40g2000cwc.googlegroups.com> Message-ID: <44972FA0.80608@websafe.com> Warren wrote: > I am running win2k pro and was wondering if writing python scripts or > running modules dumps anything in the "C" drive? I have 3 partitions > and run python on the 3rd one or "E"drive. > My "C" drive is almost full and keeps loading up with stuff I don't > want or need. Some of it I can find some not. > So until I can get a new HD I need to keep weeding out the weeds! > > TIA. > > Warren > Python puts .pyc modules in same directory as .py module. It is a LOT more likely that you are filling up the hard drive with temp files or cached files from the browser. Clear out your Temporary Internet files (if you haven't already) and change the location of temporary Internet files to another drive. Also check c:\windows\temp. That directory gets lots of crud that I have to clean out. -Larry From baiju.m.mail at gmail.com Sat Jun 10 10:02:27 2006 From: baiju.m.mail at gmail.com (Baiju M) Date: 10 Jun 2006 07:02:27 -0700 Subject: convert .pdf files to .txt files In-Reply-To: <1149945556.411580.143850@j55g2000cwa.googlegroups.com> References: <1149945556.411580.143850@j55g2000cwa.googlegroups.com> Message-ID: <1149948147.781967.168460@u72g2000cwu.googlegroups.com> Davor wrote: > Hi, my name is david. > I need to read information from .pdf files and convert to .txt files, > and I have to do this on python, If you have 'xpdf' installed in your system, 'pdftotext' command will be available in your system. Now to convert a pdf to text from Python use system call. For example: import os os.system("pdftotext -layout my_pdf_file.pdf") This will create 'my_pdf_file.txt' file. Regards, Baiju M From marshall.spight at gmail.com Sun Jun 25 16:02:45 2006 From: marshall.spight at gmail.com (Marshall) Date: 25 Jun 2006 13:02:45 -0700 Subject: Termination and type systems In-Reply-To: <4ving.213803$8W1.62401@fe1.news.blueyonder.co.uk> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <86Qmg.10725$o4.1907@newsread2.news.pas.earthlink.net> <0neng.213767$8W1.1948@fe1.news.blueyonder.co.uk> <1151171209.684163.143410@c74g2000cwc.googlegroups.com> <4ving.213803$8W1.62401@fe1.news.blueyonder.co.uk> Message-ID: <1151265765.438798.203480@r2g2000cwb.googlegroups.com> David Hopwood wrote: > Marshall wrote: > > David Hopwood wrote: > > > >>A type system that required an annotation on all subprograms that do not > >>provably terminate, OTOH, would not impact expressiveness at all, and would > >>be very useful. > > > > Interesting. I have always imagined doing this by allowing an > > annotation on all subprograms that *do* provably terminate. If > > you go the other way, you have to annotate every function that > > uses general recursion (or iteration if you swing that way) and that > > seems like it might be burdensome. > > Not at all. Almost all subprograms provably terminate (with a fairly > easy proof), even if they use general recursion or iteration. Well, um, hmmm. If a subprogram uses recursion, and it is not structural recursion, then I don't know how to go about proving it terminates. Are the proof-termination techniques I don't know about? If we can specify a total order on the domain or some subcomponents of the domain, and show that recursive calls are always invoked with arguments less than (by the order) those of the parent call, (and the domain is well founded) then we have a termination proof. (If we don't use recursion at all, and we only invoke proven-terminating functions, same thing; actually this is a degenerate case of the above.) For iteration? Okay, a bounded for-loop is probably easy, but a while loop? What about a function that calculates the next prime number larger than its argument? Do we have to embed a proof of an infinity of primes somehow? That seems burdensome. > If it were not the case that almost all functions provably terminate, > then the whole idea would be hopeless. I agree! > If a subprogram F calls G, then > in order to prove that F terminates, we probably have to prove that G > terminates. Consider a program where only half of all subprograms are > annotated as provably terminating. In that case, we would be faced with > very many cases where the proof cannot be discharged, because an > annotated subprogram calls an unannotated one. Right, and you'd have to be applying the non-terminating annotation all over the place. > If, on the other hand, more than, say, 95% of subprograms provably > terminate, then it is much more likely that we (or the inference > mechanism) can easily discharge any particular proof involving more > than one subprogram. So provably terminating should be the default, > and other cases should be annotated. Well, I can still imagine that the programmer doesn't care to have non-termination examined for every part of his code. In which case, he would still be required to add annotations even when he doesn't care about a particular subprograms lack of a termination proof. The pay-for-it-only-if-you-want-it approach has some benefits. On the other hand, if it really is as common and easy as you propose, then annotating only when no proof is available is perhaps feasible. I'm still a bit sceptical, though. > I do not know how well such a type system would work in practice; it may > be that typical programs would involve too many non-trivial proofs. This > is something that would have to be tried out in a research language. Yeah. Marshall From invalidemail at aerojockey.com Fri Jun 23 10:03:55 2006 From: invalidemail at aerojockey.com (Carl Banks) Date: 23 Jun 2006 07:03:55 -0700 Subject: Using metaclassed to dynamically generate a class based on a parameter to the objects init function. In-Reply-To: <1151018669.849641.265990@g10g2000cwb.googlegroups.com> References: <1151018669.849641.265990@g10g2000cwb.googlegroups.com> Message-ID: <1151071434.945199.39490@i40g2000cwc.googlegroups.com> sashang at gmail.com wrote: > Hi > > I'd like to use metaclasses to dynamically generate a class based on a > parameter to the objects init function. > > For example: > > class MetaThing(type): > def __init__(cls, name, bases, dict, extra_information): > super(MetaThing, cls).__init__(name, bases, dict) > #setup the class based on the parameter extra_information > > class Thing: > __metaclass__ = MetaThing > def __init__(self, extra_information): > #Somehow pass extra_information to the MetaThing > > extra_information = 1 > t = Thing(extra_information) Tricky. First of all, __init__ belongs to the class, not the object. (Sometimes it's convenient to say it's the object's __init__ method, but when mucking around with metaclasses it's important be precise about what belongs to who, otherwise everyone gets confused.) Because __init__ belongs to the class, the object's class must already exist before calling it, which is contrary to what you seem to want to do. It seem as if, when creating an object, you want to create it's very own class to go with it. I suppose there could be use case for it, but I highly recommend you consider whether features like instance methods or classmethods can accomplish what you want. If you'd still rather that a Thing have its very own class, I recommend you forget about metaclasses and use a factory function with a closure: def create_thing(extra_information): class Thing(object): def __init__(self): # use extra_information here ... return Thing() If you don't like this, or if you insist on using a metaclass, and you don't care that you'll be confusing the hell out of anyone reading the code, the answer is to override the class's __new__ method. Unlike __int__, the __new__ method can return any object it wants, including an object of a different class. The class should subclass itself in its __new__ method, providing the passed extra_information to the constructor of the new subclass, then return an object created from that subclass. The subclass should override __new__ so as not to repeat the hijinks of the class's __new__. Don't follow? The actual source code won't be much easier. Here's an example. class MetaThing(type): def __new__(metacls,name,bases,clsdict,extra_information): # use extra_information return type.__new__(metacls,name,bases,clsdict) class Thing(object): def __new__(cls,extra_information): clsdict = {'__new__':object.__new__} my_very_own_class = MetaThing( "Subthing",(Thing,),clsdict,extra_information) return object.__new__(my_very_own_class) Note that Thing doesn't and shouldn't define __metaclass__, since it creates its subclass directly from the metaclass's constructor. You could, of course, also use the closure method I demonstrated above in Thing's __new__ method--essentially you'd be using Thing's __new__ method as the factory function. > The above sample won't work but I hope it demonstrates what I'm trying > to do. Again, I highly recommend you consider whether what you're "trying to do" can be done more easily with instance or class methods. Carl Banks From memracom at yahoo.com Thu Jun 8 17:37:58 2006 From: memracom at yahoo.com (Michael Dillon) Date: Thu, 08 Jun 2006 21:37:58 -0000 Subject: Python to be used to build OLPC apps Message-ID: The $100 laptop from MIT will be providing Python for application developers to use. This laptop is a low-power consumption innovative laptop that includes features like: - low-power wi-fi with longer than normal range and the ability to keep communicating after the CPU has been put to sleep. - color LCD screen that can be switched to an extra-low power reflective monochrome mode for reading ebooks. - limited memory, flash storage and no hard drive like a PDA - several USB ports - accepts DC input voltages from 5 to 25 volts to recharge battery - ships with a hand-crank power generator The table of contents of their wiki is the best place to learn more: http://wiki.laptop.org/index.php/Table_of_Contents Other key pages are http://wiki.laptop.org/index.php/OLPC_Python_Environment and http://wiki.laptop.org/index.php/Sugar From chris at kateandchris.net Thu Jun 15 16:31:15 2006 From: chris at kateandchris.net (Chris Lambacher) Date: Thu, 15 Jun 2006 16:31:15 -0400 Subject: Which compiler will Python 2.5 / Windows (Intel) be built with? In-Reply-To: References: <1150367139.495114.148550@g10g2000cwb.googlegroups.com> <44917535$1@nntp0.pdx.net> <1150391891.130185.4640@f6g2000cwb.googlegroups.com> Message-ID: <20060615203115.GA30039@kateandchris.net> On Thu, Jun 15, 2006 at 08:36:21PM +0200, Jarek Zgoda wrote: > Fredrik Lundh napisa?(a): > > > hint: most people who provide third-party extensions to Python support > > more than just the latest Python version... > > We're happy with your support for us, Windows users, but you are an > exception to the general rule of providing only sources. > > That's the reason we are fragile on compiler. If the core will be buid > with "non-generally-available" compiler, we would end up with searching > for person willing to compile a library for us, if the MinGW way won't > succeed. I'd like to see core compiled with latest available "free" > toolkit compiler available, as previous versions can not be downloaded > from provider's home. There is only one extension that I have ever found that I could not build with MingW. That one was the win32all extensions. The free (beer) compiler that Microsoft provides did not work for that either since you MFC. There should be no problem building extensions with MinGW unless you are writing an extension to an extension that was written in C++ and distributed only in object form(ie no source), or the extension makes use of the c runtime (fopen, printf etc). That said it would be nice if the barrier to entry on compiling Python windows was reduced by making the effort to moving to gcc as the compiler. Given that this argument has come up several times on both c.l.p and the python-dev list with no one biting, I would say that it is not likely to happen any time soon. I also seem to remember a discussion about it being possible to compile python with VS2005, but you would then be responsible for your own build of python, plus building any extension modules you need. -Chris From mensanator at aol.com Thu Jun 1 17:25:10 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 1 Jun 2006 14:25:10 -0700 Subject: integer to binary... References: <1149189570.376091.319890@j55g2000cwa.googlegroups.com> Message-ID: <1149197110.225383.107770@f6g2000cwb.googlegroups.com> nicolasg at gmail.com wrote: > does anyone know a module or something to convert numbers like integer > to binary format ? > > for example I want to convert number 7 to 0111 so I can make some > bitwise operations... > > Thanks Use the gmpy module. >>> import gmpy >>> a = 14 >>> b = 7 >>> c = 8 >>> help(gmpy.digits) Help on built-in function digits: digits(...) digits(x[,base]): returns Python string representing x in the given base (2 to 36, default 10 if omitted or 0); leading '-' present if x<0, but no leading '+' if x>=0. x must be an mpz, or else gets coerced into one. >>> print gmpy.digits(a,2) 1110 >>> print gmpy.digits(b,2) 111 >>> print gmpy.digits(c,2) 1000 >>> help(gmpy.setbit) Help on built-in function setbit: setbit(...) setbit(x,n,v=1): returns a copy of the value of x, with bit n set to value v; n must be an ordinary Python int, >=0; v, 0 or !=0; x must be an mpz, or else gets coerced to one. >>> d = gmpy.setbit(c,1,1) >>> print gmpy.digits(d,2) 1010 >>> help(gmpy.scan1) Help on built-in function scan1: scan1(...) scan1(x, n=0): returns the bit-index of the first 1-bit of x (that is at least n); n must be an ordinary Python int, >=0. If no more 1-bits are in x at or above bit-index n (which can only happen for x>=0, notionally extended with infinite 0-bits), None is returned. x must be an mpz, or else gets coerced to one. >>> help(gmpy.scan0) Help on built-in function scan0: scan0(...) scan0(x, n=0): returns the bit-index of the first 0-bit of x (that is at least n); n must be an ordinary Python int, >=0. If no more 0-bits are in x at or above bit-index n (which can only happen for x<0, notionally extended with infinite 1-bits), None is returned. x must be an mpz, or else gets coerced to one. >>> print gmpy.scan1(a) 1 >>> print gmpy.scan1(b) 0 >>> print gmpy.scan1(c) 3 >>> print gmpy.scan1(d) 1 >>> print gmpy.scan0(a) 0 >>> print gmpy.scan0(b) 3 >>> print gmpy.scan0(c) 0 >>> print gmpy.scan0(d) 0 >>> help(gmpy.popcount) Help on built-in function popcount: popcount(...) popcount(x): returns the number of 1-bits set in x; note that this is 'infinite' if x<0, and in that case, -1 is returned. x must be an mpz, or else gets coerced to one. >>> print gmpy.popcount(a) 3 >>> print gmpy.popcount(b) 3 >>> print gmpy.popcount(c) 1 >>> print gmpy.popcount(d) 2 >>> help(gmpy.hamdist) Help on built-in function hamdist: hamdist(...) hamdist(x,y): returns the Hamming distance (number of bit-positions where the bits differ) between x and y. x and y must be mpz, or else get coerced to mpz. >>> print gmpy.hamdist(a,b) 2 >>> print gmpy.hamdist(a,c) 2 >>> print gmpy.hamdist(a,d) 1 >>> print gmpy.hamdist(b,c) 4 >>> print gmpy.hamdist(b,d) 3 >>> print gmpy.hamdist(c,d) 1 From david.nospam.hopwood at blueyonder.co.uk Wed Jun 21 19:01:36 2006 From: david.nospam.hopwood at blueyonder.co.uk (David Hopwood) Date: Wed, 21 Jun 2006 23:01:36 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: <1150918629.818145.143220@y41g2000cwy.googlegroups.com> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150902275.129780.50260@p79g2000cwp.googlegroups.com> <1150918629.818145.143220@y41g2000cwy.googlegroups.com> Message-ID: Marshall wrote: > Chris Smith wrote: >>Marshall wrote: >> >>>I think what this highlights is the fact that our existing terminology >>>is not up to the task of representing all the possible design >>>choices we could make. Some parts of dynamic vs. static >>>a mutually exclusive; some parts are orthogonal. >> >>Really? I can see that in a strong enough static type system, many >>dynamic typing features would become unobservable and therefore would be >>pragmatically excluded from any probable implementations... but I don't >>see any other kind of mutual exclusion between the two. > > Well, it strikes me that some of what the dynamic camp likes > is the actual *absence* of declared types, or the necessity > of having them. So why aren't they happy with something like, say, Alice ML, which is statically typed, but has a "dynamic" type and type inference? I mean this as a serious question. > At the very least, requiring types vs. not requiring > types is mutually exclusive. Right, but it's pretty well established that languages that don't require type *declarations* can still be statically typed. -- David Hopwood From ask at me Wed Jun 21 21:39:37 2006 From: ask at me (alf) Date: Wed, 21 Jun 2006 21:39:37 -0400 Subject: dynamic inheritance In-Reply-To: <1150877222.185843.139710@m73g2000cwd.googlegroups.com> References: <_IidnWMwvOnfRBXZnZ2dneKdnZydnZ2d@comcast.com> <44892d3a$0$5594$626a54ce@news.free.fr> <_sCdnYfsraI5AQXZnZ2dnUVZ_o-dnZ2d@comcast.com> <1150877222.185843.139710@m73g2000cwd.googlegroups.com> Message-ID: Michele Simionato wrote: > alf wrote: > Python is ways cooler than C++. I switched to Python from C++ over year ago and do not see a way back. C++ just sucks at each corner. > This is a sensible use case where you may > want to change the base class at runtime: Thx for the example. A. From srijit at yahoo.com Tue Jun 27 07:29:47 2006 From: srijit at yahoo.com (Srijit Kumar Bhadra) Date: 27 Jun 2006 04:29:47 -0700 Subject: Modelica Message-ID: <1151407787.676569.57700@m73g2000cwd.googlegroups.com> I am looking for possible options to interface Modelica (http://www.modelica.org/) with Python (scipy and numpy). Any suggestions? Best Regards, Srijit From kay.schluehr at gmx.net Fri Jun 9 05:45:27 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 9 Jun 2006 02:45:27 -0700 Subject: better Python IDE? Mimics Maya's script editor? In-Reply-To: <1149810048.765664.107820@i40g2000cwc.googlegroups.com> References: <1149810048.765664.107820@i40g2000cwc.googlegroups.com> Message-ID: <1149846327.618865.244950@g10g2000cwb.googlegroups.com> warpcat wrote: > I've been scripting in Maya, via mel for years now. Recently learning > to Python, love it. Thing that's driving me nuts it the IDE. http://wiki.python.org/moin/IntegratedDevelopmentEnvironments From per9000 at gmail.com Wed Jun 21 07:20:15 2006 From: per9000 at gmail.com (per9000) Date: 21 Jun 2006 04:20:15 -0700 Subject: How to truncate/round-off decimal numbers? References: <1150875897.866447.312150@g10g2000cwb.googlegroups.com> Message-ID: <1150888815.526201.102340@u72g2000cwu.googlegroups.com> Nick Maclaren wrote: > |> just a thought: if you *always* work with "floats" with two decimals, > |> you are in fact working with integers, but you represent them as a > |> floats - confusing for the internal representation. > > No, you aren't - you are working with fixed-point Nick, your answer has so many layers, I'll try to explain how I think :-D 1) if you use integers you can think of them as having one part bigger than 100 and one part smaller than 100, like so: >>> a = 11122 >>> (a/100,a%100) (111, 22) Here the output 111,22 looks like something else than an integer, but this is just a matter of representation. a *is* an integer, but we represent it *as if it was* a "decimal" number. (Compare with (minutes,seconds) or (euro,cents) or (feet,inch) or any other "arbitrary" position system) 2) If we use floats with two decimals >>> b = 222.33 >>> b 222.33000000000001 they look like fix-point numbers (I had to look it up http://en.wikipedia.org/wiki/Fixed-point :-D) but python stores it (correct me if I am wrong) as a float (or double or quad or whatever). If we want to work with fix-point aritmetics we have to invent new functions to do most math. 3) Most "decimal numbers" cannot be stored exactly as floats - that is why b gave the ugly print. But some can, f.x >>> quart = 0.25 >>> quart 0.25 quart translates to a finite "decimal" number in binary (0.01 I think). The point is: representing should-be integers as floats makes you loose precision (negligable probalby but still...). 4) > |> So why not work with int(float * 100) instead? This way you only have > |> to take care of roundoffs etc when dividing. > > And multiplying, and calling most mathematical functions. You are correct of course. My mistake. But, the multiplication is exact before you start rounding off - I wont start counting ordos for int*int vs. float*float, but it could have some advantages >>> a 11122 >>> b 22233 >>> a*b 247275426 >>> (a*b/10000,a*b%10000) (24727, 5426) On the other hand you will quickly loose accuracy if you perform multiple multiplications or divisions or use other mathematical functions. 5) So, when could this way of thinking be useful? Well, rarely, but if you only add/subtract "decimals" and/or multiply "decimals" with whole numbers or if you want to use some non-metric system to do scientific stuff (compute square feet when having (feet1,inch1) * (feet2,inch2) assuming that inches are atomic.) This could of course be extended to (feet, inch, quarter_of_afoot, sixteeth_of_a_foot) if you'd like - it is all a matter of representation. Regards, Per ---- "It is a gift. A gift to the foes of 'the Terrorists'. Why not use this 'terrorism'? Long has my father, 'George Bush Sr', kept the forces of 'the terrorists' at bay. By the blood of our people are your lands kept safe. Give 'the land of the brave' the weapon of the enemy. Let us use it against him." From jarrod.roberson at gmail.com Tue Jun 6 22:51:50 2006 From: jarrod.roberson at gmail.com (fuzzylollipop) Date: 6 Jun 2006 19:51:50 -0700 Subject: 10GB XML Blows out Memory, Suggestions? In-Reply-To: <1149623638.736338.185320@h76g2000cwa.googlegroups.com> References: <1149594519.098115.8980@u72g2000cwu.googlegroups.com> <2Qfhg.18186$0v4.787@tornado.texas.rr.com> <1149623638.736338.185320@h76g2000cwa.googlegroups.com> Message-ID: <1149648710.179563.274320@c74g2000cwc.googlegroups.com> axwack at gmail.com wrote: > Paul, > > This is interesting. Unfortunately, I have no control over the XML > output. The file is from Goldmine. However, you have given me an > idea... > > Is it possible to read an XML document in compressed format? compressing the footprint on disk won't matter, you still have 10GB of data that you need to process and it can only be processed uncompressed. I would just export the data in smaller batches, there should not be any reason you can't export subsets and process them that way. From fredrik at pythonware.com Thu Jun 15 17:36:52 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 15 Jun 2006 23:36:52 +0200 Subject: a good programming text editor (not IDE) In-Reply-To: <1150402733.116243.9680@y41g2000cwy.googlegroups.com> References: <_xgkg.2317$No6.48542@news.tufts.edu> <1150402733.116243.9680@y41g2000cwy.googlegroups.com> Message-ID: BartlebyScrivener wrote: > Emacs must be dying if this thread could get all the way to 20 with > nobody arguing with the vi folks. hints: 1) editor wars are so last century. 2) emacs has already won. From antroy at gmail.com Thu Jun 15 13:51:59 2006 From: antroy at gmail.com (Ant) Date: 15 Jun 2006 10:51:59 -0700 Subject: a good programming text editor (not IDE) In-Reply-To: <_xgkg.2317$No6.48542@news.tufts.edu> References: <_xgkg.2317$No6.48542@news.tufts.edu> Message-ID: <1150393919.514359.55580@h76g2000cwa.googlegroups.com> > I've tried a few others, like TextPad and Crimson, and right now I use > UltraEdit, which I love actually, except for minor issues here and > there. But it'd be nice to make the move, as much as possible, to free, > open-source, cross-platform software. Vim is great if you have a good memory... Otherwise you end up trawling through the help to find out how to do stuff that would in another IDE be just a few menu clicks away. jEdit is for me still the best text editor available. Very extensible with macros (which can be written in Jython with the appropriate plugin installed). Full mapping of key-bindings to built in commands, plugin commands and macros a-la Vim, emacs etc. Also comes with a range of plugins if you do want that little bit more power... Java based so cross platform. From david.nospam.hopwood at blueyonder.co.uk Sun Jun 25 17:36:10 2006 From: david.nospam.hopwood at blueyonder.co.uk (David Hopwood) Date: Sun, 25 Jun 2006 21:36:10 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: <449eba8d$1@nntp0.pdx.net> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150908952.804184.218990@r2g2000cwb.googlegroups.com> <1150991074.705803.211570@m73g2000cwd.googlegroups.com> <1151244628.566060.40500@p79g2000cwp.googlegroups.com> <449eba8d$1@nntp0.pdx.net> Message-ID: Scott David Daniels wrote: > rossberg at ps.uni-sb.de wrote: > >> Huh? There is a huge, fundamental difference: namely whether a type >> system is sound or not. A soundness proof is obligatory for any serious >> type theory, and failure to establish it simply is a bug in the theory. > > So you claim Java and Objective C are "simply bugs in the theory." Java's type system was unsound for much of its life. I think that supports the point that it's inadequate to simply "wish and hope" for soundness, and that a proof should be insisted on. -- David Hopwood From eval.apply at gmail.com Tue Jun 20 13:09:01 2006 From: eval.apply at gmail.com (Joe Marshall) Date: 20 Jun 2006 10:09:01 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> Message-ID: <1150823341.079992.98350@y41g2000cwy.googlegroups.com> Chris Smith wrote: > Joe Marshall wrote: > > > > Agreed. That is why there is the qualifier `dynamic'. This indicates > > that it is a completely different thing from static types. > > If we agree about this, then there is no need to continue this > discussion. I'm not sure we do agree, though, because I doubt we'd be > right here in this conversation if we did. I think we do agree. The issue of `static vs. dynamic types' comes up about twice a year in comp.lang.lisp It generally gets pretty heated, but eventually people come to understand what the other person is saying (or they get bored and drop out of the conversation - I'm not sure which). Someone always points out that the phrase `dynamic types' really has no meaning in the world of static type analysis. (Conversely, the notion of a `static type' that is available at runtime has no meaning in the dynamic world.) Much confusion usually follows. You'll get much farther in your arguments by explaining what you mean in detail rather than attempting to force a unification of teminology. You'll also get farther by remembering that many of the people here have not had much experience with real static type systems. The static typing of C++ or Java is so primitive that it is barely an example of static typing at all, yet these are the most common examples of statically typed languages people typically encounter. From david.nospam.hopwood at blueyonder.co.uk Wed Jun 21 00:29:40 2006 From: david.nospam.hopwood at blueyonder.co.uk (David Hopwood) Date: Wed, 21 Jun 2006 04:29:40 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: <1150827075.175209.8800@i40g2000cwc.googlegroups.com> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150823341.079992.98350@y41g2000cwy.googlegroups.com> <1150827075.175209.8800@i40g2000cwc.googlegroups.com> Message-ID: genea wrote: > [...] NOW that being said, I think > that the reason I like Haskell, a very strongly typed language, is that > because of it's type system, the language is able to do things like > lazy evaluation, [...] Lazy evaluation does not depend on, nor is it particularly helped by static typing (assuming that's what you mean by "strongly typed" here). An example of a non-statically-typed language that supports lazy evaluation is Oz. (Lazy functions are explicitly declared in Oz, as opposed to Haskell's implicit lazy evaluation, but that's not because of the difference in type systems.) -- David Hopwood From jon+usenet at unequivocal.co.uk Thu Jun 8 12:46:15 2006 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: 8 Jun 2006 16:46:15 GMT Subject: Select hangs after some reads References: <1149737234.816833.177710@j55g2000cwa.googlegroups.com> <1149764138.868847.326250@i39g2000cwa.googlegroups.com> <128g8uvi6aj4240@corp.supernews.com> <1149779056.498540.46620@f6g2000cwb.googlegroups.com> Message-ID: In article , Steve Holden wrote: > Of course, if the client forces the TCP PSH flag true then the receiver > is guaranteed to debuffer the stream up to that point - this is how FTP > clients work, for example. I don't think that's right. You are confusing the PSH flag (which is basically unused in Unix networking I think) and the URG flag (which is extremely rarely used, but is indeed used by FTP to get abort requests to 'jump the queue' as it were). From jjlee at reportlab.com Thu Jun 1 18:26:34 2006 From: jjlee at reportlab.com (John J. Lee) Date: Thu, 01 Jun 2006 22:26:34 GMT Subject: ANN: ReportLab PDF Library version 2.0 and 1.21 released Message-ID: ReportLab are proud to announce not one but two major releases of our PDF document generation framework. The ReportLab PDF Toolkit lets you generate rich flowing documents in PDF from dynamic data, complete with multiple columns, tables and charts, at extremely high speeds; and to generate charts and data graphics in PDF and bitmap formats. It was first released in mid-2000 and the previous stable release, 1.20, was in late 2004. The 2.0 release includes many new features, and works with Unicode or UTF8 input throughout. This simplifies many things but may break old code that uses non-ASCII input. It should be trivial to upgrade your app using the Python codecs package, which now includes codecs for most of the world's languages. http://www.reportlab.org/whatsnew_2_0.html We have also produced a 1.21 release with a number of minor enhancements and bug fixes since 1.20, and with the old character handling behaviour. This should provide a safe upgrade for all existing users. http://www.reportlab.org/whatsnew_1_21.html ReportLab's commercial products (Report Markup Language, Diagra and PageCatcher) also have their own 2.0 and 1.21 releases and are documented on http://developer.reportlab.com/index.html. Open source users are encouraged to review the RML examples and test cases, which provide very clear examples of what's possible with the underlying Python objects. Best regards, John From aisaac at american.edu Fri Jun 9 12:30:16 2006 From: aisaac at american.edu (Alan Isaac) Date: Fri, 09 Jun 2006 12:30:16 -0400 Subject: Writing PNG with pure Python References: <1149853401.521169.112530@i39g2000cwa.googlegroups.com> Message-ID: On Fri, 09 Jun 2006 07:43:21 -0400, Johann C. Rocholl wrote: > here's my first attempt at > implementing a subset of the PNG spec in pure Python. I license it to > you under the terms of the GNU GPL. > http://trac.browsershots.org/browser/trunk/shotfactory/lib/image/png.py It's your code, so you get to license it. But if you wish to solicit patches, a more Pythonic license is IMHO more likely to prove fruitful. Alan Isaac From steve at holdenweb.com Tue Jun 13 12:45:49 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 13 Jun 2006 17:45:49 +0100 Subject: Decimals In-Reply-To: <1150191995.559582.140270@p79g2000cwp.googlegroups.com> References: <1150188516.739925.102810@h76g2000cwa.googlegroups.com> <1150190908.231517.314040@h76g2000cwa.googlegroups.com> <1150191995.559582.140270@p79g2000cwp.googlegroups.com> Message-ID: Tgone wrote: > Sybren Stuvel wrote: > >>Tgone enlightened us with: >> >>>Sorry, when I print out the variable it displays as '15.0'. The >>>price is '15.00' in the database though. >> >>That's the same thing, isn't it? 15.0 == 15.000000000 > > > Yes, they're both mathematically the same. I never said they weren't... > > >>>Here's my code: >>> >>>product = Product.get(2) >>>print product.price # 15.0 >> >>Try string formatting: >> >>print '%.2f' % product.price > > > That works. I expected Python to display the data exactly as it is in > the database, like most languages. > Well I'm sorry Python doesn't live up to your expectations, but I think your assertion "like most languages" is a little over-reaching. What's actually happening is that the database is storing the number in some internal format known to itself. The module you are using to access the database is actually converting that value to a floating-point number (I'm guessing here: some more modern modules will convert it to a decimal). That's where the scaling factor gets lost, as until fairly recently Python only *had* floats (well, and complex numbers)to represent non-integral numbers. So basically you are likely to be stuck with formatting the data the way you want to see it. This is fairly usual in my experience. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From akameswaran at gmail.com Sat Jun 10 23:49:04 2006 From: akameswaran at gmail.com (akameswaran at gmail.com) Date: 10 Jun 2006 20:49:04 -0700 Subject: Most elegant way to generate 3-char sequence In-Reply-To: <1149889784.391965.271570@h76g2000cwa.googlegroups.com> References: <1149889784.391965.271570@h76g2000cwa.googlegroups.com> Message-ID: <1149997744.183221.7500@i40g2000cwc.googlegroups.com> I'm not sure if you ever got a good answer. I for one am too lazy to look up the pages I found... but - check out http://aspn.activestate.com/ASPN/search?query=combinations§ion=PYTHONCKBK&type=Subsection Tons of nice recipes... Personally I liked the one that dynamically generated a nested function - just cuz it was cool - total overkill for a 3 element permutation. otherwise a simple nested generator is perfect for this solution. Actually you could use the generator function generator to show you what the generator function should look like - try sayin that five times fast. Rob Cowie wrote: > Hi all, > > I wish to generate a sequence of the form 'aaa', 'aab', aac'.... 'aba', > 'abb', 'abc' etc. all the way to 'zzz'. > > How would you construct a generator to acheive this? > > A simple, working but somewhat inelegant solution is... > > alpha = ['a','b','c','d'] #shortened for brevity > alpha2 = ['a','b','c','d'] > alpha3 = ['a','b','c','d'] > > def generator(): > for char in alpha: > for char2 in alpha2: > for char3 in alpha3: > yield char + char2 + char3 > > x = generate() > x.next() # etc, etc, etc, From kiana.toufighi at utoronto.ca Mon Jun 26 17:51:06 2006 From: kiana.toufighi at utoronto.ca (Kiana Toufighi) Date: Mon, 26 Jun 2006 17:51:06 -0400 Subject: Having problems with strings in HTML Message-ID: <44A056CA.7090003@utoronto.ca> Hi, I get a very odd error: ValueError: unsupported format character 't' (0x74) at index 237 Here's my code: HI_LITE_FILE_NAME = '/var/tmp/out.txt' print ''' GraphicalOutput ''' % {'OUT_FILE_NAME': OUT_FILE_NAME, 'HI_LITE_FILE_NAME': HI_LITE_FILE_NAME} I wonder if this has something to do with HTML's % character. KT From steve at holdenweb.com Thu Jun 8 06:24:32 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 08 Jun 2006 11:24:32 +0100 Subject: XML, JSON, or what? In-Reply-To: <1149755672.088330.42610@h76g2000cwa.googlegroups.com> References: <1149749530.734275.181300@j55g2000cwa.googlegroups.com> <1149755672.088330.42610@h76g2000cwa.googlegroups.com> Message-ID: Ant wrote: >>to use? I could go back to XML, or I could switch to JSON - I have read > > > I'd favour JSON if the data structures are simple personally. XML is > comparatively speaking a pain to deal with, where with JSON you can > simply eval() the data and you have a Python dictionary at your > disposal. > Modulo any security problems that alert and malicious users are able to inject into your application. Simply using eval() uncritically on whatever comes down the pipe is a train wreck waiting to happen. > I recently used JSON as a way of passing data from a Java backend to a > web page for Javascript to deal with, with the added side effect that > my Python testing scripts could also easily read the same data. > Oh, well as ling as we're talking about the *web* that's all right, then :-) regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From nmm1 at cus.cam.ac.uk Thu Jun 29 12:53:45 2006 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 29 Jun 2006 16:53:45 GMT Subject: Bug reporting impossible References: Message-ID: In article , Georg Brandl writes: |> |> You should have said what the bug is. Well, maybe, but it is more amusing than serious. I have now reported it properly, as Sourceforge is back up. |> The problem is that Python does not know whether a file name is bogus |> or an actual file. So it was assumed that names like "" or "" |> are safe enough to use them as subsitutes. That is no justification for spuriously executing a file called '' when attempting to produce a diagnostic for one called 'fred'. strace or equivalent shows up clearly what the bug is. |> I don't know whether this is worth fixing. It's definitely worth fixing, but not as a high priority. Invoking a file spuriously is potentially serious, with very low probability. Regards, Nick Maclaren. From siona at chiark.greenend.org.uk Tue Jun 27 11:57:43 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 27 Jun 2006 16:57:43 +0100 (BST) Subject: Having problems with strings in HTML References: Message-ID: Richard Brodie wrote: >"Sion Arrowsmith" wrote in message >news:gLB*BXekr at news.chiark.greenend.org.uk... > [ ... ] >>>By the way, you _do_ realize that your "&" characters should be escaped >>>as "&", don't you? >> No they shouldn't. They part of the url, which is (IIRC) a CDATA >> attribute of the A element, not PCDATA. >It is CDATA but ampersands still need to be escaped. I'll take back that "shouldn't" as per Fredrik's post. Maybe they *should* be escaped, but they don't *need* to be. I've never, and never seen, anyone doing that in a decade of writing cgi; a straw poll of peers suggests that the majority would write the former; and I've never encountred a browser getting tripped up by it. I suppose you might need it if you've got parameters called quot or nbsp, but it's hardly the most broken way of writing HTML. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From girish at cse.iitb.ac.in Mon Jun 12 05:48:20 2006 From: girish at cse.iitb.ac.in (Girish Sahani) Date: Mon, 12 Jun 2006 15:18:20 +0530 (IST) Subject: Function to remove elements from a list working, but python hangs :(( In-Reply-To: <448d346b$0$20350$636a55ce@news.free.fr> References: <448d346b$0$20350$636a55ce@news.free.fr> Message-ID: <50545.10.209.4.1.1150105700.squirrel@10.105.1.3> Hey Bruno...you are seeing the wrong post :P...please ignore this and check out the one with (corrected) appended at the end... Also, i used the list comprehension thingy which u have given, but now the problem is python just hangs if my list l4 contains around 50 pairs...considering its not that big a data, this shouldnt happen.... Should it?? > Girish Sahani wrote: >> Hi, >> I am trying to convert a list of pairs (l4) to list l5 by removing >> those >> pairs from l4 which are not present in a third list called pairList. > > > > >> The following is a simplified part of the routine i have written. >> However >> it does not give the correct output. Please help! >> Its possible i have made a trivial mistke since i am a newbie. >> >> def getl5(): > > Please avoid this kind of names : it's both meaningless (what the ... is > 'l5', I wonder ???) and confusing (is it 'l5' or '15' ?) > > FWIW, read this: > http://mindprod.com/jgloss/unmain.html > >> l5 = [] >> pairList = [[1,2],[3,4],[3,5],[3,6],[9,7],[8,9],[8,7],[7,9],[11,10]] > >>From a semantic POV, you should use tuples for pairs - not lists. > >> l4 = >> [[4,2],[4,7],[4,10],[4,12],[9,2],[9,7],[9,10],[9,12],[11,2],[11,7]] >> for pair in l4: >> if pair not in pairList: > err... see below... >> element.remove(l4) >> l5.append(element) > This is outside the for loop, so this would be executed only once (if > the rest of the code was correct, of course...) > >> print "l5 is",l5 >> > > You did not test this code, did you ? > >>>> getl5() > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/tmp/python-961l_S.py", line 7, in getl5 > NameError: global name 'element' is not defined >>>> > > The SimpleStupid(tm) way to do this is far more simple - at least if I > understood your specifications: > > pairList = [(1,2),(3,4),(3,5),(3,6),(9,7),(8,9),(8,7),(7,9),(11,10)] > l4 = [(4,2),(4,7),(4,10),(4,12),(9,2),(9,7),(9,10),(9,12),(11,2),(11,7)] > l5 = [pair for pair in l4 if pair in pairList] > print "l5 is : ", l5 > > Now this is not necessarily the most efficient solution... > > -- > bruno desthuilliers > python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for > p in 'onurb at xiludom.gro'.split('@')])" > -- > http://mail.python.org/mailman/listinfo/python-list > From greg.kujawa at gmail.com Tue Jun 6 16:01:43 2006 From: greg.kujawa at gmail.com (gregarican) Date: 6 Jun 2006 13:01:43 -0700 Subject: 10GB XML Blows out Memory, Suggestions? References: <1149594519.098115.8980@u72g2000cwu.googlegroups.com> <2Qfhg.18186$0v4.787@tornado.texas.rr.com> <1149623307.191676.321400@y43g2000cwc.googlegroups.com> Message-ID: <1149624103.372741.61660@g10g2000cwb.googlegroups.com> That a good sized Goldmine database. In past lives I have supported that app and recall that you could match the Goldmine front end against an SQL backend. If you can get to the underlying data utilizing SQL you can selectively port over sections of the database and might be able to attack things more methodically than parsing through a mongo XML file. Instead you could bulk insert portions of the Goldmine data into SugarCRM. Know what I mean? axwack at gmail.com wrote: > The file is an XML dump from Goldmine. I have built a document parser > that allows for the population of data from Goldmine into SugarCRM. The > clients data se is 10gb. > > Felipe Almeida Lessa wrote: > > Em Ter, 2006-06-06 ?s 13:56 +0000, Paul McGuire escreveu: > > > (just can't open it up like a text file) > > > > Who'll open a 10 GiB file anyway? > > > > -- > > Felipe. From cito at online.de Sun Jun 4 05:43:06 2006 From: cito at online.de (Christoph Zwerschke) Date: Sun, 04 Jun 2006 11:43:06 +0200 Subject: Python less error-prone than Java In-Reply-To: <1149405998.784652.68510@y43g2000cwc.googlegroups.com> References: <1149405998.784652.68510@y43g2000cwc.googlegroups.com> Message-ID: Kaz Kylheku wrote: > You can have statically typed languages with inadequate type safety, > and you can have dynamically typed languages with inadequate type > safety. But the point in this example was that the Java program ironically had the bug *because* Java handles ints in a type-safe way, while Python does not. >> What's better about the Python version? First, it will operate on >> *any* sorted array, no matter which type the values have. > > Uh huh! With hard-coded < and = operators, how stupid. What if you > want to use it on strings? > Would that be a case-insensitive lexicographic comparison, or > case-insensitive? How do you specify what kind of less-than and equal > you want to do? Where's the problem? The function uses the standard ordering of the values you feed to it, i.e. case-insensitive lexicographical order if you feed a lis of ordinary tuples of strings. You can also feed objects with a different ordering, like case-insensitive. Anyway, that was completely not the point. The point was that you could take that Java program, convert it directly to Python, and have automatically eliminated a bug. I did not claim that the resulting Python program was automatically a real good and Pythonic one. > -1 to indicate not found? Why copy Java braindamage induced by an > antiquated form of static typing? The Java version has to do that So you would call Python's str.find() method braindamaged as well? But as I said, that was not the point here anyway. -- Christoph From max at alcyone.com Mon Jun 5 17:46:55 2006 From: max at alcyone.com (Erik Max Francis) Date: Mon, 05 Jun 2006 14:46:55 -0700 Subject: C# equivalent to range() In-Reply-To: <1149226573.446484.17340@c74g2000cwc.googlegroups.com> References: <1149214153.359809.288610@i39g2000cwa.googlegroups.com> <1149214491.034665.29030@j55g2000cwa.googlegroups.com> <1149217547.618703.209770@i39g2000cwa.googlegroups.com> <1149226573.446484.17340@c74g2000cwc.googlegroups.com> Message-ID: Luis M. Gonz?lez wrote: > There are thousands of threads to choose from in this forum. > If they didn't like this question, they could have picked any other one > to discuss. > There's no need to be disagreeable :-) Plenty of people _did_ helpfully respond to his question with the right answer. The right answer is: This is the wrong forum; as your question in a C#-related forum. It was then the _original poster_ who became "disagreeable" by assigning motive to the people who _actually helped him_ by telling him the right place to ask his question, saying that the "enjoy to waste their time niggling." He's complaining that people weren't nice to help. But they _were_. They answered his question politely and to the point. It's _he_ that turned rude after that. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis What a crime to waste [youth] on children. -- George Bernard Shaw From andrewdalke at gmail.com Wed Jun 14 10:01:42 2006 From: andrewdalke at gmail.com (andrewdalke at gmail.com) Date: 14 Jun 2006 07:01:42 -0700 Subject: Trace KeyboardInterrupt exception? References: <*firstname*nlsnews-B3800F.13431013062006@news.verizon.net> Message-ID: <1150293702.090195.324550@y43g2000cwc.googlegroups.com> Tony Nelson wrote: > I'm trying to find out what is eating some KeyboardInterrupt exceptions > in a fairly large program (yum). My KeyboardInterrupt handler is called > for some Ctl-C presses, but for others nothing seems to happen. > ... I'd like to use a debugger to trace > KeyboardInterrupt exceptions, make sure that they're happening, and see > what is handling them. I don't know how to do that in Idle. You can replace the default Ctrl-C interrupt handler with your own and use that to inspect the current stack. For example, >>> import signal >>> signal.getsignal(signal.SIGINT) >>> prev_handler = signal.getsignal(signal.SIGINT) >>> def new_int_handler(*args): ... print "Keyboard Interrupt!" ... traceback.print_stack() ... prev_handler(*args) ... >>> signal.signal(signal.SIGINT, new_int_handler) >>> def spin(): ... while 1: pass ... >>> import traceback >>> spin() ^CKeyboard Interrupt! File "", line 1, in ? File "", line 2, in spin File "", line 3, in new_int_handler Traceback (most recent call last): File "", line 1, in ? File "", line 2, in spin File "", line 4, in new_int_handler KeyboardInterrupt >>> There's no real need to call the old handler. You could "raise KeyboardInterrupt" or SystemExit or just ignore it, as in >>> count = 0 >>> def new_int_handler(signum, frame): ... global count ... print messages[count] ... if count >= len(messages)-1: ... raise KeyboardInterrupt ... count += 1 ... >>> messages = {0: "Sorry, did you want me to do something?", ... 1: "That's ticklish!", ... 2: "Now, where did that off button go to....", ... 3: "Do that again and I'll leave.", ... 4: "Shutdown activated"} >>> >>> def spin(): ... while 1: pass ... >>> spin() ^CTraceback (most recent call last): File "", line 1, in ? File "", line 2, in spin KeyboardInterrupt >>> >>> import signal >>> signal.signal(signal.SIGINT, new_int_handler) >>> >>> spin() ^CSorry, did you want me to do something? ^CThat's ticklish! ^CNow, where did that off button go to.... ^CDo that again and I'll leave. ^CShutdown activated Traceback (most recent call last): File "", line 1, in ? File "", line 2, in spin File "", line 5, in new_int_handler KeyboardInterrupt >>> Andrew dalke at dalkescientific.com From david.nospam.hopwood at blueyonder.co.uk Sat Jun 24 19:06:58 2006 From: david.nospam.hopwood at blueyonder.co.uk (David Hopwood) Date: Sat, 24 Jun 2006 23:06:58 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: <1151098655.828408.286630@y41g2000cwy.googlegroups.com> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150998222.352746.65520@i40g2000cwc.googlegroups.com> <1151026856.064429.36460@c74g2000cwc.googlegroups.com> <1151079774.429512.68840@c74g2000cwc.googlegroups.com> <1151098655.828408.286630@y41g2000cwy.googlegroups.com> Message-ID: Marshall wrote: > Joe Marshall wrote: > >>Marshall wrote: > >>>2) I want to run my program, even though it is broken, and I >>>want to run right up to a broken part and trap there, so I can >>>use the runtime facilities of the language to inspect what's >>>going on. >> >>I do this quite often. Sometimes I'll develop `in the debugger'. I'll >>change some piece of code and run the program until it traps. Then, >>without exiting the debugger, I'll fix the immediate problem and >>restart the program at the point it trapped. This technique takes a >>bit of practice, but if you are working on something that's complex and >>has a lot of state, it saves a lot of time because you don't have to >>reconstruct the state every time you make a change. The problem with this is that from that point on, what you're running is neither the old nor the new program, since its state may have been influenced by the bug before you corrected it. I find it far simpler to just restart the program after correcting anything. If this is too difficult, I change the design to make it less difficult. > Wow, interesting. > > (I say the following only to point out differing strategies of > development, not to say one or the other is right or bad or > whatever.) > > I occasionally find myself doing the above, and when I do, > I take it as a sign that I've screwed up. I find that process > excruciating, and I do everything I can to avoid it. Over the > years, I've gotten more and more adept at trying to turn > as many bugs as possible into type errors, so I don't have > to run the debugger. > > Now, there might be an argument to be made that if I had > been using a dynamic language, the process wouldn't be > so bad, and I woudn't dislike it so much. But mabe: > > As a strawman: suppose there are two broad categories > of mental strategies for thinking about bugs, and people > fall naturally into one way or the other, the way there > are morning people and night people. One group is > drawn to the static analysis, one group hates it. > One group hates working in the debugger, one group > is able to use that tool very effectively and elegantly. > > Anyway, it's a thought. I don't buy this -- or at least, I am not in either group. A good debugger is invaluable regardless of your attitude to type systems. Recently I was debugging two programs written to do similar things in the same statically typed language (C), but where a debugger could not be used for one of the programs. It took maybe 5 times longer to find and fix each bug without the debugger, and I found it a much more frustrating experience. -- David Hopwood From deets at nospam.web.de Thu Jun 22 04:31:01 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 22 Jun 2006 10:31:01 +0200 Subject: Can PyObjC be used on shared Mac OS X hosting? In-Reply-To: <1150957073.204624.4600@r2g2000cwb.googlegroups.com> References: <1150957073.204624.4600@r2g2000cwb.googlegroups.com> Message-ID: <4fv2q0F1l4m8fU1@uni-berlin.de> weston schrieb: > Does anyone have experience with (or failing that, theoretical > knowledge about) installing using the PyObjC bridge on a Mac OS X > machine in a context where one doesn't have root/admin access (and > therefore can't install things in conventional locations)? Can such a > thing be done? Yes, it can be done. You can install a python frameworkbuild in ~/Library/Frameworks, and then install pyobjc using that python installation. Diez From slomojo83 at gmail.com Thu Jun 15 21:05:51 2006 From: slomojo83 at gmail.com (Josiah Manson) Date: 15 Jun 2006 18:05:51 -0700 Subject: list of polynomial functions In-Reply-To: References: <1150390140.459461.169900@i40g2000cwc.googlegroups.com> <4491AA55.7030200@tim.thechases.com> <4491c005$1@nntp0.pdx.net> Message-ID: <1150419951.424352.44810@g10g2000cwb.googlegroups.com> > I'm curious why the very first attempt to call p(3) doesn't bomb > out with the NameError that "polys" wasn't defined before it even > got to the point of attempting to call it. In the first call, the 0th lambda function is evaluated, and it was defined as the constant function 1. The functions after that each refer to the previous polynomial, so they mess up. The first doesn't so it's fine. I'm new to this, as evidenced by my original posting, so I may be missing something. I hope I helped, Josiah From yairchu at gmail.com Wed Jun 7 04:44:12 2006 From: yairchu at gmail.com (yairchu at gmail.com) Date: 7 Jun 2006 01:44:12 -0700 Subject: what are you using python language for? In-Reply-To: References: Message-ID: <1149669851.969248.248960@u72g2000cwu.googlegroups.com> scientific computing testing systems hobby: games. check http://mashebali.com/?Chess_2 From mcPas.De.Spam at mclaveauPas.De.Spam.com Mon Jun 12 11:53:50 2006 From: mcPas.De.Spam at mclaveauPas.De.Spam.com (Michel Claveau) Date: Mon, 12 Jun 2006 17:53:50 +0200 Subject: Using PHP in Python References: <1150104925.811155.3550@y43g2000cwc.googlegroups.com> Message-ID: Hi! Only in Windows, I can call PHP (more exactly PHP-script) from Python. I can, also, call, from Python, PHP-defined-functions, like a method of a Python-class. It's a combination of Active-scripting & dynamic method add to a class. -- @-salutations Michel Claveau From pc at p-cos.net Tue Jun 27 16:57:34 2006 From: pc at p-cos.net (Pascal Costanza) Date: Tue, 27 Jun 2006 22:57:34 +0200 Subject: What is a type error? In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <7i3mg.204167$8W1.155367@fe1.news.blueyonder.co.uk> <44992e6c$2$664$bed64819@news.gradwell.net> <%Igmg.464974$xt.353729@fe3.news.blueyonder.co.uk> <4fv0v3F1kipa6U1@individual.net> <4gakhiF1m698cU1@individual.net> <4galqlF1mae4qU1@individual.net> <4gb8tiF1e75njU1@individual.net> Message-ID: <4gdkduF1ldalhU1@individual.net> Chris Smith wrote: > Pascal Costanza wrote: >>> Clearly, in this example, the program >>> is invoking an operation (division) on values that are not appropriate >>> (zero for the second argument). Hence, if your definition really is a >>> definition, then this must qualify. >> Here, you are asking more from dynamic type systems than any existing >> type system provides. The definition of what is considered to be a type >> error and what not is always part of the specification of a type system. > > No, I'm not. Were we to follow this path of definition, it would not > require that dynamic type systems catch ALL type errors; only that they > catch some. Not that it matters, though. I am analyzing the logical > consequences of your own definition. If those logical consequences were > impossible to fulfill, that would be an even more convincing reason to > find a new definition. Concepts of fairness don't enter into the > equation. Yes it does. All static type systems define only a strict subset of all possible errors to be covered, and leave others as runtime errors. The same holds for dynamic type systems. >>> If you want to make a statement instead of the sort you've implied >>> above... namely that a type error is *any* error that's raised by a type >>> system, then that's fine. It certainly brings us closer to static >>> types. Now, though, the task is to define a type system without making >>> a circular reference to types. You've already rejected the statement >>> that all runtime errors are type errors, because you specifically reject >>> the division by zero case as a type error for most languages. What is >>> that distinction? >> I don't need such a distinction. I can just define what is covered by a >> type system and what is not. All type systems work that way. > > You've got to define something... or, I suppose, just go on using words > without definitions. You claimed to give a definition, though. > > I have been led by others to believe that the right way to go in the > dynamic type sense is to first define type errors, and then just call > anything that finds type errors a type system. That would work, but it > would require a type error. You seem to want to push that work off of > the word "type error" and back onto "type system", but that requires > that you define what a type system is. I didn't know I was supposed to give a definition. > Incidentally, in the case of static type systems, we define the system > (for example, using the definition given from Pierce many times this > thread), and then infer the definition of types and type errors from > there. Because a solid definition has been given first for a type > system without invoking the concepts of types or type errors, this > avoids being circular. Do you mean this one? "A type system is a tractable syntactic method for proving the absence of certain program behaviors by classifying phrases according to the kinds of values they compute." This isn't really such a strong definition because it shifts the problem of what exactly a type system is to finding a definition for the word "kind". But if this makes you happy, here is an attempt: "A dynamic type system is a tractable syntactic method for proving the absence of certain program behaviors by classifying values according to their kinds." Basically, this correlates with the typical approach of using tags to indicate the type/kind/class of values. And indeed, this is what dynamic type systems typically do: they check tags associated with values. Other kinds of runtime errors are not raised because of such checks, but because of other reasons. Therefore, there is naturally a distinction between runtime errors that are type errors and those that are not. I am not convinced that this definition of mine is a lot clearer than what I have said before, but I am also not convinced that Pierce's definition is any clearer either. It is merely a characterization of what static type systems do. The preciseness comes into play when actually defining a type system: then you have to give definitions what the errors at runtime are that you want to prove absent by way of the static type system, give the typing rules for the type system, and then prove soundness by showing that the typing rules correlate precisely to the runtime errors in the first stage. Since you have to map two different views of the same thing to each other you have to be precise in giving definitions that you can then successfully use in your proofs. In dynamic type system, this level of precision is not necessary because proving that dynamic type errors is what the dynamic type system catches is trivially true, and most programmers don't care that there is a distinction between runtime type errors and runtime "other" errors. But this doesn't mean that this distinction doesn't exist. Pascal -- 3rd European Lisp Workshop July 3 - Nantes, France - co-located with ECOOP 2006 http://lisp-ecoop06.bknr.net/ From sjmachin at lexicon.net Mon Jun 26 19:59:50 2006 From: sjmachin at lexicon.net (John Machin) Date: Tue, 27 Jun 2006 09:59:50 +1000 Subject: Extracting 3-byte integers In-Reply-To: References: Message-ID: <44a074f5$1@news.eftel.com> On 27/06/2006 9:36 AM, Bob Greschke wrote: > I have some binary data read from a file that is arranged like > > <3-byte int> <3-byte int> <3-byte int> etc. > > The "ints" are big-endian and there are 169 of them. Is there any clever > way to convert these to regular Python ints other than (struct) unpack'ing > them one at a time and doing the math? > I'd call that "arithmetic", not "math" :-) Here's another way, not touted as "clever": |>> guff = "\x00\x00\x01\x00\x02\x01\x03\x00\x00\x00\x00\xFF" |>> expected = [1, 513, 3 * 65536, 255] |>> expected [1, 513, 196608, 255] |>> import array |>> b = array.array('B', guff) |>> b array('B', [0, 0, 1, 0, 2, 1, 3, 0, 0, 0, 0, 255]) |>> actual = [b[x]*65536 + b[x+1]*256 + b[x+2] for x in range(0, len(b), 3)] |>> actual [1, 513, 196608, 255] |>> actual == expected True Cheers, John From fc14301589 at icqmail.com Sun Jun 11 02:06:05 2006 From: fc14301589 at icqmail.com (TheSaint) Date: Sun, 11 Jun 2006 14:06:05 +0800 Subject: Very newbie programming References: <448ae8ce_1@news.tm.net.my> Message-ID: <448bb2c7_1@news.tm.net.my> Maric Michaud wrote: > Le Samedi 10 Juin 2006 17:44, TheSaint a ?crit?: >> > begin using more explicit variable names. Frankly it's a very rooted way of programming, since C64 basic :-) A part of this, how python catch variables, the longer the slower, isn't it? Even supposing to use a set of similar name of variables. Of course nowadays this operations ending up in term of msecs. I still be used in old fashion. I'll change it by the time of necessity. > and I generally avoid creating names I use only once, so : > > if not os.listdir('/media') : Great idea and common sense :-) > There more expressive or more direct ways of doing all these, I like one > liners (but a two steps can be more clear) : I like the clearer. I think python does it as we would think it off. >> x = ptn.readlines() > > this time we cut in two steps but this also just filtering. I found the bothering of having to remove the trailing LF "\n". Perhaps need some new function to strip the last LF, for all of the files opened. >> if len(c) != 1: >> sys.exit(0) # if none or more than one match exit >> > why ? > > os.system('umount "%s"' % devices[0]) I wasn't able to handle more than one mount a time. Furthermore, the script is executed every minute in a cron schedule. I don't expect to remove devices in so fast fashion :-) BTW, this operation is necessary because the kernel doesn't do it on its own, for pendrives and Compact Flash into PCMCIA socket. (Kernel 2.6.15 actually) One more point, suppose to use multiple removal, how will it remove also the icon(s) from the KDE desktop? Good to applying myself on studying on it :-) > this will do exactly the same > > for icon_file in (open(dskt + e) for e in os.listdir(dskt) if '.desktop' > in e) : > for line in icon_file : > if 'URL=/media' in line : > icon = icon.name > dvc = line[11:-1] > break > A simple question, how do I'll get out of all loops, once found the right result? F From vinstce at gmail.com Sat Jun 24 06:27:39 2006 From: vinstce at gmail.com (vinodh kumar) Date: Sat, 24 Jun 2006 15:57:39 +0530 Subject: search engine Message-ID: <4a8ca98f0606240327r29ff4b62vb36979bdf8e3206c@mail.gmail.com> hai all, i am student of computer science dept. i have planned to design a search engine in python. i am seeking info about how to proceed further. i need to know what r the modules that can be used. - From johnjsal at NOSPAMgmail.com Tue Jun 6 15:00:22 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 06 Jun 2006 19:00:22 GMT Subject: tkinter: making widgets instance or not? Message-ID: This is from the Tkinter tutorial: from Tkinter import * class App: def __init__(self, master): frame = Frame(master) frame.pack() self.button = Button(frame, text="QUIT", fg="red", command=frame.quit) self.button.pack(side=LEFT) self.hi_there = Button(frame, text="Hello", command=self.say_hi) self.hi_there.pack(side=LEFT) def say_hi(self): print "hi there, everyone!" root = Tk() app = App(root) root.mainloop() I'm wondering, why is frame created as a local variable, and the buttons as instance variables? What is the difference? Can you make frame an instance variable, or vice versa? (I tried it with the buttons and it seems 'self.' isn't necessary, but is this just good practice for larger programs?) From danmcleran at yahoo.com Fri Jun 9 10:26:32 2006 From: danmcleran at yahoo.com (danmcleran at yahoo.com) Date: 9 Jun 2006 07:26:32 -0700 Subject: removing dictionary key-pair In-Reply-To: <128j0r7tla1qi12@corp.supernews.com> References: <128j0r7tla1qi12@corp.supernews.com> Message-ID: <1149863192.221715.137370@u72g2000cwu.googlegroups.com> JD wrote: > Hello, > > I try to remove a dictionary key-pair (remove an entry), > but I'm unsuccessful. Does anyone know how to achieve this? > > Thanks d = dict(a=1, b=2, c=3) print d del d['a'] print d From quentel.pierre at wanadoo.fr Wed Jun 28 03:27:58 2006 From: quentel.pierre at wanadoo.fr (Pierre Quentel) Date: 28 Jun 2006 00:27:58 -0700 Subject: a class variable question In-Reply-To: References: <1151474768.546012.254380@p79g2000cwp.googlegroups.com> <1151475322.648696.21880@b68g2000cwa.googlegroups.com> Message-ID: <1151479678.475687.35740@75g2000cwc.googlegroups.com> Erik Max Francis wrote: > Note this only changes the attribute in the instance. If he wants it to > be changed for all other instances, he needs to change it in the class > with:: A._var1 = 1 Yes, but in the OP's code func1() is called by __init__ for every instance - which in fact makes declaring _var1 as a class attribute useless Anyway, I find that changing the class attribute by calling a method on an instance is a little confusing. I would rather set the class attribute like this : class A2: _var1 = 0 def getvarValue(self): return self._var1 a = A2() print a.getvarValue() >>> 0 A2._var1 = 0 # change class attribute print a.getvarValue() >>> 1 b = A2() print b.getvarValue() >>> 1 Or using a class method : class A3: _var1 = 0 @classmethod def func1(cls): cls._var1 = 1 def getvarValue(self): return self._var1 a = A3() print a.getvarValue() >>> 0 A3.func1() # change class attribute print a.getvarValue() >>> 1 b = A3() print b.getvarValue() >>> 1 Pierre From sjmachin at lexicon.net Thu Jun 1 20:40:35 2006 From: sjmachin at lexicon.net (John Machin) Date: 1 Jun 2006 17:40:35 -0700 Subject: Can Python format long integer 123456789 to 12,3456,789 ? In-Reply-To: <1149207227.173231.126990@h76g2000cwa.googlegroups.com> References: <8oKfg.1621$Su3.139425@news20.bellglobal.com> <1149207227.173231.126990@h76g2000cwa.googlegroups.com> Message-ID: <1149208835.496934.303730@u72g2000cwu.googlegroups.com> james.wondrasek at gmail.com wrote: > A.M wrote: > > Hi, > > > > Is there any built in feature in Python that can format long integer > > 123456789 to 12,3456,789 ? > > > > Thank you, > > Alan > > I did this for putting commas into monetary amounts (thus the .2f): > > def commas(value): > return "".join(commafy("%.2f" % value)) > > def commafy(s): > pieces = s.split(".") > l = len(pieces[0]) > for i in range(0,l): > if (l - i) % 3 or not i: > yield pieces[0][i] > else: > yield "," > yield pieces[0][i] > if len(pieces) > 1: > yield "." + pieces[1] > I dips me lid -- that's far fuglier than mine!!! From diffuser78 at gmail.com Sun Jun 18 16:09:08 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 18 Jun 2006 13:09:08 -0700 Subject: wxPython GUI designer Message-ID: <1150661348.837969.46870@r2g2000cwb.googlegroups.com> I am newbie learning wxPython. I tried using GUI designer called wxGlade. When it generated code I couldnt get the same level of flexibility as writing the code by oneself. Any view on what you think about using GUI designer tools. Every help is appreciated. From onurb at xiludom.gro Tue Jun 20 08:16:21 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 20 Jun 2006 14:16:21 +0200 Subject: Calling every method of an object from __init__ In-Reply-To: References: <1150746953.156851.92820@r2g2000cwb.googlegroups.com> Message-ID: <4497e716$0$10269$636a55ce@news.free.fr> Tim Chase wrote: (snip) >>>> class Foo(object): > ... def __init__(self): > ... for method in dir(self): > ... if method == method.strip("_"): if not method.startswith('_'): -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From antroy at gmail.com Thu Jun 15 03:13:28 2006 From: antroy at gmail.com (Ant) Date: 15 Jun 2006 00:13:28 -0700 Subject: Regular Expression pattern group In-Reply-To: <1150352039.497654.256490@r2g2000cwb.googlegroups.com> References: <1150352039.497654.256490@r2g2000cwb.googlegroups.com> Message-ID: <1150355608.612276.214300@y41g2000cwy.googlegroups.com> > I am a fussy learner. Could someone explain to me why the following > inconsistency exists between methods? How can it be justified if it is > considered all right? It's the standard way of accessing groups from regex matches in pretty much all languages that support them. In most modern languages, I believe regexes are generally designed to be compatible with Perl regexes - but these I guess derive from earlier languages like awk and sed. So it's not an inconsistency. Think of 0 as being an implicit group around the entire expression. In addition, if the match around the entire group was only accessible via a different method, then how would you refer to the entire match in back-references/substitutions? From *firstname*nlsnews at georgea*lastname*.com Tue Jun 13 13:42:56 2006 From: *firstname*nlsnews at georgea*lastname*.com (Tony Nelson) Date: Tue, 13 Jun 2006 17:42:56 GMT Subject: Trace KeyboardInterrupt exception? Message-ID: <*firstname*nlsnews-B3800F.13431013062006@news.verizon.net> I'm trying to find out what is eating some KeyboardInterrupt exceptions in a fairly large program (yum). My KeyboardInterrupt handler is called for some Ctl-C presses, but for others nothing seems to happen. Grepping the source (what of it I've found, looking at import statements) doesn't turn up anything likely. My thinking is that either some "except:" clause is eating them, or some place I haven't looked is eating them, or possibly C code is eating them. For the first two, at least, I'd like to use a debugger to trace KeyboardInterrupt exceptions, make sure that they're happening, and see what is handling them. I don't see a way to trace or break on a specific exception type in Idle. Can someone give me a hint on how to do this? I'm willing to consider other debuggers, including gdb (DDD). ________________________________________________________________________ TonyN.:' *firstname*nlsnews at georgea*lastname*.com ' From jeff_barish at earthlink.net Wed Jun 7 22:07:50 2006 From: jeff_barish at earthlink.net (Jeffrey Barish) Date: Wed, 07 Jun 2006 20:07:50 -0600 Subject: Debugging a pickle Message-ID: I use cPickle to serialize some data so that I can read it back later. It works sometimes, but other times I get an EOFError at the data = cPickle.load(fileobj) statement. I assume that this error indicates that cPickle is not able to retrieve as much data from the file as it expects -- or that the dump did not write as much data as it should have. Is that assumption correct? Are there any debugging techniques I can use to figure out what is going wrong? -- Jeffrey Barish From Bulkan at gmail.com Mon Jun 5 02:52:40 2006 From: Bulkan at gmail.com (placid) Date: 4 Jun 2006 23:52:40 -0700 Subject: Is device Connected Windows? In-Reply-To: References: Message-ID: <1149490360.147668.265590@u72g2000cwu.googlegroups.com> Tim Golden wrote: > [placid] > > | Just wondering is there a way (not brute force) to check if a usb > | storage device is connected? > > Hmmm. How do you identify "a usb storage device" to know that > it is or isn't connected? > > You can certainly do something useful with wmi. eg, > > > import wmi > > c = wmi.WMI () > for usb_disk in c.Win32_DiskDrive (InterfaceType="USB"): > print usb_disk.Caption > print usb_disk.PNPDeviceID > > > > Now, assuming that the PNPDeviceID is unique enough for > your purpose, you could probably do something with it > to keep hold of it and then check later whether the > same device is still inserted. One possibility is > to use a WMI watcher to spot when devices are removed: > > > import wmi > > c = wmi.WMI () > usb_watcher = c.watch_for ( > notification_type="Deletion", > wmi_class="Win32_DiskDrive", > delay_secs=2, > InterfaceType="USB" > ) > > while True: > usb_removed = usb_watcher () # can optionally timeout > print usb_removed.PNPDeviceID > > > Thanks mate, this is what i was after, i can work my way through here. From claird at lairds.us Thu Jun 8 07:56:18 2006 From: claird at lairds.us (Cameron Laird) Date: Thu, 8 Jun 2006 11:56:18 +0000 Subject: Test tool for python code. References: <1149738987.990132.142610@c74g2000cwc.googlegroups.com> Message-ID: <2sfll3-vhd.ln1@lairds.us> In article <1149738987.990132.142610 at c74g2000cwc.googlegroups.com>, wrote: >Is there any tool available that will tell me what are the different >test paths for any python code? . . . , especially . From kyosohma at gmail.com Tue Jun 13 16:21:55 2006 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 13 Jun 2006 15:21:55 -0500 Subject: Redirecting Print Streams Message-ID: Hi, I am working on a Tkinter GUI that will display software package's install status. I work for a company that wants to control how software is installed and where. Anyway, the package installer I am working with currently prints to a console window for each software package installed. So, if we have 4 packages, it would open 4 windows in sequence. I want it to just print what it is doing in a Tkinter GUI instead of opening windows, but I cannot figure out how to redirect the print streams in the custom package installer. Here is the main module I am trying to redirect data from: def InstallPack(PackageName): """ Installs a software package """ iniFile = '\\\\%s\\client$\\Packages\\%s\\package.ini' % (serverName, PackageName) print iniFile config = section2Dict(iniFile) reg = ConnectRegistry(None, HKEY_LOCAL_MACHINE) regpath = r"SOFTWARE\MCIS" key = OpenKey(reg, regpath, 0, KEY_ALL_ACCESS) iniSerial = config['SerialNumber'] try: q = QueryValueEx(key, PackageName) RegSerial = q[0] #print "Package: %s found in Registry!" % PackageName if RegSerial == iniSerial: print "Package already installed. Installation aborted!" sys.exit(0) except WindowsError: # Package not installed pass print 'Installing package: %s' % PackageName print 'Description: %s' % config['Description'] zipPart(PackageName, config['ZipFile']) regPart(PackageName, config['RegFile'], config['RegType']) SetValueEx(key, PackageName, 0, REG_EXPAND_SZ, iniSerial) CloseKey(key) Thanks a lot! Mike -------------- next part -------------- An HTML attachment was scrubbed... URL: From nick at craig-wood.com Mon Jun 5 06:30:07 2006 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 05 Jun 2006 05:30:07 -0500 Subject: Best way to check that a process is running on a Unix system? References: <16de708d0605272205m66cbadc9h25e699fe4f7b32ec@mail.gmail.com> Message-ID: BJ?rn Lindqvist wrote: > > What is the best way to check that a process is running (or better yet > > number of instances) based on the name of the process? Would have to > > work on a unix/linux system. > > Use "ps -C proc_name". Then either read the nr of lines in the output > (for the number of instances) or read the return value. 0 if the > process is running. Or read the /proc/*/status files and check if your > process is in any of them. Here is a module I wrote ages ago which does the grubbling around in /proc for you. >>> import process >>> p = process.ProcessList() >>> p.named("emacs") [Process(pid = 20610), Process(pid = 6076), Process(pid = 6113), Process(pid = 6590), Process(pid = 857), Process(pid = 1394), Process(pid = 28974)] >>> Parsing the output of "ps -ef" will be more portable between unixes though! ------------------------------------------------------------ """ Manage Processes and a ProcessList under Linux. """ import os import signal class Process(object): """Represents a process""" def __init__(self, pid): """Make a new Process object""" self.proc = "/proc/%d" % pid pid,command,state,parent_pid = file(os.path.join(self.proc, "stat")).read().strip().split()[:4] command = command[1:-1] self.pid = int(pid) self.command = command self.state = state self.parent_pid = int(parent_pid) self.parent = None self.children = [] def kill(self, sig = signal.SIGTERM): """Kill this process with SIGTERM by default""" os.kill(self.pid, sig) def __repr__(self): return "Process(pid = %r)" % self.pid def getcwd(self): """Read the current directory of this process or None for can't""" try: return os.readlink(os.path.join(self.proc, "cwd")) except OSError: return None class ProcessList(object): """Represents a list of processes""" def __init__(self): """Read /proc and fill up the process lists""" self.by_pid = {} self.by_command = {} for f in os.listdir("/proc"): if f.isdigit(): process = Process(int(f)) self.by_pid[process.pid] = process self.by_command.setdefault(process.command, []).append(process) for process in self.by_pid.values(): try: parent = self.by_pid[process.parent_pid] #print "child",process #print "parent",parent parent.children.append(process) process.parent = parent except KeyError: pass def named(self, name): """Returns a list of processes with the given name""" return self.by_command.get(name, []) ------------------------------------------------------------ -- Nick Craig-Wood -- http://www.craig-wood.com/nick From jcrocholl at googlemail.com Fri Jun 9 07:43:21 2006 From: jcrocholl at googlemail.com (Johann C. Rocholl) Date: 9 Jun 2006 04:43:21 -0700 Subject: Writing PNG with pure Python Message-ID: <1149853401.521169.112530@i39g2000cwa.googlegroups.com> Just in case anybody has the same problem, here's my first attempt at implementing a subset of the PNG spec in pure Python. I license it to you under the terms of the GNU GPL. http://trac.browsershots.org/browser/trunk/shotfactory/lib/image/png.py It encodes RGB images with 24 bits per pixel into PNG, using only the modules sys, zlib and struct. These are all included in the base distribution of Python. You don't need gd or imlib. I have done a little testing, and my implementation processes 8 megs of RGB input in 0.6 seconds. With Adam7 interlacing enabled, it takes 10 times longer. I would really appreciate any feedback and suggestions for improvement. Cheers, Johann From raffaelcavallaro at pas-d'espam-s'il-vous-plait-mac.com Fri Jun 16 11:37:45 2006 From: raffaelcavallaro at pas-d'espam-s'il-vous-plait-mac.com (Raffael Cavallaro) Date: Fri, 16 Jun 2006 11:37:45 -0400 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <2006061410510511272-raffaelcavallaro@pasdespamsilvousplaitmaccom> <2006061501423327544-raffaelcavallaro@pasdespamsilvousplaitmaccom> <2006061611291216807-raffaelcavallaro@pasdespamsilvousplaitmaccom> Message-ID: <2006061611374575249-raffaelcavallaro@pasdespamsilvousplaitmaccom> On 2006-06-16 11:29:12 -0400, Raffael Cavallaro said: > In software like this it isn't worth satisfying a static type checker > because you don't get much of the benefit > anywaytext?Dx?description?text?Dx?fromname > as being able to run and test portions of a program before other parts > are written (forward references to as yet nonexistent functions). I don't what bizarre key combination I accidentally hit here, but the original read: In software like this it isn't worth satisfying a static type checker because you don't get much of the benefit anyway and it means forgoing such advantages of dynamic typing as being able to run and test portions of a program before other parts are written (forward references to as yet nonexistent functions). From martin at v.loewis.de Wed Jun 28 12:34:04 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 28 Jun 2006 18:34:04 +0200 Subject: handling unicode data In-Reply-To: References: <1151506510.391856.207460@y41g2000cwy.googlegroups.com> Message-ID: <44a2af7d$0$7205$9b622d9e@news.freenet.de> Fredrik Lundh wrote: > looks like the DB-API driver returns 8-bit ISO-8859-1 strings instead of Unicode > strings. there might be some configuration option for this; see > Where did you want to point the OP here? > in worst case, you could do something like > > def unicodify(value): > if isinstance(value, str): > value = unicode(value, "iso-8859-1") > return value > > term = unicodify(row[1]) > > but it's definitely better if you can get the DB-API driver to do the right thing. It seems pymssql does not support such a thing. Also, it appears that DB-Library (the API used by pymssql) always returns CP_ACP characters (unless ANSI-to-OEM conversion is enabled); so the "right" encoding to use is "mbcs". Notice that Microsoft plans to abandon DB-Library, so it might be best to switch to a different module for SQL Server access. Regards, Martin From enleverlesX.XmcX at XmclaveauX.com Sat Jun 17 13:42:51 2006 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI) Date: Sat, 17 Jun 2006 19:42:51 +0200 Subject: [OT] Python Argentina T-shirt to exchange References: Message-ID: <44946d1e$0$922$ba4acef3@news.orange.fr> Hi! You can post your message on fr.comp.lang.python Bon voyage en France ! @-salutations -- Michel Claveau sites : http://mclaveau.com http://bergoiata.org http://ponx.org From bj_666 at gmx.net Mon Jun 19 11:49:07 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 19 Jun 2006 17:49:07 +0200 Subject: memory-leak in pysqlite 2.3.0 ? References: Message-ID: In , Michael Husmann wrote: > After upgrading from pysqlite 2.0.5 to pysqlite 2.3.0 writing into a > sqlite database increases memory consumption heavily. [?] > > Here a short example: > ------------------------------- > #!/usr/bin/env python > > import os > from pysqlite2 import dbapi2 > print dbapi2.version > > db = dbapi2.connect("bla.db") > c = db.cursor() > > c.execute("create table b (c integer)") > > for i in xrange(10000000): > c.execute("insert into b values (%d)" % i) Just a guess: Commit the changes from time to time. Ciao, Marc 'BlackJack' Rintsch From sekhon.hari at googlemail.com Wed Jun 21 07:34:26 2006 From: sekhon.hari at googlemail.com (Hari Sekhon) Date: Wed, 21 Jun 2006 12:34:26 +0100 Subject: What's the best way to wrap a whole script in try..except? In-Reply-To: References: Message-ID: <44992EC2.5090403@gmail.com> Jon Ribbens wrote: > In article , Hari Sekhon wrote: > >> I want to wrap a whole script in try ... except. What is the best way of >> doing this? >> > > You could do this maybe: > > import sys > > def excepthook(exc_type, exc_value, tb): > import modules_needed_to_notify_exception > ... > > sys.excepthook = excepthook > > import modules_needed_by_script > ... > I've been trying this out and your method is by far the best I've seen. This is overriding the default exception handler. I don't know the deep magic yet but it works nicely. Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From max at alcyone.com Sun Jun 11 00:17:45 2006 From: max at alcyone.com (Erik Max Francis) Date: Sat, 10 Jun 2006 21:17:45 -0700 Subject: Xah Lee network abuse In-Reply-To: References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148495974.975395.12920@i40g2000cwc.googlegroups.com> <1149998343.493200.144990@h76g2000cwa.googlegroups.com> Message-ID: Philippa Cowderoy wrote: > Rather a lot depends on which legal system you're in, for a start. > Including the standards of proof and who the onus is on. Oh, no doubt. But I don't think there's any modern legal system in which it's a crime, rather than a tort. Is there? Anyway, it's certainly a tort in all relevant jurisdictions here. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Covenants without the sword are but words. -- Camden From filipwasilewski at gmail.com Tue Jun 6 05:50:37 2006 From: filipwasilewski at gmail.com (Filip Wasilewski) Date: 6 Jun 2006 02:50:37 -0700 Subject: python socket proxy In-Reply-To: <1149577919.811693.178730@f6g2000cwb.googlegroups.com> References: <1149577919.811693.178730@f6g2000cwb.googlegroups.com> Message-ID: <1149587437.299147.314670@h76g2000cwa.googlegroups.com> jstobbs at gmail.com wrote: > Hi all > > I am trying to create a lighweight tcp proxy server. [...] There is a bunch of nice recipies in the Python Cookbook on port forwarding. In the [1] and [2] case it should be fairly simple to add an extra authentication step with pyOpenSSL. [1] http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/483730 [2] http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/114642 [3] http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/483732 best, fw From anton at appsolutions.com Sun Jun 25 03:38:53 2006 From: anton at appsolutions.com (Anton van Straaten) Date: Sun, 25 Jun 2006 07:38:53 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150904134.520639.71070@b68g2000cwa.googlegroups.com> <1151056505.908723.162580@u72g2000cwu.googlegroups.com> Message-ID: David Hopwood wrote: > But since the relevant feature that the languages in question possess is > dynamic tagging, it is more precise and accurate to use that term to > describe them. So you're proposing to call them dynamically-tagged languages? > Also, dynamic tagging is only a minor help in this respect, as evidenced > by the fact that explicit tag tests are quite rarely used by most programs, > if I'm not mistaken. It sounds as though you're not considering the language implementations themselves, where tag tests occur all the time - potentially on every operation. That's how "type errors" get detected. This is what I'm referring to when I say that dynamic tags support latent types. Tags are absolutely crucial for that purpose: without them, you have a language similar to untyped lambda calculus, where "latent type errors" can result in very difficult to debug errors, since execution can continue past errors and produce completely uninterpretable results. > IMHO, the support does not go far enough for it to be > considered a defining characteristic of these languages. Since tag checking is an implicit feature of language implementations and the language semantics, it certainly qualifies as a defining characteristic. > When tag tests are used implicitly by other language features such as > pattern matching and dynamic dispatch, they are used for purposes that are > equally applicable to statically typed and non-(statically-typed) languages. A fully statically-typed language doesn't have to do tag checks to detect static type errors. Latently-typed languages do tag checks to detect latent type errors. You can take the preceding two sentences as a summary definition for "latently-typed language", which will come in handy below. >>>or that languages >>>that use dynamic tagging are "latently typed". This simply is not a >>>property of the language (as you've already conceded). >> >>Right. I see at least two issues here: one is that as a matter of >>shorthand, compressing "language which supports latent typing" to >>"latently-typed language" ought to be fine, as long as the term's >>meaning is understood. > > > If, for the sake of argument, "language which supports latent typing" is > to be compressed to "latently-typed language", then statically typed > languages must be considered also latently typed. See definition above. The phrase "language which supports latent typing" wasn't intended to be a complete definition. > After all, statically typed languages support expression and > verification of the "types in the programmer's head" at least as well > as non-(statically-typed) languages do. In particular, most recent > statically typed OO languages use dynamic tagging and are memory safe. > And they support comments ;-) But they don't use tags checks to validate their static types. When statically-typed languages *do* use tags, in cases where the static type system isn't sufficient to avoid them, then indeed, those parts of the program use latent types, in the exact same sense as more fully latently-typed languages do. There's no conflict here, it's simply the case that most statically-typed languages aren't fully statically typed. > This is not, quite obviously, what most people mean when they say > that a particular *language* is "latently typed". They almost always > mean that the language is dynamically tagged, *not* statically typed, > and memory safe. That is how this term is used in R5RS, for example. The R5RS definition is compatible with what I've just described, because the parts of a statically-typed language that would be considered latently-typed are precisely those which rely on dynamic tags. >>But beyond that, there's an issue here about the definition of "the >>language". When programming in a latently-typed language, a lot of >>action goes on outside the language - reasoning about static properties >>of programs that are not captured by the semantics of the language. > > > This is true of programming in any language. Right, but when you compare a statically-typed language to an untyped language at the formal level, a great deal more static reasoning goes on outside the language in the untyped case. What I'm saying is that it makes no sense, in most realistic contexts, to think of untyped languages as being just that: languages in which the type of every term is simply a tagged value, as though no static knowledge about that value exists. The formal model requires that you do this, but programmers can't function if that's all the static information they have. This isn't true in the case of a fully statically-typed language. >>This means that there's a sense in which the language that the >>programmer programs in is not the same language that has a formal >>semantic definition. As I mentioned in another post, programmers are >>essentially mentally programming in a richer language - a language which >>has informal (static) types - but the code they write down elides this >>type information, or else puts it in comments. > > > If you consider stuff that might be in the programmer's head as part > of the program, where do you stop? When I maintain a program written > by someone I've never met, I have no idea what was in that programmer's > head. All I have is comments, which may be (and frequently are, > unfortunately) inaccurate. You have to make the same kind of inferences that the original programmer made. E.g. when you see a function that takes some values, manipulates them using numeric operators, and returns a value, you have to either figure out or trust the comments that the function accepts numbers (or integers, floats etc.) and returns a number. This is not some mystical psychological quality: it's something that absolutely must be done in order to be able to reason about a program at all. > (Actually, it's worse than that -- if I come back to a program 5 years > later, I probably have little idea what was in my head at the time I > wrote it.) But that's simply the reality - you have to reconstruct: recover the latent types, IOW. There's no way around that! Just to be concrete, I'll resurrect my little Javascript example: function timestwo(x) { return x*2 } Assume I wrote this and distributed it in source form as a library, and now you have to maintain it. How do you know what values to call it with, or what kind of values it returns? What stops you from calling it with a string? Note that according the formal semantics of an untyped language, the type of that function is "value -> value". The phrase "in the programmer's head" was supposed to help communicate the concept. Don't get hung up on it. >>We have to accept, then, that the formal semantic definitions of >>dynamically-checked languages are incomplete in some important ways. >>Referring to those semantic definitions as "the language", as though >>that's all there is to the language in a broader sense, is misleading. > > > Bah, humbug. The language is just the language. If you want to have this discussion precisely, you have to do better than that. There is an enormous difference between the formal semantics of an untyped language, and the (same) language which programmers work with and think of as "dynamically typed". Use whatever terms you like to characterize this distinction, but you can't deny that the distinction exists, and that it's quite a big, important one. >>In this context, the term "latently-typed language" refers to the >>language that a programmer experiences, not to the subset of that >>language which is all that we're typically able to formally define. > > > I'm with Marshall -- this is way too mystical for me. I said more in my reply to Marshall. Perhaps I'm not communicating well. At worst, what I'm talking about is informal. It's easy to prove that you can't reason about a program if you don't know what types of values a function accepts or returns - which is what an untyped formal model gives you. Anton From chris at kateandchris.net Sun Jun 11 10:13:59 2006 From: chris at kateandchris.net (Chris Lambacher) Date: Sun, 11 Jun 2006 10:13:59 -0400 Subject: TKinter In-Reply-To: <20060610172553.29578.qmail@web32813.mail.mud.yahoo.com> References: <20060610142638.GB9046@kateandchris.net> <20060610172553.29578.qmail@web32813.mail.mud.yahoo.com> Message-ID: <20060611141359.GA26714@kateandchris.net> I would try looking at Django or Turbogears. http://www.djangoproject.com/ http://www.turbogears.org/ Also have a look at: How to write a browser-based desktop app using CherryPy 2.0: http://www.cherrypy.org/wiki/SingleClickAndRun How to write a a browser-based desktop app using CherryPy 2.1: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/442481 -Chris On Sat, Jun 10, 2006 at 10:25:53AM -0700, V Sivakumar wrote: > Dear Chris, > It is really very kind of you. Actually, I planned to do as a web > program with a in built webserver. In that a the GUI creation becomes > very easy. Is Twisted (Python 2.4) a good option? > > I find no good tutorials for Python programming. Like handling HTTPRequest > and HTTPResponse. > > > Kind Regards > V Sivakumar > > "You cannot know the meaning of your life until you are connected to the > power that created you" - Shri Mataji Nirmala Devi. [1]www.tnsahaj.org. > > ----- Original Message ---- > From: Chris Lambacher > To: V Sivakumar > Cc: python-list at python.org > Sent: Saturday, 10 June, 2006 9:26:38 AM > Subject: Re: TKinter > > GTK+ + Glade > [2]http://pygtk.org/ > > WxPython has several GUI editors > [3]http://wxpython.org > > PyQt has the ability to generate code from the Qt GUI designer > [4]http://www.riverbankcomputing.co.uk/pyqt/ > > I personally have used GTK+ and Glade with great success. I found > WxPython to > be lacking in polish. I have not worked with PyQt. > > Pretty much all of the above work models are not embedded into an > IDE. There > is a GUI editor, and then you use your regular editor to write code. > > This is actually a pretty good model because from my experience, as your > application becomes bigger and more complicated, you want less GUI > generated > UI and more had written UI code. > > -Chris > > On Thu, Jun 08, 2006 at 10:29:44PM -0000, V Sivakumar wrote: > > Dear Group!, > > I am new to Python. I have Eclipse with Python support , is there > > better IDE for free and with good support for GUI development. I need > > to develop a nice looking desktop application. Like we could do in VB, > > C# and Java Swing. Is there a drag drop support GUI toolkit for > > Python like the above languages do? > > > > Thanks > > Siva > > > > > > > > > > -- > > [5]http://mail.python.org/mailman/listinfo/python-list > > References > > Visible links > 1. http://www.tnsahaj.org/ > 2. http://pygtk.org/ > 3. http://wxpython.org/ > 4. http://www.riverbankcomputing.co.uk/pyqt/ > 5. http://mail.python.org/mailman/listinfo/python-list From reply.in.the.newsgroup at my.address.is.invalid Mon Jun 12 08:31:00 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Mon, 12 Jun 2006 14:31:00 +0200 Subject: Using PHP in Python References: <1150104925.811155.3550@y43g2000cwc.googlegroups.com> <4f4qvbF1hjj7tU1@uni-berlin.de> <1150105267.463906.66700@f14g2000cwb.googlegroups.com> Message-ID: Tgone: >I have some custom PHP functions that I didn't want to re-write in >Python. But maybe I should just rewrite them :) Absolutely. The alternative is one of many IPC mechanisms that are available in both Python and PHP (such as XML-RPC). But that may require more effort than rewriting the functions. -- Ren? Pijlman From deets at nospam.web.de Tue Jun 20 05:47:09 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 20 Jun 2006 11:47:09 +0200 Subject: [OT] code is data References: <44965f53$0$12743$636a55ce@news.free.fr> <4496b29f$0$27412$626a54ce@news.free.fr> <4496e9c9$0$14868$626a54ce@news.free.fr> <4fokj4F1ihat3U1@uni-berlin.de> <4497c20e$0$29656$636a55ce@news.free.fr> Message-ID: <4fpuh5F1i9bl1U1@uni-berlin.de> bruno at modulix wrote: > Diez B. Roggisch wrote: >>>> because lots of people know how to describe XML transformations, and >>>> there are plenty of tools that implement such transformations >>>> efficiently ? >>> >>> >>> Efficiently enough for dynamic (runtime) use ? >> >> >> Using XML-transformation for AST manipulation isn't my first choice >> either - yet efficiency concerns aren't really the point here - after >> all we're talking about generating code, > > I thought we were talking about *transforming* code - just like one uses > metaclasses to transform a class definition, or @decorators to transform > a function definition... Yes we were. So where does the runtime efficiency you mention come in to play? While the _result_ of a transformation might be a less efficient piece of code (e.g. introducing a lock around each call to enable concurrent access), the transformation itself is very - if not totally - static - and usually only run once. So except from a start up latency, it has no impact. So if for whatever reason XSLT is someones favorite method of AST-transformation because it fits her mindset - perfect. As I said: it wouldn't be mine either, but I can't see your concerns about efficiency. And XSLT certainly is suited for tree manipulation, so it might be that it would be good for e.g. recursivly stripping type annotations of some kind (think of e.g. type-verifying decorators that you want to get rid of for production.) Diez From bignose+hates-spam at benfinney.id.au Tue Jun 13 22:30:04 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 14 Jun 2006 12:30:04 +1000 Subject: How do I ignore the errors thrown by the DB api? References: <1150241099.578287.116400@i40g2000cwc.googlegroups.com> Message-ID: <87d5dco4er.fsf@benfinney.id.au> "fyleow" writes: > It would be great if I could just insert values into the DB and let > the uniqueness check at the DB level to either add or refuse the > duplicate value. The Pythonic way to do this is find out what exception is generated by the event you want to handle, and handle that exception. record_stuff = build_new_record() try: insert_record(record_stuff) except FailedToInsert, e: handle_insert_failure(e, record_stuff) Define each of those functions, name the actual exception class, and you're done. -- \ "A lot of people are afraid of heights. Not me, I'm afraid of | `\ widths." -- Steven Wright | _o__) | Ben Finney From brian at sweetapp.com Thu Jun 15 12:06:48 2006 From: brian at sweetapp.com (Brian Quinlan) Date: Thu, 15 Jun 2006 18:06:48 +0200 Subject: Vancouver Python Workshop - Talk submission deadline Message-ID: <44918598.5050201@sweetapp.com> What's New? =========== This is your last change to submit a talk for the Vancouver Python Workshop. Talks will be accepted until Friday June 16th. This is a great opportunity for you to share your project or interests with the Python community, so please take advantage of it! To submit a talk, see: http://www.vanpyz.org/conference/talksubmission.html About the Vancouver Python Workshop =================================== The conference will begin with keynote addresses on August 4st by Guido van Rossum [1], Jim Hugunin [2], and Ian Cav?n [3]. Further talks (and tutorials for beginners) will take place on August 5th and 6th. The Vancouver Python Workshop is a community organized and designed for both the beginner and for the experienced Python programmer with: * tutorials for beginning programmers * advanced lectures for Python experts * case studies of Python in action * after-hours social events * informative keynote speakers * tracks on multimedia, Web development, education and more More information see: http://www.vanpyz.org/conference/ or contact Brian Quinlan at: brian at sweetapp.com Vancouver ========= In addition to the opportunity to learn and socialize with fellow Pythonistas, the Vancouver Python Workshop also gives visitors the opportunity to visit one of the most extraordinary cities in the world [4]. For more information about traveling to Vancouver, see: http://www.vanpyz.org/conference/vancouver.html http://www.tourismvancouver.com http://en.wikipedia.org/wiki/Vancouver Important dates =============== Talk proposals accepted: May 15th to June 15th Early registration (discounted): May 22nd to June 30th Normal registration: from July 1st Keynotes: August 4th Conference and tutorial dates: August 5th and 6th [1] Guido van Rossum (Google) is the inventor of Python and has managed its growth and development for more than a decade. Guido was awarded the Free Software Foundation Award in 2002 and Dr.Dobb's 1999 Excellence in Programming Award. Guido works at Google and spends half of his time on Python. [2] Jim Hugunin (Microsoft) is the creator of numerous innovations that take Python into new application domains. Jim's most recent project, IronPython integrates Python into Microsoft's .NET runtime. Jim's previous project, Jython is Python for the Java runtime and was the second production-quality implementation of Python. Before that, Jim's Numeric Python adapted Python to the needs of number crunching applications. Jim works at Microsoft adapting the .NET runtime to the needs of dynamic languages like Python. [3] Ian Cav?n is the primary developer of the Lowry Digital Images motion picture restoration system. This Python and Zope-based system has been used to restore over 150 motion pictures. Highlights include Citizen Kane, Sunset Boulevard and both the Indiana Jones and Star Wars trilogies. While Ian was Chief Scientist at Lowry Digital, his rack of computers grew from a few Macintoshes on his desktop to over six hundred Macintosh and Linux servers - at one point earning Lowry the title as the second biggest installation of parallel processing Maintoshes in the world. In 2005, Lowry Digital Images was acquired by DTS (the famous movie audio company) and renamed DTS Digital Images. The motion picture restoration system has been discussed in publications as diverse as IEEE Spectrum, USA Today, the BBC NEWS, the New York Times and Apple.com. Ian has been a Python enthusiast since 1999. [4] http://news.bbc.co.uk/2/hi/business/2299119.stm Cheers, Brian From dav.phillips at ntlworld.com Tue Jun 6 05:57:48 2006 From: dav.phillips at ntlworld.com (dav.phillips at ntlworld.com) Date: 6 Jun 2006 02:57:48 -0700 Subject: Checking var is a number? In-Reply-To: References: <1149583700.145737.170720@j55g2000cwa.googlegroups.com> Message-ID: <1149587868.671013.31550@h76g2000cwa.googlegroups.com> I took a variable to mean a container for diffirent kinds of information either strings or integers etc, as i am mainly a asp, php, asp.net developer. Thanks for the list of references, that will come in very handy Cheers Guys David P From riteshsarraf at gmail.com Wed Jun 14 06:14:39 2006 From: riteshsarraf at gmail.com (Ritesh Raj Sarraf) Date: 14 Jun 2006 03:14:39 -0700 Subject: determining file type In-Reply-To: References: <1150276935.270798.5550@i40g2000cwc.googlegroups.com> Message-ID: <1150280079.859763.280070@g10g2000cwb.googlegroups.com> But isn't there any library function ? Something like XX.filetype(name) Directory File-Tar File-Zip File-MPEG Ritesh Maric Michaud wrote: > Le Mercredi 14 Juin 2006 11:22, Ritesh Raj Sarraf a ?crit : > > Hi, > > > > I have a funtion named unzipper() which does the work of unzipping the > > files. > > > > Is there a way I can identify what is the type of the file which'll be > > passed to unzipper(). > > If yes, I'll be able to make out if it's a zip file or a tar or a bz2 > > file. > > > Under Linux you can use the file command in a pipe. > In all cases, you use the "magic" repository of the file command directly like > this (I found the '\xff\xd8' for jpeg in /usr/share/file/magic.mime on my > debian) > > In [69]: f = file ('samurai_tux.jpg') > > In [70]: s = f.read(2) > > In [71]: s == '\xff\xd8' > Out[71]: True > > > > > > Thanks, > > Ritesh > > -- > _____________ > > Maric Michaud > _____________ > > Aristote - www.aristote.info > 3 place des tapis > 69004 Lyon > Tel: +33 426 880 097 From wahab at chemie.uni-halle.de Sun Jun 25 07:36:37 2006 From: wahab at chemie.uni-halle.de (Mirco Wahab) Date: Sun, 25 Jun 2006 13:36:37 +0200 Subject: Python in HTML In-Reply-To: <1151077239.840572.175120@y41g2000cwy.googlegroups.com> References: <1151077239.840572.175120@y41g2000cwy.googlegroups.com> Message-ID: Thus spoke brochu121 at gmail.com (on 2006-06-23 17:40): > Does anyone know of a way to embed python scripts into html, much like > you would javascript or php? I do not want to use this to connect to a > database, but rather for a functional script to be called when a user > clicks on a link to open a page. Aside from the "javascript or php" joke, which does not belong in such a relation (as others have already pointed out), there are several methods to use "PHP"-like Python inclusions, something like: ... <%python> for row range(10): print "" print "" + "" print ""
NR" + str(row) + "
... One prominent Example for that would be Myghty http://www.myghty.org/docs/whatsitdo.myt some Examples shown here: http://www.myghty.org/docs/embedding.myt Regards Mirco From mnot at mnot.net Fri Jun 23 21:24:35 2006 From: mnot at mnot.net (Mark Nottingham) Date: Fri, 23 Jun 2006 18:24:35 -0700 Subject: Fwd: PEP 314 - requirements for Python itself References: Message-ID: <8421BEBC-2446-4129-9607-DF8EE8CDEA3A@mnot.net> I was thinking more about things where people can search for packages that need different versions of python, etc.; not so much for automation. On 2006/06/23, at 6:05 PM, Serge Orlov wrote: > On 6/23/06, Mark Nottingham wrote: >> I was looking for some normal (hopefully, machine-readable) way to >> indicate it so that people can figure out the version of Python >> required before they download the package. > > I'm sure writing English text like "make sure you have python 2.4 > before downloading this package" is not abnormal :) How do you expect > to prevent users from downloading your package if they don't have > python your package needs? It could be useful if there was a tool to > silently download and install python, but I'm sure it is a pain to > code and support such a tool, so nobody was crazy enough to do it. -- Mark Nottingham http://www.mnot.net/ From larry.bates at websafe.com Thu Jun 15 15:55:17 2006 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 15 Jun 2006 14:55:17 -0500 Subject: a good programming text editor (not IDE) In-Reply-To: References: <_xgkg.2317$No6.48542@news.tufts.edu> <1150393919.514359.55580@h76g2000cwa.googlegroups.com> Message-ID: John Salerno wrote: > Fredrik Lundh wrote: >> John Salerno wrote: >> >>>> jEdit is for me still the best text editor available. Very extensible >>>> with macros (which can be written in Jython with the appropriate plugin >>>> installed). >>> >>> I like the idea of being extensible, but of course I can only write >>> in Python. Are there any editors that support that? >> >> Jython is a Python implementation for Java. >> >> >> > > Oh, I know, but doesn't it require knowledge of Java? Or am I being even > more newbie-ish than I thought I was? :) Nope, no Java knowledge necessary. Jython just compiles Python code to java bytecode instead of python bytecode. Once it is in java bytecode the JVM doesn't know where it came from. -Larry Bates From jmbc at nospam.fr Mon Jun 12 18:29:07 2006 From: jmbc at nospam.fr (jean-michel bain-cornu) Date: Tue, 13 Jun 2006 00:29:07 +0200 Subject: wxpython: how do i write this without the id parameter? In-Reply-To: References: Message-ID: <448deaf5$0$7761$7a628cd7@news.club-internet.fr> Hi John John Salerno a ?crit : > I was reading in the wxPython wiki that most of the time you don't have > to include the id parameter at all, and you can just use keyword > arguments for other parameters. But I'm having trouble converting this > code into that method (i.e., without the id parameter). I keep getting > errors that involve wrong parameters, or that they are out of order, > etc. So I'm hoping someone can show me how to re-write the constructors > for InputForm and wx.Frame, as well as the __init__ method, so that they > will just deal with parent and title. May I suggest you to use wx.ID_ANY each time you need an id. It's a very clean way to give it even if you don't really care. For instance : wx.StaticBox(self,wx.ID_ANY,"etc...") Regards, jm From aahz at pythoncraft.com Sun Jun 4 12:53:18 2006 From: aahz at pythoncraft.com (Aahz) Date: 4 Jun 2006 09:53:18 -0700 Subject: carshing the interpreter in two lines References: <1149343823.789918.210110@h76g2000cwa.googlegroups.com> Message-ID: In article <1149343823.789918.210110 at h76g2000cwa.googlegroups.com>, gangesmaster wrote: > >the following (random) code crashes my interpreter >(python 2.4.3/winxp): > >from types import CodeType as code >exec code(0, 5, 8, 0, "hello moshe", (), (), (), "", "", 0, "") > >i would expect the interpreter to do some verifying, at least for >sanity (valid opcodes, correct stack size, etc.) before executing >artbitrary code... after all, it was the BDFL who said """I'm not >saying it's uncrashable. I'm saying that if you crash it, it's a >bug unless proven harebrained.""" IIRC, this has been discussed before and deemed harebrained. Check SF to see whether this specific case has been submitted previously and submit it if not. Then post to python-dev if it's a new bug and ask for a ruling on whether it's harebrained. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I saw `cout' being shifted "Hello world" times to the left and stopped right there." --Steve Gonedes From brandon.mcginty at gmail.com Mon Jun 19 14:08:04 2006 From: brandon.mcginty at gmail.com (brandon.mcginty at gmail.com) Date: Mon, 19 Jun 2006 11:08:04 -0700 Subject: operator comparison for php vs python Message-ID: <000301c693cb$506ca760$6400a8c0@brandon532f2ea> Hi All, I've already done a large amount of searching on Google to find out this information, but to no avale. Does anyone here know of a list of operators in python and there counterparts in php, or a website with this information? It would also be helpful to have this information along with perl's syntax. I'm going to be trying to port some php and perl stuff to python, and this information would be extremely useful, rather than going through all the documentation and reinventing the wheel. Thanks, ---------- Brandon McGinty Email:brandon.mcginty at gmail.com Skype:brandon.mcginty Msn:brandon_mcginty at hotmail.com Aim:brandonmcginty0 (Not currently available.) Cell:4802025790 (Weekends and nights only, please.) Languages:python, php, autoit; Currently Learning:perl "Kindness is a language that the deaf can hear and the blind can see." Mark Twain -------------- next part -------------- An HTML attachment was scrubbed... URL: From rpdooling at gmail.com Sat Jun 10 17:47:13 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 10 Jun 2006 14:47:13 -0700 Subject: infinite loop executed in emacs In-Reply-To: <1149974783.869457.231020@h76g2000cwa.googlegroups.com> References: <1149974783.869457.231020@h76g2000cwa.googlegroups.com> Message-ID: <1149976033.221169.95770@j55g2000cwa.googlegroups.com> Try Ctrl + Break http://tinyurl.com/qc8np From micklee74 at hotmail.com Wed Jun 7 13:09:12 2006 From: micklee74 at hotmail.com (micklee74 at hotmail.com) Date: 7 Jun 2006 10:09:12 -0700 Subject: printing backslash In-Reply-To: References: <1149698793.422979.148770@i40g2000cwc.googlegroups.com> Message-ID: <1149700152.569657.261170@i40g2000cwc.googlegroups.com> Tim Chase wrote: > > i want to print something like this > > > > |\| > > > > first i tried it as string > > > > a = "|\|" > > > > it prints ok > > > > but when i put it to a list > > > > a = ["|\|"] > > > > it gives me '|\\|' .there are 2 back slashes...i only want one.. how > > can i properly escape it? > > I have tried [r"|\|"] , [r'\\'] but they do not work... > > You omit how you're printing matters. > > >>> s1 = '|\|' > >>> s2 = r'|\|' > >>> s3 = '|\\|' > >>> print repr(s1), '->', s1 > '|\\|' -> |\| > >>> print repr(s2), '->', s2 > '|\\|' -> |\| > >>> print repr(s3), '->', s3 > '|\\|' -> |\| > > There's a difference between the repr() of a string (which > escapes items that need to be escaped) and printing items. All > three *print* the item as you request it. All three represent > the item with the proper backslashes. > > The preferred form of putting backslashes in a string is the s2 > or s3 form, as the s1 form can have some "unpredictable"(*) results: > > "\|" happens not to be a recognized escape sequence > "\t" is, so you get things like > >>> s = '\t\|' > >>> s > '\t\\|' > -tkc > > (*) "unpredictable" defined as, "predictable, if you happen to > have memorized the exact set of characters that do or don't need > to beescaped" thanks, i got it From andreas.lydersen at gmail.com Wed Jun 14 19:09:57 2006 From: andreas.lydersen at gmail.com (andreas.lydersen at gmail.com) Date: 14 Jun 2006 16:09:57 -0700 Subject: Negative hex to int Message-ID: <1150326597.327669.222640@r2g2000cwb.googlegroups.com> Hi! While communicating with a monitoring unit, I get some hex values representing degrees celcius from its probes. The values can be something like '19' or '7d'. To convert it to int, I do the following: --------------------------- Python 2.4.2 (#1, Sep 28 2005, 10:25:47) [GCC 3.4.3 20041212 (Red Hat 3.4.3-9.EL4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> int('7d', 16) 125 >>> int('19', 16) 25 >>> --------------------------- The problem is negative values. If the unit returns the hex value 'e7', it means -25, but python says it's 231: --------------------------- >>> int('e7', 16) 231 --------------------------- Does anyone have a clue a to what I need to do? Thanks! Andreas Lydersen From rossberg at ps.uni-sb.de Fri Jun 23 09:11:49 2006 From: rossberg at ps.uni-sb.de (Andreas Rossberg) Date: Fri, 23 Jun 2006 15:11:49 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: <449bde5e$1$663$bed64819@news.gradwell.net> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <0%Wlg.3521$MF6.947@tornado.socal.rr.com> <44992e6c$0$664$bed64819@news.gradwell.net> <449aaea0$0$656$bed64819@news.gradwell.net> <449bde5e$1$663$bed64819@news.gradwell.net> Message-ID: Chris Uppal wrote: >>> >>>Well, it seems to me that you are /assuming/ a notion of what kinds of >>>logic can be called type (theories), and I don't share your >>>assumptions. No offence intended. >> >>OK, but can you point me to any literature on type theory that makes a >>different assumption? > > 'Fraid not. (I'm not a type theorist -- for all I know there may be lots, but > my suspicion is that they are rare at best.) I would suspect the same :-). And the reason is that "type" has a well-established use in theory. It is not just my "assumption", it is established practice since 80 or so years. So far, this discussion has not revealed the existence of any formal work that would provide a theory of "dynamic types" in the sense it is used to characterise "dynamically typed" languages. So what you are suggesting may be an interesting notion, but it's not what is called "type" in a technical sense. Overloading the same term for something different is not a good idea if you want to avoid confusion and misinterpretations. > But, as a sort of half-way, semi-formal, example: consider the type environment > in a Java runtime. The JVM does formal type-checking of classfiles as it loads > them. In most ways that checking is static -- it's treating the bytecode as > program text and doing a static analysis on it before allowing it to run (and > rejecting what it can't prove to be acceptable by its criteria). However, it > isn't /entirely/ static because the collection of classes varies at runtime in > a (potentially) highly dynamic way. So it can't really examine the "whole" > text of the program -- indeed there is no such thing. So it ends up with a > hybrid static/dynamic type system -- it records any assumptions it had to make > in order to find a proof of the acceptability of the new code, and if (sometime > in the future) another class is proposed which violates those assumptions, then > that second class is rejected. Incidentally, I know this scenario very well, because that's what I'm looking at in my thesis :-). All of this can easily be handled coherently with well-established type machinery and terminology. No need to bend existing concepts and language, no need to resort to "dynamic typing" in the way Java does it either. > In code which will be executed at instant A > obj aMessage. "type correct" > obj anotherMessage. "type incorrect" > > In code which will be executed at instant B > obj aMessage. "type incorrect" > obj anotherMessage. "type correct" > > I don't see how a logic with no temporal element can arrive at all four those > judgements, whatever it means by a union type. I didn't say that the type system cannot have temporal elements. I only said that a type itself cannot change over time. A type system states propositions about a program, a type assignment *is* a proposition. A proposition is either true or false (or undecidable), but it is so persistently, considered under the same context. So if you want a type system to capture temporal elements, then these must be part of a type itself. You can introduce types with implications like "in context A, this is T, in context B this is U". But the whole quoted part then is the type, and it is itself invariant over time. - Andreas From robert.thorpe at antenova.com Tue Jun 20 10:57:41 2006 From: robert.thorpe at antenova.com (Rob Thorpe) Date: 20 Jun 2006 07:57:41 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <1150809118.677124.142230@u72g2000cwu.googlegroups.com> Message-ID: <1150815461.210286.53120@r2g2000cwb.googlegroups.com> Andreas Rossberg wrote: > Rob Thorpe wrote: > >> > >>>No, that isn't what I said. What I said was: > >>>"A language is latently typed if a value has a property - called it's > >>>type - attached to it, and given it's type it can only represent values > >>>defined by a certain class." > >> > >>"it [= a value] [...] can [...] represent values"? > > > > ??? > > I just quoted, in condensed form, what you said above: namely, that a > value represents values - which I find a strange and circular definition. Yes, but the point is, as the other poster mentioned: values defined by a class. For example, in lisp: "xyz" is a string, #(1 2 3) is an array, '(1 2 3) is a list, 45 is a fixed-point number. Each item that can be stored has a type, no item can be stored without one. The types can be tested. Most dynamic typed languages are like that. Compare this to an untyped language where types cannot generally be tested. > >>A (static) type system assigns types to (all) *expressions*. > > > > That's right most of the time yes, I probably should have said > > expressions. Though I can think of static typed languages where the > > resulting type of an expression depends on the type of the variable it > > is being assigned to. > > Yes, but that's no contradiction. A type system does not necessarily > assign *unique* types to individual expressions (consider overloading, > subtyping, polymorphism, etc). That's a fair way of looking at it. > > Well I haven't programmed in any statically typed language where values > > have types themselves. > > They all have - the whole purpose of a type system is to ensure that any > expression of type T always evaluates to a value of type T. But it only gaurantees this because the variables themselves have a type, the values themselves do not. Most of the time the fact that the variable they are held in has a type infers that the value does too. But the value itself has no type, in a C program for example I can take the value from some variable and recast it in any way I feel and the language cannot correct any errors I make because their is no information in the variable to indicate what type it is. > So when you > look at type systems formally then you certainly have to assign types to > values, otherwise you couldn't prove any useful property about those > systems (esp. soundness). Yes, but indirectly. From ben at benfinney.id.au Wed Jun 14 01:14:00 2006 From: ben at benfinney.id.au (Ben Finney) Date: Wed, 14 Jun 2006 15:14:00 +1000 Subject: Bundling an application with third-party modules Message-ID: <878xo0nwtj.fsf@benfinney.id.au> Howdy all, I'm improving an existing application that's partly written using Python and the standard library. Many of the improvements I want to make can be done by using third-party free software. The immediate customer for this application is happy to install Python on their machine, but I'd like to remove the hassle of asking them to continually install new versions of great third-party Python software that isn't packaged for their OS. I want to supply those modules as part of implementing my application. What I'd like to do is: - Pull down the external packages and modules from the internet - Put those things in a predictable location within my application's source tree - Have the third-party stuff be placed in a location specific for this application, so that I know my application is using exactly what I pulled down from the internet - Have the implementation of my application, and all the new versions of whatever third-party software I use, be automated with a command I can give to the customer I specifically *don't* want the third-party packages to need to be installed explicitly by the customer. I would prefer if all this can be done without needing root access on the implementation machine. What kind of infrastructure am I looking at? Python eggs, for my application and all its dependencies? That would likely involve making eggs of other people's programs. Moving files around and diddling the system path? I would expect this type of requirement isn't particularly unique. How have other people solved it? -- \ "Well, my brother says Hello. So, hooray for speech therapy." | `\ -- Emo Philips | _o__) | Ben Finney From gh at ghaering.de Tue Jun 13 14:52:50 2006 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 13 Jun 2006 20:52:50 +0200 Subject: [ANN] pysqlite 2.3.0 Message-ID: <448F0982.70906@ghaering.de> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 pysqlite 2.3.0 released ======================= I'm pleased to announce the availability of pysqlite 2.3.0. This is a major release with a few new features. Go to http://pysqlite.org/ for downloads, online documentation and reporting bugs. What is pysqlite? pysqlite is a DB-API 2.0-compliant database interface for SQLite. SQLite is a relational database management system contained in a relatively small C library. It is a public domain project created by D. Richard Hipp. Unlike the usual client-server paradigm, the SQLite engine is not a standalone process with which the program communicates, but is linked in and thus becomes an integral part of the program. The library implements most of SQL-92 standard, including transactions, triggers and most of complex queries. pysqlite makes this powerful embedded SQL engine available to Python programmers. It stays compatible with the Python database API specification 2.0 as much as possible, but also exposes most of SQLite's native API, so that it is for example possible to create user-defined SQL functions and aggregates in Python. If you need a relational database for your applications, or even small tools or helper scripts, pysqlite is often a good fit. It's easy to use, easy to deploy, and does not depend on any other Python libraries or platform libraries, except SQLite. SQLite itself is ported to most platforms you'd ever care about. It's often a good alternative to MySQL, the Microsoft JET engine or the MSDE, without having any of their license and deployment issues. pysqlite can be downloaded from http://pysqlite.org/ - Sources and Windows binaries for Python 2.4 are available. Windwos binaries for Python 2.3 will follow during the next days. ======= CHANGES ======= "Errors should never pass silently." ==================================== Errors in callbacks used to simply be ignored. They would lead to the column in question having a NULL value, for example. Now they result in the query being aborted with a useful error message like "User-defined function raised exception". Errors in callbacks can now be printed to stderr. You have to enable this feature first by calling enable_callback_tracebacks(1), though. Aborting long-running queries ============================= You can now interrupt queries by calling interrupt() on the connection (from a different thread) Now with built-in paranoia ========================== There is a new connection-level method set_authorizer() for adding authorizer hooks. You can use it to accept arbitrary SQL statements from users and limiting what they can do with the database, for example only allow SELECT statements and restricting access to certain tables or columns. Changes for converters ====================== Converters are now looked up in a case-insensitive manner. Bugfixes ======== Fixed a bug where it was possible that one error while constructing a result row was hidden by another error. This resulted in segmentation faults. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2.2 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFEjwmCdIO4ozGCH14RAtUAAJ9UpQFdcPhqEvQEdPWNJUaP2LtoagCcC8Hu JhIIha/vNIOpahH+pNMOZzo= =VpsE -----END PGP SIGNATURE----- From sjmachin at lexicon.net Sat Jun 3 22:52:49 2006 From: sjmachin at lexicon.net (John Machin) Date: Sun, 04 Jun 2006 12:52:49 +1000 Subject: Using print instead of file.write(str) In-Reply-To: <44809e93$0$13657$636a55ce@news.free.fr> References: <2Iq*Jzbir@news.chiark.greenend.org.uk> <44809e93$0$13657$636a55ce@news.free.fr> Message-ID: <44824B01.3040806@lexicon.net> On 3/06/2006 9:47 AM, Bruno Desthuilliers wrote: > > Now, given: > > bird = "parrot" > beautiful = "dead" > > How would you do the following with f.write() ? > > print "this", bird, "is", beautiful > > (without using string formating, of course...) Like this: f.write((' '.join(str(x) for x in ['this', bird, 'is', beautiful]) + '\n')) ... or was that a rhetorical question? Cheers, John From ldo at geek-central.gen.new_zealand Fri Jun 30 06:54:22 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 30 Jun 2006 22:54:22 +1200 Subject: Interprocess communication on multi-user machine References: <44a41cae$0$29145$9b4e6d93@newsread4.arcor-online.net> Message-ID: In article , nmm1 at cus.cam.ac.uk (Nick Maclaren) wrote: >In article , >Lawrence D'Oliveiro writes: >|> In article <44a41cae$0$29145$9b4e6d93 at newsread4.arcor-online.net>, >|> Michael Butscher wrote: >|> >|> >Normally any user could connect to an open socket on a machine >|> >regardless which user established the socket (the user's program, to be >|> >precise). >|> >|> That's not true. On *nix systems, a socket is a file, and is subject to >|> the usual file ownership and protection mechanisms. > >I am afraid that BOTH answers are badly wrong! > >Sockets are often accessed via special files, but are not files. They are files. They are not _regular_ files. >They may also be accessed by port numbers, for example. UNIX sockets have no ports. >Secondly, even when they are accessed via files, FIFOs generally >do NOT use the usual file ownership and protection mechanisms to >control access. I wasn't talking about FIFOs. Even if I was, they _are_ still subject to regular file permissions (on Linux, at least). >While any user can attempt to open any socket accessed by port >number... UNIX sockets have no ports. From sjmachin at lexicon.net Mon Jun 26 19:29:16 2006 From: sjmachin at lexicon.net (John Machin) Date: Tue, 27 Jun 2006 09:29:16 +1000 Subject: Having problems with strings in HTML In-Reply-To: References: Message-ID: <44A06DCC.7070709@lexicon.net> On 27/06/2006 7:51 AM, Kiana Toufighi wrote: > Hi, > > I get a very odd error: > ValueError: unsupported format character 't' (0x74) at index 237 > > Here's my code: > HI_LITE_FILE_NAME = '/var/tmp/out.txt' > > print ''' > href="http://bbc.botany.utoronto.ca/ntools/cgi-bin/ntools_treeview_word.cgi?input=&max=2&values_off=no&remove_bracket=no&show_line_nr=yes&show_link_out=yes&decimal_places=10&show_classification=yes&db=arabidopsis&selection=any%20term&mode=&mode_nos=&yellow_blue=yes&local_file_name=%(OUT_FILE_NAME)s&show_instructions=no&expt_link=NASCArrays&max_adjust=2&view_size=large&highlight=%(HI_LITE_FILE_NAME)s">GraphicalOutput > > ''' % {'OUT_FILE_NAME': OUT_FILE_NAME, 'HI_LITE_FILE_NAME': > HI_LITE_FILE_NAME} That code produces: NameError: name 'OUT_FILE_NAME' is not defined When that is remedied, *then* one gets the ValueError. *Please*, when asking a question, post exactly the code that you ran, and include the full traceback, not just the last line. > > I wonder if this has something to do with HTML's % character. I'm not sure why you are wondering. The error message told you exactly what the problem was and exactly where it was (offset 237) in your format string. . Your format string (the first operand of the string % operator) contains ...&selection=any%20term... and the %20t looks like a formatting operation, but (like it said) 't' is not valid. To overcome this you would need to escape any '%' that is actually part of the URL by doubling it ...&selection=any%%20term... This is nothing to do with HTML ... *any* stray '%' will give you grief: |>> '1% of %s are difficult to understand' % 'error messages' Traceback (most recent call last): File "", line 1, in ? TypeError: int argument required Have you read this: http://docs.python.org/lib/typesseq-strings.html ? It may help. Cheers, John From aleax at mac.com Fri Jun 2 22:08:48 2006 From: aleax at mac.com (Alex Martelli) Date: Fri, 2 Jun 2006 19:08:48 -0700 Subject: An oddity in list comparison and element assignment References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> <1hg9nl6.xivwcd7n0j5N%aleax@mac.com> <1149277242.199765.213600@g10g2000cwb.googlegroups.com> Message-ID: <1hgbhhi.mcrge51cyj2isN%aleax@mac.com> wrote: ... > (As an aside, may I point out that Python In A Nutshell states on page > 46 "The result of S*n or n*S is the concatenation of n copies of S". It > might be well to put a warning in a future edition that this is not > strictly the case.) Can you give me an example where, say, for a sequence S, x = S * 3 is not structurally the same as x = copy.copy(S) + copy.copy(S) + copy.copy(S) ...? That is, where the "* 3" on a sequence is NOT the concatenation of three copies (ordinary copies, of course!) of that sequence? I don't think you can... and I can't repeatedly explain or point to the distinction between normal, ordinary, shallow copies on one side, and "deep copies" on the other, every single time in which that distinction MIGHT be relevant (because some reader might not be aware of it); such endless repetition would bloat the Nutshell totally away from its role as a CONCISE desktop reference, and seriously hamper its usefulness (particularly by DESTROYING any trace of usefulness for anybody who's finally *GOT* this crucial bit, but not just in that way). > languages and methodologies. As I noted in an earlier reply, I don't > realistically expect Python to change the behavior of the == operator. Then you might have avoided trying to convince anybody, or even trying to IMPLY, that in an ideal version of Python == *SHOULD* behave your way -- Python's semantics *ARE* entirely up for rediscussion at the moment, with an eye on the future "Python 3000" release, so this is one of the very rare periods of the history of the language where backwards incompatibility of a potential change is _NOT_ a blocking point. By asserting that your version of == would be "more natural", and trying to defend that assertion by vague handwaving references to maths and "real world", you managed to entirely shift MY mindstate (and possibly that of several other discussants) into one of total and absolute opposition to the proposal -- having by now spent considerable time and energy pondering and debating the issue, I am now entirely convinced that a language with such an == operator instead of Python's current one would be such a total, unadulterated disaster that I would refuse to use that language, no matter what other "good" features it might present to me. I've walked away from great jobs, just because they would have required me to use some technology I just could not stand, more than once already in my life: and this IS how strongly (and negatively) I feel about your claim that, for built-in ==, your semantics would be in any way preferable to Python's. By managing to thus focus my mindset (and make me spend my energy and time) in opposition to your claims of "more natural", you have at least managed to ensure that I will not now lend any scrap of help or support to your debugging needs. If you were as pragmatic as you claim to be, this kind of consideration WOULD have weighed highly in your choices. I.ie., if you had WANTED to attract any such support and help, a completely different attitude than that "most natural" claim would have been ENORMOUSLY more productive -- and your continuing attempts to debate that issue aren't helping AT ALL either: > I do think that a problem arose when it was adopted from C and extended > to allow comparison of containers. In C, you can use it to compare > integers, floats, and pointers and everyone understands that p==q does > not imply *p == *q. If that is so, then everyone is utterly, totally, entirely, horribly *WRONG*, because, in C, p==q ***DOES*** imply *p == *q (whenever p -- and by consequence q, given equality -- may legitimately be dereferenced: p == q == 0 does not imply anything about *p and/or *q, which may produce random results, crash the process, or whatever -- of course). You no doubt meant to say something entirely different from what you ACTUALLY said, but I respectfully suggest you spare your breath rather than keep trying to defend an indefensible position. I do NOT agree, and I cannot imagine any state of the world that would get me to agree, with your claim that "a problem arose" by allowing equality comparison of containers in Python (many other languages allow such comparisons, BTW; I would consider it a horrible wart if a language claiming to be "higher level" did NOT). That you're "supporting" (HA!) your absurd claim with an equally absurd (and obviously, wholly false, unfounded, and misplaced) claim about C pointers doesn't "help", of course, but even perfectly accurate claims about C (or machine code, or Cobol, or RPG...) would be pretty much uninteresting and irrelevant. > Moreover, compilers issue warnings about > comparisons between different types. Some do, some don't, depending on the case -- e.g., I do not believe that even with -Wall (or the equivalent setting) any C compiler whines about EQUALITY comparisons of signed and unsigned integers (as well they shouldn't, of course)! And, just as of course, this umpteenth side-path you're introducing has really nothing to do with the case, since when you're comparing two lists-containing-lists which are equal by Python's rules but according to your original claims about what's "more natural" ``should not'' be, you ARE anyway comparing object of equal types. > Basically, I'm looking for simple diagnostic tools that make it easy to > understand what's really going on when code produces an unexpected > result. A 'strengthened equivalence' operator, to use your terminology > would have been useful to me. A *FUNCTION* performing such checks in a debugging and diagnostics package would have been -- and if you hadn't pushed me to spend so much time and energy defending Python's design choices against your claims that other choices would be "more natural", you might have gotten help and support in developing it. But you chose to make ill-founded claims of "more natural", and therefore you got a flamewar instead: your choice. > will serve to move the discussion beyond terms like 'crazy' and > 'handwaving' and 'ill-founded'. I haven't used such perjoratives in > any of my posts and would appreciate the same courtesy. You claimed that Python's semantics are "contrary to one of my fundamental expectations", "an oddity", resulting only (you said in your second post) from a "performance and memory optimization", and tried to justify this severe criticism of Python by vague (i..e, "handwaving") appeals to analogies with "maths" and "the real world". I do not believe that such scathing criticism had any sound foundations, nor that calling it "ill-founded" is anything but a fittingly accurate description: and a language where the == operator DID satisfy the constraints you claimed to desire for *THE EQUALITY OPERATOR ITSELF* (as opposed to, for some helper/checker function in a separate module for checking and debugging) would be a crazy one indeed. If my opinions that, I believe, accurately reflect the facts of the case, sound "pejorative" to you, well, that's not a matter of choice of words on my part, as much as of your choice of what to express in the first place. Take your recent claim that in C "everyone understands that p==q does not imply *p == *q"; which of the many ("pejorative") adjectives I tagged your assertion with do you think are inaccurate or inappropriate? I called it wrong, absurd, false, unfounded, and misplaced, and seasoned the mix with a choice of adverbs including "utterly" and "horribly". It appears to me that each of these adjectives and adverbs is appropriate and accurate (though it's repetitious on my part to use them all, that repetition does convey the intensity of my opinions in the matter). This is a factual issue where it's easy to defend strongly held opinions (which may be checked against "facts"); in matters of "should" (what semantics "should" a certain language construct HAVE, in order to be most natural, simplest, and most useful -- quite apart from any issues of optimization) such ease is, alas, not given... but the fact that veryfying clashing opinons about what "should" be the case is way harder than opinions easily checkable against "facts", does not mean that the "should"'s (which are even more important, potentially, in their effect on future language design!) are any less important -- on the contrary. I do not believe I am going to follow this thread any more; I wish you best of luck in your future endeavors -- and, if you can get back to being the pragmatist that you claim to be, perhaps in the future you may chose to express your debugging needs and desiderata in ways that dispose the experts on some give technology to help and support you, rather than to fight against the damage which, they opine, it would cause to the future of that technology if certain ("crazy") suggestions were to be part of it. Alex From cdsmith at twu.net Mon Jun 26 14:53:42 2006 From: cdsmith at twu.net (Chris Smith) Date: Mon, 26 Jun 2006 12:53:42 -0600 Subject: What is a type error? References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <7i3mg.204167$8W1.155367@fe1.news.blueyonder.co.uk> <44992e6c$2$664$bed64819@news.gradwell.net> <%Igmg.464974$xt.353729@fe3.news.blueyonder.co.uk> <4fv0v3F1kipa6U1@individual.net> <4gakhiF1m698cU1@individual.net> <4galqlF1mae4qU1@individual.net> Message-ID: Pascal Costanza wrote: > Chris Smith wrote: > > Of course zero is not appropriate as a second argument to the division > > operator! I can't possibly see how you could claim that it is. The > > only reasonable statement worth making is that there doesn't exist a > > type system in widespread use that is capable of checking this. > > ...and this is typically not even checked at the stage where type tags > are checked in dynamically-typed languages. Hence, it is not a type > error. (A type error is always what you define to be a type error within > a given type system, right?) Sure, it's not a type error for that language. > Note, this example was in response to David's reply that my definition > turns every runtime error into a type error. That's not the case, and > that's all I want to say. But your definition does do that. Your definition of a type error was when a program attempts to invoke an operation on values that are not appropriate for this operation. Clearly, in this example, the program is invoking an operation (division) on values that are not appropriate (zero for the second argument). Hence, if your definition really is a definition, then this must qualify. > > However, it sounds as > > if you're claiming that it wouldn't be possible for the type system to > > do this? > > No. I only need an example where a certain error is not a type error in > _some_ language. I don't need to make a universal claim here. Definitions are understood to be statements of the form "if and only if". They assert that /everything/ that fits the definition is describable by the word, and /everything/ that doesn't is not describable by the word. If that's not what you meant, then we are still in search of a definition. If you want to make a statement instead of the sort you've implied above... namely that a type error is *any* error that's raised by a type system, then that's fine. It certainly brings us closer to static types. Now, though, the task is to define a type system without making a circular reference to types. You've already rejected the statement that all runtime errors are type errors, because you specifically reject the division by zero case as a type error for most languages. What is that distinction? -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation From pc at p-cos.net Wed Jun 28 12:14:20 2006 From: pc at p-cos.net (Pascal Costanza) Date: Wed, 28 Jun 2006 18:14:20 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <7zy7vt1mz2.fsf@app-3.diku.dk> <1151384511.223582.305760@m73g2000cwd.googlegroups.com> <4gdkmiF1ldalhU3@individual.net> <4gfcclF1mpbg7U1@individual.net> <6gwog.488405$xt.80841@fe3.news.blueyonder.co.uk> <4gfiufF1mg6h9U1@individual.net> Message-ID: <4gfo6tF1cju7vU1@individual.net> Matthias Blume wrote: > Pascal Costanza writes: > >> Whether you consider something you cannot do with statically typed >> languages a bad idea or not is irrelevant. You were asking for things >> that you cannot do with statically typed languages. > > The whole point of static type systems is to make sure that there are > things that one cannot do. So the fact that there are such things are > not an argument per se against static types. I am not arguing against static type systems. I am just responding to the question what the things are that you cannot do in statically typed languages. > [ ... ] > >> Beyond that, I am convinced that the ability to update a running >> system without the need to shut it down can be an important asset. > > And I am convinced that updating a running system in the style of, > e.g., Erlang, can be statically typed. Maybe. The interesting question then is whether you can express the kinds of dynamic updates that are relevant in practice. Because a static type system always restricts what kinds of runtime behavior you can express in your language. I am still skeptical, because changing the types at runtime is basically changing the assumptions that the static type checker has used to check the program's types in the first place. For example, all the approaches that I have seen in statically typed languages deal with adding to a running program (say, class fields and methods, etc.), but not with changing to, or removing from it. >>> Note that prohibiting directly self-modifying code does not prevent a >>> program from specifying another program to *replace* it. >> ...and this creates problems with moving data from one version of a >> program to the next. > > How does this "create" such a problem? The problem is there in either > approach. In fact, I believe that the best chance we have of > addressing the problem is by adopting the "replace the code" model > along with a "translate the data where necessary at the time of > replacement". Translating the data, i.e., re-establishing the > invariants expected by the updated/replaced code, seems much harder > (to me) in the case of self-modifying code. Erlang got this one > right. ...and the "translate the date where necessary" approach is essentially triggered by a dynamic type test (if value x is of an old version of type T, update it to reflect the new version of type T [1]). QED. Pascal [1] BTW, that's also the approach taken in CLOS. -- 3rd European Lisp Workshop July 3 - Nantes, France - co-located with ECOOP 2006 http://lisp-ecoop06.bknr.net/ From onurb at xiludom.gro Tue Jun 27 07:05:25 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Tue, 27 Jun 2006 13:05:25 +0200 Subject: Replace Whole Object Through Object Method In-Reply-To: References: <1151337453.804750.293180@b68g2000cwa.googlegroups.com><44a041a6$0$17612$636a55ce@news.free.fr><1151354259.082966.25820@p79g2000cwp.googlegroups.com><1151376052.727979.71470@c74g2000cwc.googlegroups.com> <44a0f4d9$0$9022$626a54ce@news.free.fr> Message-ID: <44a110f6$0$16358$626a54ce@news.free.fr> Fredrik Lundh wrote: > Bruno Desthuilliers wrote: > > >>As a matter of fact, in Python, the class is an attribute of an object. > > > except when it isn't. Which are the cases where it isn't ? > >>>def add_role(self, role_class): >>> self.roles.append(role_class(self)) >> >>And here you create a circular reference between object and roles... > > > and ? Python has a garbage collector, you know... Yes. But garbage collection is not cost-free AFAIK. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From duncan.booth at invalid.invalid Thu Jun 15 06:56:43 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 15 Jun 2006 10:56:43 GMT Subject: nested functions References: <1150344748.652441.316680@g10g2000cwb.googlegroups.com> Message-ID: Fredrik Lundh wrote: > George Sakkis wrote: > >> It shouldn't come as a surprise if it turns out to be slower, since >> the nested function is redefined every time the outer is called. > > except that it isn't, really: all that happens is that a new function > object is created from prebuilt parts, and assigned to a local > variable. it's not slower than, say, a method call. > It looks to be somewhat faster than a method call: C:\temp>\python24\lib\timeit.py -s "import t" "t.testMethod(t.instance, 42)" 1000 loops, best of 3: 1.58 msec per loop C:\temp>\python24\lib\timeit.py -s "import t" "t.testMethod2(t.instance, 42)" 100 loops, best of 3: 1.61 msec per loop C:\temp>\python24\lib\timeit.py -s "import t" "t.testNested(t.instance, 42)" 1000 loops, best of 3: 1.06 msec per loop C:\temp>\python24\lib\timeit.py -s "import t" "t.testNested2(t.instance, 42)" 1000 loops, best of 3: 1.08 msec per loop C:\temp>\python24\lib\timeit.py -s "import t" "t.testNested3(t.instance, 42)" 1000 loops, best of 3: 1.13 msec per loop C:\temp>\python24\lib\timeit.py -s "import t" "t.testNested4(t.instance, 42)" 1000 loops, best of 3: 1.23 msec per loop --------- t.py ------------- class C: def m1(self): return 42 def m2(self, x): return x instance = C() def testMethod(instance,x): n = 0 while n < 100000: n += instance.m1() def testMethod2(instance, x): n = 0 while n < 100000: n += instance.m2(x) def testNested(instance, x): def m1(): return 42 n = 0 while n < 100000: n += m1() def testNested2(instance, x): def m2(): return x n = 0 while n < 100000: n += m2() def testNested3(instance, x): def m2(y): return y n = 0 while n < 100000: n += m2(x) def testNested4(instance, x): def m2(y): return x n = 0 while n < 100000: n += m2(x) ---------------------------- The differences between the nested function calls show how difficult it can be guessing what will be faster: #3 show that all, else being equal, accessing the closure is much slower than accessing a parameter, but #2 shows that not passing any parameters to the nested function more than compensates for the single slow closure access. From sjmachin at lexicon.net Sun Jun 4 04:24:06 2006 From: sjmachin at lexicon.net (John Machin) Date: Sun, 04 Jun 2006 18:24:06 +1000 Subject: Hostmask matching In-Reply-To: References: Message-ID: <448298A6.6020502@lexicon.net> On 4/06/2006 4:45 PM, Nexu wrote: > On Sun, 2006-06-04 at 06:26 +0000, Marc Schoechlin wrote: >> Hi ! >> >> Nexu schrieb: >>> I'm trying to write a def to match a string that is an irc hostmask. eg: >>> *one!~*name at a??-??-101-101.someisp.com >>> But using re.search(). I get an error when the string starts with '*'. >>> What is the best way to solve this? >> I suppose the problem occurs because you expression is not a valid >> regular expression. >> >> A correct regular expression should look like this: >> ".*one!~.*name at a..-..-101-101.someisp.com" > Thx for everyones input. > > This solved the problem: > host = 'someone!~thename at a80-80-101-101.someisp.com' > mask = '*one!~*name at a??-??-101-101.someisp.com' > newmask = re.sub('\*', '.*', re.sub('\?', '.', mask)) > result in that: > re.search(newmask, host) == True For a start, you must mean bool(re.search(newmask, host)) == True, because re.search() returns a MatchObject or None; neither of those will ever compare equal to True. Moving right along, you have only one facet of your multi-faceted multi-level problem fixed. Consider the following: |>>> newmask '.*one!~.*name at a..-..-101-101.someisp.com' |>>> host = 'someone!~thename at a80-80-101-101.someisp.com' |>>> bool(re.search(newmask, host)) True |>>> host2 = 'someone!~thename at a80-80-101-101.someisp.communication.problem' |>>> bool(re.search(newmask, host2)) True |>>> host3 = 'someone!~thename at a80-80-101-101XsomeispYcom' |>>> bool(re.search(newmask, host3)) True You didn't answer either of my questions that would have told me whether host2 is a problem; if it is, you need a '$' at the end of newmask. To fix the host3 problem, you need '\.' instead of '.'. There is another possible host2-like problem: if you have a hostmask that starts with 'one' (i.e. no '*' at the front), what you are doing now will give True for incoming starting with 'anyone!' or 'I_am_the_one!' or whatever. I don't think you want that to happen. Two solutions: (1) Put '^' at the start of newmask (2) use re.match() instead of re.search(). Another question: should you be doing a case-insensitive match? If so, you need re.search/match(newmask, host, re.IGNORECASE) You may wish to consider looking at the fnmatch module, at three levels: (1) calling fnmatch.fnmatchcase() may be good enough for your purpose (2) you can use the undocumented fnmatch.translate(), like this: newmask = fnmatch.translate(mask) and use re.match() (3) you can find the source code in /Lib/fnmatch.py, copy the translate function, and rip out the lines that treat '[' as special. HTH, John From siona at chiark.greenend.org.uk Fri Jun 2 11:21:04 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 02 Jun 2006 16:21:04 +0100 (BST) Subject: New to Python: Do we have the concept of Hash in Python? References: <1149182265.257263.159210@f6g2000cwb.googlegroups.com> Message-ID: gregarican wrote: >I came from using Ruby about a year or so [ ... ] That's an interesting way round. Why did you consider Python if you already knew Ruby, and which is now your preferred language? (I've no interest in learning Ruby, but from what I've seen of it I similarly can't imagine what would motivate me to learn Python.) -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From onurb at xiludom.gro Fri Jun 23 11:13:01 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Fri, 23 Jun 2006 17:13:01 +0200 Subject: what exceptions may file() and read() throw? In-Reply-To: References: Message-ID: <449c04fd$0$13036$626a54ce@news.free.fr> Daniel Sch?le wrote: > Hi > > >>You can't easily list the exceptions that your code could throw. There are >>some obvious ones apart from IOError: say filename was an int (or even >>certain strings) you would get TypeError, or you might get MemoryError or >>KeyboardInterrupt. More obscurely, if you reused file as a global variable >>you could generate any exception at all. > > > I undestand now, so it would be better to let it in the code > in case it's triggered Nope. Let it propagate, so you have a full traceback. traceback are usefull. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From webraviteja at gmail.com Mon Jun 12 22:18:43 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 12 Jun 2006 19:18:43 -0700 Subject: Combining The Best Of Python, Ruby, & Java?????? In-Reply-To: References: Message-ID: <1150165123.259163.181650@c74g2000cwc.googlegroups.com> Tim Daneliuk wrote: > So it is claimed: > > http://www.infoq.com/news/Scala--combing-the-best-of-Ruby-;jsessionid=CC7C8366455E67B04EE5864B7319F5EC > > Has anyone taken a look at this that can provide a meaningful contrast > with Python? I find the language very interesting but it is not like Python or Ruby at all. Feels a lot more like OCaml + Haskell for JVM with a more mainstream (Java) syntax. From just at xs4all.nl Wed Jun 7 18:44:31 2006 From: just at xs4all.nl (Just) Date: Thu, 08 Jun 2006 00:44:31 +0200 Subject: CENSORSHIP - Django Project (Schema Evolution Support) References: <4486B9FB.9030804@lazaridis.com> <1mbzvhr7j0x99.qlcv3kw259m6.dlg@40tude.net> Message-ID: In article , Erik Max Francis wrote: > Thorsten Kampe wrote: > > > I think I have a deja-vu... Did someone say "Xah"?! > > With a hint of Brandon. And a slice of Timothy Rue. Just From scott.daniels at acm.org Sun Jun 18 19:41:17 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Sun, 18 Jun 2006 16:41:17 -0700 Subject: mapping None values to '' In-Reply-To: References: <1150632320.443681.42640@r2g2000cwb.googlegroups.com> <0Rblg.5940$zy5.141663@twister1.libero.it> Message-ID: <4495dfba@nntp0.pdx.net> Roberto Bonvallet wrote: > imho : >> map(lambda x:"" , [i for i in [a,b,c] if i in ("None",None) ]) > You don't need map when using list comprehensions: > ["" for i in [a, b, c] if i in ("None", None)] > More like: [(i, "")[i in ("None", None)] for i in [a,b,c]] -- --Scott David Daniels scott.daniels at acm.org From aum at spam.me.please Thu Jun 29 17:28:38 2006 From: aum at spam.me.please (aum) Date: Fri, 30 Jun 2006 09:28:38 +1200 Subject: Leo 4.4.1 beta 3 released References: Message-ID: On Thu, 29 Jun 2006 11:39:08 -0500, Edward K. Ream wrote: > Leo 4.4.1 beta 3 is now available at: > http://sourceforge.net/project/showfiles.php?group_id=3458&package_id=29106 > > This release corrects several long-standing bugs and adds optional flashing > of matching brackets. (snip) The author's surname needs an 's' on the end to indicate the quantity of paper that would be needed to communicate the virtues of his software, and the value of the tireless efforts he's put into it over the years. -- Cheers aum From fredrik at pythonware.com Fri Jun 9 03:52:58 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 09 Jun 2006 09:52:58 +0200 Subject: Error in Chain of Function calls In-Reply-To: <53637.10.209.4.2.1149834663.squirrel@10.105.1.3> References: <53637.10.209.4.2.1149834663.squirrel@10.105.1.3> Message-ID: Girish Sahani wrote: > However i am getting an error at the line marked with ***. what error ? > Also,i am getting a ValueError in the code below: > > for s in prunedNew: > substrings = [s[:i]+s[i+1:] for i in range(len(s))] > for string in substrings: > if string not in prunedK: > prunedNew.remove(s) > continue > continue > > The error is: > prunedNew.remove(s) > ValueError: list.remove(x): x not in list the ValueError means exactly what it says -- have you verified that the value of "s" really is present in the list? did you really mean to remove "s" and not, say, "string" ? From bayerj at in.tum.de Thu Jun 22 09:32:25 2006 From: bayerj at in.tum.de (bayerj) Date: 22 Jun 2006 06:32:25 -0700 Subject: Registry of Methods via Decorators Message-ID: <1150983145.387222.5600@c74g2000cwc.googlegroups.com> I want to make a registry of methods of a class during creation. My attempt was this """ classdecorators.py Author: Justin Bayer Creation Date: 2006-06-22 Copyright (c) 2006 Chess Pattern Soft, All rights reserved. """ class decorated(object): methods = [] @classmethod def collect_methods(cls, method): cls.methods.append(method.__name__) return method class dec2(decorated): @collect_methods def first_func(self): pass @collect_methods def second_func(self): pass def main(): print dec2.methods if __name__ == '__main__': main() This does not work and exits with "NameError: ("name 'collect_methods' is not defined",)". Which is understandable due to the fact that the class dec2 is not complete. Anyone can give me a hint how to work around this? From Mike.S.Duffy at gmail.com Sat Jun 17 04:34:13 2006 From: Mike.S.Duffy at gmail.com (Mike Duffy) Date: 17 Jun 2006 01:34:13 -0700 Subject: Legitimate use of the "is" comparison operator? In-Reply-To: References: <1150530591.422197.304300@p79g2000cwp.googlegroups.com> Message-ID: <1150533253.400675.232510@g10g2000cwb.googlegroups.com> Fredrik Lundh wrote: > > except that it doesn't work. > > writing broken code is never a good practice. > With all due respect, for some reason it seems to work on my machine. Because I certainly agree with you about writing broken code. Python 2.4.2 (#1, Jan 17 2006, 16:52:02) [GCC 4.0.0 20041026 (Apple Computer, Inc. build 4061)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> a = range(5) >>> b = range(5) >>> >>> if len(a) is len(b): ... print "They're the same size!" ... else: ... print "They're not the same size!" ... They're the same size! >>> > > (the reason that it appears to work for small integers is that the > interpreter is caching the objects for some commonly used values, > including small integers and one-character strings. but that's an > interpreter implementation detail, not something you can rely on). > That's very interesting. Thank you for explaining :-) From ken.carlino at gmail.com Wed Jun 7 17:15:49 2006 From: ken.carlino at gmail.com (ken.carlino at gmail.com) Date: 7 Jun 2006 14:15:49 -0700 Subject: Regular Expression question Message-ID: <1149714949.542234.148800@y43g2000cwc.googlegroups.com> Hi, I am new to python regular expression, I would like to use it to get an attribute of an html element from an html file? for example, I was able to read the html file using this: req = urllib2.Request(url=acaURL) f = urllib2.urlopen(req) data = f.read() my question is how can I just get the src attribute value of an img tag? something like this: (.*)(.*) I need to get the href of the image source. Thanks. From edgrsprj at ix.netcom.com Tue Jun 13 07:39:00 2006 From: edgrsprj at ix.netcom.com (edgrsprj) Date: Tue, 13 Jun 2006 11:39:00 GMT Subject: Earthquake and Tornado Forecasting Programs June 13, 2006 References: Message-ID: "edgrsprj" wrote in message news:D7qAe.21003$eM6.9503 at newsread3.news.atl.earthlink.net... > PROPOSED EARTHQUAKE FORECASTING > COMPUTER PROGRAM DEVELOPMENT EFFORT > > Posted July 11, 2005 > My main earthquake forecasting Web page is: > http://www.freewebz.com/eq-forecasting/Data.html > EARTHQUAKE AND TORNADO FORECASTING PROGRAMS Posted by E.D.G. June 13, 2006 http://www.freewebz.com/eq-forecasting/Data.html The information in this report represents expressions of personal opinion. On July 11, 2005 I posted a report to a number of Internet Newsgroups including sci.geo.earthquakes stating that I was considering creating a Web site where researchers around the world could post notes and develop computer programs associated with the science of earthquake forecasting. This present report is an update on that project. The effort is still underway. The present plan is to try to get the proposed Web site organized for the science of earthquake forecasting and then expand it to include other sciences such as tornado forecasting and different areas of medicine. The ultimate goal is to have discussion areas there for as many of the problems which threaten the health and lives of people around the world as possible. Professional and amateur computer programmers would probably be heavily involved with this work. Since that first report was posted last July I have been able to establish what looks like it will be a stable source of funding for the effort. It should at least enable me to continue working on the project and pay for things such as Web site rental fees etc. And I am presently working with two groups of legal people who are attempting to create a formal organization through which the actual funding and Web site operation etc. will take place. How fast this effort will progress is at the moment largely up to those legal groups. One of them is supposed to create the necessary legal documents. The other will be doing the filing with government agencies etc. Unfortunately, since I am not a major client of either group they are doing the work when they are not busy with other clients. A formal legal organization intended to be an introductory version of this new organization has existed since 2002. But it took my legal people about eight months to get all of the paperwork done and filed. The present effort has been underway for a month. Hopefully it will not take another seven months to finish. PROPOSED WEB SITE A number of years ago I worked with a Web site development expert to create a discussion group for earthquake forecasting. I believe that it eventually evolved into the two following discussion groups. The original Web site expert is no longer involved. http://groups.yahoo.com/group/earthwaves http://www.earthwaves.org/wwwboard/wwwboard.html For this proposed Web site I would probably try to use a discussion board which would be a highly modified version of that second board. And it will take a fair amount of computer programming to create the new version. The problem with the existing discussion board control computer program is that it is does not offer the necessary posting options. When researchers post a note to such a board, rules have to be in place regarding what types of notes other people can post in response. That is an absolute necessity. And the structure of that present board does not contain those types of rules within the control computer program itself. More details regarding that proposed Web site can be found in the following report that I submitted for a United Nations disaster mitigation related discussion back in July of 2004: http://www.unisdr.org/wcdr-dialogue/t3-dialogue.htm#34 Based on their starting dates etc. I believe that my report might have already led to the creation of the following Web sites: http://www.hewsweb.org http://www.grassroots.org Keep your fingers crossed. If the effort to create this proposed Web site is successful then it might assist researchers in quite a few areas of science and medicine around the world with significantly accelerating their lifesaving efforts. From davefowler at gmail.com Wed Jun 14 10:58:13 2006 From: davefowler at gmail.com (godavemon) Date: 14 Jun 2006 07:58:13 -0700 Subject: convert floats to their 4 byte representation Message-ID: <1150297093.191223.152330@c74g2000cwc.googlegroups.com> I need to take floats and dump out their 4 byte hex representation. This is easy with ints with the built in hex function or even better for my purpose def hex( number, size ): s = "%"+str(size) + "X" return (s % number).replace(' ', '0') but I haven't been able to find anything for floats. Any help would be great. From meng.yan at gmail.com Fri Jun 2 04:15:38 2006 From: meng.yan at gmail.com (Mike Meng) Date: 2 Jun 2006 01:15:38 -0700 Subject: Are there something like "Effective Python"? In-Reply-To: <1149229055.088793.89010@i39g2000cwa.googlegroups.com> References: <1149224468.481470.74580@i39g2000cwa.googlegroups.com> <1149229055.088793.89010@i39g2000cwa.googlegroups.com> Message-ID: <1149236138.364915.189890@i40g2000cwc.googlegroups.com> Bart, I'm sorry, it's 2nd edtion. Thanks. mike BartlebyScrivener ??? > >> I just finished reading Learning Python 3rd ed, > > For real? I thought there was only a 2nd edition. > > http://www.oreilly.com/catalog/lpython2/ From s99999999s2003 at yahoo.com Wed Jun 14 06:43:39 2006 From: s99999999s2003 at yahoo.com (s99999999s2003 at yahoo.com) Date: 14 Jun 2006 03:43:39 -0700 Subject: joining NoneType and DateTimeType Message-ID: <1150281819.253235.118960@f6g2000cwb.googlegroups.com> hi i have some databse results that are NoneType and DateTimeType. now i have trouble joining these row results together like "|".join(result) as it says cannot join NoneType , DateTimeType . How can i change these types so i can join the columns together as string? thanks From faisjobs at yahoo.co.in Sun Jun 25 13:33:31 2006 From: faisjobs at yahoo.co.in (faisjobs) Date: 25 Jun 2006 10:33:31 -0700 Subject: USA UK CANADA AUSTRALIA Jobs With VISA Sponsorship, VISA immigration, VISA Sponsorship Message-ID: <1151256811.030627.129360@u72g2000cwu.googlegroups.com> USA UK CANADA AUSTRALIA Jobs click here http://visajobs2u.50webs.com/ IT Jobs, Medical Jobs, Marketing Jobs, Engineering Jobs, Call Center Jobs, HRM Jobs, Administrative Jobs, Customer-related Jobs, Non Customer-related Jobs, and many more. Career Opportunities, Vacancies, Hiring, Job Fairs, Recruitment Agency, Employer, Manpower Pooling, etc. click here http://visajobs2u.50webs.com/ ACCEPTED LANGUAGE: ENGLISH ONLY. Members will receive emails everyday. Update your Resume NOW! click here http://visajobs2u.50webs.com/ click here http://visajobs2u.50webs.com/ International Jobs includes the Countries around Asia: Afghanistan Jobs, Armenia Jobs, Azerbaijan Jobs, Bahrain Jobs, Bangladesh Jobs, Bhutan Jobs, Brunei Jobs, Burma (Myanmar) Jobs, Cambodia Jobs, China Jobs, Georgia Jobs, Hong Kong Jobs, India Jobs, Indonesia Jobs, Iran Jobs, Iraq Jobs, Israel Jobs, Japan Jobs, Jordan Jobs, Kazakstan Jobs, (North and South) Korea Jobs, Kuwait Jobs, Kyrgyzstan Jobs, Laos Jobs, Lebanon Jobs, Malaysia Jobs, Maldives Jobs, Mongolia Jobs, Myanmar Jobs, Nepal Jobs, Oman Jobs, Pakistan Jobs, Philippines Jobs, Qatar Jobs, Russia Jobs, Saudi Arabia Jobs, Singapore Jobs, Sri Lanka Jobs, Syria Jobs, Taiwan Jobs, Tajikistan Jobs, Thailand Jobs, Turkey Jobs, Turkmenistan Jobs, United Arab Emirates Jobs, Uzbekistan Jobs, Vietnam Jobs, and Yemen Jobs. You send your reesume and details, click here http://visajobs2u.50webs.com/ Your details will be stored on my jobs data base, your resume match any jobs position we will inform you, lot of jobs with VISA sponsorship available. You send your resume here click here http://visajobs2u.50webs.com/ From dickey at saltmine.radix.net Wed Jun 7 15:28:04 2006 From: dickey at saltmine.radix.net (Thomas Dickey) Date: Wed, 07 Jun 2006 19:28:04 -0000 Subject: Need pixie dust for building Python 2.4 curses module on Solaris 8 References: Message-ID: <128ea64n7knbg53@corp.supernews.com> skip at pobox.com wrote: > I'm having no success building the curses module on Solaris 8 (yes, I know > it's ancient - advancing the state-of-the-art is not yet an option) for > Python 2.4. Sun provides an apparently ancient version of curses in > /usr/lib, so I downloaded and installed ncurses 5.5, both using default > settings and using --with-shared. When the curses module is linked against for Solaris, you also should add --enable-rpath -- Thomas E. Dickey http://invisible-island.net ftp://invisible-island.net From paul at boddie.org.uk Sat Jun 24 09:43:43 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 24 Jun 2006 06:43:43 -0700 Subject: Python web server References: <1151146727.087240.264800@r2g2000cwb.googlegroups.com> Message-ID: <1151156623.234359.207350@p79g2000cwp.googlegroups.com> arvind wrote: > When I run the script on server,only HTML part gets executed. > But the python code appears as it is on the screen in the text format. > How to run the CGI script on web server using Python2.4.3? We don't have much specific information from you here, but taking a few guesses, it sounds like you have put a Python program in some directory that your Web server knows about, but when you visit the address in your browser that should let you use that program, you just see the program text, not the output of the program when it is run. What you need to do is to tell your Web server that the file is a "script". With Apache, for example, instead of using configuration directives like "Alias", you use "ScriptAlias" instead. Of course, Apache has lots of different ways to make files behave like scripts, and you may be using a completely different Web server, so a bit more information would be welcome. Still, one really simple method with Apache is to expose your program like this: ScriptAlias /myprogram "/home/me/programs/myprogram.py" Provided you set the permissions of myprogram.py to be readable and executable by the Web server user (if appropriate), and provided the Web server user can navigate to the /home/me/programs directory, you should at least get the program running. More configuration may be needed - why not let us know how far you get? Paul From roger.miller at nova-sol.com Fri Jun 2 16:51:41 2006 From: roger.miller at nova-sol.com (Roger Miller) Date: 2 Jun 2006 13:51:41 -0700 Subject: Sampling a population References: Message-ID: <1149281501.117141.304060@u72g2000cwu.googlegroups.com> For your example, since the probabilities are all multiples of 0.01 you could make a list of 100 elements. Set one of them to a, 5 of them to b, 50 of them to c, etc. Then just randomly sample from the table (which is O(1)). Of course if the probabilities can be arbitrary floating point values then this won't work. But if you can live with rounding to 3 or 4 digits this is probably the fastest and easiest approach. From ptmcg at austin.rr._bogus_.com Fri Jun 9 11:07:23 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 09 Jun 2006 15:07:23 GMT Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> Message-ID: "Joe Marshall" wrote in message news:1149863687.298352.45980 at h76g2000cwa.googlegroups.com... > > Expressiveness isn't necessarily a good thing. For instance, in C, you > can express the > addresses of variables by using pointers. You cannot express the same > thing in Java, and > most people consider this to be a good idea. > For those who remember the bad old days of COBOL, its claim to fame was that it was more like English prose, with the intent of making a programming language that was as readable as English, assuming that this was more "expressive", and not requiring as much of a mental mapping exercise for someone trying to "read" a program. Even the language terminology itself strived for this: statements were "sentences"; blocks were "paragraphs". The sentence model may have ended up being one of COBOL's Achilles Heel's - the placement of terminating periods for an IF THEN ELSE block was crucial for disambiguating which ELSE went with which IF. Unfortunately, periods are one of the least visible printed characters, and an extra or missing period could cause hours of extra debugging. (Of course, at the time of COBOL's inception, the only primary languages to compare with were assembly or FORTRAN-60, so this idea wasn't totally unfounded.) -- Paul From JohnRoth1 at jhrothjr.com Sun Jun 18 08:25:14 2006 From: JohnRoth1 at jhrothjr.com (John Roth) Date: 18 Jun 2006 05:25:14 -0700 Subject: Cycles between package imports References: Message-ID: <1150633514.024828.95330@g10g2000cwb.googlegroups.com> Martin Blais wrote: > Hi > > I'm a tad confused over a problem involving cycles between > packages. [lengthy example snipped] > > > I don't see why the reference to module a.alice could not be > available via the "from" syntax, even if it is still incompletely > initialized at the time of import. > > Can anyone shed some light onto this? Is there a rule for > determining when a module becomes available to import from a > package using the "from" syntax? It's really easy to see if you trace out, in detail, the exact order in which things happen and when each object is initialized and shows up in the respective module's namespace. The general rule is: don't do that. It doesn't work, and the hoops you have to go through to force it to work are so complex and bizzare that they're not worth it. Redesign the modules so you don't have cyclic dependencies. John Roth From onurb at xiludom.gro Tue Jun 6 12:25:29 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 06 Jun 2006 18:25:29 +0200 Subject: what are you using python language for? In-Reply-To: References: Message-ID: <4485ac79$0$24924$626a54ce@news.free.fr> hacker1017 wrote: > im just asking out of curiosity. > Err... Programming ?-) Sorry... Actually, mostly web applications (CMS, groupware, small/medium business apps etc), and admin utilities. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From fredrik at pythonware.com Tue Jun 20 06:40:47 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 20 Jun 2006 12:40:47 +0200 Subject: Debugging C++ code called from Python 2.2 with Visual Studio.NET References: <1150799634.503338.302780@b68g2000cwa.googlegroups.com> Message-ID: egodet at equisys.com wrote: > I've seen in various groups that python22_d.lib is not available for > download anymore but that it is easy to recompile. Could someone send > it to me, explain how to build it or, even better, both. load the project file (under PCbuild), select the debug targets, and build them. From hdante at gmail.com Sat Jun 17 20:13:33 2006 From: hdante at gmail.com (hdante) Date: 17 Jun 2006 17:13:33 -0700 Subject: File read and writing in binary mode... References: <1150286103.249888.99610@i40g2000cwc.googlegroups.com> Message-ID: <1150589613.402997.132090@g10g2000cwb.googlegroups.com> Hi, I'm sorry, but you have a conceptual error there. Text files differ from binary files because they are not considered raw. When you say that this or that file is a text file, python and/or the operating system takes the liberty to insert and or remove semantics from the file, according to some formatting agreed/imposed by them. Text files are formatted files. Binary files are raw files. You can't expect by any means that python will respect your raw data when writing text files. The solution to the question "how can I write a binary file into a text file" requires that you convert the binary file to a format suitable for textual access. For example, you can "uuencode" the binary file inside your text file. In simple terms: mytext = serialize(binary_file.read()) text_file.write(mytext) ... mydata = deserialize(text_file.read()) The functions "serialize" and "deserialize" are responsible for converting the binary data to/from some textual representation. HOWEVER, why would you want to put binary data into a text file ? Is this some information that will be used by your application ? Or will you transfer it to some other person in a portable way ? Maybe you should leave those files alone and not try to merge them. If it is a complex structure you should put it into a database instead of doing those strange things. In the worst case, you could just write a text file, write a binary file and concatenate them later. See if this really is a requirement for your project. nicolasg at gmail.com wrote: > Hi, > > I'm trying to open a file (any file) in binary mode and save it inside > a new text file. > After that I want to read the source from the text file and save it > back to the disk with its original form. The problem is tha the binary > source that I extract from the text file seems to be diferent from the > source I saved. Here is my code: > 1) > handle=file('image.gif','rb') > source=handle.read() > handle.close() > > if I save the file directly everything is well : > 2A) > handle=file('imageDuplicated.gif','wb') > handle.write(source) > handle.close() > > the file imageDuplicated.gif will be exactly the same as the original > image.gif. > But if I save the source to a text file I have porblem : > 2B) > handle=file('text.txt','w') > handle.write(source) > handle.close() > > handle=file('text.txt','r') > source2=handle.read() > handle.close() > > handle=file('imageDuplicated.gif','wb') > handle.write(source2) > handle.close() > > the files are completly different and I even cant display the image > from the imageDuplicated.gif . > > something changes when I save the source in the text file because in > 2B) source == source2 returns a False . > I suspect that maybe the encoding is making a conflict but I don't know > how to manipulate it... > Every help is welcome, thanks. From dio.lee at gmail.com Tue Jun 27 02:49:30 2006 From: dio.lee at gmail.com (Dio) Date: 26 Jun 2006 23:49:30 -0700 Subject: Select in Python In-Reply-To: References: <1151388082.261840.306260@75g2000cwc.googlegroups.com> Message-ID: <1151390970.076748.80690@x69g2000cwx.googlegroups.com> K.S.Sreeram ??? > Dio wrote: > > while 1: > > (rr, wr, er) = select([stdin], [], []) > > for fd in rr: > > print fd > > > > program block in the first select(), after I type something and "enter > > ", it never block in select() again,why? > > select blocks until there is some data to read from stdin, but it does > not *clear* the data. so once you enter data, select will not block > until you read the data. once you're done reading the available data, > you can again use select to block until more data is available. > > Regards > Sreeram Thanks a lot?I use stdin.readline() after select and it's ok :) From nicola.musatti at gmail.com Tue Jun 6 09:07:41 2006 From: nicola.musatti at gmail.com (Nicola Musatti) Date: 6 Jun 2006 06:07:41 -0700 Subject: 10GB XML Blows out Memory, Suggestions? In-Reply-To: <1149594519.098115.8980@u72g2000cwu.googlegroups.com> References: <1149594519.098115.8980@u72g2000cwu.googlegroups.com> Message-ID: <1149599261.275140.91070@u72g2000cwu.googlegroups.com> axwack at gmail.com wrote: > I wrote a program that takes an XML file into memory using Minidom. I > found out that the XML document is 10gb. > > I clearly need SAX or something else? What you clearly need is a better suited file format, but I suspect you're not in a position to change it, are you? Cheers, Nicola Musatti From DustanGroups at gmail.com Tue Jun 13 09:14:03 2006 From: DustanGroups at gmail.com (Dustan) Date: 13 Jun 2006 06:14:03 -0700 Subject: Making a Label that looks the same as a button. Message-ID: <1150204443.568118.185030@c74g2000cwc.googlegroups.com> I have a Button object that gets replaced by a Label when clicked. Button(buttonsframe,text=' ',command=c,font=buttonsFont) Note that the text is a single space. buttonsFont uses 'Courier New' as a family. When clicked, the Button is destroyed and replaced with a Label object: Label(buttonsframe,text=x,font=buttonsFont,relief=RAISED) The intent is for the Label object to look identical to the button object, except for the non-space character x. The Label object is a little smaller than the Button object. When I set borderwidth, the label object does increase in size, but that's not going to make it look the same, since it makes the border thicker. How do I get the Label object to look just like the Button object? From kydavis77 at gmail.com Mon Jun 26 14:29:08 2006 From: kydavis77 at gmail.com (kydavis77 at gmail.com) Date: 26 Jun 2006 11:29:08 -0700 Subject: Beginner Programmer Question In-Reply-To: References: <1151342733.742416.180370@r2g2000cwb.googlegroups.com> <1151343383.139891.219270@u72g2000cwu.googlegroups.com> <1151343473.722970.251360@r2g2000cwb.googlegroups.com> Message-ID: <1151346548.583760.48810@m73g2000cwd.googlegroups.com> Tim Chase wrote: > > bigone = 100 > > > > number = input("Whats the first number?") > > number2 = input ("Whats the second number?") > > nu3 = number+number2 > > while nu3 < bigone: > > print ("Not there yet, next number please") > > > > print "Finally there!" > > > > thats what i thought maybe it was...but after the first two numbers it > > just continually scrolls on the screen with finally there > > Gaak! it's doing exactly what you told it to do! Bad program! :) > > Inside the loop it neither > 1) gets further input from the user nor > 2) reassigns/sums nu3 > > Thus, neither of the elements of your condition (nu3 < bigone) > change, so you're stuck in an infinite loop of printing "not > there yet..." > > Here's some sample code that works and does about what you > describe. Tweak accordingly. :) > > total = 0 > target = 3600 > values = [ > 82, 69, 87, 83, 78, 65, 0, 89, 83, 85, 79, 76, 0, 83, 73, > 72, 84, 0, 83, 65, 87, 0, 84, 79, 71, 0, 41, 0, 76, 76, > 65, 0, 68, 78, 65, 0, 78, 79, 72, 84, 89, 80, 14, 71, 78, > 65, 76, 14, 80, 77, 79, 67, 0, 78, 79, 0, 78, 79, 73, 84, > 83, 69, 85, 81, 0, 75, 82, 79, 87, 69, 77, 79, 72, 0, 65, > 0, 68, 69, 75, 83, 65, 0, 41 > ] > > while total < target: > # still haven't found the value > value = values.pop() # so we get another number > print chr(value+32), #h have a little fun > total += value #accumulate our total > # and do it until we've accumlated more than target > print "Hey...we're over %s" % target > > > -tkc I finally got it to work. Thanks all for the help. Im sure ill be back with plenty more question!!! From bignose+hates-spam at benfinney.id.au Thu Jun 1 22:37:13 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 02 Jun 2006 12:37:13 +1000 Subject: C# equivalent to range() References: <1149214153.359809.288610@i39g2000cwa.googlegroups.com> Message-ID: <87zmgwxoyu.fsf@benfinney.id.au> "Neuruss" writes: > I'm sorry for asking about another language here, but since I only > know Python and I'm trying to write something in C#, I guess this is > the best place... Really, it isn't. Post in a C# discussion forum, describing the behaviour you want from your program. -- \ "The only tyrant I accept in this world is the still voice | `\ within." -- Mahatma Gandhi | _o__) | Ben Finney From marshall.spight at gmail.com Thu Jun 22 12:55:59 2006 From: marshall.spight at gmail.com (Marshall) Date: 22 Jun 2006 09:55:59 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: <1150988625.527780.148710@c74g2000cwc.googlegroups.com> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150902275.129780.50260@p79g2000cwp.googlegroups.com> <1150918629.818145.143220@y41g2000cwy.googlegroups.com> <4fv081F1jh4ifU1@individual.net> <1150967543.947096.72840@g10g2000cwb.googlegroups.com> <4fv84rF1kp06kU1@individual.net> <1150988625.527780.148710@c74g2000cwc.googlegroups.com> Message-ID: <1150995359.404878.316920@m73g2000cwd.googlegroups.com> Marshall wrote: > > In this simple example, > the static case is better, but this is not free, and the cost > of the static case is evident elsewhere, but maybe not > illuminated by this example. Ugh, please forgive my ham-fisted use of the word "better." Let me try again: In this simple example, the static case is provides you with a guarantee of type safety, but this is not free, and the cost of the static case may be evident elsewhere, even if not illuminated by this example. Marshall From bborcic at gmail.com Mon Jun 26 14:16:50 2006 From: bborcic at gmail.com (Boris Borcic) Date: Mon, 26 Jun 2006 20:16:50 +0200 Subject: How to generate all permutations of a string? In-Reply-To: <449c3002$1_5@news.bluewin.ch> References: <449c3002$1_5@news.bluewin.ch> Message-ID: <44a024ae$1_2@news.bluewin.ch> I wrote: > Another generator solution, based on computing a permutation from its > rank according to some natural order. Written for strings. > > def perms(s) : > def nth(n,L,k=1) : > if k>len(L) : > if n : > raise StopIteration > return '' > return nth(n/k,L,k+1)+L.pop(n%k) > for n in xrange(1<<30) : > yield nth(n,list(s)) Same principle, simpler (no recursion, no helper func, less tokens, easier to read) : def perms(s) : for n in xrange(1<<30) : R,L = [],list(s) while L : n,k = divmod(n,len(L)) R.append(L.pop(k)) if n : break yield ''.join(R) Or if you *really* prefer lisp-style recursions, here is the solution as a single lambda that returns a tuple of strings (not a generator as above) perms = lambda *S : \ (len(S)>=len(S[0]) and S[0]==S[-1]) \ and S[min(1,len(S)-1):] \ or perms(''.join(L.pop(k) for n,L in [[len(S),list(S[-1])]] for _ in S[0] for n,k in [divmod(n,len(L))] ) ,*S) From nospamformeSVP at gmail.com Wed Jun 21 20:12:20 2006 From: nospamformeSVP at gmail.com (Don Taylor) Date: Wed, 21 Jun 2006 20:12:20 -0400 Subject: OT: wxPython GUI designer In-Reply-To: References: <1150661348.837969.46870@r2g2000cwb.googlegroups.com> Message-ID: Frithiof Andreas Jensen wrote: > Just gave is a spin yesterday: How does on fix the size of layout; I > can only manage to get sizers to distribute space evently amongst the > fields, which is *not* what I want. > Use spacers. Don. From onurb at xiludom.gro Tue Jun 6 04:49:08 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 06 Jun 2006 10:49:08 +0200 Subject: Writing to a certain line? In-Reply-To: <1149576072.168354.14470@f6g2000cwb.googlegroups.com> References: <1149576072.168354.14470@f6g2000cwb.googlegroups.com> Message-ID: <44854184$0$29904$636a55ce@news.free.fr> Tommy B wrote: > I was wondering if there was a way to take a txt file and, while > keeping most of it, replace only one line. This is a FAQ (while I don't know if it's in the FAQ !-), and is in no way a Python problem. FWIW, this is also CS101... You can't do this in place with a text file (would be possible with a fixed-length binary format). The canonical way to do so - whatever the language, is to write the modified version in a new file, then replace the old one. import os old = open("/path/to/file.txt", "r") new = open("/path/to/new.txt", "w") for line in old: if line.strip() == "Bob 62" line = line.replace("62", "66") new.write(line) old.close() new.close() os.rename("/path/to/new.txt", "/path/to/file.txt") If you have to do this kind of operation frequently and don't care about files being human-readable, you may be better using some lightweight database system (berkeley, sqlite,...) or any other existing lib that'll take care of gory details. Else - if you want/need to stick to human readable flat text files - at least write a solid librairy handling this, so you can keep client code free of technical cruft. HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From mumarathe at gmail.com Fri Jun 9 16:54:02 2006 From: mumarathe at gmail.com (Manish Marathe) Date: Fri, 9 Jun 2006 13:54:02 -0700 Subject: Killing a thread In-Reply-To: References: <7c8a9a970606091338t174fbcb0wc73cdb8b385f8ccd@mail.gmail.com> Message-ID: <7c8a9a970606091354u73308bf8o2758eea5ef690c39@mail.gmail.com> On 6/9/06, Fredrik Lundh wrote: > > Manish Marathe wrote: > > > I am creating threads using my self defined class which inherits the > > threading.Thread class. I want to know how can I kill the threads which > > are being created by the object of my self defined class. > > you cannot kill a thread "from the outside"; you have to design your > thread tasks so they can kill themselves, when asked to do that. Thanks for the reply. So can a thread listen to an event i.e. can we send an event to the thread indicating to kill itself. Thanks -- Manish Marathe SpikeSource, Inc. http://developer.spikesource.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From jo at durchholz.org Sun Jun 25 13:52:30 2006 From: jo at durchholz.org (Joachim Durchholz) Date: Sun, 25 Jun 2006 19:52:30 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: <1151244628.566060.40500@p79g2000cwp.googlegroups.com> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150908952.804184.218990@r2g2000cwb.googlegroups.com> <1150991074.705803.211570@m73g2000cwd.googlegroups.com> <1151244628.566060.40500@p79g2000cwp.googlegroups.com> Message-ID: rossberg at ps.uni-sb.de schrieb: > Joachim Durchholz write: >> Another observation: type safeness is more of a spectrum than a clearcut >> distinction. Even ML and Pascal have ways to circumvent the type system, > > No. I'm not sure about Pascal, You'd have to use an untagged union type. It's the standard maneuver in Pascal to get unchecked bitwise reinterpretation. Since it's an undefined behavior, you're essentially on your own, but in practice, any compilers that implemented a different semantics were hammered with bug reports until they complied with the standard - in this case, an unwritten (and very unofficial) one, but a rather effective one. > but (Standard) ML surely has none. NLFFI? > Same with Haskell as defined by its spec. Um... I'm not 100% sure, but I dimly (mis?)remember having read that UnsafePerformIO also offered some ways to circumvent the type system. (Not that this would be an important point anyway.) > OCaml has a couple of clearly > marked unsafe library functions, but no unsafe feature in the language > semantics itself. If there's a library with not-typesafe semantics, then at least that language implementation is not 100% typesafe. If all implementations of a language are not 100% typesafe, then I cannot consider the language itself 100% typesafe. Still, even Pascal is quite a lot "more typesafe" than, say, C. >> and even C is typesafe unless you use unsafe constructs. > > Tautology. Every language is "safe unless you use unsafe constructs". No tautology - the unsafe constructs aren't just typewise unsafe ;-p That's exactly why I replaced Luca Cardelli's "safe/unsafe" "typesafe/not typesafe". There was no definition to the original terms attached, and this discussion is about typing anyway. > (Unfortunately, you can hardly write interesting programs in any safe > subset of C.) Now that's a bold claim that I'd like to see substantiated. >> IOW from a type-theoretic point of view, there is no real difference >> between their typesafe and not typesafe languages in the "statically >> typed" column; the difference is in the amount of unsafe construct usage >> in practial programs. > > Huh? There is a huge, fundamental difference: namely whether a type > system is sound or not. I think you're overstating the case. In type theory, of course, there's no such things as an "almost typesafe language" - it's typesafe or it isn't. In practice, I find no implementation where type mismatches cannot occur, if only when interfacing with the external world (except if you cheat by treating everything external as a byte sequence, which is like saying that all languages have at least a universal ANY type and are hence statically-typed). And in those languages that do have type holes, these holes may be more or less relevant - and it's a *very* broad spectrum here. And from that perspective, if ML indeed has no type hole at all, then it's certainly an interesting extremal point, but I still have a relevant spectrum down to assembly language. Regards, Jo From scott.daniels at acm.org Thu Jun 1 12:46:43 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Thu, 01 Jun 2006 09:46:43 -0700 Subject: Zope / Plone Groups In-Reply-To: <1149178209.825191.128050@c74g2000cwc.googlegroups.com> References: <1149178209.825191.128050@c74g2000cwc.googlegroups.com> Message-ID: <447f158d$1@nntp0.pdx.net> d.schulz81 at gmx.net wrote: > are there any specific groups for zope / plone regarding questions? Check gmane (google for it). -- --Scott David Daniels scott.daniels at acm.org From pydecker at gmail.com Thu Jun 22 13:01:05 2006 From: pydecker at gmail.com (Peter Decker) Date: Thu, 22 Jun 2006 13:01:05 -0400 Subject: Feed wxComboBox with dictionary/hash In-Reply-To: <1150983925.131182.88670@i40g2000cwc.googlegroups.com> References: <1150983925.131182.88670@i40g2000cwc.googlegroups.com> Message-ID: On 22 Jun 2006 06:45:25 -0700, Roland Rickborn wrote: > My first question: > how can a wx.ComboBox be fed by a dictionary? This is one of those annoying things about wxPython that made me so happy to switch to using the dabo.ui wrapper for wxPython instead. You can set up the dabo.ui.dComboBox like this, given a dictionary 'dd': cb = dabo.ui.dComboBox(self) cb.Choices = dd.Values() cb.Keys = dd You can then get the selected item via the StringValue property, or its associated key via the KeyValue property. That's it. Simple. -- # p.d. From aisaac0 at verizon.net Fri Jun 9 18:19:54 2006 From: aisaac0 at verizon.net (David Isaac) Date: Fri, 09 Jun 2006 22:19:54 GMT Subject: Most elegant way to generate 3-char sequence References: <1149889784.391965.271570@h76g2000cwa.googlegroups.com> Message-ID: "Rob Cowie" wrote in message news:1149889784.391965.271570 at h76g2000cwa.googlegroups.com... > alpha = ['a','b','c','d'] #shortened for brevity > alpha2 = ['a','b','c','d'] > alpha3 = ['a','b','c','d'] > > def generator(): > for char in alpha: > for char2 in alpha2: > for char3 in alpha3: > yield char + char2 + char3 Basically fine, but you only need one string. E.g., alpha = "abcd" used three times. Alan Isaac From subramanian2003 at indiatimes.com Thu Jun 29 07:03:10 2006 From: subramanian2003 at indiatimes.com (subramanian2003) Date: Thu, 29 Jun 2006 16:33:10 +0530 Subject: Python 2.4 tutorial Message-ID: <200606291011.PAA20206@WS0005.indiatimes.com> Hello All, From where I can get the detailed python 2.4 tutorial(other than python.org). Thanks, Subramanian. From fredrik at pythonware.com Thu Jun 1 08:54:16 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 1 Jun 2006 14:54:16 +0200 Subject: DB-API: how can I find the column names in a cursor? References: Message-ID: "A.M" wrote: > The problem is I don't know how to find out what are the column name and type that comes out of > query (each row in cursor). > > Is there any possibility that my Python code can find out the column name and type in each row in > cursor? >From "cursor objects" in the DB-API documentation: .description "This read-only attribute is a sequence of 7-item sequences. Each of these sequences contains information describing one result column: (name, type_code, display_size, internal_size, precision, scale, null_ok). The first two items (name and type_code) are mandatory, the other five are optional and must be set to None if meaningfull values are not provided." The full spec is available here: http://www.python.org/dev/peps/pep-0249/ From fredrik at pythonware.com Fri Jun 2 08:17:48 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 2 Jun 2006 14:17:48 +0200 Subject: Selection in Tkinter Text widget. References: <1149246483.809582.8310@i39g2000cwa.googlegroups.com> Message-ID: "Ant" wrote: > I have been trying to select text in a Text widget programmatically. I > have been trying the following minimal example: > #================================= > from Tkinter import * > > def showgui(): > win = Tk() > > area = Text(win, width = 50, height = 20) > area.pack() > > new = """Lots of text here > and here > and here...""" > area.insert("1.0", new) > > area.tag_add(SEL, "1.0", END) area.focus_set() > win.mainloop() > > if __name__ == "__main__": > showgui() > #================================== > > The area.tag_add(...) line should - from what I have read in Frederik's > Intro to Tkinter guide - select all of the text in the text area. It > doesn't however... it does, but by default, the selection is only shown for widgets that has the key- board focus. if you add an explicit focus_set() call, you'll see the selection. From 63q2o4i02 at sneakemail.com Mon Jun 5 13:18:19 2006 From: 63q2o4i02 at sneakemail.com (63q2o4i02 at sneakemail.com) Date: 5 Jun 2006 10:18:19 -0700 Subject: Storing nothing in a dictionary and passing it to a function Message-ID: <1149527899.364138.312150@j55g2000cwa.googlegroups.com> Hi, I'm writing a hand-written recursive decent parser for SPICE syntax parsing. In one case I have one function that handles a bunch of similar cases (you pass the name and the number of tokens you're looking for). In another case I have a function that handles a different set of tokens and so it can't use the same arguments as the first one, and in fact takes no arguments. However, these functions are semantically similar and are called from the same place one right after the other. I'd like to have a dictionary (actually a nested dictionary) to call these functions so I can avoid if-then-elsing everything. Eath dictionary item has three things in it: the function to be called, a string to pass to the function (which is also the key to the dict), and a tuple to pass to the function. In the case of the function with no arguments, obviously I'd like not to pass anything. I'm trying to do this 'functionally' (i guess), by avoiding if-then-elses and just calling out the functions by accessing them and their arguments from the dictionary. something like this: alldict = \ {'pulse': {'func': self.arbtrandef, 'args':(2,5)},\ 'sin' : {'func': self.arbtrandef, 'args':(2,3)},\ 'exp' : {'func': self.arbtrandef, 'args':(2,4)},\ 'pwl' : {'func': self.pwldef , 'args': (None,)},\ <------- how do I store "no" arguments? 'sffm' : {'func': self.arbtrandef, 'args':(5,0)}} for it in alldict.items(): name = it[0] args = (name,) + it[1]['args'] it[1]['func'](*args) So basically this doesn't work. I am either trying to pass a tuple of (name, None,) to a function (pwldef) that doesn't take any arguments, or I'm trying to pass None itself, which also doesn't work. I could try changing pwldef to take 3 arguments and then just throw them away, but that's cheesy. It almost seems like in 'args' there should be a little function that creates an argument. I tried using a lambda in another situation to "do" something (an assignment) rather than "return" something, but it didn't work. Any thoughts? thanks ms From david.nospam.hopwood at blueyonder.co.uk Mon Jun 26 18:40:10 2006 From: david.nospam.hopwood at blueyonder.co.uk (David Hopwood) Date: Mon, 26 Jun 2006 22:40:10 GMT Subject: What is a type error? In-Reply-To: <4gakhiF1m698cU1@individual.net> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <7i3mg.204167$8W1.155367@fe1.news.blueyonder.co.uk> <44992e6c$2$664$bed64819@news.gradwell.net> <%Igmg.464974$xt.353729@fe3.news.blueyonder.co.uk> <4fv0v3F1kipa6U1@individual.net> <4gakhiF1m698cU1@individual.net> Message-ID: Pascal Costanza wrote: > David Hopwood wrote: >> Pascal Costanza wrote: >>> Chris Smith wrote: >>> >>>> While this effort to salvage the term "type error" in dynamic >>>> languages is interesting, I fear it will fail. Either we'll all have >>>> to admit that "type" in the dynamic sense is a psychological concept >>>> with no precise technical definition (as was at least hinted by >>>> Anton's post earlier, whether intentionally or not) or someone is >>>> going to have to propose a technical meaning that makes sense, >>>> independently of what is meant by "type" in a static system. >>> >>> What about this: You get a type error when the program attempts to >>> invoke an operation on values that are not appropriate for this >>> operation. >>> >>> Examples: adding numbers to strings; determining the string-length of a >>> number; applying a function on the wrong number of parameters; applying >>> a non-function; accessing an array with out-of-bound indexes; etc. >> >> This makes essentially all run-time errors (including assertion failures, >> etc.) "type errors". It is neither consistent with, nor any improvement >> on, the existing vaguely defined usage. > > Nope. This is again a matter of getting the levels right. > > Consider division by zero: appropriate arguments for division are > numbers, including the zero. The dynamic type check will typically not > check whether the second argument is zero, but will count on the fact > that the processor will raise an exception one level deeper. That is an implementation detail. I don't see its relevance to the above argument at all. > This is maybe better understandable in user-level code. Consider the > following class definition: > > class Person { > String name; > int age; > > void buyPorn() { > if (< this.age 18) throw new AgeRestrictionException(); > ... > } > } > > The message p.buyPorn() is a perfectly valid message send and will pass > both static and dynamic type tests (given p is of type Person in the > static case). However, you will still get a runtime error. Your definition above was "You get a type error when the program attempts to invoke an operation on values that are not appropriate for this operation." this.age, when less than 18, is a value that is inappropriate for the buyPorn() operation, and so this satisfies your definition of a type error. My point was that it's difficult to see any kind of program error that would *not* satisfy this definition. -- David Hopwood From bearophileHUGS at lycos.com Thu Jun 8 17:00:59 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 8 Jun 2006 14:00:59 -0700 Subject: How to generate k+1 length strings from a list of k length strings? References: <44883789$1_4@news.bluewin.ch> <1149785331.109164.208340@i39g2000cwa.googlegroups.com> <4488658e$1_5@news.bluewin.ch> Message-ID: <1149800459.244528.220790@u72g2000cwu.googlegroups.com> Boris Borcic: > I challenge you to write simpler code to do the equivalent. I don't do challenges. I too have written the code to solve that problem, it wasn't much different from your one (it uses a generator function xpairs, to yeild a scan of the different pairs, about half the square, it uses symmetric_difference, etc), but it's on different lines, with variables (object names), etc. And maybe comments too. It's not that difficult to improve the readability of a quite long line, you can start splitting it. > Sure, but the case is we each were *distinct* children. Every person is different, so every person defines the style he/she likes and understands more. But there can be defined some "coding suggestions", useful for most people, to avoid the most common errors, and one of such errors is to write very long lines, full of a lot of stuff, like your one. Bye, bearophile From steve at holdenweb.com Mon Jun 5 07:25:28 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 05 Jun 2006 12:25:28 +0100 Subject: Large Dictionaries In-Reply-To: References: <1147699064.107490@teuthos> <1147772420.405097@teuthos> <1147818548.532882.94180@i39g2000cwa.googlegroups.com> <1147874585.728471@teuthos> <1148514158.790760.205630@i40g2000cwc.googlegroups.com> <447af556$1@nntp0.pdx.net> Message-ID: Lawrence D'Oliveiro wrote: > In article <447af556$1 at nntp0.pdx.net>, > Scott David Daniels wrote: > > >>For example, time timsort (Python's internal sort) on pre-sorted >>data; you'll find it is handled faster than random data. > > > But isn't that how a reasonable sorting algorithm should behave? Less > work to do if the data is already sorted? Isn't that just your definition of "reasonable"? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From lee at example.com Fri Jun 16 17:52:12 2006 From: lee at example.com (Lee Harr) Date: Fri, 16 Jun 2006 21:52:12 GMT Subject: Cross-site scripting (XSS) defense References: <1150480621.563312.134500@c74g2000cwc.googlegroups.com> Message-ID: On 2006-06-16, johnzenger at gmail.com wrote: > Is there a module (or, better yet, sample code) that scrubs > user-entered text to remove cross-site scripting attacks, while also > allowing a small subset of HTML through? > > Contemplated application: a message board that allows people to use >, , and so on, but does not allow any javascript, > vbscript, or other nasties. > I use Strip-o-Gram: http://www.zope.org/Members/chrisw/StripOGram It is used quite a bit in Zope, but I believe it will also stand on its own. From fredrik at pythonware.com Mon Jun 5 16:24:48 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 05 Jun 2006 22:24:48 +0200 Subject: C# equivalent to range() In-Reply-To: <1149509893.031953.19310@i40g2000cwc.googlegroups.com> References: <1149468919.951745.163700@g10g2000cwb.googlegroups.com> <1149481675.192638.275140@c74g2000cwc.googlegroups.com> <1149509893.031953.19310@i40g2000cwc.googlegroups.com> Message-ID: Neuruss wrote: > [more childish blah blah blah] do you think the few of us who haven't already done so would miss anything if we plonked you now? From nhv at cape.com Tue Jun 27 16:21:28 2006 From: nhv at cape.com (Norman Vine) Date: Tue, 27 Jun 2006 16:21:28 -0400 Subject: SWIG problems with gcc and Cygwin? References: Message-ID: "Michael Yanowitz"wrote > > > I am just trying out SWIG, but quickly ran into problems. > Using Cygwin gcc, I tried the following: > > 3)ran in cygwin: swig -i python example.i try 'swig -python example.i' > 4)Attempted to run on cygwin: ld -shared example.o example_wrap.o -o > _example.so try $ gcc -I/usr/include/python2.4 -L/lib/python2.4/config --shared example.c example_wrap.c -lpython2.4 -o _example.dll $ python Python 2.4.1 (#1, May 27 2005, 18:02:40) [GCC 3.3.3 (cygwin special)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> from example import * >>> get_time() 'Tue Jun 27 16:17:41 2006\n' HTH Norman From evahlis at gmail.com Fri Jun 9 13:54:01 2006 From: evahlis at gmail.com (pesachzon) Date: 9 Jun 2006 10:54:01 -0700 Subject: Deep copy of XML elements from one document to another Message-ID: <1149875641.306311.40680@i40g2000cwc.googlegroups.com> In case anyone is wondering how to do this, here's a short explanation: http://eugene.eggkeg.com/?p=16 From michael.f.ellis at gmail.com Thu Jun 1 11:02:21 2006 From: michael.f.ellis at gmail.com (michael.f.ellis at gmail.com) Date: 1 Jun 2006 08:02:21 -0700 Subject: An oddity in list comparison and element assignment Message-ID: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> The following script puzzles me. It creates two nested lists that compare identically. After identical element assignments, the lists are different. In one case, a single element is replaced. In the other, an entire column is replaced. --------------------------------------------------------------------------------------- ''' An oddity in the behavior of lists of lists. Occurs under Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)] on win32. Not tested on other platforms or builds. ''' a =[[[1,2],[1,2]],[[1,2],[1,2]]] b = [[range(1,3)]*2]*2 assert(a==b) print "Initially, python reports that the lists are equal" a[1][1]=[5] b[1][1]=[5] try: assert(a==b) except AssertionError: print "After identical element assignments, the lists are not equal" print "a is now ", a print "b is now ", b ------------------------------------------------------------------------------------- Here's the output on my system. ------------------------------------------------------------------------------------ Initially, python reports that the lists are equal After identical element assignments, the lists are not equal a is now [[[1, 2], [1, 2]], [[1, 2], [5]]] b is now [[[1, 2], [5]], [[1, 2], [5]]] ------------------------------------------------------------------------------------ This seems contrary to one of my fundamental expectations, namely that objects which compare equally must remain equal after identical operations. I think what must be going on is that the 'b' list contains replicated references instead of copies of [range(1,3)]*2 . IMO, python's == operator should detect this difference in list structure since it leads to different behavior under element assignments. Mike Ellis From siona at chiark.greenend.org.uk Fri Jun 9 06:30:44 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 09 Jun 2006 11:30:44 +0100 (BST) Subject: Instead of saving text files i need as html References: <1149777499.506986.292830@j55g2000cwa.googlegroups.com> Message-ID: Tim Chase wrote: >> [ ... ] >> urllib.urlretrieve(lines.strip('/n'), 'c:\\temp\\' \ >> + outfilename.strip('\n')[7:] + '.html') > [ ... ] I'm not sure what the odd >slicing is for, but I'll presume the OP knows what they're doing. It's taking the "http://" off the front of the URL. >>> len("http://") 7 -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From fuzzyman at gmail.com Tue Jun 27 18:02:37 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 27 Jun 2006 15:02:37 -0700 Subject: Tkinter - Button Overrelief In-Reply-To: References: <1151409965.666818.179750@y41g2000cwy.googlegroups.com> Message-ID: <1151445757.232286.23360@p79g2000cwp.googlegroups.com> Eric Brunel wrote: > On Tue, 27 Jun 2006 14:06:05 +0200, Fuzzyman wrote: > > > Hello all, > > > > I have some Tkinter buttons that display images. I would like to change > > these to 'active' images when the mouse is over the button. > > > > I see that the button widget can take an 'overrelief' argument in the > > constructor. What values can this take ? > > The same as the 'relief' option, i.e the ones described here: > http://www.tcl.tk/man/tcl8.4/TkCmd/options.htm#M-relief > > Note that Tkinter contains symbolic constants for these values: 'raised' > is Tkinter.RAISED, 'flat' is Tkinter.FLAT, and so on. > Cool, I'll have to look into this and see how they look. Thanks. > > Also - can anyone provide an example of using the equivalent of a > > 'mouseover' event to change the image used by a button in Tkinter ? I'm > > afraid google has not helped me much here. > > The events you're after are '' and ''; see here: > http://www.tcl.tk/man/tcl8.3/TkCmd/bind.htm#M7 > > Here is an example showing how to change the button text (changing the > image is similar): > > -------------------------------- > from Tkinter import * > > root = Tk() > > b = Button(root, width=8, text='foo') > b.pack() > > def enterB(event): > b.configure(text='bar') > > def leaveB(event): > b.configure(text='foo') > > b.bind('', enterB) > b.bind('', leaveB) > > root.mainloop() That works like a charm, great. Much Appreciated Fuzzyman http://www.voidspace.org.uk/python/index.shtml > -------------------------------- > > HTH > -- > python -c "print ''.join([chr(154 - ord(c)) for c in > 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From onurb at xiludom.gro Sat Jun 24 08:22:16 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Sat, 24 Jun 2006 14:22:16 +0200 Subject: templating languages for webdev In-Reply-To: <1151090904.496637.75220@u72g2000cwu.googlegroups.com> References: <1151090904.496637.75220@u72g2000cwu.googlegroups.com> Message-ID: <449d2e79$0$1170$626a54ce@news.free.fr> a wrote: > cheetah vs django vs kid You forgot SimpleTal and Myghty (and many others). I don't like cheetah's syntax at all. I'm not in love with Django templates choices for markup ( '{% tag %}' and '{{ var }}'), but it can be customised, and I found the system very nice otherwise. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From tim.leeuwvander at nl.unisys.com Mon Jun 26 08:43:08 2006 From: tim.leeuwvander at nl.unisys.com (Tim N. van der Leeuw) Date: 26 Jun 2006 05:43:08 -0700 Subject: About python 2.5 and its try statement. In-Reply-To: <1151325349.040404.77730@i40g2000cwc.googlegroups.com> References: <1151325349.040404.77730@i40g2000cwc.googlegroups.com> Message-ID: <1151325788.147428.308350@y41g2000cwy.googlegroups.com> Hi, defcon8 wrote: > I can't remember the proposal number, but many of you reading will have > probably read the features that will be added to python 2.5. The actual > part I wanted to talk about was the finally part of try. Isn't it > totally defeating a compiler's job by executing the finally part even > if there is an error in the previous statements? Or have I understood > something wrong? try ... finally already exists in current python; what's new is that it can be combined in 1 statement with try ... except ... finally. No, this is not defeating a compilers job. It's very useful. It defines an amount of cleanup that needs to happen no matter what, exception or no exception. Example: closing an open file. You'll want to close the file, whether after you done the job you intended to do, or after an exception occurred while doing something. So you put 'f.close()' in your finally - suite. Another example of a useful 'finally' is logging function-exit -- not the actual 'return' statement, but just a log-statement recording function-exit. (Putting a 'return' statement in a 'finally' suite is totally defeating the point of exceptions that you want thrown to the caller, yes. So don't put your 'return' statement there.) Clearer? Cheers, --Tim From larry.bates at websafe.com Tue Jun 13 17:48:09 2006 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 13 Jun 2006 16:48:09 -0500 Subject: Getting "TypeError:list indices must be integers" In-Reply-To: References: <448E6466.10908@lexicon.net> Message-ID: <6LCdncGnldAOrxLZnZ2dneKdnZydnZ2d@comcast.com> Girish Sahani wrote: >> On 13/06/2006 4:11 PM, Girish Sahani wrote: >> [snip] >>> instance = ti2(k) >>> tiNew = ti1.append(instance) >> ti2 is quacking "function" but ti1 is quacking "list". >> >> Possibilities: >> (1) You meant to type ti2[k] ... and this section of code has not yet >> been executed, and would have featured as episode N+1 had morbid >> curiosity not led me to read further. > That is corrected. I'm appending a particular element of ti2 to ti1. > It hasnt been executed because i'm stuck on that TypeError since 2 hours > :( (2) You have the weirdest system of choosing names that I have seen for >> decades. > :(( >> (3) Both of the above. >> >> Cheers, >> John >> > How about just inserting some print statements that show you the type and value of each index before you use it. It is old fashioned, but it actually works. -Larry Bates From gneuner2/ at comcast.net Sun Jun 11 18:20:42 2006 From: gneuner2/ at comcast.net (George Neuner) Date: Sun, 11 Jun 2006 18:20:42 -0400 Subject: Xah Lee network abuse References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148495974.975395.12920@i40g2000cwc.googlegroups.com> <1149998343.493200.144990@h76g2000cwa.googlegroups.com> Message-ID: <8d2p82pq930hq4klnhbidr0i1t0hd8hqq2@4ax.com> On Sun, 11 Jun 2006 06:05:22 GMT, "Mike Schilling" wrote: > >"Philippa Cowderoy" wrote in message >news:Pine.WNT.4.61.0606110548540.1652 at SLINKY... >> On Sun, 11 Jun 2006, Mike Schilling wrote: >> >>> I'm not aware of any definition of libel that includes "making statements >>> that are not provably true". >> >> I believe UK law uses one that's close to it. > >If I were to write, say, that Tony Blair's tax policy will lead to higher >deficits, I could be convicted of libel? Even if that's true, it's not a >priori provable. DISCLAIMER - I AM NOT A LAWYER In the US, the defense against a libel claim is to prove the statement or accusation is true. In the US, libel involves damage to someone's reputation by means of deliberately false statements or accusations. Expert opinion is explicitly protected from libel claims unless it malicious. Non-expert opinion is generally judged on the intent of the author. Unprovable supposition is generally held to be non-libelous, however unprovable accusation is not allowed. Moreover, in the US, political figures are explicitly denied some (but not all) libel protections because it is expected that their actions will cause some measure of public dissent. I don't know UK defamation law but I suspect it is quite similar to US law. In your polite example, your opinion of Tony Blair's policy would be unprovable supposition at the time of the writing (as would Blair's own) and would therefore not be libelous. However, if your opinion took an accusatory tone saying, for example, that he was increasing the public deficit to line his pockets, then you had better be right. George -- for email reply remove "/" from address From stever at cruzio.com Fri Jun 30 18:49:07 2006 From: stever at cruzio.com (Steve) Date: 30 Jun 2006 15:49:07 -0700 Subject: Regular Expression - old regex module vs. re module References: <1151607229.548737.145800@d56g2000cwd.googlegroups.com> Message-ID: <1151707747.611123.65800@m73g2000cwd.googlegroups.com> Hi All! Thanks for your suggestions and comments! I was able to use some of your code and suggestions and have come up with this new version of Report.py. Here's the updated code : ----------------------------------------------------------------- #!/usr/bin/env python """Provides two classes to create formatted reports. The ReportTemplate class reads a template file or string containing a fixed format with field tokens and substitutes member values from an arbitrary python object. The ColumnReportTemplate class takes a string argument to define a header and line format for multiple calls with sequence data. 6/30/2006 Steve Reiss (reiss at google.com) - Converted to re module methods """ __author__ = "Robin Friedrich Robin.Friedrich at pdq.net" __version__ = "1.0.0" import string import sys import re from types import StringType, ListType, TupleType, InstanceType, FileType #these regex pattern objects are used in the _make_printf function exponentPattern = re.compile('\(^\|[^\\#]\)|#+\.#+\*\*\*\*') floatPattern = re.compile('\(^\|[^\\#]\)|#+\.#+') integerPattern = re.compile("\(^\|[^\\#]\)|\##+") leftJustifiedStringPattern = re.compile('\(^\|[^\\<]\)|\<<+') rightJustifiedStringPattern = re.compile('\(^\|[^\\>]\)|\>>+') ################################################################### # _make_printf # ################################################################### def _make_printf(s): """Convert perl style format symbology to printf tokens. Take a string and substitute computed printf tokens for perl style format symbology. For example: ###.## yields %6.2f ######## yields %8d <<<<< yields %-5s """ # print("Original String = %s\n\n") % (s) while 1: # process all sci notation fields if exponentPattern.search(s) < 0: break i1 , i2 = exponentPattern.search(s).span() width_total = i2 - i1 field = s[i1:i2-4] width_mantissa = len( field[string.find(field,'.')+1:] ) f = '%'+`width_total`+'.'+`width_mantissa`+'e' s = exponentPattern.sub(f, s, 1) while 1: # process all floating pt fields if floatPattern.search(s) < 0: break i1 , i2 = floatPattern.search(s).span() width_total = i2 - i1 field = s[i1:i2] width_mantissa = len( field[string.find(field,'.')+1:] ) f = '%'+`width_total`+'.'+`width_mantissa`+'f' s = floatPattern.sub(f, s, 1) while 1: # process all integer fields if integerPattern.search(s) < 0: break i1 , i2 = integerPattern.search(s).span() width_total = i2 - i1 f = '%'+`width_total`+'d' s = integerPattern.sub(f, s, 1) while 1: # process all left justified string fields if leftJustifiedStringPattern.search(s) < 0: break i1 , i2 = leftJustifiedStringPattern.search(s).span() width_total = i2 - i1 f = '%-'+`width_total`+'s' s = leftJustifiedStringPattern.sub(f, s, 1) while 1: # process all right justified string fields if rightJustifiedStringPattern.search(s) < 0: break i1 , i2 = rightJustifiedStringPattern.search(s).span() width_total = i2 - i1 f = '%'+`width_total`+'s' s = rightJustifiedStringPattern.sub(f, s, 1) s = re.sub('\\\\', ' ', s) # print # print("printf format = %s") % (s) return s ################################################################### # ReportTemplate # ################################################################### class ReportTemplate: """Provide a print formatting object. Defines an object which holds a formatted output template and can print values substituted from a data object. The data members from another Python object are used to substitute values into the template. This template object is initialized from a template file or string which employs the formatting technique below. The intent is to provide a specification template which preserves spacing so that fields can be lined up easily. Special symbols are used to identify fields into which values are substituted. These symbols are: ##### for right justified integer #.### for fixed point values rounded mantissa #.###**** for scientific notation (four asterisks required) <<<<< for left justified string >>>>> for right justified string %% is needed in the template to signify a real percentage symbol \# A backslash is used to escape the above ##, <<, >> symbols if you need to use them outside a field spec. The backslash will be removed upon output. The total width of the symbol and it's decimal point position is used to compute the appropriate printf token; see 'make_printf' method. The symbol must have at least two adjacent characters for it to be recognized as a field specifier. To the right of each line of template body, following a '@@' delimiter, is a comma separated list for corresponding variable names. Sequence objects are supported. If you place a name of a 5-tuple for example, there should be five fields specified on the left prepared to take those values. Also, individual element or slices can be used. The values from these variable names will be substituted into their corresponding fields in sequence. For example: a line of template might look like: TGO1 = ####.# VGO = ##.####**** Vehicle: <<<<<<<<<< @@ t_go,v_go, vname and would print like: TGO1 = 22.4 VGO = -1.1255e+03 Vehicle: Atlantis """ delimiter = '@@' def __init__( self, template = ''): self.body = [] self.vars = [] #read in and parse a format template try: tpl = open(template, 'r') lines = string.split(tpl.read(), '\n')[:-1] tpl.close() except IOError: lines = string.split(template, '\n') self.nrows = len(lines) for i in range(self.nrows): self.body.append([]) self.vars.append([]) for i in range(self.nrows): splits = string.split(lines[i], self.delimiter) body = splits[0] # I don't use tuple unpacking here because # I don't know if there was indeed a @@ on the line if len(splits) > 1 : vars = splits[1] else: vars = '' #if body[-1] == '\n': #self.body[i] = body[:-1] #else: self.body[i] = body varstrlist = string.split(vars, ',') #print i, varstrlist for item in varstrlist: self.vars[i].append(string.strip(item)) #print self.vars[i] if len(self.vars[i]) > 0: self.body[i] = _make_printf( self.body[i] ) else: print 'Template formatting error, line', i+1 def __repr__(self): return string.join(self.body, '\n') def __call__(self, *dataobjs): return self._format(dataobjs[0]) def _format( self, dataobj ): """Return the values of the given data object substituted into the template format stored in this object. """ # value[] is a list of lists of values from the dataobj # body[] is the list of strings with %tokens to print # if value[i] == None just print the string without the % argument s = '' value = [] for i in range(self.nrows): value.append([]) for i in range(self.nrows): for vname in self.vars[i]: try: if string.find(vname, '[') < 0: # this is the nominal case and a simple get will be faster value[i].append(getattr(dataobj, vname)) else: # I use eval so that I can support sequence values # although it's slow. value[i].append(eval('dataobj.'+vname)) except AttributeError, SyntaxError: value[i].append('') if value[i][0] != '': try: temp_vals = [] for item in value[i]: # items on the list of values for this line # can be either literals or lists if type(item) == ListType: # take each element of the list and tack it # onto the printing list for element in item: temp_vals.append(element) else: temp_vals.append(item) # self.body[i] is the current output line with % tokens # temp_vals contains the values to be inserted into them. s = s + (self.body[i] % tuple(temp_vals)) + '\n' except TypeError: print 'Error on this line. The data value(s) could not be formatted as numbers.' print 'Check that you are not placing a string value into a number field.' else: s = s + self.body[i] + '\n' return s def writefile(self, file, dataobj): """takes either a pathname or an open file object and a data object. Instantiates the template with values from the data object sending output to the open file. """ if type(file) == StringType: fileobj = open(file,'w') elif type(file) == FileType: fileobj = file else: raise TypeError, '1st argument must be a pathname or an open file object.' fileobj.write(self._format(dataobj)) if type(file) == StringType: fileobj.close() ################################################################### # isReportTemplate # ################################################################### def isReportTemplate(obj): """Return 1 if obj is an instance of class ReportTemplate. """ if type(obj) == InstanceType and \ string.find(`obj.__class__` , ' ReportTemplate ') > -1: return 1 else: return 0 ################################################################### # ColumnReportTemplate # ################################################################### class ColumnReportTemplate: """This class allows one to specify column oriented output formats. The first argument to the constructor is a format string containing the header text and a line of field specifier tokens. A line containing nothing but dashes, underbars, spaces or tabs is detected as the separator between these two sections. For example, a format string might look like this: '''Page &P Date: &M/D/Y Time: &h:m:s Time Event Factor A2 Factor B2 -------- ------------------- ----------- ------------- ###.#### <<<<<<<<<<<<<<<<<<< ##.###**** ##.######****''' The last line will be treated as the format for output data contained in a four-sequence. This line would (for example) be translated to '%8.4f %-19s %10.3e %13.6e' for value substitution. In the header text portion one may use special variable tokens indicating that runtime values should be substituted into the header block. These tokens start with a & character and are immediately followed by either a P or a time/date format string. In the above example the header contains references to page number, current date in month/day/year order, and the current time. Today it produced 'Page 2 Date: 10/04/96 Time: 15:13:28' See doc string for now() function for further details. An optional second argument is an output file handle to send written output to (default is stdout). Keyword arguments may be used to tailor the instance. At this time the 'page_length' parameter is the only useful one. Instances of this class are then used to print out any number of records with the write method. The write method argument must be a sequence of elements matching the number and data type implied by the field specification tokens. At the end of a page, a formfeed is output as well as new copy of the header text. """ page_length = 50 lineno = 1 pageno = 1 first_write = 1 def __init__(self, format = '', output = sys.stdout, **kw): # print("Original format = ", format) self.output = output self.header_separator = re.compile('\n[-_\s\t]+\n') self.header_token = re.compile('&([^ \n\t]+)') for item, value in kw.items(): setattr(self, item, value) try: # use try block in case there is NOT a header at all result = self.header_separator.search(format).start() # NEW separation of header and body from format # print("result = ", result) HeaderLine = self.header_separator.search(format).group() # get the header lines that were matched if result > -1: # separate the header text from the format # print("split = ", self.header_separator.split(format) ) HeaderPieces = self.header_separator.split(format) # print("HeaderPiece[0] = ", HeaderPieces[0]) # print("HeaderPiece[1] = ", HeaderPieces[1]) self.header = HeaderPieces[0] + HeaderLine # header text PLUS the matched HeaderLine self.body = _make_printf(HeaderPieces[1]) # convert the format chars to printf expressions except : self.header = '' # fail block of TRY - no headings found - set to blank self.body = _make_printf(format) # need to process the format # print("header = ", self.header) # print("body = ", self.body) self.header = self.prep_header(self.header) # parse the special chars (&Page &M/D/Y &h:m:s) in header self.header_len = len(string.split(self.header,'\n')) self.max_body_len = self.page_length - self.header_len def prep_header(self, header): """Substitute the header tokens with a named string printf token. """ start = 0 new_header = '' self.header_values = {} # print("original header = %s") % (header) HeaderPieces = self.header_token.split(header) # split up the header w/ the regular expression HeadCount = 0 for CurrentHeadPiece in HeaderPieces : if HeadCount % 2 == 1: # matching tokens to the pattern will be in the ODD indexes of Heads[] # print("Heads %s = %s") % (HeadCount,CurrentHeadPiece) new_header = new_header + '%(' + CurrentHeadPiece +')s' self.header_values[CurrentHeadPiece] = 1 else: new_header = new_header + CurrentHeadPiece HeadCount = HeadCount + 1 # print("new header = %s") % (new_header) return new_header def write(self, seq): """Write the given sequence as a record in field format. Length of sequence must match the number and data type of the field tokens. """ seq = tuple(seq) if self.lineno > self.max_body_len or self.first_write: self.new_page() self.first_write = 0 self.output.write( self.body % seq + '\n' ) self.lineno = self.lineno + 1 def new_page(self): """Issue formfeed, substitute current values for header variables, then print header text. """ for key in self.header_values.keys(): if key == 'P': self.header_values[key] = self.pageno else: self.header_values[key] = now(key) header = self.header % self.header_values self.output.write('\f'+ header +'\n') self.lineno = 1 self.pageno = self.pageno + 1 def isColumnReportTemplate(obj): """Return 1 if obj is an instance of class ColumnReportTemplate. """ if type(obj) == InstanceType and \ string.find(`obj.__class__` , ' ColumnReportTemplate ') > -1: return 1 else: return 0 ################################################################### # now - return date and/or time value # ################################################################### def now(code='M/D/Y'): """Function returning a formatted string representing the current date and/or time. Input arg is a string using code letters to represent date/time components. Code Letter Expands to D Day of month M Month (two digit) Y Year (two digit) h hour (two digit 24-hour clock) m minutes s seconds Other characters such as '/' ':' '_' '-' and ' ' are carried through as is and can be used as separators. """ import time T = {} T['year'], T['month'], T['dom'], T['hour'], T['min'], T['sec'], \ T['dow'], T['day'], T['dst'] = time.localtime(time.time()) T['yr'] = repr(T['year'])[-2:] formatstring = '' tokens = {'D':'%(dom)02d', 'M':'%(month)02d', 'Y':'%(yr)02s', 'h':'%(hour)02d', 'm':'%(min)02d', 's':'%(sec)02d', '/':'/', ':':':', '-':'-', ' ':' ' , '_':'_', ';':';', '^':'^'} for char in code: formatstring = formatstring + tokens[char] return formatstring % T ################################################################### # test_Rt - Test Report Template # ################################################################### def test_RT(): template_string = """ -------------------------------------------------- Date <<<<<<<<<<<<<<<<<<<<<<<<<<< Time >>>>>>> @@ date, time Input File : <<<<<<<<<<<<<<<<<<<<< @@ file[0] Output File : <<<<<<<<<<<<<<<<<<<<< @@ file[1] Corr. Coeff : ##.########**** StdDev : ##.### @@ coeff, deviation Fraction Breakdown : ###.# %% Run :\# ### @@ brkdwn, runno Passed In Value : ### @@ invalue -------------------------------------------------- """ class Data: def __init__(self, InValue): # self.date = "September 12, 1998" self.date = now() # self.time = "18:22:00" self.time = now('h:m:s') #datetime.time() self.file = ['TX2667-AE0.dat', 'TX2667-DL0.dat'] self.coeff = -3.4655102872e-05 self.deviation = 0.4018 self.runno = 56 + InValue self.brkdwn = 43.11 self.invalue = InValue Report = ReportTemplate(template_string) for i in range(2): D = Data(i) print Report(D) ################################################################### # test_Rt_file - Test Report Template from file # ################################################################### def test_RT_file(): template_string ='ReportFormat1.txt' # filename of report format class Data: def __init__(self, InValue): self.date = now() self.time = now('h:m:s') #datetime.time() self.file = ['TX2667-AE0.dat', 'TX2667-DL0.dat'] self.coeff = -3.4655102872e-05 self.deviation = 0.4018 self.runno = 56 + InValue self.brkdwn = 43.11 self.invalue = InValue Report = ReportTemplate(template_string) for i in range(2): D = Data(i) print Report(D) ################################################################### # test_CRT - Test Column Report Template # ################################################################### def test_CRT(): print print print "test_CRT()" print format=''' Page &P Date: &M/D/Y Time: &h:m:s Test Column Report 1 Time Event Factor A2 Factor B2 -------- ------------------- ----------- ------------- ####.### <<<<<<<<<<<<<<<<<<< ##.###**** ##.######****''' data = [12.225, 'Aftershock', 0.5419, 144.8] report = ColumnReportTemplate( format, page_length=15 ) for i in range(0,200,10): if i > 0 : data = [data[0]+i, data[1], data[2]/i*10., data[3]*i/20.] report.write( data ) ################################################################### # test_CRT2 - Test Column Report Template # ################################################################### def test_CRT2(): print print print "test_CRT2()" print format=''' Page &P Date: &M/D/Y Time: &h:m:s Test Column Report 2 I ID City Factor A2 Factor B2 --- ------ ------------------- ----------- ------------- >>> #### <<<<<<<<<<<<<<<<<<< #####.## >>>>>>>''' data = [0, 5, 'Mt. View', 541, 144.2] report = ColumnReportTemplate( format, page_length=15 ) for i in range(0,201,10): data = [i, data[1]+i, data[2], data[3] + (i*10), data[4] + (i * 20)] report.write( data ) ################################################################### # test_CRT3 - Test Column Report Template - no header chars # ################################################################### def test_CRT3(): print print print "test_CRT3()" print format=''' Test Column Report 3 I ID City Factor A2 Factor B2 --- ------ ------------------- ----------- ------------- >>> #### <<<<<<<<<<<<<<<<<<< #####.## <<<<<<<<<<''' #--- ------ ------------------- ----------- ------------- data = [0, 5, 'Santa Cruz', 541, 144.2] report = ColumnReportTemplate( format, page_length=15 ) for i in range(0,201,10): data = [i, data[1]+i, data[2], data[3] + (i*10), data[4] + (i * 20)] report.write( data ) ################################################################### # test_CRT4 - Test Column Report Template - no header at all # ################################################################### def test_CRT4(): print print print "test_CRT4()" print format='''>>> #### <<<<<<<<<<<<<<<<<<< #####.## #####.##''' data = [0, 5, 'Santa Cruz', 541, 144.2] report = ColumnReportTemplate( format, page_length=50 ) for i in range(0,201,10): data = [i, data[1]+i, data[2], data[3] + (i*10), data[4] + (i * 20)] report.write( data ) ################################################################### ############# M A I N ########################### ################################################################### def Main(): print "\n\nTesting this module.\n\n" TheHeading = ''' simple heading \# r-just int fixed point sci-notation left-just string right-just string ##### #.### #.###**** <<<<< >>>>>''' print print " Make printf Test : " print _make_printf(TheHeading) print print test_RT() test_CRT() print test_RT_file() print test_CRT2() test_CRT3() test_CRT4() print print "Current Date & time = ", now('M-D-Y h:m:s') if __name__ == "__main__": Main() From jstroud at ucla.edu Tue Jun 20 00:32:29 2006 From: jstroud at ucla.edu (James Stroud) Date: Mon, 19 Jun 2006 21:32:29 -0700 Subject: interactive multi-file search and replace In-Reply-To: References: Message-ID: Ryan Krauss wrote: > I need to do some searching and replacing in about 10 latex files. > Does anyone have an existing script that does this on an interactive > basis? I would like to show each match and ask whether or not it > should be replaced. > > This seems like a fairly common task and I don't want to re-invent the > wheel. > > Ryan Most people probably use something like vim rather than re-inventing the wheel themselves. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From onurb at xiludom.gro Fri Jun 9 04:30:45 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 09 Jun 2006 10:30:45 +0200 Subject: what are you using python language for? In-Reply-To: <4488ba3c$0$22970$c83e3ef6@nn1-read.tele2.net> References: <4488ba3c$0$22970$c83e3ef6@nn1-read.tele2.net> Message-ID: <448931b6$0$10302$636a55ce@news.free.fr> baalbek wrote: > To score with the chicks! > > A Python script roams the nightclubs for beautiful women, finds an > appropriate woman based on my preferances, charms her with its sleek > Pythonic manners, calls for a cab and brings the lady to my recidency. > > Works like a charm! Is that OSS ?-) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From johnjsal at NOSPAMgmail.com Wed Jun 7 13:39:54 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 07 Jun 2006 17:39:54 GMT Subject: GUI Program Error In-Reply-To: <1149700099.634036.88090@f6g2000cwb.googlegroups.com> References: <1149536396.375285.319390@y43g2000cwc.googlegroups.com> <920hg.2238$No6.47697@news.tufts.edu> <1149700099.634036.88090@f6g2000cwb.googlegroups.com> Message-ID: Byte wrote: > Also, how do > I code a GUI Hello World program? P.S. The link I supplied begins with two versions of a Hello World app. From david.nospam.hopwood at blueyonder.co.uk Sat Jun 24 18:00:54 2006 From: david.nospam.hopwood at blueyonder.co.uk (David Hopwood) Date: Sat, 24 Jun 2006 22:00:54 GMT Subject: Saying "latently-typed language" is making a category mistake In-Reply-To: <4g24rlF1l16viU1@individual.net> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <4g24rlF1l16viU1@individual.net> Message-ID: Pascal Costanza wrote: > Vesa Karvonen wrote: > >> I think that we're finally getting to the bottom of things. While >> reading your reponses something became very clear to me: latent-typing and >> latent-types are not a property of languages. Latent-typing, also known as >> informal reasoning, is something that all programmers do as a normal part >> of programming. To say that a language is latently-typed is to make a >> category mistake, because latent-typing is not a property of languages. > > I disagree with you and agree with Anton. Here, it is helpful to > understand the history of Scheme a bit: parts of its design are a > reaction to what Schemers perceived as having failed in Common Lisp (and > other previous Lisp dialects). > > One particularly illuminating example is the treatment of nil in Common > Lisp. That value is a very strange beast in Common Lisp because it > stands for several concepts at the same time: most importantly the empty > list and the boolean false value. Its type is also "interesting": it is > both a list and a symbol at the same time. It is also "interesting" that > its quoted value is equivalent to the value nil itself. This means that > the following two forms are equivalent: > > (if nil 42 4711) > (if 'nil 42 4711) > > Both forms evaluate to 4711. > > It's also the case that taking the car or cdr (first or rest) of nil > doesn't give you an error, but simply returns nil as well. > > The advantage of this design is that it allows you to express a lot of > code in a very compact way. See > http://www.apl.jhu.edu/~hall/lisp/Scheme-Ballad.text for a nice > illustration. > > The disadvantage is that it is mostly impossible to have a typed view of > nil, at least one that clearly disambiguates all the cases. There are > also other examples where Common Lisp conflates different types, and > sometimes only for special cases. [1] > > Now compare this with the Scheme specification, especially this section: > http://www.schemers.org/Documents/Standards/R5RS/HTML/r5rs-Z-H-6.html#%25_sec_3.2 > > This clearly deviates strongly from Common Lisp (and other Lisp > dialects). The emphasis here is on a clear separation of all the types > specified in the Scheme standard, without any exception. This is exactly > what makes it straightforward in Scheme to have a latently typed view of > programs, in the sense that Anton describes. So latent typing is a > property that can at least be enabled / supported by a programming > language, so it is reasonable to talk about this as a property of some > dynamically typed languages. If anything, I think that this example supports my and Vesa's point. The example demonstrates that languages *that are not distinguished in whether they are called latently typed* support informal reasoning about types to varying degrees. -- David Hopwood From zabaione at uk2.net Mon Jun 19 12:31:06 2006 From: zabaione at uk2.net (freesteel) Date: 19 Jun 2006 09:31:06 -0700 Subject: multithreading windows and embedding python Message-ID: <1150734666.413397.197810@p79g2000cwp.googlegroups.com> I have posted about this problem before. SInce then I found a much better article to help with embedding python in a multithreaded application: http://www.linuxjournal.com/article/3641 I found this article very good and it clarified for me what needs doing. Now I have an example application that almost works, but it is far from reliable. If I run this several times I get crashes telling me that the heap is modified after deallocation. Can anybody else reproduce this? At the bottom of this file I left a debug dump, and a stack dump. Here is my application, compile in windows using a standard windows application project. #include #include #include #include #include #include static int threadnum = 0; UINT MyThread(LPVOID lpParam) { ASSERT(Py_IsInitialized()); threadnum++; PyThreadState* mainThreadState = (PyThreadState *)lpParam; // get the global lock PyEval_AcquireLock(); // get a reference to the PyInterpreterState PyInterpreterState * mainInterpreterState = mainThreadState->interp; PyThreadState_Swap(mainThreadState); // create a thread state object for this thread PyThreadState * myThreadState = PyThreadState_New(mainInterpreterState); // free the lock PyEval_ReleaseLock(); // lock - swap in thread state - swap out thread state - unlock PyEval_AcquireLock(); PyThreadState_Swap(myThreadState); int num = 0; int ret = 0; ret = PyRun_SimpleString("x = []"); ret = PyRun_SimpleString("for i in range(10):\n x.append(i)"); char cmd[100]; sprintf(cmd, "f = open('c:/windows/temp/test%d.txt', 'w')", threadnum); ret = PyRun_SimpleString(cmd); ret = PyRun_SimpleString("f.write('%s\\n' % x.__str__())"); sprintf(cmd, "f.write('0x%d\\n')", &myThreadState); ret = PyRun_SimpleString(cmd); ret = PyRun_SimpleString("f.close()"); PyThreadState_Swap(NULL); PyEval_ReleaseLock(); // clean up // grab the lock PyEval_AcquireLock(); // swap my thread state out of the interpreter PyThreadState_Swap(NULL); // clear out any cruft from thread state object PyThreadState_Clear(myThreadState); // delete my thread state object PyThreadState_Delete(myThreadState); // release the lock PyEval_ReleaseLock(); return 0; } class CMyWinApp : public CWinApp { public: CMyWinApp() { } BOOL InitInstance() { Py_Initialize(); PyEval_InitThreads(); // save a pointer to the main PyThreadState object PyThreadState * mainThreadState = PyThreadState_Get(); // release the lock PyEval_ReleaseLock(); const int nhandles = 100; HANDLE hnd[nhandles]; CWinThread* pThread[nhandles]; for (int ih = 0; ih < nhandles; ih++) { pThread[ih] = AfxBeginThread(MyThread, mainThreadState, THREAD_PRIORITY_NORMAL, CREATE_SUSPENDED); pThread[ih]->m_bAutoDelete = false; pThread[ih]->ResumeThread(); hnd[ih] = pThread[ih]->m_hThread; } int nwaits, nfails; do { nwaits = 0; nfails = 0; for (int ih = 0; ih < nhandles; ih++) { DWORD ret = WaitForSingleObject(hnd[ih], INFINITE); switch (ret) { case WAIT_OBJECT_0: printf("WAIT_OBJECT_0\n"); break; case WAIT_TIMEOUT: ++nwaits; printf("WAIT_TIMEOUT\n"); break; case WAIT_FAILED: ++nfails; printf("WAIT_FAILED\n"); break; } } } while (nwaits > 0); ASSERT(nfails == 0); // delete all windows threads for (int ih = 0; ih < nhandles; ++ih) delete pThread[ih]; PyEval_AcquireLock(); PyThreadState_Swap(mainThreadState); Py_Finalize(); return TRUE; }; }; CMyWinApp app; Debug dump: 'pyembed_test.exe': Loaded 'C:\mdunschen\pyembed_test\Debug\pyembed_test.exe', Symbols loaded. 'pyembed_test.exe': Loaded 'C:\WINDOWS\system32\ntdll.dll', No symbols loaded. 'pyembed_test.exe': Loaded 'C:\WINDOWS\system32\mscoree.dll', No symbols loaded. 'pyembed_test.exe': Loaded 'C:\WINDOWS\system32\kernel32.dll', No symbols loaded. 'pyembed_test.exe': Loaded 'C:\WINDOWS\system32\advapi32.dll', No symbols loaded. 'pyembed_test.exe': Loaded 'C:\WINDOWS\system32\rpcrt4.dll', No symbols loaded. 'pyembed_test.exe': Loaded 'C:\WINDOWS\system32\user32.dll', No symbols loaded. 'pyembed_test.exe': Loaded 'C:\WINDOWS\system32\gdi32.dll', No symbols loaded. 'pyembed_test.exe': Loaded 'C:\WINDOWS\system32\comctl32.dll', No symbols loaded. 'pyembed_test.exe': Loaded 'C:\WINDOWS\system32\shlwapi.dll', No symbols loaded. 'pyembed_test.exe': Loaded 'C:\WINDOWS\system32\msvcrt.dll', No symbols loaded. 'pyembed_test.exe': Loaded 'C:\WINDOWS\system32\oleacc.dll', No symbols loaded. 'pyembed_test.exe': Loaded 'C:\WINDOWS\system32\msvcp60.dll', No symbols loaded. 'pyembed_test.exe': Loaded 'C:\WINDOWS\system32\ole32.dll', No symbols loaded. 'pyembed_test.exe': Loaded 'C:\WINDOWS\system32\oleaut32.dll', No symbols loaded. 'pyembed_test.exe': Loaded 'C:\WINDOWS\system32\winspool.drv', No symbols loaded. 'pyembed_test.exe': Loaded 'C:\WINDOWS\system32\comdlg32.dll', No symbols loaded. 'pyembed_test.exe': Loaded 'C:\WINDOWS\system32\shell32.dll', No symbols loaded. 'pyembed_test.exe': Loaded 'C:\WINDOWS\system32\python24.dll', No symbols loaded. 'pyembed_test.exe': Loaded 'C:\WINDOWS\system32\msvcr71.dll', Symbols loaded. 'pyembed_test.exe': Loaded 'C:\WINDOWS\WinSxS\x86_Microsoft.Windows.Common-Controls_6595b64144ccf1df_6.0.2600.2180_x-ww_a84f1ff9\comctl32.dll', No symbols loaded. 'pyembed_test.exe': Loaded 'C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\mscorwks.dll', No symbols loaded. 'pyembed_test.exe': Loaded 'C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\fusion.dll', No symbols loaded. 'pyembed_test.exe': Loaded 'C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\mscorlib.dll', No symbols loaded. 'pyembed_test.exe': Loaded 'C:\WINDOWS\assembly\NativeImages1_v1.1.4322\mscorlib\1.0.5000.0__b77a5c561934e089_ca105f6f\mscorlib.dll', No symbols loaded. 'pyembed_test.exe': Loaded 'C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\diasymreader.dll', No symbols loaded. 'DefaultDomain': Loaded 'c:\windows\microsoft.net\framework\v1.1.4322\mscorlib.dll', No symbols loaded. 'pyembed_test.exe': Loaded 'C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\mscorsn.dll', No symbols loaded. 'pyembed_test': Loaded 'c:\mdunschen\pyembed_test\Debug\pyembed_test.exe', Symbols loaded. 'pyembed_test.exe': Loaded 'C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\mscorjit.dll', No symbols loaded. 'pyembed_test.exe': Loaded 'C:\WINDOWS\system32\uxtheme.dll', No symbols loaded. The thread '_threadstartex' (0x500) has exited with code 0 (0x0). The thread '_threadstartex' (0xadc) has exited with code 0 (0x0). The thread '' (0xadc) has exited with code 0 (0x0). The thread '' (0x500) has exited with code 0 (0x0). The thread '_threadstartex' (0x928) has exited with code 0 (0x0). The thread '' (0x928) has exited with code 0 (0x0). The thread '_threadstartex' (0xe48) has exited with code 0 (0x0). The thread '' (0xe48) has exited with code 0 (0x0). The thread '_threadstartex' (0x984) has exited with code 0 (0x0). The thread '' (0x984) has exited with code 0 (0x0). The thread '_threadstartex' (0x108) has exited with code 0 (0x0). HEAP[pyembed_test.exe]: HEAP: Free Heap block eb5bd8 modified at eb5c24 after it was freed Unhandled exception at 0x7c901230 in pyembed_test.exe: User breakpoint. Stack dump: > pyembed_test.exe!_heap_alloc_dbg(unsigned int nSize=15400960, int nBlockUse=1073741920, const char * szFileName=0x00000064, int nLine=1242368) Line 359 + 0x1e C pyembed_test.exe!_heap_alloc_base(unsigned int size=100) Line 212 C pyembed_test.exe!_heap_alloc_dbg(unsigned int nSize=64, int nBlockUse=12582916, const char * szFileName=0x004c4dd4, int nLine=311) Line 397 + 0x9 C pyembed_test.exe!_nh_malloc_dbg(unsigned int nSize=64, int nhFlag=0, int nBlockUse=12582916, const char * szFileName=0x004c4dd4, int nLine=311) Line 260 + 0x15 C pyembed_test.exe!_malloc_dbg(unsigned int nSize=64, int nBlockUse=12582916, const char * szFileName=0x004c4dd4, int nLine=311) Line 176 + 0x1b C pyembed_test.exe!operator new(unsigned int nSize=64, int nType=12582916, const char * lpszFileName=0x004c4dd4, int nLine=311) Line 403 + 0x15 C++ pyembed_test.exe!CObject::operator new(unsigned int nSize=64, const char * lpszFileName=0x004c4dd4, int nLine=311) Line 93 + 0x16 C++ pyembed_test.exe!AfxBeginThread(unsigned int (void *)* pfnThreadProc=0x00401b80, void * pParam=0x00df7b10, int nPriority=0, unsigned int nStackSize=4, unsigned long dwCreateFlags=0, _SECURITY_ATTRIBUTES * lpSecurityAttrs=0x00000000) Line 311 + 0x11 C++ 00aaa43d() pyembed_test.exe!CMyWinApp::InitInstance() Line 87 + 0x26 bytes C++ pyembed_test.exe!AfxWinMain(HINSTANCE__ * hInstance=0x00400000, HINSTANCE__ * hPrevInstance=0x00000000, char * lpCmdLine=0x00141f12, int nCmdShow=5) Line 39 + 0xb C++ pyembed_test.exe!WinMain(HINSTANCE__ * hInstance=0x00400000, HINSTANCE__ * hPrevInstance=0x00000000, char * lpCmdLine=0x00141f12, int nCmdShow=5) Line 25 C++ pyembed_test.exe!WinMainCRTStartup() Line 251 + 0x30 C From faulkner612 at comcast.net Mon Jun 5 17:14:18 2006 From: faulkner612 at comcast.net (faulkner) Date: 5 Jun 2006 14:14:18 -0700 Subject: Adding attribute to objetcs In-Reply-To: References: Message-ID: <1149542058.273735.259150@u72g2000cwu.googlegroups.com> when you set an attribute of an object, python secretly calls that objects __setattr__ method. class test: def __setattr__(self, attr_name, attr_value): print self, attr_name, attr_value self.__dict__[attr_name] = attr_value # do what the original __setattr__ method does. test().fred = 'george' # prints fred george Miguel Galves wrote: > Hello, > > I`m starting to learn python, and I hava a very good background in Java > and C/C++ programming. I was reading Dive into python chapter about > OO and I saw that in python we can do the following: > > class Person: > pass > > joe = new Person() > joe.name = "Joe" > joe.age = 13 > > It seems that it is possible to add attributes to any object instance > in run time, as in Javascript. It seems to me that it can be a source > of errors. One that come in my mind is the follwing: > > class Person: > name = "" > > joe = new Person() > joe.nome = "Joe" > > The code above adds an attribute called nome, but the programmer may think > it's name. > > What is the real interest of this feature ? Is there a way to block this > kind of error ? > > Thanks, > > Miguel > -- > Miguel Galves - Engenheiro de Computa??o > J? leu meus blogs hoje? > Para geeks http://log4dev.blogspot.com > Pra pessoas normais > http://miguelgalves.blogspot.com > > "N?o sabendo que era imposs?vel, ele foi l? e fez..." From marshall.spight at gmail.com Fri Jun 23 13:15:56 2006 From: marshall.spight at gmail.com (Marshall) Date: 23 Jun 2006 10:15:56 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: <449bde5e$1$663$bed64819@news.gradwell.net> References: <7zpshbsvjy.fsf@app-1.diku.dk><4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <0%Wlg.3521$MF6.947@tornado.socal.rr.com> <44992e6c$0$664$bed64819@news.gradwell.net> <449aaea0$0$656$bed64819@news.gradwell.net> <449bde5e$1$663$bed64819@news.gradwell.net> Message-ID: <1151082956.067238.45100@b68g2000cwa.googlegroups.com> Chris Uppal wrote: > > But, as a sort of half-way, semi-formal, example: consider the type environment > in a Java runtime. The JVM does formal type-checking of classfiles as it loads > them. In most ways that checking is static -- it's treating the bytecode as > program text and doing a static analysis on it before allowing it to run (and > rejecting what it can't prove to be acceptable by its criteria). However, it > isn't /entirely/ static because the collection of classes varies at runtime in > a (potentially) highly dynamic way. So it can't really examine the "whole" > text of the program -- indeed there is no such thing. So it ends up with a > hybrid static/dynamic type system -- it records any assumptions it had to make > in order to find a proof of the acceptability of the new code, and if (sometime > in the future) another class is proposed which violates those assumptions, then > that second class is rejected. I have to object to the term "hybrid". Java has a static type system. Java has runtime tags and tag checks. The two are distinct, and neither one is less than complete, so I don't think "hybrid" captures the situation well. Marshall From sreeram at tachyontech.net Tue Jun 13 14:47:50 2006 From: sreeram at tachyontech.net (K.S.Sreeram) Date: Wed, 14 Jun 2006 00:17:50 +0530 Subject: daily python url - gmane links dead? Message-ID: <448F0856.4090303@tachyontech.net> Is it just me.. or are all the gmane links on daily-python dead? All the c.l.py.announce entries point to gmane, and none of them seem to be working. This is the error i get on gmane: Warning: fsockopen(): unable to connect to hugh:8010 in /home/httpd/gmane/php/lib.php on line 18 Couldn't contact hugh:8010 The web interface is down for maintenance. How about using google groups or the python.org archives instead of gmane? Regards Sreeram -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 260 bytes Desc: OpenPGP digital signature URL: From sjmachin at lexicon.net Fri Jun 9 18:45:48 2006 From: sjmachin at lexicon.net (John Machin) Date: Sat, 10 Jun 2006 08:45:48 +1000 Subject: First question on extending Python... In-Reply-To: References: Message-ID: <4489FA1C.5050009@lexicon.net> On 10/06/2006 8:32 AM, Redefined Horizons wrote: > I still new to Python, and I've only dabbled in C, but I've got my > first project I need to tackle that involves both languages. I was > hoping to get some advice on how to proceed. > > There is a third-party application that I need to work with. It is > closed-source, but it exposes a C API. I want to wrap this C API so > that it is available from Python. I have no ability to modify the C > API of the third part application. > > Do I the C functions that I wrap in an extensions module for Python > need to be in a certian format? No. > If so, I will have to write an > intermediate DLL in C that wraps the third-party application and > exports the functions in a form that Python can use. No way. You need only *one* layer of glue. > > Or can an extension module for Python wrap any C function? I've never heard of a C function that couldn't be wrapped. If there were such a function, having more C code in a separate DLL wouldn't make it wrappable. > If this is > the case I think I can skip the intermediate C DLL. I think so too. > > Are there any advantages to using the intermediate DLL written in C in > this particular case where I will not have ability to manipulate the C > API of the third party application directly? (For example, if the > third-party application developers are willing to call a "call-back" > function that must be written in C, but not Python. No advantages that I can see. Your C call-back function could then call a Python function if you really wanted to -- the 3rd-party devs don't need to know :-) > Could the same > extension module export both C functions and serve as a Python > module?) Yes. Cheers, John From fredrik at pythonware.com Tue Jun 6 06:20:49 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 06 Jun 2006 12:20:49 +0200 Subject: How to add few pictures into one In-Reply-To: <1149587802.895959.37210@f6g2000cwb.googlegroups.com> References: <1149511692.796038.155930@c74g2000cwc.googlegroups.com> <1149517433.880564.128350@h76g2000cwa.googlegroups.com> <1149529269.228019.120480@u72g2000cwu.googlegroups.com> <1149573892.526072.6770@i39g2000cwa.googlegroups.com> <1149580572.739202.110940@y43g2000cwc.googlegroups.com> <1149587802.895959.37210@f6g2000cwb.googlegroups.com> Message-ID: Lad wrote: > Open a picture file( download it from internet) and write it in a > result file( being open in binary mode). > Then download another file and append to the result file. > And so on... > But is it possible? Will be the pictures in the result file seen > well?? the internal structure of an image file is quite a bit more complicated than the internal structure of a text file, so it's not very likely that you would get very far with that approach. why not just put all the files in a directory, and use an image viewer with collage or slideshow support ? From blais at furius.ca Wed Jun 21 01:41:44 2006 From: blais at furius.ca (Martin Blais) Date: Wed, 21 Jun 2006 01:41:44 -0400 Subject: Cycles between package imports In-Reply-To: <1150633514.024828.95330@g10g2000cwb.googlegroups.com> References: <1150633514.024828.95330@g10g2000cwb.googlegroups.com> Message-ID: <8393fff0606202241j1a3cb847pfa55575e48ea4fc0@mail.gmail.com> On 18 Jun 2006 05:25:14 -0700, John Roth wrote: > Martin Blais wrote: > > Hi > > > > I'm a tad confused over a problem involving cycles between > > packages. > > [lengthy example snipped] > > > > > > > I don't see why the reference to module a.alice could not be > > available via the "from" syntax, even if it is still incompletely > > initialized at the time of import. > > > > Can anyone shed some light onto this? Is there a rule for > > determining when a module becomes available to import from a > > package using the "from" syntax? > > It's really easy to see if you trace out, in detail, the exact > order in which things happen and when each object is initialized and > shows up in the respective module's namespace. No it's not, at least I don't see it. The order in which the symbols appear is different whether you're using the simple "import" form or the "from ... import" form. This is exactly what the question is about. > The general rule is: don't do that. It doesn't work, and the > hoops you have to go through to force it to work are so > complex and bizzare that they're not worth it. Redesign > the modules so you don't have cyclic dependencies. This is a matter completely aside the question. Whether it's worth it or not depends on the specific case --not included in the example-- and in the case where it shows up in my code, removing the cycle actually made sense (it does, most of the time, but not always). Thanks. cheers, From pc at p-cos.net Fri Jun 16 05:59:25 2006 From: pc at p-cos.net (Pascal Costanza) Date: Fri, 16 Jun 2006 11:59:25 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: <7zu06lqxhu.fsf@app-1.diku.dk> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> Message-ID: <4ffdntF1iei4hU1@individual.net> Torben ?gidius Mogensen wrote: > Pascal Costanza writes: > >> Torben ?gidius Mogensen wrote: >> >>> On a similar note, is a statically typed langauge more or less >>> expressive than a dynamically typed language? Some would say less, as >>> you can write programs in a dynamically typed language that you can't >>> compile in a statically typed language (without a lot of encoding), >>> whereas the converse isn't true. >> It's important to get the levels right here: A programming language >> with a rich static type system is more expressive at the type level, >> but less expressive at the base level (for some useful notion of >> expressiveness ;). >> >>> However, I think this is misleading, >>> as it ignores the feedback issue: It takes longer for the average >>> programmer to get the program working in the dynamically typed >>> language. >> This doesn't seem to capture what I hear from Haskell programmers who >> say that it typically takes quite a while to convince the Haskell >> compiler to accept their programs. (They perceive this to be >> worthwhile because of some benefits wrt correctness they claim to get >> in return.) > > That's the point: Bugs that in dynamically typed languages would > require testing to find are found by the compiler in a statically > typed language. Yes. However, unfortunately statically typed languages also reject programs that don't have such bugs. It's a tradeoff whether you want to spend time to deal with them or not. > So whil eit may take onger to get a program thatgets > past the compiler, it takes less time to get a program that works. That's incorrect. See http://haskell.org/papers/NSWC/jfp.ps - especially Figure 3. Pascal -- 3rd European Lisp Workshop July 3 - Nantes, France - co-located with ECOOP 2006 http://lisp-ecoop06.bknr.net/ From find at my.address.elsewhere Fri Jun 23 09:18:09 2006 From: find at my.address.elsewhere (Matthias Blume) Date: Fri, 23 Jun 2006 08:18:09 -0500 Subject: Saying "latently-typed language" is making a category mistake References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <86Qmg.10725$o4.1907@newsread2.news.pas.earthlink.net> <4g251pF1knc6tU1@individual.net> Message-ID: Pascal Costanza writes: > Patricia Shanahan wrote: >> Vesa Karvonen wrote: >> ... >>> An example of a form of informal reasoning that (practically) every >>> programmer does daily is termination analysis. There are type systems >>> that guarantee termination, but I think that is fair to say that it >>> is not >>> yet understood how to make a practical general purpose language, whose >>> type system would guarantee termination (or at least I'm not aware >>> of such >>> a language). It should also be clear that termination analysis need not >>> be done informally. Given a program, it may be possible to >>> formally prove >>> that it terminates. >> To make the halting problem decidable one would have to do one of >> two >> things: Depend on memory size limits, or have a language that really is >> less expressive, at a very deep level, than any of the languages >> mentioned in the newsgroups header for this message. > > Not quite. See http://en.wikipedia.org/wiki/ACL2 What do you mean "not quite"? Of course, Patricia is absolutely right. Termination-guaranteeing languages are fundamentally less expressive than Turing-complete languages. ACL2 was not mentioned in the newsgroup header. From bnblazer at gmail.com Wed Jun 7 12:05:58 2006 From: bnblazer at gmail.com (Brian) Date: 7 Jun 2006 09:05:58 -0700 Subject: creating and naming objects Message-ID: <1149696358.065614.76150@h76g2000cwa.googlegroups.com> I have a question that some may consider silly, but it has me a bit stuck and I would appreciate some help in understanding what is going on. For example, lets say that I have a class that creates a student object. Class Student: def setName(self, name) self.name = name def setId(self, id) self.id = id Then I instantiate that object in a method: def createStudent(): foo = Student() /add stuff Now, suppose that I want to create another Student. Do I need to name that Student something other than foo? What happens to the original object? If I do not supplant the original data of Student (maybe no id for this student) does it retain the data of the previous Student object that was not altered? I guess I am asking how do I differentiate between objects when I do not know how many I need to create and do not want to hard code names like Student1, Student2 etc. I hope that I am clear about what I am asking. Thanks, Brian From fredrik at pythonware.com Fri Jun 30 11:13:01 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 30 Jun 2006 17:13:01 +0200 Subject: Chapter 9 Tutorial for Classes Not Working In-Reply-To: <44A534D4.9060404@nepinc.com> References: <44A534D4.9060404@nepinc.com> Message-ID: Tom Grove wrote: > I am trying the classes example from the tutorial because some other > class related stuff I am doing is not working either. > > Straight from Chapter 9: > > class MyClass: > "A simple example class" > i = 12345 > def f(self): > return 'hello world' > > > From here I run: > > x = MyClass the tutorial says: Class instantiation uses function notation. Just pretend that the class object is a parameterless function that returns a new instance of the class. For example (assuming the above class): x = MyClass() creates a new instance of the class and assigns this object to the local variable x. From johnzenger at gmail.com Fri Jun 30 14:55:54 2006 From: johnzenger at gmail.com (johnzenger at gmail.com) Date: 30 Jun 2006 11:55:54 -0700 Subject: string replace In-Reply-To: <1aapg.21924$_J1.275201@twister2.libero.it> References: <1aapg.21924$_J1.275201@twister2.libero.it> Message-ID: <1151693754.233027.320530@p79g2000cwp.googlegroups.com> Check out the .translate method and the string.maketrans documentation. You can use it to delete a list of characters all in one line: >>> s = "I am the walrus" >>> import string >>> s.translate(string.maketrans("",""),"aeiou") 'I m th wlrs' Michele Petrazzo wrote: > Hi, > a lot of times I need to replace more than one char into a string, so I > have to do something like > > value = "test" > chars = "e" > for c in chars: > value = value.replace(c, "") > > A solution could be that "replace" accept a tuple/list of chars, like > that was add into the new 2.5 for startswith. > > I don't know, but can be this feature included into a future python release? > > Thanks, > Michele From dndfan at hotpop.com Thu Jun 1 14:50:13 2006 From: dndfan at hotpop.com (The Prophet) Date: 1 Jun 2006 11:50:13 -0700 Subject: os.walk trouble In-Reply-To: <447f32c4_2@newspeer2.tds.net> References: <1149173920.903876.68370@c74g2000cwc.googlegroups.com> <447f32c4_2@newspeer2.tds.net> Message-ID: <1149187813.790336.285680@c74g2000cwc.googlegroups.com> Kent Johnson wrote: > The Prophet wrote: > > As my first Python script, I am trying to make a program that recurses > > a directory searching for files whose names match a pattern. > > If your patterns are simple (supported by fnmatch), the path module > makes this very easy: > import path > for f in path.path(dirname).walkfiles('*.foo'): > # process a .foo file here > > http://www.jorendorff.com/articles/python/path/index.html > > Kent Well, it ain't that simple, but the suggestion is helpful, since I am only a beginner. Thanks for everything, friends, now this aspect is clear to me. From arv.nntp at gmail.com Thu Jun 22 16:03:12 2006 From: arv.nntp at gmail.com (Alexis Roda) Date: Thu, 22 Jun 2006 22:03:12 +0200 Subject: Quick Question In-Reply-To: <1151006076.949700.130110@u72g2000cwu.googlegroups.com> References: <1151006076.949700.130110@u72g2000cwu.googlegroups.com> Message-ID: En/na xkenneth ha escrit: > I want to be able to cycle through an array and print something in > hexadecimal. Such as this > thisArray = ["AF","0F","5F"] > for x in range(len(thisArray)): > print "\x" + thisArray[x] > > However python chokes on the escaped identifier, how can I get around > this? What's the expected output? \xAF \x=F \x5F ? for x in thisArray : print "\\x" + x HTH From wegwerp at gmail.com Wed Jun 21 18:02:58 2006 From: wegwerp at gmail.com (Bas) Date: 21 Jun 2006 15:02:58 -0700 Subject: returning index of minimum in a list of lists References: <1150901648.832039.165590@b68g2000cwa.googlegroups.com> <1150905017.886816.81750@m73g2000cwd.googlegroups.com> <1150905851.500826.165160@m73g2000cwd.googlegroups.com> Message-ID: <1150927378.221918.249930@p79g2000cwp.googlegroups.com> JJLaRocque at gmail.com wrote: > Thanks so much for your help. I was wondering if there was anything > even simpler, but this will be great. >>> from numpy import * >>> a=array([[3,3,3,3], [3,3,3,1], [3,3,3,3]]) >>> where(a==a.min()) (array([1]), array([3])) Probably overkill for your simple problem, but this is a nice alternative if you do a lot of matrix work. Bas From jzgoda at o2.usun.pl Thu Jun 15 17:41:07 2006 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Thu, 15 Jun 2006 23:41:07 +0200 Subject: a good programming text editor (not IDE) In-Reply-To: References: <_xgkg.2317$No6.48542@news.tufts.edu> <1150402733.116243.9680@y41g2000cwy.googlegroups.com> Message-ID: Fredrik Lundh napisa?(a): >> Emacs must be dying if this thread could get all the way to 20 with >> nobody arguing with the vi folks. > 1) editor wars are so last century. > 2) emacs has already won. You died in last century with your editor, we have tabs. -- Jarek Zgoda http://jpa.berlios.de/ From alan.franzoni.xyz at gmail.com Wed Jun 28 10:41:25 2006 From: alan.franzoni.xyz at gmail.com (Alan Franzoni) Date: Wed, 28 Jun 2006 16:41:25 +0200 Subject: compiling python (or ironpython) to .exe or .dll for or not for .NET References: <1151501398.664329.142920@d56g2000cwd.googlegroups.com> Message-ID: <1rqfdn3hquqhz$.1r6xz02yzes1a$.dlg@40tude.net> Il 28 Jun 2006 06:29:58 -0700, per9000 ha scritto: > Is the newest Ironpython really as old as from 2004 July 28 (as stated > on http://www.ironpython.com/)? Sorry again, the up to date page is the following one: http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython -- Alan Franzoni - Togli .xyz dalla mia email per contattarmi. Rremove .xyz from my address in order to contact me. - GPG Key Fingerprint: 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E - Blog: http://laterradeglieroi.verdiperronchi.com From y.glodt at sitasoftware.lu Wed Jun 7 03:05:27 2006 From: y.glodt at sitasoftware.lu (Yves Glodt) Date: Wed, 07 Jun 2006 09:05:27 +0200 Subject: pyqt show wizard Message-ID: <44867AB7.8030702@sitasoftware.lu> Hi, I have a mainwindow in my pyqt application, and on click of a button I want to start an assistant (wizard). I have create the wizard with the Qt Designer, generated the python code with pyuic, imported it "from assistant import *", and subclassed it as usual. To show it, the onclick method of the button does: w = Wizard() w.show() bot nothing happens... How must I do to start the wizard...? Best regards, Yves From nospam at nospam.com Wed Jun 21 18:41:50 2006 From: nospam at nospam.com (3c273) Date: Wed, 21 Jun 2006 15:41:50 -0700 Subject: OS specific command in Python References: <1150781429.090359.148560@c74g2000cwc.googlegroups.com> <44979b35$0$8390$626a54ce@news.free.fr> <1150823140.295590.307390@i40g2000cwc.googlegroups.com> <4498d973$0$25496$626a54ce@news.free.fr> <4499ad49$0$23551$626a54ce@news.free.fr> Message-ID: "Avell Diroll" wrote in message news:4499ad49$0$23551$626a54ce at news.free.fr... > 3c273 wrote: > > I was just trying to learn how to use .communicate() and all of the examples > > I see have [0] after .communicate(). What is the significance of the [0]? > > > From the Python Library Reference > (http://docs.python.org/lib/node239.html), you learn that the method > communicate() from the subprocess.Popen() class returns a tuple > containing the standard output as first item and the standard error of > the child process as second item. So the [0] in the example is for > selecting the first item of the tuple ... Thank you for taking the time to make that clear for me. I did read the docs, I just didn't really understand what communicate() did, but I do now. Thanks again. Louis From pythoncurious at gmail.com Mon Jun 5 10:07:45 2006 From: pythoncurious at gmail.com (pythoncurious at gmail.com) Date: 5 Jun 2006 07:07:45 -0700 Subject: strategy pattern and non-public virtual functions Message-ID: <1149516464.874257.194030@j55g2000cwa.googlegroups.com> Hi python experts In C++ I can do something like this: class Base { public: void f() { this->f_(); } private: virtual void f_() = 0; }; class Derived : public Base { private: void f_() { // Do something } }; int main() { Derived d; d.f(); } The point of this is that the a number of classes will inherit from Base and only implement a private member function that only will be accessed from the base class public 'f' function. The Base::f() can then perform validation of input/return values, add logging and things like that. The users of the derived classes are unable to bypass this base class function. I've been wanting to do the same thing in python, to make sure that there is no confusion about what function to call. Just translating this code to python won't work, due to the name mangling of private functions: class B(object): def f(self): self.__f() class D(B): def __f(self): pass d = D() d.f() Traceback (most recent call last): File "", line 1, in ? File "", line 3, in f AttributeError: 'D' object has no attribute '_B__f' So my questions are: 1. Is there a "pythonic" way to do what I'm trying to do? 2. Should I be doing this at all? Any thoughts? From david.nospam.hopwood at blueyonder.co.uk Tue Jun 27 17:57:13 2006 From: david.nospam.hopwood at blueyonder.co.uk (David Hopwood) Date: Tue, 27 Jun 2006 21:57:13 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: <4gdkmiF1ldalhU3@individual.net> References: <7zy7vt1mz2.fsf@app-3.diku.dk> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <1151384511.223582.305760@m73g2000cwd.googlegroups.com> <4gdkmiF1ldalhU3@individual.net> Message-ID: Pascal Costanza wrote: > David Hopwood wrote: >> Marshall wrote: >> >>> The real question is, are there some programs that we >>> can't write *at all* in a statically typed language, because >>> they'll *never* be typable? >> >> In a statically typed language that has a "dynamic" type, all >> dynamically typed programs are straightforwardly expressible. > > What about programs where the types change at runtime? Staged compilation is perfectly compatible with static typing. Static typing only requires that it be possible to prove absence of some category of type errors when the types are known; it does not require that all types are known before the first-stage program is run. There are, however, staged compilation systems that guarantee that the generated program will be typeable if the first-stage program is. (It's clear that to compare the expressiveness of statically and dynamically typed languages, the languages must be comparable in other respects than their type system. Staged compilation is the equivalent feature to 'eval'.) -- David Hopwood From jstobbs at gmail.com Thu Jun 8 02:46:54 2006 From: jstobbs at gmail.com (jstobbs at gmail.com) Date: 7 Jun 2006 23:46:54 -0700 Subject: python socket proxy In-Reply-To: References: <1149577919.811693.178730@f6g2000cwb.googlegroups.com> <1149587437.299147.314670@h76g2000cwa.googlegroups.com> <1149685669.978416.235630@u72g2000cwu.googlegroups.com> Message-ID: <1149749214.591592.158260@j55g2000cwa.googlegroups.com> cool, nice one, thanks. Jeethu Rao wrote: > Simplest way would be to rename your python file with a .pyw extension > instead of a .py extension. > If you're looking for windows services, checkout > win32serviceutil.ServiceFramework in pywin32. > > Jeethu Rao > > jstobbs at gmail.com wrote: > > Hi > > > > Thanks for the reply. > > > > I found a proxy that works for me. Now I would like to know if its > > possible to run a python script, so its not visible in the cmd window > > (windows, i know, its bad :-) ) Maybe run it as a windows service? > > > > > > > > Filip Wasilewski wrote: > > > >> jstobbs at gmail.com wrote: > >> > >>> Hi all > >>> > >>> I am trying to create a lighweight tcp proxy server. > >>> > >> [...] > >> > >> There is a bunch of nice recipies in the Python Cookbook on port > >> forwarding. In the [1] and [2] case it should be fairly simple to add > >> an extra authentication step with pyOpenSSL. > >> > >> [1] http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/483730 > >> [2] http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/114642 > >> [3] http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/483732 > >> > >> best, > >> fw > >> > > > > From austuff at gmail.com Mon Jun 26 10:55:06 2006 From: austuff at gmail.com (janama) Date: 26 Jun 2006 07:55:06 -0700 Subject: Formatted string to object References: <1150731552.799052.47320@r2g2000cwb.googlegroups.com> <4496d806$0$9017$626a54ce@news.free.fr> Message-ID: <1151333706.837501.40170@m73g2000cwd.googlegroups.com> Thankyou everyone for help last time: The following works ok when setting a wx.lib.buttons.GenBitmapTextButton's disabled bitmap in using wxpython instead of this: self.b1.SetBitmapDisabled(self.yellow) i can use this: aaa = 1 result1 = eval("self.b%s.SetBitmapDisabled(self.yellow)" % aaa) result YAY! How would i to achieve this with getattr() ? getattr(locals()['parent'], aaa) ??? Why would this be better as recommended in previous post here http://groups.google.com.au/group/comp.lang.python/browse_frm/thread/2529515bc85cd954/c2f080b21d668081?q=janama&rnum=1#c2f080b21d668081 Any help appreciated ta From iamkey9 at 126.com Sat Jun 3 05:30:08 2006 From: iamkey9 at 126.com (key9) Date: Sat, 3 Jun 2006 17:30:08 +0800 Subject: can python be a "shell" of c++ program? Message-ID: Hi all I have some data to process, whith complex mechanism,I put these process mechanism as plugins. and design lots of classes to abstract data themselves. but the question is how to drive them work together. That cause too much jobs: I should write UI,parser......almost a completed system. The problem is I don't know what these processed data will finally needed to display to user. maybe this , may be that, these can not know on design time. what I need is on outside of program, I can use some interface to get these data what I want , or push back data, or told program to recalculate it. can I have a way to drive c++ code use this script-like way ? thank you very much key9 From bapolis at gmail.com Mon Jun 12 05:41:07 2006 From: bapolis at gmail.com (Tgone) Date: 12 Jun 2006 02:41:07 -0700 Subject: Using PHP in Python In-Reply-To: <4f4qvbF1hjj7tU1@uni-berlin.de> References: <1150104925.811155.3550@y43g2000cwc.googlegroups.com> <4f4qvbF1hjj7tU1@uni-berlin.de> Message-ID: <1150105267.463906.66700@f14g2000cwb.googlegroups.com> Diez B. Roggisch wrote: > Tgone wrote: > > > Hello, > > > > I've come across sites that discuss embedding Python in PHP, but is it > > possible to access PHP functions in Python? > > I'm not aware of a generic wrapper thingy. Which doesn't mean there is none. > But which functions are you interested in? I can't believe there is much > that PHP can do that python _can't_ do, so maybe we can point you in the > right direction. > > Diez I have some custom PHP functions that I didn't want to re-write in Python. But maybe I should just rewrite them :) From steve at holdenweb.com Thu Jun 29 08:41:35 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 29 Jun 2006 13:41:35 +0100 Subject: Widget access In-Reply-To: <1151573351.708542.63070@m73g2000cwd.googlegroups.com> References: <1151573351.708542.63070@m73g2000cwd.googlegroups.com> Message-ID: arvind wrote: > how to make the widgets defined inside the function available outside > it without using OOPs concept? > Only ways to have something created in function available outside are a) have function store widget refs in global (poor coupling), b) have mutable function argument into which function places widget references, or c) return references to widgets as (part of) function value. It usually boils down to a choice between b) and c). regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From rossberg at ps.uni-sb.de Sun Jun 25 15:42:44 2006 From: rossberg at ps.uni-sb.de (rossberg at ps.uni-sb.de) Date: 25 Jun 2006 12:42:44 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150908952.804184.218990@r2g2000cwb.googlegroups.com> <1150991074.705803.211570@m73g2000cwd.googlegroups.com> <1151244628.566060.40500@p79g2000cwp.googlegroups.com> Message-ID: <1151264564.653872.151090@m73g2000cwd.googlegroups.com> Joachim Durchholz wrote: > > > but (Standard) ML surely has none. > > NLFFI? > > > Same with Haskell as defined by its spec. > > Um... I'm not 100% sure, but I dimly (mis?)remember having read that > UnsafePerformIO also offered some ways to circumvent the type system. Neither NLFFI nor unsafePerformIO are official part of the respective languages. Besides, foreign function interfaces are outside a language by definition, and can hardly be taken as an argument - don't blame language A that unsafety arises when you subvert it by interfacing with unsafe language B on a lower level. > >> and even C is typesafe unless you use unsafe constructs. > > > > Tautology. Every language is "safe unless you use unsafe constructs". > > No tautology - the unsafe constructs aren't just typewise unsafe ;-p > > That's exactly why I replaced Luca Cardelli's "safe/unsafe" > "typesafe/not typesafe". There was no definition to the original terms > attached, and this discussion is about typing anyway. The Cardelli paper I was referring to discusses it in detail. And if you look up the context of my posting: it was exactly whether safety is to be equated with type safety. > >> IOW from a type-theoretic point of view, there is no real difference > >> between their typesafe and not typesafe languages in the "statically > >> typed" column; the difference is in the amount of unsafe construct usage > >> in practial programs. > > > > Huh? There is a huge, fundamental difference: namely whether a type > > system is sound or not. > > I think you're overstating the case. > > In type theory, of course, there's no such things as an "almost typesafe > language" - it's typesafe or it isn't. Right, and you were claiming to argue from a type-theoretic POV. [snipped the rest] - Andreas From riquito at gmail.com Sat Jun 24 13:15:08 2006 From: riquito at gmail.com (riquito at gmail.com) Date: 24 Jun 2006 10:15:08 -0700 Subject: PyGTK and Py2Exe troubles In-Reply-To: <1151141748.172141.285890@p79g2000cwp.googlegroups.com> References: <1151141748.172141.285890@p79g2000cwp.googlegroups.com> Message-ID: <1151169308.365744.108440@u72g2000cwu.googlegroups.com> Tim N. van der Leeuw ha scritto: > I tried to create a windows executable of a pygtk program. My first > attempt worked, kinda, except that no themes were applied and no > readable fonts were found by pango; so all letters where just empty > squares. But the program worked. > > I looked up some docs, found the following recipe on the PyGTK Wiki > site: > http://starship.python.net/crew/theller/moin.cgi/Py2exeAndPyGTK > > I followed those instructions to convert my setup.py file; everything > still worked the same as before. versions of python,gtk,pygtk? wich windows? wich installer of gtk have you used? did you install pycairo too? try again with these one, if different from yours gtk -> http://gladewin32.sourceforge.net pygtk/pycairo -> http://www.mapr.ucl.ac.be/~gustin/win32_ports/ bye, Riccardo From behnel_ml at gkec.informatik.tu-darmstadt.de Wed Jun 28 07:29:46 2006 From: behnel_ml at gkec.informatik.tu-darmstadt.de (Stefan Behnel) Date: Wed, 28 Jun 2006 13:29:46 +0200 Subject: [Pyrex] pyrex functions to replace a method (Re: replace a method in class: how?) In-Reply-To: <44A261CF.4000309@bryant.edu> References: <44A06A6B.6010200@bryant.edu> <44A11564.9030009@bryant.edu> <44A1C5C7.4090007@canterbury.ac.nz> <44A261CF.4000309@bryant.edu> Message-ID: <44A2682A.6030804@gkec.informatik.tu-darmstadt.de> Brian Blais wrote: > Greg Ewing wrote: >> Brian Blais wrote: >>> I have found a very similar problem trying to replace a method using a >>> function defined in pyrex. >> >> What *should* work is to define the method inside a >> class in Pyrex (plain class, not extension type) and >> extract it out of the class's __dict__. That's because >> Pyrex pre-wraps a function defined in a class in an >> unbound method object before putting it in the class. >> > > So I tried: > > #--------------------------------------------------------------------------------- > > #module_pyrex.pyx > > class update_funcs: > > def pyrex_update_within_class(self,val): > print "pyrex module within class",val > > > #--------------------------------------------------------------------------------- > > #(adding to test_replace_method.py) > > This.update4=module_pyrex.update_funcs.__dict__['pyrex_update_within_class'] > > t.update4('pyrex within class') # doesn't work > > #--------------------------------------------------------------------------------- > > and get: > > TypeError: unbound method pyrex_update_within_class() must be called with > update_funcs instance as first argument (got str instance instead) > > did I do this wrong? Yes. :) What you got was an unbound method. You can't call unbound methods without specifying the object you want to call them on (i.e. the 'self' argument). http://docs.python.org/tut/node11.html#SECTION0011340000000000000000 When you're using 'plain classes', you can do with them whatever you do in standard Python, so replacing a method is just done with an attribute assignment. Stefan From frank at chagford.com Fri Jun 16 10:06:36 2006 From: frank at chagford.com (Frank Millman) Date: 16 Jun 2006 07:06:36 -0700 Subject: XML, JSON, or what? In-Reply-To: <1149760146.136587.124710@h76g2000cwa.googlegroups.com> References: <1149749530.734275.181300@j55g2000cwa.googlegroups.com> <1149760146.136587.124710@h76g2000cwa.googlegroups.com> Message-ID: <1150466796.646397.149890@p79g2000cwp.googlegroups.com> Alan Kennedy wrote: > [Frank Millman] > > I am writing a multi-user accounting/business application, which uses > > sockets to communicate between server and client. The server contains > > all the business logic. It has no direct knowledge of the client. I > > have devised a simple message format to exchange information between > > the two. > > > > If you're going to mix javascript client and python server, you > definitely need something cross platform, like XML or JSON. > [...] > > I'd go with JSON, for simplicity and portability. If you have any > specific questions about it, ask. > Thanks for the offer. I have just tried it out, and instantly bumped my head. I think I know the problem, and I don't think there is a simple answer, but I will ask here first before starting to figure out a way around it. My client-server is Python-to-Python. At present, I am using cPickle to transfer objects between the two. Among other things, I sometimes transfer a tuple. Using JSON it appears on the other side as a list. As I sometimes use the tuple as a dictionary key, this fails, as you obviously cannot use a list as a key. I am using 'simplejson'. I see there is also something called json-py, but I have not tried it yet, as I am assuming (maybe wrongly) that it will have the same problem. My hunch is that javascript/JSON does not have the concept of a tuple, and therefore the problem is inherent. Can someone confirm this, or is there an easy workaround? Thanks Frank From tjreedy at udel.edu Thu Jun 8 04:02:28 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 8 Jun 2006 04:02:28 -0400 Subject: language-x-isms References: <1149753206.451066.120960@h76g2000cwa.googlegroups.com> Message-ID: "astyonax" wrote in message news:1149753206.451066.120960 at h76g2000cwa.googlegroups.com... > > Fredrik Lundh wrote: >> Bryan wrote: >> >> > for example, i've noticed several java developers i know >> > write python code like >> > this: >> > >> > foo_list = [...] >> > for i in range(len(foo_list)): >> > print '%d %s' % (i, foo_list[i]) >> >> which is a perfectly valid way of doing things if you're targeting older >> Python platforms as well (including Jython). >> >> > > But it's not the pythonic way. I don't think you understood what Fredrik said. It was the Python way before enumerate() builtin was added and remains the Python way if you wish to write for older versions of Python and Jython. I don't do either but respect those who do, sometimes not exactly by choice. Ultimately, the 'pythonic' way is to do something that works rather than nothing at all. Terry Jan Reedy From kewashi at gmail.com Sun Jun 11 23:48:42 2006 From: kewashi at gmail.com (KenAggie) Date: 11 Jun 2006 20:48:42 -0700 Subject: Screen Scraping for Modern Applications? In-Reply-To: <1150077617.598735.85540@h76g2000cwa.googlegroups.com> References: <1150077617.598735.85540@h76g2000cwa.googlegroups.com> Message-ID: <1150084122.201218.12840@j55g2000cwa.googlegroups.com> I just learned about a python library called BeautifulSoup in a thread responding to my Southwest Airlines script that I wrote and posted on the Python cookbook web site. I wrote my script using the provided HTMLParser class. BeautifulSoup could have saved me some time perhaps. Take a look. Feel free to browse my code for an example of how to use HTMLParser for a moderately involved project. BeautifulSoup link: http://www.crummy.com/software/BeautifulSoup/ My Southwest Boarding pass script link: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496790 Enjoy. - Ken ljr2600 at gmail.com wrote: > Hello, > > I'm very new to python and still familiarizing myself with the > language, sorry if the post seems moronic or simple. > > For a side project I'm working on I need to be able to scrape a modern > computer desktop. Is there any basic material already available to do > this? I'd rather not need to write my own to interact with hardware. > > Thanks! From jo at durchholz.org Thu Jun 22 15:51:37 2006 From: jo at durchholz.org (Joachim Durchholz) Date: Thu, 22 Jun 2006 21:51:37 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: <1150904475.363283.234730@y41g2000cwy.googlegroups.com> References: <7zpshbsvjy.fsf@app-1.diku.dk><4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <1150809118.677124.142230@u72g2000cwu.googlegroups.com> <1150815461.210286.53120@r2g2000cwb.googlegroups.com> <1150823297.816352.75370@u72g2000cwu.googlegroups.com> <7zzmg6amm1.fsf@app-3.diku.dk> <1150904475.363283.234730@y41g2000cwy.googlegroups.com> Message-ID: Marshall schrieb: > immutable = can't change > vary-able = can change > > Clearly a contradiction in terms. Not in mathematics. The understanding there is that a "variable" varies - not over time, but according to the whim of the usage. (E.g. if a function is displayed in a graph, the parameter varies along the X axis. If it's used within a term, the parameter varies depending on how it's used. Etc.) Similarly for computer programs. Of course, if values are immutable, the value associated with a parameter name cannot vary within the same invocation - but it can still vary from one invocation to the next. Regards, Jo From cvanarsdall at mvista.com Mon Jun 12 14:12:17 2006 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Mon, 12 Jun 2006 11:12:17 -0700 Subject: Advanced lockfiles In-Reply-To: <448DABC1.9030801@ilm.com> References: <448DABC1.9030801@ilm.com> Message-ID: <448DAE81.7060206@mvista.com> David Hirschfield wrote: > I want some kind of lockfile implementation that will allow one process > to lock a file (or create an appropriately named lockfile that other > processes will find and understand the meaning of), but there are some > important requirements: > > 1. Multiple processes will be attempting to grab a lock on the file, and > they must not freeze up if they can't get a lock > 2. The processes can be on different hosts on a network, attempting to > grab a lock on a file somewhere in network storage > 3. All processes involved will know about the locking system, so no need > to worry about rogue processes that don't care about whatever setup we have > 4. The locking process has to be "crash safe" such that if the process > that locked a file dies, the lock is released quickly, or other > processes can find out if the lock is held by a dead process and force a > release > > I've tried a bunch of ideas, looked online, and still don't have a good > way to make a system that meets all the requirements above, but I'm not > too well-read on this kind of synchronicity problem. > It just so turns out I had to do a project with similar requirements. In our environment we had a common file available to 70 machines via NFS. We wanted to make sure that only a single machine at a time could access this file. So we did this using a combination of a couple technologies(this is in linux btw): 1. fcntl system calls - these are the calls to do the locking 2. rpc/lockd - this handles our locking over nfs there is an fcntl that you can import from the python standard library. I found that I couldn't get these to work with my existing system setup and eventually gave up on them. What I ended up doing what writing a C extension, this allows for blocking and non-blocking calls to get a lock on a file. Another thing I had a problem with was in order to lock the file a python program had to open a pointer to it to test for the lock. After having multiple processes on 80 machines do this I ran into problems where the shell complained about too many open files. I attempted to solve this by having the module open the file when its loaded and close it when its unloaded. Maybe not the right way, but I haven't had the problem come up since. I also don't know much about lockd, that was installed by another member of my team but I'm sure you can find good information on google This wasn't written to be the omni-solution but a solution to my problem. Here's the module: #include "Python.h" #include #include #include #include /*Globals*/ int fp; /*Both functions need access to this but we can't open and close the file within the boundries of any /single function, this will be opened once by the module initializer */ /*getLock() will make fnctl calls to do nonblocking or blocking locks depending on the arguements passed*/ static PyObject * lock_getLock(PyObject *self, PyObject *args) { int blockingCall, retVal; struct flock myLock; if (!PyArg_ParseTuple(args,"i", &blockingCall)) { return NULL; /*NULL indicating arg failure*/ } if(fp < 0) { perror("Error Opening lock file, check initialization functions"); /*insert sys.exit(1) python call here*/ } /*populate mylock*/ myLock.l_type = F_WRLCK; myLock.l_whence = SEEK_SET; myLock.l_start = 0; myLock.l_len = 0; myLock.l_pid = 0; if(blockingCall) { /*It turns out python is incredibly sensitive, in order to make these blocking functions play well*/ /*With threading in python, we need some happy macros*/ Py_BEGIN_ALLOW_THREADS /*release global interpreter lock*/ retVal = fcntl(fp,F_SETLKW,&myLock); Py_END_ALLOW_THREADS /*aquire global interpreter lock*/ return Py_BuildValue("i", retVal); } else /*non blocking call*/ { retVal = fcntl(fp,F_SETLK,&myLock); return Py_BuildValue("i", retVal); } } /*releaseLock() will release any lock on a file*/ static PyObject * lock_releaseLock(PyObject *self, PyObject *args) { int retVal; struct flock myflock; if(fp < 0) { perror("Error with File Pointer, there is a problem in the initialization of this module"); return Py_BuildValue("i",-1); } myflock.l_type = F_UNLCK; myflock.l_whence = SEEK_SET; myflock.l_start = 0; myflock.l_len = 0; myflock.l_pid = 0; retVal=fcntl(fp,F_SETLK,&myflock); return Py_BuildValue("i", retVal); } static PyMethodDef lock_methods[] = { {"getLock", lock_getLock, METH_VARARGS, "calls fcntl to get a lock on lockfile"}, {"releaseLock", lock_releaseLock, METH_VARARGS, "releases lock on lockfile"}, {NULL, NULL} }; /*Close the file to be neat about things*/ void cleanupModule(void) { close(fp); } /*Init function that python needs to load this as a module*/ void initlock() { fp = open("/home/build/bin/resourceManager/lock", O_RDWR); (void) Py_InitModule("lock", lock_methods); Py_AtExit((void*)cleanupModule); } -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From invalidemail at aerojockey.com Fri Jun 9 20:08:42 2006 From: invalidemail at aerojockey.com (Carl Banks) Date: 9 Jun 2006 17:08:42 -0700 Subject: os.link makes a copy, not a link In-Reply-To: References: Message-ID: <1149898122.054522.96910@y43g2000cwc.googlegroups.com> Dan M wrote: > I'm a little bit confused. According to the sources I've looked at on the > net, > os.link('file1', 'file2') > should make a hard link from file1 to file2. But what I'm finding is that > it's actually making a copy. Am I forgetting a step or something? > > Python 2.3.4 running on CentOS 4.3 Are file1 and file2 on the same filesystem? Looks like os.link just calls the OS's link system call, which, for your system, might copy the file. Carl Banks From cdsmith at twu.net Wed Jun 21 14:34:37 2006 From: cdsmith at twu.net (Chris Smith) Date: Wed, 21 Jun 2006 12:34:37 -0600 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150902275.129780.50260@p79g2000cwp.googlegroups.com> Message-ID: Marshall wrote: > I think what this highlights is the fact that our existing terminology > is not up to the task of representing all the possible design > choices we could make. Some parts of dynamic vs. static > a mutually exclusive; some parts are orthogonal. Really? I can see that in a strong enough static type system, many dynamic typing features would become unobservable and therefore would be pragmatically excluded from any probable implementations... but I don't see any other kind of mutual exclusion between the two. -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation From gdiaczok at verizon.net Thu Jun 8 22:12:45 2006 From: gdiaczok at verizon.net (gregory diaczok) Date: Fri, 09 Jun 2006 02:12:45 GMT Subject: UltraEdit and Python Message-ID: How do I sent up Ultra Edit to work w/ Python? How do I get Ultra Edit to run a Python script currently in the edit window and supply results? I can't figure out how to get Ultra Edit to invoke the Python debugger to allow stepping through a Python script and view each line reults? How do I set pause / break points in Ultra Edit for a Python script? -- Thanks, Greg gdiaczok at verizon.net From marshall.spight at gmail.com Thu Jun 22 21:40:56 2006 From: marshall.spight at gmail.com (Marshall) Date: 22 Jun 2006 18:40:56 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: <1150998222.352746.65520@i40g2000cwc.googlegroups.com> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150998222.352746.65520@i40g2000cwc.googlegroups.com> Message-ID: <1151026856.064429.36460@c74g2000cwc.googlegroups.com> Joe Marshall wrote: > > That's the important point: I want to run broken code. I want to make sure I understand. I can think of several things you might mean by this. It could be: 1) I want to run my program, even though I know parts of it are broken, because I think there are parts that are not broken and I want to try them out. 2) I want to run my program, even though it is broken, and I want to run right up to a broken part and trap there, so I can use the runtime facilities of the language to inspect what's going on. > I want to run > as much of the working fragments as I can, and I want a `safety net' to > prevent me from performing undefined operations, but I want the safety > net to catch me at the *last* possible moment. This statement is interesting, because the conventional wisdom (at least as I'm used to hearing it) is that it is best to catch bugs at the *first* possible moment. But I think maybe we're talking about different continua here. The last last last possible moment is after the software has shipped to the customer, and I'm pretty sure that's not what you mean. I think maybe you mean something more like 2) above. Marshall From cfc at shell01.TheWorld.com Tue Jun 27 00:37:05 2006 From: cfc at shell01.TheWorld.com (Chris F Clark) Date: 27 Jun 2006 00:37:05 -0400 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> Message-ID: I wrote: > The important thing is the dynamicism of lisp allowed one to write > polymorphic programs, before most of us knew the term. Chris Smith writes: > Sure. In exchange for giving up the proofs of the type checker, you > could write all kinds of programs. To this day, we continue to write > programs in languages with dynamic checking features because we don't > have powerful enough type systems to express the corresponding type > system. And to me the question is what kinds of types apply to these dynamic programs, where in fact you may have to solve the halting problem to know exactly when some statement is executed. I expect that some programs have type signatures that exceed the expressibility of any static system (that is Turing complete). Therefore, we need something that "computes" the appropriate type at run-time, because we need full Turing power to compute it. To me such a system is a "dynamic type system". I think dynamic tags are a good approximation, because they only compute what type the expression has this time. > I believe that, in fact, it would be trivial to imagine a type system > which is capable of expressing that type. Okay, not trivial, since it > appears to be necessary to conceive of an infinite family of integer > types with only one value each, along with range types, and > relationships between them; but it's probably not completely beyond the > ability of a very bright 12-year-old who has someone to describe the > problem thoroughly and help her with the notation. Well, it look like you are right in that I see following is a Haskell program that looks essentially correct. I wanted something that was simple enough that one could see that it could be computed, but which was complex enough that it had to be computed (and couldn't be statically expressed with a system that did no "type computations"). Perhaps, there is no such beast. Or, perhaps I just can't formulate it. Or, perhaps we have static type checkers which can do computations of unbounded complexity. However, I thought that one of the characteristics of type systems was that they did not allow unbounded complexity and weren't Turing Complete. > You would, of course, need a suitable type system first. For example, > it appears to me that there is simply no possible way of expressing what > you've described in Java, even with the new generics features. Perhaps > it's possible in ML or Haskell (I don't know). My point is that if you > were allowed to design a type system to meet your needs, I bet you could > do it. Or, I could do as I think the dynamic programmers do, dispense with trying to formulate a sufficiently general type system and just check the tags at the appropriate points. > Sure. The important question, then, is whether there exists any program > bug that can't be formulated as a type error. If you allow Turing Complete type systems, then I would say no--every bug can be reforumlated as a type error. If you require your type system to be less powerful, then some bugs must escape it. -Chris From cdsmith at twu.net Thu Jun 22 17:08:39 2006 From: cdsmith at twu.net (Chris Smith) Date: Thu, 22 Jun 2006 15:08:39 -0600 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> Message-ID: Claudio Grondi wrote: > Looking this thread growing it appears to me, that at least one thing > becomes evident here: > > Xah unwillingness to learn from the bad past experience contaminates > others (who are still posting to his trolling threads). > > Here another try to rescue these ones who are just virgin enough not to > know what I am speaking about: I am enjoying the discussion. I think several other people are, too. (At least, I hope so!) It matters not one whit to me who started the thread, or the merits of the originating post. Why does it matter to you? -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation From johnjsal at NOSPAMgmail.com Tue Jun 13 16:09:12 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 13 Jun 2006 20:09:12 GMT Subject: wxpython: bringing up a dialog box with a button Message-ID: I'm not exactly sure how to call the method ShowModal(). This is what I have so far: -------------- import wx class InputForm(wx.Frame): def __init__(self, parent=None, id=wx.ID_ANY, title=''): wx.Frame.__init__(self, parent, id, title) panel = wx.Panel(self) btnModal = wx.Button(panel, -1, 'Modal') dialog = wx.Dialog(self, -1, 'Modal Dialog') self.Bind(wx.EVT_BUTTON, dialog.ShowModal, btnModal) class MyApp(wx.App): def OnInit(self): frame = InputForm(title='Data Entry Form') self.SetTopWindow(frame) frame.Show() return True app = MyApp(redirect=False) app.MainLoop() --------------------- and this is what I get: >>> Traceback (most recent call last): File "C:\Python24\Lib\site-packages\wx-2.6-msw-ansi\wx\_windows.py", line 688, in ShowModal return _windows_.Dialog_ShowModal(*args, **kwargs) TypeError: Dialog_ShowModal() takes exactly 1 argument (2 given) >>> Hope someone can correct me here! From khemkaamit at gmail.com Fri Jun 30 02:46:19 2006 From: khemkaamit at gmail.com (Amit Khemka) Date: Fri, 30 Jun 2006 12:16:19 +0530 Subject: Import: Multiple modules with same name Message-ID: <1360b7230606292346h224fcf8bs51818361f39b1d4e@mail.gmail.com> Hello All, I have multiple modules with same name in different directories (well I guess thats may not be a good practise, but i needed it for debugging and working with various versions). Now how do I import a module with specifying a path. Few minutes of googling suggested: import ihooks import os def my_import(filename): loader = ihooks.BasicModuleLoader() path, file = os.path.split(filename) name, ext = os.path.splitext(file) module = loader.find_module_in_dir(name, path) if not module: raise ImportError, name module = loader.load_module(name, module) return module But It looked like an overkill, Is there a more elegant and better way of doing it ? Thanks in advance, cheers, amit. -- ---- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. From John.Grayson at gdc4s.com Tue Jun 13 09:49:06 2006 From: John.Grayson at gdc4s.com (Grayson, John) Date: Tue, 13 Jun 2006 09:49:06 -0400 Subject: Making a Label that looks the same as a button. Message-ID: <8C431EC125E9924186D8BB91DC1152B70F1B7160@TNTNC4SXCH.gdc4s.com> Buttons can look like labels without the need to create another object - just remove the Command binding, set state to DISABLED and disabledforeground='same color as NORMAL'... This demonstrates how to play with button styles: import Tkinter as tk class GUI: def __init__(self): self.root = tk.Tk() self.root.title('Button Styles') for bdw in range(5): setattr(self, 'of%d' % bdw, tk.Frame(self.root, borderwidth=0)) tk.Label(getattr(self, 'of%d' % bdw), text='borderwidth = %d ' % bdw).pack(side=tk.LEFT) for relief in [tk.RAISED, tk.SUNKEN, tk.FLAT, tk.RIDGE, tk.GROOVE, tk.SOLID]: tk.Button(getattr(self, 'of%d' % bdw), text=relief, borderwidth=bdw, relief=relief, width=10, command=lambda s=self, r=relief, b=bdw: s.prt(r,b))\ .pack(side=tk.LEFT, padx=7-bdw, pady=7-bdw) getattr(self, 'of%d' % bdw).pack() def prt(self, relief, border): print '%s:%d' % (relief, border) myGUI = GUI() myGUI.root.mainloop() John Grayson -----Original Message----- From: python-list-bounces+john.grayson=gdc4s.com at python.org [mailto:python-list-bounces+john.grayson=gdc4s.com at python.org] On Behalf Of Dustan Sent: Tuesday, June 13, 2006 9:14 AM To: python-list at python.org Subject: Making a Label that looks the same as a button. I have a Button object that gets replaced by a Label when clicked. Button(buttonsframe,text=' ',command=c,font=buttonsFont) Note that the text is a single space. buttonsFont uses 'Courier New' as a family. When clicked, the Button is destroyed and replaced with a Label object: Label(buttonsframe,text=x,font=buttonsFont,relief=RAISED) The intent is for the Label object to look identical to the button object, except for the non-space character x. The Label object is a little smaller than the Button object. When I set borderwidth, the label object does increase in size, but that's not going to make it look the same, since it makes the border thicker. How do I get the Label object to look just like the Button object? -- http://mail.python.org/mailman/listinfo/python-list From paddy3118 at netscape.net Sun Jun 18 16:30:55 2006 From: paddy3118 at netscape.net (Paddy) Date: 18 Jun 2006 13:30:55 -0700 Subject: Seeking regex optimizer In-Reply-To: <1150650439.651839.38180@y41g2000cwy.googlegroups.com> References: <1150650439.651839.38180@y41g2000cwy.googlegroups.com> Message-ID: <1150662655.541745.174430@u72g2000cwu.googlegroups.com> Kay Schluehr wrote: > I have a list of strings ls = [s_1,s_2,...,s_n] and want to create a > regular expression sx from it, such that sx.match(s) yields a SRE_Match > object when s starts with an s_i for one i in [0,...,n]. There might > be relations between those strings: s_k.startswith(s_1) -> True or > s_k.endswith(s_1) -> True. An extreme case would be ls = ['a', 'aa', > ...,'aaaa...ab']. For this reason SRE_Match should provide the longest > possible match. > > Is there a Python module able to create an optimized regex rx from ls > for the given constraints? > > Regards, > Kay A start would be: regexp = "^(" + "|".join(sorted(ls, reverse=True)) + ")" But the above does not work if you have special characters in your strings. You say you want something that is optimised. What have have you tried? - Pad. From alexreinhart at satx.rr.com Tue Jun 13 18:36:12 2006 From: alexreinhart at satx.rr.com (Alex Reinhart) Date: Tue, 13 Jun 2006 22:36:12 GMT Subject: [OT] Re: Python open proxy honeypot In-Reply-To: <1150236597.152868.250740@y43g2000cwc.googlegroups.com> References: <1150236597.152868.250740@y43g2000cwc.googlegroups.com> Message-ID: Serge Orlov wrote: > IMHO it's pretty useless, spammers are starting to use botnets, and the > more you make inconvenient to them use open proxies, the more of them > will move to closed botnets. As long as I inconvenience them, or at least catch one or two, I'll be satisfied. > My spam folder at gmail is not growing anymore for many months (it is > about 600-700 spams a month). Have spammers given up spamming gmail.com > only or is it global trend? > I get several spam mails a day at gmail.com. From rschroev_nospam_ml at fastmail.fm Wed Jun 28 12:46:31 2006 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Wed, 28 Jun 2006 16:46:31 GMT Subject: Immutability In-Reply-To: References: <4Qj*cEjkr@news.chiark.greenend.org.uk> Message-ID: Nick Maclaren schreef: > > Most especially since it isn't working very well for me, and I am trying > to track down why. When I run: > class fred : > @property > def joe (self) : > print "Inside /joe\n" > > a = fred() > a.joe() > > I get: > > Inside joe > > Traceback (most recent call last): > File "crap.py", line 14, in > a.joe() > TypeError: 'NoneType' object is not callable Since joe is a property, you shouldn't access it as a method. This works: a = fred() a.joe Inside joe If you call it as a function, first the function is executed (printing "Inside joe"), but then Python tries to call the return value of the function, which is None. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From fredrik at pythonware.com Thu Jun 29 17:02:09 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 29 Jun 2006 23:02:09 +0200 Subject: Problem with sets and Unicode strings In-Reply-To: <44a427c0$1@news.uni-ulm.de> References: <44a17d05$1@news.uni-ulm.de> <44a19d55$2@news.uni-ulm.de> <44a2b2cc$2@news.uni-ulm.de> <4gfr58F1mijo5U2@uni-berlin.de> <44a41e06$1@news.uni-ulm.de> <44a427c0$1@news.uni-ulm.de> Message-ID: Dennis Benzinger wrote: >>> shadows the error of not setting sys.defaultencoding()? >> >> You can't set the default encoding. If you could, then scripts that run >> on your machine wouldn't run on mine. >> [...] > > As Serge Orlov wrote in one of his posts you _can_ set the default > encoding (at least in site.py). See > yes, but you're not supposed to do that, for several reasons, including the reasons Robert provided: if you mess with the interpreter defaults, code you write isn't portable, and code written by others may not work on your machine. the interpreter isn't fully encoding agnostic either; things are not guaranteed to work properly if you're not using the default. From ldo at geek-central.gen.new_zealand Thu Jun 29 05:30:40 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 29 Jun 2006 21:30:40 +1200 Subject: Execute Commands on Remote Computers over Network References: <1151378614.481850.271340@c74g2000cwc.googlegroups.com> <1151443795.343874.290790@u72g2000cwu.googlegroups.com> Message-ID: In article <1151443795.343874.290790 at u72g2000cwu.googlegroups.com>, "dylpkls91" wrote: >Lawrence D'Oliveiro wrote: >> In article <1151378614.481850.271340 at c74g2000cwc.googlegroups.com>, >> "dylpkls91" wrote: >> >> >I have been researching this topic and come up with some code to make >> >it work. It uses SSL and requires the 3rd party package Paramiko (which >> >requires PyCrypto). >> >> Why not just spawn an invocation of SSH? > >Can you explain what this means, and how I could do it in Python? SSH is the standard means of remotely executing commands on one *nix system from another . It is included with all self-respecting *nix systems these days. You can set up a trust relationship between particular accounts on two systems, so one can connect to the other without a password. All communication is encrypted to lock out eavesdroppers. From felipe.lessa at gmail.com Fri Jun 2 17:13:56 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Fri, 02 Jun 2006 18:13:56 -0300 Subject: Open Source Charting Tool In-Reply-To: References: <1L0gg.1841$Su3.159041@news20.bellglobal.com> Message-ID: <1149282836.4189.5.camel@kenshin.CASA> Em Sex, 2006-06-02 ?s 16:56 -0400, A.M escreveu: > I can't browse to www.reporlab.org, but I found http://www.reportlab.com/ > which has a commercial charting product. Is that what you referring to? ReportLab (the commercial bussiness thing on .com) is where the main developers of ReportLab (a library freely available on www.reporlab.org) work. So what you want really is .org, but apparently it's having problems right now. -- Felipe. From jim.lewis at miclog.com Sat Jun 3 14:56:23 2006 From: jim.lewis at miclog.com (Jim Lewis) Date: 3 Jun 2006 11:56:23 -0700 Subject: Pyrex list/array Message-ID: <1149360983.373137.200740@i39g2000cwa.googlegroups.com> I'm trying to move a function into pyrex for speed. The python side needs to pass a list to the pyrex function. Do I need to convert to array or something so pyrex can generate tight code? I'm not clear how to do this. From sonja.coussell at gmail.com Wed Jun 21 12:38:42 2006 From: sonja.coussell at gmail.com (sonjaa) Date: 21 Jun 2006 09:38:42 -0700 Subject: Update on Memory problem with NumPy arrays Message-ID: <1150907922.908497.120310@u72g2000cwu.googlegroups.com> Hi last week I posted a problem with running out of memory when changing values in NumPy arrays. Since then I have tried many different approaches and work-arounds but to no avail. I was able to reduce the code (see below) to its smallest size and still have the problem, albeit at a slower rate. The problem appears to come from changing values in the array. Does this create another reference to the array, which can't be released? Also, are there other python methods/extensions that can create multi-deminsional arrays? thanks again to those who repsonded to the last post Sonja PS. to watch the memory usage I just used task manager the code: from numpy import * y = ones((501,501)) z = zeros((501,501)) it = 50 for kk in xrange(it): y[1,1] = 4 y[1,2] = 4 y[1,0] = 4 y[2,1] = 6 print "Iteration #:%s" %(kk) for ee in xrange(0,501): for ff in xrange(0,501): if y[ee,ff] == 4 or y[ee,ff] == 6: y[ee,ff] = 2 else: pass From martin at v.loewis.de Fri Jun 16 19:48:09 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 17 Jun 2006 01:48:09 +0200 Subject: msvcr71.dll necessary? - Re: Which compiler will Python 2.5 / Windows (Intel) be built with? In-Reply-To: References: <1150367139.495114.148550@g10g2000cwb.googlegroups.com> Message-ID: <44934339$0$28177$9b622d9e@news.freenet.de> robert wrote: > For me the great great problem with Python2.4's lib geometry was that > the size of distributable app installers swelled suddenly by many megs > with msvcr71.dll and mfc71 and codecs in core and all. codecs are in python24.dll, mscvr71, mfc71 and all are not. However, they are not in core - the operating system demand-pages code, loading into core memory only what is being used. So if you don't use the codecs, they are not loaded into core. While mscvr71 is likely loaded into core (even though it is not in python24.dll), mfc71.dll does not play a role at all in Python 2.4. Python is written entire in C, not in C++. > * Is there a fundamental reason that the C-RTL of VC6 (which is > pre-installed on on all Windows today) is not sufficient for current > Python and extensions? instable? The compiler that is used (VS 2003) won't ship it, and links with msvcr71.dll. That's why that library version is used. > In case not: As the short living VS 2003 compiler is now more rare than > the good old VC6, wouldn't it be better to switch back to VC6 for Py2.5 > or at least to VC6 libs (which are maybe "free" of dev-license as they > sit on each Windows). Better in what respect? Predictability of software development? Certainly not: the development will be more predictable if a decision that was once taken is implemented as promised. Making more users happy? Certainly not, either. Some users request that VS2005 is being used, not that VC6 is being used. Other users request that Python 2.5 continues to be built with VS 2003. You can't please everybody. > Maybe a suitable policy: the default crtl for Python should better be > the default library of the OS and not that of a random compiler which is > currently hip? That would make a good policy if the OS had a system C library. Windows doesn't. Windows NT does have a CRT, namely crtdll.dll - but you weren't suggesting to use that one, were you? > * can't the Mingw/gcc be used together with Windows default crt/mfc libs > for Python2.5 ? - Python getting away the from this MS studio (lib) > harassment? Sure, you can use gcc/mingw to build extensions for Python 2.4 and Python 2.5. > * how many (serious) python users require to build distributable > installers (which have carry the python-rtls and non-default crtl's)? Apparently not many. I repeatedly asked for contribution of a specification how pythonxy.dll should be modularized, and never received one. Regards, Martin From bdesth.quelquechose at free.quelquepart.fr Tue Jun 20 19:01:31 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 21 Jun 2006 01:01:31 +0200 Subject: __getattribute__ doesn't work on 'type' type for '__class__' In-Reply-To: <8k8g92tgqmhu70au13od2fn1ihut04sr0o@4ax.com> References: <8k8g92tgqmhu70au13od2fn1ihut04sr0o@4ax.com> Message-ID: <44984e3a$0$11196$636a55ce@news.free.fr> Barry Kelly a ?crit : > I'm running this version of Python: > > Python 2.4.3 (#1, May 18 2006, 07:40:45) > [GCC 3.3.3 (cygwin special)] on cygwin > > I read in the documentation that these two expressions are > interchangeable: > > x.__getattribute__('name') <==> x.name I wouldn't say they are interchangeable. FWIW, __getattribute__ starts and ends with two underscores which in Python - and a lot of other languages - has a very strong 'language internals, black magic stuff, not intented for direct client code use'. > > Yet when I try this with the 'type' type, it doesn't work: > > ---8<--- > >>>>x.__class__.__class__ > > > >>>>x.__class__.__getattribute__('__class__') You're calling __getattribute__ on x.__class__, not on x.__class__.__class__. But anyway, __getattribute__ is a descriptor, which implies different behaviour when called on a class object. Please read the doc on the descriptor protocol. For making long things short, instance.__getattribute__('attrname') translates to klass.__getattribute__(instance, 'attrname') > Traceback (most recent call last): > File "", line 1, in ? > TypeError: descriptor '__getattribute__' requires a 'int' object but > received a 'str' I deduce from this that your 'x' is an int. Since you're calling __getattribute__ on the type 'int', you have to pass an int as the first parameter, ie: >>> x = 1 >>> x.__class__.__getattribute__(x, '__class__') Note BTW that it returns x.__class__, not x.__class__.__class__ From bj_666 at gmx.net Wed Jun 21 07:55:26 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 21 Jun 2006 13:55:26 +0200 Subject: help() on stdout.closed References: Message-ID: In , Pekka Karjalainen wrote: > Suppose I had no idea what sys.stdout.closed was and wanted to find out. > Where would I look it up? `sys.stdout` is a file (like) object: http://docs.python.org/lib/bltin-file-objects.html Ciao, Marc 'BlackJack' Rintsch From rogue_pedro at yahoo.com Fri Jun 30 01:46:29 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 29 Jun 2006 22:46:29 -0700 Subject: How to get indices of a two dimensional list References: <1151639976.664310.183620@x69g2000cwx.googlegroups.com> Message-ID: <1151646389.108201.65940@75g2000cwc.googlegroups.com> sramaswamy at gmail.com wrote: > I have a list > > x = [0] * 2 > x = x * [2] You're certainly not doing that. >>> x = [0] * 2 >>> x = x * [2] Traceback (most recent call last): File "", line 1, in ? TypeError: can't multiply sequence by non-int And even if you *do* do what it looks like you think you want to do >>> x = [[0] * 2] * 2 >>> x [[0, 0], [0, 0]] ..you don't get what you think you'd get.. So, let's say you do this >>> x[1][1] = 7 >>> x [[0, 7], [0, 7], [0, 7], [0, 7]] .. still not what you thought >>> x = [[0] * 2] * 4 >>> x [[0, 0], [0, 0], [0, 0], [0, 0]] > x[1,1] = 7 > > This gives me the x value > [[0,0] [0,0] [0,0] [0,7]] > > I want to get the indices of the value 7. > i.e. something like > i = a.index(max(a)) gives me '1' > > This only gives me the index in one dimension. Is there any method by > which I can get (1,1) as the answer. When you sort out what you're actually trying to do, the answer to your question may be in this thread: http://groups.google.ca/group/comp.lang.python/browse_frm/thread/2f82408e1bcaa02e/27925504b2a4eb4a > > Thanks in advance. Hope this helps, ~Simon From esj at harvee.org Wed Jun 21 09:21:24 2006 From: esj at harvee.org (Eric S. Johansson) Date: Wed, 21 Jun 2006 09:21:24 -0400 Subject: need all python dialog equivalent In-Reply-To: <1150866055.048937.217350@b68g2000cwa.googlegroups.com> References: <1150866055.048937.217350@b68g2000cwa.googlegroups.com> Message-ID: <449947D4.3080007@harvee.org> Miki wrote: > Hello Eric, > >> Is there anything like an all Python dialog equivalent floating around? > http://www.pythonware.com/library/tkinter/introduction/ I'm sorry. I should have been more explicit. I need a textbased interface such as the ones you would get with curses and dialogue. ---eric From tjreedy at udel.edu Sat Jun 3 19:25:26 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 3 Jun 2006 19:25:26 -0400 Subject: An oddity in list comparison and element assignment References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com><1hg8ug8.m01zhwehpk66N%aleax@mac.com><1149177617.985251.74560@c74g2000cwc.googlegroups.com><1hg9nl6.xivwcd7n0j5N%aleax@mac.com><1149277242.199765.213600@g10g2000cwb.googlegroups.com> <1hgbjx1.1gn7haipx7x5N%aleax@mac.com> Message-ID: "Alex Martelli" wrote in message news:1hgbjx1.1gn7haipx7x5N%aleax at mac.com... > Terry Reedy wrote: > >> wrote in message >> news:1149277242.199765.213600 at g10g2000cwb.googlegroups.com... >> > (As an aside, may I point out that Python In A Nutshell states on page >> > 46 "The result of S*n or n*S is the concatenation of n copies of S". Alex, in responding to this sentence lifted out of context by Michael, I am responding more to him and his claim of 'not strictly the case' than to you. What I wrote is also more a draft of a paragraph for a book of mine (of no competition to yours) than a suggestion for a future edition of your book. >> It would be more exact to say that S*n is [] extended with S n times, A**b is often explained as 'A multiplied by itself b times' or some such. It is more exact to say it is '1 multiplied by A b times' >> which makes it clear that 0*S == S*0 == [] which makes it clear that A**0, including 0**0, is 1. >> and which avoids the apparently misleading word 'copy'. Given the number of people, including Michael, who have posted puzzlement based on their confusion as to what does and does not get copied, I don't think it unfair to call 'copy' 'apparently misleading. My intention in this phrase is to suggest that one who misunderstands 'copy' in this context will be mislead while one who understands just what is copied and what is not copied will not. The point of my code snippet was to explain/illustrate what is copied. While it will (obviously) only executive as Python code for lists, I believe the algorithm is generic if the initial assignment and list.extend method are suitably interpreted. Of course, I presume that in the CPython code, the actual initialization is more like (length one blank value) * (n*len(S)) followed by n slice assignments, but the Python code for this would still be list specific and would also be more complex, without much aiding comprehension of the result. Strings are a somewhat special case since the characters in the string are not wrapped as Python objects unless and until extracted from the string. So one cannot as easily talk about the object(s) contained in the sequence. > Considering that the very next (and final) sentence in that same > paragraph is "If n is zero or less than zero, the result is an empty > sequence of the same type as S", I don't think there's anything > misleading in the quoted sentence. In its original context, with respect to that issue, no. But as I said, I was responding to Michael's removed-from-context quotation and his claim about the need for a warning. I wonder if you read down to the end, where I asked him whether I had missed anything he might find fault with, before you responded. > Moreover, since the paragraph is about sequences, not just lists, This *thread* is about repetition of lists, and in particular, a list of one (or more) lists, and the consequences of the mutability of the inner lists, and that is the context in which I wrote. > it *WOULD* be horribly wrong to use the phrasing you suggest: In a generic context, [] would obviously have to be replaced by 'null sequence of the type of S', which in many cases is type(S)(). And 'extend' would have to be interpreted generically, as something the interpreter would do behind the scenes in type(S). __new__, although as I said before, I don't think that is exactly what it does do. >"bah!"*3 is NOT a list, Duh., > it's EXACTLY the > concatenation of three copies of that string -- no more, no less. Depends what one means by 'copy'. See below for your alternate wording. >> Or one could say that the result *is the same as* (not *is*) the > > I find this distinction, in this context, to be empty padding, with zero > added value on ANY plane -- including the plane of "pedantry";-). Perhaps you should tone down the overwrought emotionalism and take a look in a mirror. In *your* response to Michael you made the *same* distinction: >> Can you give me an example where, say, for a sequence S, >> x = S * 3 >> is not structurally the same as >> x = copy.copy(S) + copy.copy(S) + copy.copy(S) I agree that adding 'structurally' makes the 'padding' even better. >> concatenation of n *shallow* copies of S. 'Shallow' means that each >> copy > I do not think it would be good to introduce the concept of "shallow" at > a point in the text which is talking about ALL sequences -- including > ones, such as strings, for which it just does not apply. Again, I was not suggesting that you do so. Adding 'shallow' was intentially pedantic for Michael's 'benefit'. To be clear, I was *NOT* supporting his warning suggestion. > But, thanks for the suggestions, anyway! We both have the goal of expaining Python better so beginners hit fewer bumps on the road. Terry Jan Reedy From junkytownMAKNI at gmail.com Mon Jun 5 13:35:08 2006 From: junkytownMAKNI at gmail.com (SuperHik) Date: Mon, 05 Jun 2006 19:35:08 +0200 Subject: re beginner In-Reply-To: References: Message-ID: WOW! Thanks for all the answers, even those not related to regular expressions tought me some stuff I wasn't aware of. I appreciate it very much. SuperHik wrote: > hi all, > > I'm trying to understand regex for the first time, and it would be very > helpful to get an example. I have an old(er) script with the following > task - takes a string I copy-pasted and wich always has the same format: > > >>> print stuff > Yellow hat 2 Blue shirt 1 > White socks 4 Green pants 1 > Blue bag 4 Nice perfume 3 > Wrist watch 7 Mobile phone 4 > Wireless cord! 2 Building tools 3 > One for the money 7 Two for the show 4 > > >>> stuff > 'Yellow hat\t2\tBlue shirt\t1\nWhite socks\t4\tGreen pants\t1\nBlue > bag\t4\tNice perfume\t3\nWrist watch\t7\tMobile phone\t4\nWireless > cord!\t2\tBuilding tools\t3\nOne for the money\t7\tTwo for the show\t4' > > I want to put items from stuff into a dict like this: > >>> print mydict > {'Wireless cord!': 2, 'Green pants': 1, 'Blue shirt': 1, 'White socks': > 4, 'Mobile phone': 4, 'Two for the show': 4, 'One for the money': 7, > 'Blue bag': 4, 'Wrist watch': 7, 'Nice perfume': 3, 'Yellow hat': 2, > 'Building tools': 3} > > Here's how I did it: > >>> def putindict(items): > ... items = items.replace('\n', '\t') > ... items = items.split('\t') > ... d = {} > ... for x in xrange( len(items) ): > ... if not items[x].isdigit(): d[items[x]] = int(items[x+1]) > ... return d > >>> > >>> mydict = putindict(stuff) > > > I was wondering is there a better way to do it using re module? > perheps even avoiding this for loop? > > thanks! From paddy3118 at netscape.net Sun Jun 18 18:45:59 2006 From: paddy3118 at netscape.net (Paddy) Date: 18 Jun 2006 15:45:59 -0700 Subject: Seeking regex optimizer References: <1150650439.651839.38180@y41g2000cwy.googlegroups.com> <1150662655.541745.174430@u72g2000cwu.googlegroups.com> <1150664973.879328.228330@y41g2000cwy.googlegroups.com> Message-ID: <1150670758.936932.98720@i40g2000cwc.googlegroups.com> Kay Schluehr wrote: > with reverse sorting as in your proposal.The naive solution is easy to > generate but I'm sceptical about its cost effectiveness. On the other > hand I do not want to investigate this matter if somebody else already > did it thoroughly. > > Regards, > Kay Hi Kay, The only way to know if something is optimised enough, is for you to test it in your application. If you haven't finished your application, then don't sweat it. take a note of your options, stick one in, then get the application finished. Its only when its finished that you can really say if further optimisations are necessary, and you would have to profile the complete prog to see where it's spending its time. I usually find myself using string methods where possible, then regular expressions only for things that string methods cannot do. When I finish my script I usually find that Pythons speed is adequate for most of my text processing tasks, or if speed IS an issue, then i needed to profile the completed application anyway. - Pad. From alanmk at hotmail.com Thu Jun 8 06:30:25 2006 From: alanmk at hotmail.com (Alan Kennedy) Date: 8 Jun 2006 03:30:25 -0700 Subject: language-x-isms References: <1149753206.451066.120960@h76g2000cwa.googlegroups.com> <1149759486.695563.110640@g10g2000cwb.googlegroups.com> <1149760633.796809.166430@h76g2000cwa.googlegroups.com> Message-ID: <1149762625.346302.135220@y43g2000cwc.googlegroups.com> [Alan Kennedy] > On jython 2.1, I use something like this > #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= > try: > enumerate > except NameError: > def enumerate(iterable): > results = [] ; ix = 0 > for item in iterable: > results.append( (ix, item) ) > ix = ix+1 > return results [Fredrik Lundh] >> at least in CPython, using a user-defined enumerate function is a bit >> slower than using the built-in version. [Alan Kennedy] >> Who's using a user-defined enumerate on cpython? [Fredrik Lundh] > anyone targeting older Python platforms. You mean python platforms where there is no built-in enumerate? Your comment makes "using a user-defined enumerate [on cpython] is slower than using the built-in version" makes no sense in relation to the code I posted, which only defines a user-defined enumerate *if there is no builtin enumerate*. [Alan Kennedy] >> On cpython, the reference to enumerate doesn't generate a NameError, [Fredrik Lundh] > > python > Python 2.2.3 (#42, May 30 2003, 18:12:08) > >>> enumerate > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'enumerate' is not defined Right: there is no built-in enumerate on cpython 2.2. So how could a user-defined one be slower than it? Of course, my cpython comment referred to recent cpythons, i.e. 2.3, 2.4, 2.5. The code I supplied works on all versions of python, and *never* replaces the built-in enumerate, if there is one. So what's the problem, exactly? regards, -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From digitalorganics at gmail.com Mon Jun 26 11:24:54 2006 From: digitalorganics at gmail.com (digitalorganics at gmail.com) Date: 26 Jun 2006 08:24:54 -0700 Subject: Search String for Word In-Reply-To: References: <1151332947.985001.226510@r2g2000cwb.googlegroups.com> Message-ID: <1151335494.652957.229870@m73g2000cwd.googlegroups.com> And what if I want to search for an item in a tuple, is there a similarly easy method? Tim Chase wrote: > > What's the best way to search a string for a particular word and get a > > booleen value indicating whether it exists in the string or not? > > >>> substring = 'foo' > >>> targetstring = 'blah foo bar' > >>> substring in targetstring > True > >>> if substring in targetstring: print 'yup' > yup > > http://docs.python.org/lib/typesseq.html > > -tkc From chris.uppal at metagnostic.REMOVE-THIS.org Fri Jun 23 08:11:53 2006 From: chris.uppal at metagnostic.REMOVE-THIS.org (Chris Uppal) Date: Fri, 23 Jun 2006 13:11:53 +0100 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150904134.520639.71070@b68g2000cwa.googlegroups.com> <1151030140.202720.245140@y41g2000cwy.googlegroups.com> Message-ID: <449bde5f$1$663$bed64819@news.gradwell.net> Anton van Straaten wrote: > In that case, you could say that the conceptual type is different than > the inferred static type. But most of the time, the human is reasoning > about pretty much the same types as the static types that Haskell > infers. Things would get a bit confusing otherwise. Or any mechanised or formalised type system, for any language. If a system doesn't match pretty closely with at least part of the latent type systems (in your sense) used by the programmers, then that type system is useless. (I gather that it took, or maybe is still taking, theorists a while to get to grips with the infromal type logics which were obvious to working OO programmers.) -- chris From claudio.grondi at freenet.de Fri Jun 2 10:08:25 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Fri, 02 Jun 2006 16:08:25 +0200 Subject: integer to binary... In-Reply-To: <1149197110.225383.107770@f6g2000cwb.googlegroups.com> References: <1149189570.376091.319890@j55g2000cwa.googlegroups.com> <1149197110.225383.107770@f6g2000cwb.googlegroups.com> Message-ID: mensanator at aol.com wrote: > nicolasg at gmail.com wrote: > >>does anyone know a module or something to convert numbers like integer >>to binary format ? >> >>for example I want to convert number 7 to 0111 so I can make some >>bitwise operations... >> >>Thanks > > > Use the gmpy module. > > >>>>import gmpy >>>>a = 14 >>>>b = 7 >>>>c = 8 > > >>>>help(gmpy.digits) > > Help on built-in function digits: > > digits(...) > digits(x[,base]): returns Python string representing x in the > given base (2 to 36, default 10 if omitted or 0); leading '-' > present if x<0, but no leading '+' if x>=0. x must be an mpz, > or else gets coerced into one. > > >>>>print gmpy.digits(a,2) > > 1110 > >>>>print gmpy.digits(b,2) > > 111 > >>>>print gmpy.digits(c,2) > > 1000 > > > >>>>help(gmpy.setbit) > > Help on built-in function setbit: > > setbit(...) > setbit(x,n,v=1): returns a copy of the value of x, with bit n set > to value v; n must be an ordinary Python int, >=0; v, 0 or !=0; > x must be an mpz, or else gets coerced to one. > > >>>>d = gmpy.setbit(c,1,1) >>>>print gmpy.digits(d,2) > > 1010 > > > > >>>>help(gmpy.scan1) > > Help on built-in function scan1: > > scan1(...) > scan1(x, n=0): returns the bit-index of the first 1-bit of x (that > is at least n); n must be an ordinary Python int, >=0. If no more > 1-bits are in x at or above bit-index n (which can only happen for > x>=0, notionally extended with infinite 0-bits), None is returned. > x must be an mpz, or else gets coerced to one. > > >>>>help(gmpy.scan0) > > Help on built-in function scan0: > > scan0(...) > scan0(x, n=0): returns the bit-index of the first 0-bit of x (that > is at least n); n must be an ordinary Python int, >=0. If no more > 0-bits are in x at or above bit-index n (which can only happen for > x<0, notionally extended with infinite 1-bits), None is returned. > x must be an mpz, or else gets coerced to one. > > >>>>print gmpy.scan1(a) > > 1 > >>>>print gmpy.scan1(b) > > 0 > >>>>print gmpy.scan1(c) > > 3 > >>>>print gmpy.scan1(d) > > 1 > >>>>print gmpy.scan0(a) > > 0 > >>>>print gmpy.scan0(b) > > 3 > >>>>print gmpy.scan0(c) > > 0 > >>>>print gmpy.scan0(d) > > 0 > > >>>>help(gmpy.popcount) > > Help on built-in function popcount: > > popcount(...) > popcount(x): returns the number of 1-bits set in x; note that > this is 'infinite' if x<0, and in that case, -1 is returned. > x must be an mpz, or else gets coerced to one. > > >>>>print gmpy.popcount(a) > > 3 > >>>>print gmpy.popcount(b) > > 3 > >>>>print gmpy.popcount(c) > > 1 > >>>>print gmpy.popcount(d) > > 2 > > > >>>>help(gmpy.hamdist) > > Help on built-in function hamdist: > > hamdist(...) > hamdist(x,y): returns the Hamming distance (number of bit-positions > where the bits differ) between x and y. x and y must be mpz, or > else > get coerced to mpz. > > >>>>print gmpy.hamdist(a,b) > > 2 > >>>>print gmpy.hamdist(a,c) > > 2 > >>>>print gmpy.hamdist(a,d) > > 1 > >>>>print gmpy.hamdist(b,c) > > 4 > >>>>print gmpy.hamdist(b,d) > > 3 > >>>>print gmpy.hamdist(c,d) > > 1 > For those digging deeper into this subject who are looking for speed, reading the past discussion on this newsgroup I was part of myself looking for fastest way of such integer to binary conversion can maybe be of interest: http://mail.python.org/pipermail/python-list/2006-January/319295.html (includes full source code of all compared approaches) Claudio From mscottschilling at hotmail.com Sun Jun 11 00:40:39 2006 From: mscottschilling at hotmail.com (Mike Schilling) Date: Sun, 11 Jun 2006 04:40:39 GMT Subject: Xah Lee network abuse References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148495974.975395.12920@i40g2000cwc.googlegroups.com> <1149998343.493200.144990@h76g2000cwa.googlegroups.com> Message-ID: "Mallor" wrote in message news:1149998343.493200.144990 at h76g2000cwa.googlegroups.com... > > I know I'm coming late to the barbeque. In passing, I ask: do you have > an objective, impartial perspective on the subject of committing > crimes? Because libel is a crime. It all depends on whether what you > state about Xah is provably true or not. I'm not aware of any definition of libel that includes "making statements that are not provably true". From tactics40 at gmail.com Fri Jun 30 11:33:55 2006 From: tactics40 at gmail.com (tac-tics) Date: 30 Jun 2006 08:33:55 -0700 Subject: Chapter 9 Tutorial for Classes Not Working In-Reply-To: References: Message-ID: <1151681635.648736.35170@i40g2000cwc.googlegroups.com> > x = MyClass > xf = x.f > while True: > print xf() Python has some VERY nasty gotchas concerning parenthesis (or lack there of). In the first line here, you assign x = MyClass. That means x becomes an alias for the class MyClass..... not an object like you intended. Look back at the tutorial. You simply left of the parenthesis. Another time this may cause you headaches is with functions: #!/usr/bin/python def fun(): print "Hello world!" if __name__ == "__main__": fun Run this script, and you will get no output at all. Forgetting the () on the end of "fun" on the last line makes the difference between executing the function and returning a reference to it. From kydavis77 at gmail.com Wed Jun 28 17:52:07 2006 From: kydavis77 at gmail.com (kydavis77 at gmail.com) Date: 28 Jun 2006 14:52:07 -0700 Subject: for and while loops Message-ID: <1151531527.496772.65130@i40g2000cwc.googlegroups.com> i was wondering if anyone could point me to some good reading about the for and while loops i am trying to write some programs "Exercise 1 Write a program that continually reads in numbers from the user and adds them together until the sum reaches 100. Write another program that reads 100 numbers from the user and prints out the sum. " but im not quite grasping those functions.. please bear im mind i am an extreme newbie at this...thanks in advance From nogradi at gmail.com Mon Jun 12 02:23:35 2006 From: nogradi at gmail.com (Daniel Nogradi) Date: Mon, 12 Jun 2006 08:23:35 +0200 Subject: Screen Scraping for Modern Applications? In-Reply-To: References: <1150077617.598735.85540@h76g2000cwa.googlegroups.com> <1150088989.408815.290690@c74g2000cwc.googlegroups.com> Message-ID: <5f56302b0606112323m620a6497q4d8667c1a99e2035@mail.gmail.com> > > Scrape means simply scraping pixel colors from locations on the screen. > > I'll worry about assembling it into meaningful information. > > import ImageGrab > im = ImageGrab.grab() > v = im.getpixel((x, y)) > > requires: > > http://www.pythonware.com/products/pil/ > > ## # (New in 1.1.3) The ImageGrab module can be used to copy # the contents of the screen to a PIL image memory. #

# The current version works on Windows only.

# How about doing the same on linux? From cfbolz at gmx.de Wed Jun 7 13:13:27 2006 From: cfbolz at gmx.de (Carl Friedrich Bolz) Date: Wed, 07 Jun 2006 19:13:27 +0200 Subject: Python to C converter In-Reply-To: References: <1149506038.843016.298470@c74g2000cwc.googlegroups.com> <1149513389.922653.272900@u72g2000cwu.googlegroups.com> <1149517179.095435.266060@j55g2000cwa.googlegroups.com> Message-ID: <44870937.6010708@gmx.de> Chance Ginger wrote: > If you are looking for a "real" python to C, well in this case > C++ look for the shedskin compiler. It will take a rather > nice subset of Python and generate C++ code from it. In which sense is shedskin a more "real" python to C/C++ compiler than some of the other mentioned projects? As most of the others (PyPy, Pyrex), Shedskin works only for a small number of Python programs that don't mix types too wildly. BTW: While the RPython (the subset of the Python language that PyPy can compile) might not be extremely advanced, using it gives you a number of very interesting features: like having the resulting program been enhanced to not use the C stack (for deeply recursive code), using different garbage collection strategies... Cheers, Carl Friedrich Bolz From pmartin at snakecard.com Sat Jun 3 14:21:49 2006 From: pmartin at snakecard.com (pcm) Date: Sat, 03 Jun 2006 13:21:49 -0500 Subject: Python + WinCE + serial port Message-ID: <4481d342$0$21359$636a55ce@news.free.fr> Hi, Has anyone ever worked on a Python-WinCE-based program that involved serial port management ? Regards, Philippe From aisaac at american.edu Thu Jun 29 10:50:40 2006 From: aisaac at american.edu (Alan Isaac) Date: Thu, 29 Jun 2006 10:50:40 -0400 Subject: Numeric help! References: <1151510615.139278.167520@j72g2000cwa.googlegroups.com> <1151540468.434688.242530@75g2000cwc.googlegroups.com> <1151573125.651727.322660@i40g2000cwc.googlegroups.com> Message-ID: On Thu, 29 Jun 2006 05:25:25 -0400, Sheldon wrote: > I am learning python on > my own and Numeric is not properly documented 1. Use NumPy (Numeric's successor): http://www.numpy.org/ 2. Documentation is excellent: http://www.tramy.us/ (Also see http://www.scipy.org/Cookbook ) Cheers, Alan Isaac From dnew at san.rr.com Wed Jun 21 13:07:20 2006 From: dnew at san.rr.com (Darren New) Date: Wed, 21 Jun 2006 17:07:20 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <0%Wlg.3521$MF6.947@tornado.socal.rr.com> <44992e6c$0$664$bed64819@news.gradwell.net> Message-ID: Matthias Blume wrote: > There are *tons* of languages that "actually" facilitate abstract data > types, and some of these languages are actually used by real people. I don't know of any others in actual use. Could you name a couple? Note that I don't consider things like usual OO languages (Eiffel, Smalltalk, etc) to have "abstract data types". -- Darren New / San Diego, CA, USA (PST) My Bath Fu is strong, as I have studied under the Showerin' Monks. From digitalorganics at gmail.com Mon Jun 12 10:53:04 2006 From: digitalorganics at gmail.com (digitalorganics at gmail.com) Date: 12 Jun 2006 07:53:04 -0700 Subject: Very nice python IDE (windows only) In-Reply-To: <448d5f3d$0$815$3a628fcd@textreader.nntp.hccnet.nl> References: <1149694235.741274.325200@u72g2000cwu.googlegroups.com> <1149701880.540109.10100@y43g2000cwc.googlegroups.com> <1149704292.676501.138530@h76g2000cwa.googlegroups.com> <448d5f3d$0$815$3a628fcd@textreader.nntp.hccnet.nl> Message-ID: <1150123984.819338.84330@u72g2000cwu.googlegroups.com> Jan Bijsterbosch wrote: > Hello ago, Bernard, > > "ago" schreef in bericht > news:1149704292.676501.138530 at h76g2000cwa.googlegroups.com... > > > > Bernard Lebel wrote: > >> Not me. I'll probably sound pedantic but > >> - the editor text looks awful, changing the editor options had no effect > >> at all > >> - there is no network access of UNC paths other than through File > > >> Open and Python Paths..... all of my code is on a network location > >> - expanding and collapsing directories is done with a transition > >> effect.... that drives me nuts > > > > You can certainly change the font of the editor (Tools>Options>Editor > > Options>Display>Editor Font>Font), not to be confused with the font of > > the Gutter which only changes the font inside the left bar (i.e. for > > line numbers). Admittedly there are not too many fonts to choose from. > > Furthermore the full source of the editor is available in the Delphi python > VCL components package as an example from the same site. If you're a happy > owner of Delphi, you just can change everything to your liking and > recompile...;-)) > > Greetings from sunny Amsterdam, > > Jan I happen to have delphi, so if someone wants me to make small changes, just let me know, I'll try to help.... From riteshsarraf at gmail.com Wed Jun 14 06:41:44 2006 From: riteshsarraf at gmail.com (Ritesh Raj Sarraf) Date: 14 Jun 2006 03:41:44 -0700 Subject: determining file type In-Reply-To: References: <1150276935.270798.5550@i40g2000cwc.googlegroups.com> Message-ID: <1150281704.342529.206640@u72g2000cwu.googlegroups.com> Also, f = file ('some_file.jpg') throws an error. "str object is not callable" Ritesh Maric Michaud wrote: > Le Mercredi 14 Juin 2006 11:22, Ritesh Raj Sarraf a ?crit : > > Hi, > > > > I have a funtion named unzipper() which does the work of unzipping the > > files. > > > > Is there a way I can identify what is the type of the file which'll be > > passed to unzipper(). > > If yes, I'll be able to make out if it's a zip file or a tar or a bz2 > > file. > > > Under Linux you can use the file command in a pipe. > In all cases, you use the "magic" repository of the file command directly like > this (I found the '\xff\xd8' for jpeg in /usr/share/file/magic.mime on my > debian) > > In [69]: f = file ('samurai_tux.jpg') > > In [70]: s = f.read(2) > > In [71]: s == '\xff\xd8' > Out[71]: True > > > > > > Thanks, > > Ritesh > > -- > _____________ > > Maric Michaud > _____________ > > Aristote - www.aristote.info > 3 place des tapis > 69004 Lyon > Tel: +33 426 880 097 From diffuser78 at gmail.com Sun Jun 18 17:05:28 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 18 Jun 2006 14:05:28 -0700 Subject: wxPython GUI designer In-Reply-To: References: <1150661348.837969.46870@r2g2000cwb.googlegroups.com> Message-ID: <1150664728.435902.210930@y41g2000cwy.googlegroups.com> Are there any good commercial project built with wx ? I am a newbie and a have to write a small application in Python. I was wondering which optin would be best for me in terms of least learning curve and getting the final product ASAP. Thanks DH wrote: > In my opinion none of the wx* or gtk* related designer tools are > any good. QT Designer (which can be used with pyqt) is excellent, > however, you probably would only want to use that if you are > developing non-commercial software or else can afford a commercial > license from Trolltech. For wx and gtk projects, I usually just write > the gui by hand like you have already been doing. From onurb at xiludom.gro Wed Jun 21 05:27:45 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Wed, 21 Jun 2006 11:27:45 +0200 Subject: separation events In-Reply-To: <1150870476.561722.190970@c74g2000cwc.googlegroups.com> References: <1150870476.561722.190970@c74g2000cwc.googlegroups.com> Message-ID: <44991112$0$23277$626a54ce@news.free.fr> Ghido wrote: > Hi all, i'm writing a software with python and wxpython for manage the > quality/environmental/security system for the my factory. I want to > separate the gui structure from the events and database operations for > obtain a very modular software, for this reason i start to use > sqlalchemy. Unfortunately i don't understand if is possibile to have a > file with only the gui structure and another file with the database > operations and the events of the gui. It is possibile? You may want to look for MVC (Model/View/Controller). > the use of > sqlalchemy is a good thing? > Thanks a lot > > Ghido > -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From fredrik at pythonware.com Thu Jun 29 07:16:13 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 29 Jun 2006 13:16:13 +0200 Subject: ftplib.FTP.retrbinary() hangs on completion References: Message-ID: "aum" wrote: > What happens is that after all the data comes in over the data connection, > .retrbinary() does 'return self.voidresp()'. This has a call chain ending > with 'self.file.readline()'. > > To investigate, I overrode the .getline() method with one > which replaces the self.file.readline() with a self.sock.recv(1) loop, and > determined from this that after the last byte of binary data comes in on > the data connection, not a single byte comes in on the control connection. since both sides has closed the data connection socket when you get that far, it looks like the server you're talking to is broken; see http://cr.yp.to/ftp/retr.html for details on what the server is supposed to do, and what the client can expect from the server. From grante at visi.com Fri Jun 16 00:15:00 2006 From: grante at visi.com (Grant Edwards) Date: Fri, 16 Jun 2006 04:15:00 -0000 Subject: a good programming text editor (not IDE) References: <_xgkg.2317$No6.48542@news.tufts.edu> <1150402733.116243.9680@y41g2000cwy.googlegroups.com> Message-ID: <1294c24mua53aed@corp.supernews.com> On 2006-06-15, Jarek Zgoda wrote: > You died in last century with your editor, we have tabs. My condolences. I hear there's a cure for that, though. -- Grant Edwards grante Yow! These PRESERVES at should be FORCE-FED to visi.com PENTAGON OFFICIALS!! From michele.petrazzo at TOGLIunipex.it Sat Jun 17 03:50:54 2006 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Sat, 17 Jun 2006 07:50:54 GMT Subject: Problem on win xp and run time error In-Reply-To: References: Message-ID: Fredrik Lundh wrote: >> I see that the page says: """ This problem may occur when you use >> the /GR and the /MD compiler switches """ > > hint 1: the use of "may" in that sentence is intentional. This is the only, real, answer/solution that I found on internet, so I thought that was the problem. This also convince me because the page said that this happen only on win xp sp2, that is the platform where the problem happens! All work on win2k! > > hint 2: python 2.4 wasn't built with Visual C++ 6.0 (but python 2.3 > was) > But, I have problems only on with 2.4! With 2.3, and the *same* code, all work! > hint 3: on Windows, this message is displayed when the "abort" > function is called (including when an assert fails): > > http://msdn2.microsoft.com/en-us/library/k089yyh0.aspx > > the python interpreter will call abort() when it stumbles upon a > fatal error (Py_FatalError), or when an internal assertion fails. > when this happens, the program will print a "Fatal Python error" > message to both stderr and the debug console before it calls abort. Normally py2exe catch that messages and show them when the program are closed, but in this case, I don't see any message :( Is it possible that some, but I don't know what, can be modified from py2.3 to py2.4 and now my program wont work? Is there some tried that I can do for try to solve my issue? > > > Thanks, Michele From spam.noam at gmail.com Sat Jun 10 16:00:05 2006 From: spam.noam at gmail.com (spam.noam at gmail.com) Date: 10 Jun 2006 13:00:05 -0700 Subject: Allowing zero-dimensional subscripts In-Reply-To: <1149908197.118535.199910@j55g2000cwa.googlegroups.com> References: <1149801040.936452.26270@i40g2000cwc.googlegroups.com> <1149908197.118535.199910@j55g2000cwa.googlegroups.com> Message-ID: <1149969605.765077.166740@y43g2000cwc.googlegroups.com> George Sakkis wrote: > spam.noam at gmail.com wrote: > > > However, I'm designing another library for > > managing multi-dimensional arrays of data. Its purpose is similiar to > > that of a spreadsheet - analyze data and preserve the relations between > > a source of a calculation and its destination. > > Sounds interesting. Will it be related at all to OLAP or the > Multi-Dimensional eXpressions language > (http://msdn2.microsoft.com/en-us/library/ms145506.aspx) ? > Thanks for the reference! I didn't know about any of these. It will probably be interesting to learn from them. From a brief look at OLAP in wikipedia, it may have similarities to OLAP. I don't think it will be related to Microsoft's language, because the language will simply by Python, hopefully making it very easy to do whatever you like with the data. I posted to python-dev a message that (hopefully) better explains my use for x[]. Here it is - I think that it also gives an idea on how it will look like. I'm talking about something similar to a spreadsheet in that it saves data, calculation results, and the way to produce the results. However, it is not similar to a spreadsheet in that the data isn't saved in an infinite two-dimensional array with numerical indices. Instead, the data is saved in a few "tables", each storing a different kind of data. The tables may be with any desired number of dimensions, and are indexed by meaningful indices, instead of by natural numbers. For example, you may have a table called sales_data. It will store the sales data in years from set([2003, 2004, 2005]), for car models from set(['Subaru', 'Toyota', 'Ford']), for cities from set(['Jerusalem', 'Tel Aviv', 'Haifa']). To refer to the sales of Ford in Haifa in 2004, you will simply write: sales_data[2004, 'Ford', 'Haifa']. If the table is a source of data (that is, not calculated), you will be able to set values by writing: sales_data[2004, 'Ford', 'Haifa'] = 1500. Tables may be computed tables. For example, you may have a table which holds for each year the total sales in that year, with the income tax subtracted. It may be defined by a function like this: lambda year: sum(sales_data[year, model, city] for model in models for city in cities) / (1 + income_tax_rate) Now, like in a spreadsheet, the function is kept, so that if you change the data, the result will be automatically recalculated. So, if you discovered a mistake in your data, you will be able to write: sales_data[2004, 'Ford', 'Haifa'] = 2000 and total_sales[2004] will be automatically recalculated. Now, note that the total_sales table depends also on the income_tax_rate. This is a variable, just like sales_data. Unlike sales_data, it's a single value. We should be able to change it, with the result of all the cells of the total_sales table recalculated. But how will we do it? We can write income_tax_rate = 0.18 but it will have a completely different meaning. The way to make the income_tax_rate changeable is to think of it as a 0-dimensional table. It makes sense: sales_data depends on 3 parameters (year, model, city), total_sales depends on 1 parameter (year), and income_tax_rate depends on 0 parameters. That's the only difference. So, thinking of it like this, we will simply write: income_tax_rate[] = 0.18 Now the system can know that the income tax rate has changed, and recalculate what's needed. We will also have to change the previous function a tiny bit, to: lambda year: sum(sales_data[year, model, city] for model in models for city in cities) / (1 + income_tax_rate[]) But it's fine - it just makes it clearer that income_tax_rate[] is a part of the model that may change its value. Have a good day, Noam From michele.petrazzo at TOGLIunipex.it Thu Jun 22 05:51:39 2006 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Thu, 22 Jun 2006 09:51:39 GMT Subject: Problem on win xp and run time error In-Reply-To: References: Message-ID: Chris Lambacher wrote: > On Sat, Jun 17, 2006 at 07:32:34AM +0000, Michele Petrazzo wrote: >> Chris Lambacher wrote: >>> On Fri, Jun 16, 2006 at 06:11:53PM +0000, Michele Petrazzo wrote: >>> >>>> Hi list, just found in this moment that my applications stop to >>>> work with win xp and receive this error: >>>> >>>> """ This application has requested the Runtime to terminate it >>>> in an unusual way. Please contact the application's support >>>> team for more information. """ >>>> >>>> (Note that the same application [python source code + py2exe] >>>> with python 2.3.x work well!) >>> Don't use the single file executatble option with py2exe and the >>> problem will go away. >>> >> I'm not using that option! (that has also problems on win9x with >> python+wx) > Do you get the problem when you are not using py2exe? That will be > your real clue about what the culprit is. > No, but... >> I'm not using any of the "bundle_files" options, but only: zipfile >> = "lib/libraries.zip" > Try setting that to the default value for the moment and see if it > gets you anywhere. You might also want to try an older version of > py2exe. I would blame an interaction between py2exe and some > extension you are using, unless you can get it to happen without > py2exe. > Was, I think, a win problem because after the last "windows update" all now work! Thanks for the support, Michele From serge.orlov at gmail.com Fri Jun 23 14:04:01 2006 From: serge.orlov at gmail.com (Serge Orlov) Date: Fri, 23 Jun 2006 11:04:01 -0700 Subject: PEP 314 - requirements for Python itself In-Reply-To: <75C72D66-19F4-43AA-9120-09919076A4E5@mnot.net> References: <75C72D66-19F4-43AA-9120-09919076A4E5@mnot.net> Message-ID: On 6/23/06, Mark Nottingham wrote: > PEP 314 introduces metadata that explains what packages are required > by a particular package. Is there any way to express what version of > Python itself is required? No, but you can do it yourself: # do not edit this file, edit actualsetup.py instead import sys if sys.version_info < (2, 4): print "Error: Python 2.4 or greater is required to use this package" sys.exit(1) import actualsetup Disclaimer: I haven't actually run or tested this code, but the idea is to write the checking code that is compatible with very old python versions and do the actual work in actualsetup.py From rpdooling at gmail.com Thu Jun 1 19:27:25 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 1 Jun 2006 16:27:25 -0700 Subject: Replace one element of a tuple (LONG) In-Reply-To: <127usq9lrqavm3d@corp.supernews.com> References: <127ulhn6h7hvj22@corp.supernews.com> <1149198946.567904.260480@f6g2000cwb.googlegroups.com> <127upu8k63qnu10@corp.supernews.com> <1149202416.959127.71620@i39g2000cwa.googlegroups.com> <127usq9lrqavm3d@corp.supernews.com> Message-ID: <1149204445.622897.26390@c74g2000cwc.googlegroups.com> >> that one column is always the same, the name of the host that >> the database resides on. Then why are you pulling all of the other stuff out of the db? Why don't you just UPDATE tablename SET hostname(or colname) = 'localhost' WHERE search condition = the rows you want to change From sjmachin at lexicon.net Tue Jun 6 19:27:18 2006 From: sjmachin at lexicon.net (John Machin) Date: Wed, 07 Jun 2006 09:27:18 +1000 Subject: Writing to a certain line? In-Reply-To: <1149630414.246008.270720@f6g2000cwb.googlegroups.com> References: <1149576072.168354.14470@f6g2000cwb.googlegroups.com> <44854184$0$29904$636a55ce@news.free.fr> <1149630414.246008.270720@f6g2000cwb.googlegroups.com> Message-ID: <44860F56.2040901@lexicon.net> On 7/06/2006 7:46 AM, Tommy B wrote: > > Umm... I tried using this method and it froze. Infiinite loop, I'm > guessing. > Don't guess. Instead: (1) Put some print statements into your code to show what is happening: (a) before start of loop (b) one or more salient points inside loop (c) at (expected) loop termination point. (2) If that doesn't point you at the problem, ask again, showing the actual whole .py file that you ran -- copy/paste, don't re-type what you thought you might have run :-) It would also help if you described what "froze" means. Evidence of disk activity? Evidence of CPU activity? Did recovery involve merely closing the process's window, or did you need to re-boot? Also potentially helpful in getting better help: what version of Python; what operating system; are you running your code in an IDE (e.g. IDLE) or at the command line? HTH, John From ptmcg at austin.rr._bogus_.com Wed Jun 28 06:02:23 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 28 Jun 2006 10:02:23 GMT Subject: Questions about OSS projects. References: <1151431692.418333.123060@y41g2000cwy.googlegroups.com> Message-ID: "Daniel Dittmar" wrote in message news:e7tf7j$kio$1 at news.sap-ag.de... > If you've written a few small scripts that might be of use to others and > that you assume that there are others who do the same, you might start > with a wiki or something like the Python Cookbook > (http://aspn.activestate.com/ASPN/Python/Cookbook/), but geared toward > labs and biology. I would suggest going the wiki route - wikispaces.com makes this very easy, and free if you don't mind ads on your wikipages. Could be a low-cost/low-effort way to get started. -- Paul From tim.peters at gmail.com Thu Jun 22 17:40:21 2006 From: tim.peters at gmail.com (Tim Peters) Date: Thu, 22 Jun 2006 17:40:21 -0400 Subject: Is Queue.Queue.queue.clear() thread-safe? In-Reply-To: <1151008374.303940.251300@c74g2000cwc.googlegroups.com> References: <1151008374.303940.251300@c74g2000cwc.googlegroups.com> Message-ID: <1f7befae0606221440p619c9865y66e4b404fcd142c1@mail.gmail.com> [Russell Warren] > I'm guessing no, since it skips down through any Lock semantics, Good guess :-) It's also unsafe because some internal conditions must be notified whenever the queue becomes empty (else you risk deadlock). > but I'm wondering what the best way to clear a Queue is then. > > Esentially I want to do a "get all" and ignore what pops out, but I > don't want to loop through a .get until empty because that could > potentially end up racing another thread that is more-or-less blindly > filling it asynchronously. > > Worst case I think I can just borrow the locking logic from Queue.get > and clear the deque inside this logic, but would prefer to not have to > write wrapper code that uses mechanisms inside the object that might > change in the future. There's simply no defined way to do this now. > Also - I can of course come up with some surrounding architecture to > avoid this concern altogether, but a thread-safe Queue clear would do > the trick and be a nice and short path to solution. > > If QueueInstance.queue.clear() isn't thread safe... what would be the > best way to do it? Also, if not, why is the queue deque not called > _queue to warn us away from it? "Consenting adults" -- if you want an operation that isn't supplied out of the box, and are willing to take the risk of breaking into the internals, Python isn't going to stop you from doing whatever you like. "mutex" isn't named "_mutex" for the same reason. A q.mutex.acquire() try: q.queue.clear() q.unfinished_tasks = 0 q.not_full.notify() q.all_tasks_done.notifyAll() finally: q.mutex.release() sequence probably works (caveat emptor). BTW, it may be _possible_ you could use the newer task_done()/join() Queue gimmicks in some way to get what you're after (I'm not really clear on that, exactly). Anyway, yes, there is cross-release risk in breaking into the internals like that. That's an "adult decision" for you to make. The only way to get permanent relief is to re-think your approach, or propose adding a new Queue.clear() method and Queue._clear() default implementation. I don't know whether that would be accepted -- it seems simple enough, although since you're the first person to ask for it 15 years :-), you won't get much traction arguing that's a critical lack, and every new bit of cruft becomes an ongoing burden too. From nomail at nixmail.com Sun Jun 11 07:11:16 2006 From: nomail at nixmail.com (DarkBlue) Date: Sun, 11 Jun 2006 19:11:16 +0800 Subject: Import elfclass32 issue References: <448bc040@127.0.0.1> Message-ID: <448bfa54@127.0.0.1> Sybren Stuvel wrote: > file /path/to I installed the package on other 64 machines running suse9.2 64 and 9.3 64 without trouble That's the way : python setup.py build result: successfull python setup.py install result: successfull then tried to import and I get the elfclass32 error and that's all I did. The suse10.1 installation is pristine only auto updated with the latest patches of the day. Db From fredrik at pythonware.com Wed Jun 7 14:58:07 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 07 Jun 2006 20:58:07 +0200 Subject: tkinter: native look to windows? In-Reply-To: <89Fhg.2258$No6.47844@news.tufts.edu> References: <89Fhg.2258$No6.47844@news.tufts.edu> Message-ID: John Salerno wrote: > I'm a little confused. I was under the impression (perhaps incorrectly) > that Tkinter will create GUI widgets that are native to your OS only for some widgets; some native widgets are not flexible enough. and even native widgets don't always look like XP widgets (windows uses a rather obscure manifest XML resource file to control the look and feel for a specific application). to get better XP styling, you can use the Tile library: http://tkinter.unpythonic.net/wiki/UsingTile http://tktable.sourceforge.net/tile/screenshots/windowsxp.html or an 8.5 development version (which, afaik, includes the Tile library). From scott.daniels at acm.org Tue Jun 27 12:16:59 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Tue, 27 Jun 2006 09:16:59 -0700 Subject: Inconsistent float behaviour on "inf" - current state? In-Reply-To: References: Message-ID: <44a154db@nntp0.pdx.net> Peter Kn?rrich wrote: > .... why "float('inf')" isn't supported everywhere, and I > understand the underlying problem: > libc simply isn't that good - never mind standard - with regard to floats. I think you believe there is an underlying model of floating point numbers that all machines share. That is not true. Many systems (even those that support IEEE 754) make distinct choices about what particular bit patterns in memory represent what particular values. You can take a pickle of a data structure in CPython on one machine, carry it to a different machine with a different CPU & FPU and a different OS, and reasonably expect that the unpickled data structure running on the CPython on the other machine will produce essentially the same value. That is _amazing_. You might not have the same number of bits of precision, you might not have the same range of exponents, and the base of the exponent might even be different (well, ... perhaps nobody is running Python on 360s -- I may exaggerate here). This is not accomplished by lots of clever coding of distinct implementations across the range of machines CPython runs on. It is accomplished by staying close to the middle of the road in the C89 standard. And it breaks down for infinities and the various denormals and NaNs that you can at least detect in C99. C89, the standard we go by for CPython, provides pretty good support for floating point numbers in "reasonable" ranges with "reasonable" amounts of precision. That is to say, you can calculate with C doubles and get pretty similar results for the same C program running on quite different compilers, operating systems, and hardware _if_ you "walk the middle of the road" (staying away from rough edges, boundary values, things like calculating sin(1e300) [trigs work better w/in -2pi to 2pi] and the like. C89 does not mention the Not-A-Number group at all, and only says that infinity is something that an "implementation may support." That "may" means that a C89 compiler is free to do nothing for Infinities, and even if it does something, it it doesn't have to behave like some other C89 compiler's version of what to do with Infinities. So it is no wonder that values like plus and minus infinity "behave funny" across different CPython systems. In the eighties (when C89 was being worked on), it was not clear whether IEEE 754 would be _the_ standard or _a_ standard for floating point. It would have been pointless to force all C implementers (and they included Lifeboat Systems who did C compilers for Z80s as well as Cray Research, who did C compilers for slightly larger machines) to specify how to make positive and negative zeroes, how and when to produce "denormalized" numbers, how to produce positive and negative infinity (and whether they are distinct from each other), how create the various signaling and quiet NaNs when may systems did not have IEEE 754 floating point hardware. C is kind of a "glorified assembler," and (as such) it reveals the hardware it works on. That is why the C expression ((-7) % 4) can be 1 or -1; different hardware solves that problem differently, and C doesn't want to slow down all divisions on some hardware just to get a consistent result. If you stick to positive numbers for division, both kinds of hardware get the same result, and the programmer can put the test in if he needs it. It would not be in the spirit of C to dictate a floating point behavior that would require a lot of code generated on each operation, and without common hardware, the infinity / denormal / NaN behavior would mean code at every floating point operation. The C standards body was not interested in that work. --Scott David Daniels scott.daniels at acm.org From mcPas.De.Spam at mclaveauPas.De.Spam.com Sun Jun 25 15:28:18 2006 From: mcPas.De.Spam at mclaveauPas.De.Spam.com (Michel Claveau) Date: Sun, 25 Jun 2006 21:28:18 +0200 Subject: Life + Python = Golly References: Message-ID: Cool ! Thanks ! -- @-salutations Michel Claveau From bearophileHUGS at lycos.com Mon Jun 26 05:24:42 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 26 Jun 2006 02:24:42 -0700 Subject: Mix-In Class Methods At Run-Time In-Reply-To: <449fa027$0$24929$626a54ce@news.free.fr> References: <1151191406.755252.210300@i40g2000cwc.googlegroups.com> <1151193767.589325.158820@m73g2000cwd.googlegroups.com> <1151269186.710343.41210@c74g2000cwc.googlegroups.com> <1151270770.030282.237050@u72g2000cwu.googlegroups.com> <449fa027$0$24929$626a54ce@news.free.fr> Message-ID: <1151313882.568395.198080@r2g2000cwb.googlegroups.com> I can't give much answers, I am not that expert yet. Bruno Desthuilliers: > newstyle classes can do whatever oldstyle classes > did, *and much more* (descriptors and usable > metaclasses) - and they are somewhat faster too. In the past I have done few tests, and it seemed that new style classes are a bit slower (but the difference doesn't make much difference). Maybe for Py2.5 the situation will be different. Bye, bearophile From email at christoph-haas.de Thu Jun 15 04:59:26 2006 From: email at christoph-haas.de (Christoph Haas) Date: Thu, 15 Jun 2006 10:59:26 +0200 Subject: Correctly reading stdout/stderr from subprocess In-Reply-To: <200606151037.18563.maric@aristote.info> References: <20060613222002.GB5153@workaround.org> <200606141556.16856.maric@aristote.info> <20060614175617.GB5018@workaround.org> <200606151037.18563.maric@aristote.info> Message-ID: <20060615085925.GA6157@torf.workaround.org> On Thu, Jun 15, 2006 at 10:37:18AM +0200, Maric Michaud wrote: > Le Mercredi 14 Juin 2006 19:56, Christoph Haas a ?crit?: > > > > Quite interesting. I dived into /usr/lib/python2.4/subprocess.py and > > found out that the "communicate()" method actually works similarly. I > > might even prefer your version > > You should'nt IMO, the former 'run2' was quite short compared to this one. > Also Popen.communicate is maintained by experienced folks, your function > (mine in this case :) ) is not. This is just more job. Indeed. Still it's interesting to see that your solution was similar. > > because I get the returncode from > > run.wait() what "communicate()" does not. > > > > What the problem with getting it from an attribute (returncode) ? communicate() does not return it. Kindly Christoph From bdesth.quelquechose at free.quelquepart.fr Wed Jun 28 23:40:27 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 29 Jun 2006 05:40:27 +0200 Subject: for and while loops In-Reply-To: <1151533155.078053.61100@x69g2000cwx.googlegroups.com> References: <1151531527.496772.65130@i40g2000cwc.googlegroups.com> <1151533155.078053.61100@x69g2000cwx.googlegroups.com> Message-ID: <44a31b59$0$10290$636a55ce@news.free.fr> Bayazee a ?crit : > hi > > #Exercise 1 : > s=0 > while 1: > s+=input("Enter a num : ") > if s>=100: > print "The sum is greater than 100 : ",s > break Why do you manually check the condition when the construct is meant to take care of it ? the_sum = 0 while the_sum < 100: try: sum += int(raw_input("please enter a num: ") except ValueError: pass > #Exercise 1 : > s=0 > for i in range(5): Was supposed to be 100, not 5. > s+=input("Enter num #%d > "%(i+1)) idem as above. Using input() is usually a bad idea: >>> import sys >>> s = input("please hack my machine: ") please hack my machine: sys.path.insert(0, '/path/to/malicious/stuff') >>> sys.path[0] '/path/to/malicious/stuff' >>> From claudio.grondi at freenet.de Sun Jun 11 16:46:09 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Sun, 11 Jun 2006 22:46:09 +0200 Subject: how to get the length of a number In-Reply-To: References: Message-ID: Stan Cook wrote: > Can anyone tell me how to get the length of a number. I know > len(string) will get the length of a string, but it doesn't like > len(int). I seem to remember something like %s string. I tried to set > a variable = to %s int, but that doesn't work. Is there a function I've > forgotten about to convert an integer to a string? > > Regards > > Stan len('%s'%(1234567,)) gives 7 len('%s'%(1234**45,)) and len(str(1234**45)) give 140 Claudio From jeremy+complangpython at jeremysanders.net Wed Jun 7 15:10:15 2006 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Wed, 07 Jun 2006 20:10:15 +0100 Subject: Mutual interdependency problem Message-ID: I'm getting problems with modules with interdependencies when using the import form "import foo.bar as bar". Here are a set of files which replicate the problem :::::::::::::: importproblem/__init__.py :::::::::::::: # This is blank :::::::::::::: importproblem/dir1/__init__.py :::::::::::::: from bar import * :::::::::::::: importproblem/dir1/bar.py :::::::::::::: import importproblem.dir2 as foo def hello(): print "Hello world" :::::::::::::: importproblem/dir2/__init__.py :::::::::::::: from foo import * :::::::::::::: importproblem/dir2/test.py :::::::::::::: import importproblem.dir1.bar as bar def hello(): print "Hello world" :::::::::::::: importproblem/dir2/foo.py :::::::::::::: import importproblem.dir1 as dir1 def hello(): print "Hello world" If you now do >>> import importproblem.dir1 Traceback (most recent call last): File "", line 1, in ? File "importproblem/dir1/__init__.py", line 1, in ? from bar import * File "importproblem/dir1/bar.py", line 1, in ? import importproblem.dir2 as foo File "importproblem/dir2/__init__.py", line 1, in ? from foo import * File "importproblem/dir2/foo.py", line 1, in ? import importproblem.dir1 as dir1 AttributeError: 'module' object has no attribute 'dir1' [GCC 4.1.0 20060210 (Red Hat 4.1.0-0.24)] If you remove the "as dir1" from the import line in dir2/foo.py then this works. Can this be explained or fixed? Maybe the "from foo import *" style in __init__.py is a bad idea, but it allows you to expose a flat namespace without having to put all the code into one file. Then naturally you need mutual interdependencies, and then it breaks! I can work around it by removing the "as XXX" parts on the import statement, but it gets annoying having to specify the full path. Jeremy -- Jeremy Sanders http://www.jeremysanders.net/ From bj_666 at gmx.net Fri Jun 16 12:43:57 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Fri, 16 Jun 2006 18:43:57 +0200 Subject: Pycrypto References: <1150446904.527285.255170@g10g2000cwb.googlegroups.com> <1150458752.342042.189650@h76g2000cwa.googlegroups.com> <1150462237.224431.213020@c74g2000cwc.googlegroups.com> <1150466793.537546.149690@p79g2000cwp.googlegroups.com> <1150470895.257327.302460@h76g2000cwa.googlegroups.com> Message-ID: In <1150470895.257327.302460 at h76g2000cwa.googlegroups.com>, luca72 wrote: > Hello again i have solve doing this: > > from Crypto.Cipher import AES > stri=(chr(int('9b',16))+chr(int('d3',16))+chr(int('2d',16))+chr(int('24',16))+chr(int('af',16))+chr(int('c9',16))+chr(int('e9',16))+chr(int('d7',16))+chr(int('46',16))+chr(int('69',16))+chr(int('71',16))+chr(int('32',16))+chr(int('45',16))+chr(int('5f',16))+chr(int('27',16))+chr(int('0b',16))) > luca = str(stri) > crypt = AES.new(luca, AES.MODE_ECB) > testo=(chr(int('ea',16))+chr(int('52',16))+chr(int('3a',16))+chr(int('66',16))+chr(int('4d',16))+chr(int('ab',16))+chr(int('aa',16))+chr(int('44',16))+chr(int('76',16))+chr(int('d3',16))+chr(int('12',16))+chr(int('26',16))+chr(int('a1',16))+chr(int('e3',16))+chr(int('ba',16))+chr(int('b0',16))) > testo = str(testo) > c = crypt.encrypt(testo) > > I don't know if this is the best way , but anyway it work In [26]:import binascii In [27]:binascii.unhexlify('ea523a664dabaa4476d31226a1e3bab0') Out[27]:'\xeaR:fM\xab\xaaDv\xd3\x12&\xa1\xe3\xba\xb0' Ciao, Marc 'BlackJack' Rintsch From rpdooling at gmail.com Thu Jun 29 08:49:32 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 29 Jun 2006 05:49:32 -0700 Subject: Python 2.4 tutorial References: Message-ID: <1151585372.707966.88440@m73g2000cwd.googlegroups.com> Search the group for "tutorial" http://tinyurl.com/h5obg Or look here http://wiki.python.org/moin/BeginnersGuide/NonProgrammers Ask better questions. http://www.catb.org/esr/faqs/smart-questions.html Are you a programmer or a nonprogrammer? rd From istvan.albert at gmail.com Tue Jun 20 09:47:51 2006 From: istvan.albert at gmail.com (Istvan Albert) Date: 20 Jun 2006 06:47:51 -0700 Subject: new python icons for windows Message-ID: <1150811271.282850.321510@p79g2000cwp.googlegroups.com> I've been using the new python icons for windows for about two weeks now and I must say they've turned out to be far less functional than I thought. From purely visual standpoint the new icons look better, the old ones had a certain level of 'cuteness' associated to them .. I could see why that might have been a turnoff for some. But these new icons are too large, too blocky and too pastel. On my laptop time and again I found myself squinting trying to figure out just what the actual icon is. For example it resembles the icon for text files. It always feels like I need to make a small mental effort of first recognizing then mapping the icon to python. I can recall ever having this problem with the old icons ... or windows icons in general for that matter. Just an opinion. Istvan PS can someone point me to a page/link that contains the old icons? From paul at boddie.org.uk Wed Jun 14 18:56:52 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 14 Jun 2006 15:56:52 -0700 Subject: Tiddlywiki type project in Python? In-Reply-To: <4fan0nF1i5atjU1@uni-berlin.de> References: <1150289313.533749.52330@i40g2000cwc.googlegroups.com> <44900ae9$0$8386$626a54ce@news.free.fr> <1150291679.746132.114730@y43g2000cwc.googlegroups.com> <4fan0nF1i5atjU1@uni-berlin.de> Message-ID: <1150325812.573157.131690@y41g2000cwy.googlegroups.com> Diez B. Roggisch wrote: > [Quoting jkn...] > > Well, that may be an/the answer, since another form of my question > > would be 'how can I write a TiddlyWikiLike using Python instead of JS' > > ;-). I appreciate that it might involve, for instance, a local server. > > Does the idea of embedding python in a browser instead of Javascript > > make any sense at all? > > Nope. Not really. While I think TiddlyWiki is interesting from the perspective of creating sites that are editable in the browser without having to install or configure server-side Wiki software (which many people find intimidating, even if it's a ten line program that uses BaseHTTPServer), the drawbacks are numerous: even moderately small Wikis are slow since browser-based DOMs aren't designed for storing and manipulating large documents; published Wikis can be edited and saved, but their changes remain unmerged with the original unless you install various server-side extensions, compromising the simple "all in one place" storage model; last time I looked, production of non-Wiki, navigable sites from TiddlyWiki wasn't supported unless you wrote your own tools. A lot of the effort getting around these problems is arguably better invested in coming to terms with installing some traditional Wiki software. But where I don't agree with a negative assessment of Python in the browser is in one area that TiddlyWiki inadvertently illustrates quite nicely: the ability to conveniently distribute a sandbox to other people which has its own rather nice, widely-supported input/output system. People have been more enthusiastic about virtualisation recently: "safe Python" in the browser (or with other visualisation front-ends) would be a good lightweight virtualisation solution of sorts, I think. Paul From digitalorganics at gmail.com Mon Jun 26 22:40:52 2006 From: digitalorganics at gmail.com (digitalorganics at gmail.com) Date: 26 Jun 2006 19:40:52 -0700 Subject: Replace Whole Object Through Object Method In-Reply-To: References: <1151337453.804750.293180@b68g2000cwa.googlegroups.com> <44a041a6$0$17612$636a55ce@news.free.fr> <1151354259.082966.25820@p79g2000cwp.googlegroups.com> Message-ID: <1151376052.727979.71470@c74g2000cwc.googlegroups.com> Maric Michaud wrote: > Le lundi 26 juin 2006 22:37, digitalorganics at gmail.com a ?crit : > > Won't work because there will be employers that aren't workers. > > And yes, only some workers will become employers, but also only some > > employers will also be workers (at some point in program). Let me be > > more clear: > > > > workers > > --> subset of workers --become--> employers > > employers > > --> subset of employers --become--> workers > > > > It is very important that both should maintain attribute values, > > regardless of whether they take on new "roles". Furthermore, this is a > > very simple case and ultimately in my program an object should be able > > to dynamically take on a multitude of roles (classes of behavior) > > without mucking at all with their pre-existing states. > > This seem to be a OO design problem and you clearly make a misuse of > inheritance, if a person can eventually have many roles, but doesn't have > this role for all his lifetime, then the person *is* not his roles. > That the meaning of inheritance, class B(A) means a B is a A. > The association between a person and his roles is obviously a 1-n association, > which can be rendered by different patterns (delegation, composition, > strategy, etc.). > You should google on "design patterns" and make your choice. A misuse of inheritance eh? Inheritance, like other language features, is merely a tool. I happen to be using this tool to have my virtual persons change roles at different points in their lifetime, as many real people tend to do. Thus, at these points, B is indeed an A. What a person is, whether in real life or in my program, is not static and comes into definition uniquely for each moment (micro-moment, etc.) of existence. Now, please, I have no intention of carrying the conversation in such a silly direction, I wasn't inviting a discussion on philosophy or some such. I seek to work the tools to my needs, not the other way around. > > -- > _____________ > > Maric Michaud > _____________ > > Aristote - www.aristote.info > 3 place des tapis > 69004 Lyon > Tel: +33 426 880 097 From kay.schluehr at gmx.net Tue Jun 20 14:50:46 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 20 Jun 2006 11:50:46 -0700 Subject: Iteration over recursion? In-Reply-To: References: <1150808045.539887.291180@i40g2000cwc.googlegroups.com> <1150816827.826028.114740@h76g2000cwa.googlegroups.com> Message-ID: <1150829446.122164.295070@h76g2000cwa.googlegroups.com> Nick Maclaren wrote: > Tail recursion removal can often eliminate the memory drain, but the > code has to be written so that will work - and I don't know offhand > whether Python does it. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691 Regards, Kay From jwkenne at attglobal.net Thu Jun 22 11:37:09 2006 From: jwkenne at attglobal.net (John W. Kennedy) Date: Thu, 22 Jun 2006 11:37:09 -0400 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150892256.591282.43880@u72g2000cwu.googlegroups.com> Message-ID: Rob Warnock wrote: > Another language which has *neither* latent ("dynamic") nor > manifest ("static") types is (was?) BLISS[1], in which, like > assembler, variables are "just" addresses[2], and values are > "just" a machine word of bits. 360-family assembler, yes. 8086-family assembler, not so much. -- John W. Kennedy "The blind rulers of Logres Nourished the land on a fallacy of rational virtue." -- Charles Williams. "Taliessin through Logres: Prelude" From flupke at nonexistingdomain.com Fri Jun 30 08:08:32 2006 From: flupke at nonexistingdomain.com (flupke) Date: Fri, 30 Jun 2006 12:08:32 GMT Subject: logging error with RotatingFileHandler In-Reply-To: <1151604839.290366.90950@m73g2000cwd.googlegroups.com> References: <_asng.501715$x64.12701762@phobos.telenet-ops.be> <1151391562.198586.249130@m73g2000cwd.googlegroups.com> <1151604839.290366.90950@m73g2000cwd.googlegroups.com> Message-ID: <4v8pg.511318$Hm7.12716147@phobos.telenet-ops.be> Vinay Sajip schreef: > flupke wrote: > >> If this bug is fixed, where will i find a fixed version and how do i >> install it? >> Also, more important to me, what am i doing wrong to get this error >> message in the first place? > > You're not doing anything particularly wrong, though it's not exactly > good practice to call fileConfig lots of times. (It's really meant for > one-off configuration, not incremental configuration.) > > I get an error with just the following script typed in at the > interactive prompt: > > import logging.config > logging.config.fileConfig("logconf.ini") > logging.config.fileConfig("logconf.ini") > > So, I will investigate, and when I check in a fix to the Python > Subversion repository, I will post a message to this thread. > > Regards, > > Vinay Sajip > Hi Vinay, thanks for the info. I tried to change the handlers.py file. First, i changed some code in doRollover. if os.path.exists(dfn): os.remove(dfn) try: #os.rename(self.baseFilename, dfn) -> The rename fails for some reason. I tried with the move function of shutil shutil.move(self.baseFilename, dfn) This partially works: the file is now rotated but i still get an error: The error that i get is this: Error [Errno 13] Permission denied: 'E:\\python\\proj1\\src\\proj1.log' Traceback (most recent call last): File "C:\Python24\lib\logging\handlers.py", line 72, in emit self.doRollover() File "C:\Python24\lib\logging\handlers.py", line 141, in doRollover self.handleError(record) NameError: global name 'record' is not defined The last part of the error shows that the part where the exception is caugth is also not working correctly as the "record" isn't know. When i close my program, i get this error as well: Error in atexit._run_exitfuncs: Traceback (most recent call last): File "C:\Python24\lib\atexit.py", line 24, in _run_exitfuncs func(*targs, **kargs) File "C:\Python24\lib\logging\__init__.py", line 1333, in shutdown h.close() File "C:\Python24\lib\logging\__init__.py", line 772, in close StreamHandler.close(self) File "C:\Python24\lib\logging\__init__.py", line 674, in close del _handlers[self] KeyError: Error in sys.exitfunc: Traceback (most recent call last): File "C:\Python24\lib\atexit.py", line 24, in _run_exitfuncs func(*targs, **kargs) File "C:\Python24\lib\logging\__init__.py", line 1333, in shutdown h.close() File "C:\Python24\lib\logging\__init__.py", line 772, in close StreamHandler.close(self) File "C:\Python24\lib\logging\__init__.py", line 674, in close del _handlers[self] KeyError: Regards Benedict From no-spam at no-spam-no-spam.com Sat Jun 17 04:24:23 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Sat, 17 Jun 2006 10:24:23 +0200 Subject: msvcr71.dll necessary? - Re: Which compiler will Python 2.5 / Windows (Intel) be built with? In-Reply-To: <44934339$0$28177$9b622d9e@news.freenet.de> References: <1150367139.495114.148550@g10g2000cwb.googlegroups.com> <44934339$0$28177$9b622d9e@news.freenet.de> Message-ID: Martin v. L?wis wrote: > robert wrote: > > codecs are in python24.dll, mscvr71, mfc71 and all are not. > However, they are not in core - the operating system demand-pages code, > loading into core memory only what is being used. So if you don't use > the codecs, they are not loaded into core. > > While mscvr71 is likely loaded into core (even though it is not in > python24.dll), mfc71.dll does not play a role at all in Python 2.4. > Python is written entire in C, not in C++. yes, yet as a consequence win32xx is forced to be linked against MFC71.dll (no other functional reason): another MegaByte which I'd need to package most times - while mfc42 from VC6 is pre-installed on each Windows. > >>* Is there a fundamental reason that the C-RTL of VC6 (which is >>pre-installed on on all Windows today) is not sufficient for current >>Python and extensions? instable? > > > The compiler that is used (VS 2003) won't ship it, and links with > msvcr71.dll. That's why that library version is used. hmm, yet msvcrt4 is obviously preinstalled on each Windows - and its in Windows Update Process. Its tagged: "4.20 - OS use only. DO NOT DISTRIBUTE") Think, in principle its possible to compile against that with VS2003/2005... ? ( think msvcrt4 is not delivered extra even in the python2.3 installer ) >>In case not: As the short living VS 2003 compiler is now more rare than >>the good old VC6, wouldn't it be better to switch back to VC6 for Py2.5 >>or at least to VC6 libs (which are maybe "free" of dev-license as they >>sit on each Windows). > > Better in what respect? Predictability of software development? > Certainly not: the development will be more predictable if a decision > that was once taken is implemented as promised. 2.4 and 2.5 compiled stuff is anyway not interchangeable - thus at alpha-stage a (down) step to a common system lib would probably have no countable negative effects at all. > Making more users happy? Certainly not, either. Some users request that > VS2005 is being used, not that VC6 is being used. Other users request > that Python 2.5 continues to be built with VS 2003. You can't please > everybody. Yet if the C runtime lib (distribution) problem is solved, the question of the compiler becomes irrelevant. Everybody could use his compiler without worry - a soft recommendation could be in the Python2.5 doc's to link extensions also against the same common basic ctrl in order to keep the numer of libs small. >>Maybe a suitable policy: the default crtl for Python should better be >>the default library of the OS and not that of a random compiler which is >>currently hip? > > That would make a good policy if the OS had a system C library. Windows > doesn't. Windows NT does have a CRT, namely crtdll.dll - but you weren't > suggesting to use that one, were you? msvcrt4 is probably a reliable system C lib and still used by most apps. Think it doesn't lack Pythons needs. there is also a "msvcrt.dll" - also updated by the Windows system. maybe its on each Windows ? On XP it has version 7. What is this? >>* can't the Mingw/gcc be used together with Windows default crt/mfc libs >>for Python2.5 ? - Python getting away the from this MS studio (lib) >>harassment? > > Sure, you can use gcc/mingw to build extensions for Python 2.4 and > Python 2.5. yes, the lib is 90% the object of concern. > >>* how many (serious) python users require to build distributable >>installers (which have carry the python-rtls and non-default crtl's)? > > > Apparently not many. I repeatedly asked for contribution of a That would be very intersting for me - number about where (project type, LOC, #-of-users) and how (system, distribution, ..) python is used. Is there already something. Maybe a research/poll in this NG would be feasible. > specification how pythonxy.dll should be modularized, and never > received one. Maybe most a most simple cutoff criteria with "costs" does it magically. Basic proposal: cost = (C1 * module-size - C2 * frequency-of-module-usage) I'd suggest: cutoff cost = 0 C1 = 1/200kB C2 = 1/80% Example CJK codecs: cost = 500k/200k - 30%/80% = 2.13 => too expensive by far Example zlib: cost = 70k/200k - 95%/80% = -0.84 => go in -robert From grante at visi.com Wed Jun 14 12:22:31 2006 From: grante at visi.com (Grant Edwards) Date: Wed, 14 Jun 2006 16:22:31 -0000 Subject: Numerics, NaNs, IEEE 754 and C99 References: <12904mjhl493t49@corp.supernews.com> <4490315e$1@nntp0.pdx.net> Message-ID: <1290du7rn7pg667@corp.supernews.com> On 2006-06-14, Scott David Daniels wrote: > Grant Edwards wrote: > >> While you're at it, the pickle modules need to be fixed so they >> support NaN and Inf. ;) > The NaN problem is portability -- NaN values are not standard, My copy of IEEE 754 defines them quite precisely. :) > and pretending they are won't help. There are many possible > NaNs, several of which have desirable behaviors, and different > processors (and Floating Point settings) choose different bit > representations for those NaNs. There are at least: Inf, > -Inf, NaN, Ind (Indeterminant). I don't think +Inf and -Inf aren't NaNs (in IEEE 754 terminology). I think Pickle ought to handle them as well. > Being able to pickle some of these will produce values that > "don't behave right" on a different machine. The values "don't behave right" now. Having them "behave right" on 99.9% of the hosts in the world would be a vast improvement. > Up until now, I think you can send a pickle of a data > structure and unpickle it on a different processor to get > equivalent data. No, you can't. Nan, Inf, and Ind floating point values don't work. -- Grant Edwards grante Yow! Yow! STYROFOAM... at visi.com From timothy.grant at gmail.com Tue Jun 6 13:29:10 2006 From: timothy.grant at gmail.com (Timothy Grant) Date: Tue, 6 Jun 2006 10:29:10 -0700 Subject: what are you using python language for? In-Reply-To: References: Message-ID: On 6/4/06, hacker1017 wrote: > im just asking out of curiosity. My current gig is perl only, but I still use python for personal stuff 1) +Twisted for a couple of IRC Bots 2) an interface between TextMate and py.test 3) a soccer management game (wxPython + PyGame) -- Stand Fast, tjg. From find at my.address.elsewhere Wed Jun 21 09:45:22 2006 From: find at my.address.elsewhere (Matthias Blume) Date: Wed, 21 Jun 2006 08:45:22 -0500 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> Message-ID: Joachim Durchholz writes: > Matthias Blume schrieb: >> Joachim Durchholz writes: >> >>> Matthias Blume schrieb: >>>> Perhaps better: A language is statically typed if its definition >>>> includes (or ever better: is based on) a static type system, i.e., a >>>> static semantics with typing judgments derivable by typing rules. >>>> Usually typing judgmets associate program phrases ("expressions") with >>>> types given a typing environment. >>> This is defining a single term ("statically typed") using three >>> undefined terms ("typing judgements", "typing rules", "typing >>> environment"). >> This was not meant to be a rigorous definition. > > Rigorous or not, introducing additional undefined terms doesn't help > with explaining a term. I think you missed my point. My point was that a language is statically typed IF IT IS DEFINED THAT WAY, i.e., if it has a static type system that is PART OF THE LANGUAGE DEFINITION. The details are up to each individual definition. >> Also, I'm not going to repeat the textbook definitions for those >> three standard terms here. > > These terms certainly aren't standard for Perl, Python, Java, or Lisp, Indeed. That's because these languages are not statically typed. From alanalan at newsgroup.nospam Fri Jun 9 07:25:30 2006 From: alanalan at newsgroup.nospam (A.M) Date: Fri, 9 Jun 2006 07:25:30 -0400 Subject: Win XP: Problem with shell scripting in Python References: Message-ID: "Fredrik Lundh" wrote in message news:mailman.6785.1149837599.27775.python-list at python.org... > A.M wrote: > > > in python, "MD" is spelled os.mkdir. > >> Am I missing anything? > > the difference between STDOUT and STDERR, and the difference between > buffered output and non-buffered output, and perhaps a few other things > related to how STDIO behaves on modern computers... however, if you want > to pretend that STDOUT and STDERR are the same thing, you can use > os.popen4: > > >>> o, i = os.popen4("md :") > >>> i.read() > 'The filename, directory name, or volume label syntax is incorrect.\n' > > or the subprocess module. > >> Considering the fact that Ruby doesn't have any problem with redirecting > > STDOUT into files or string variables, is Python the right tool for > > this kinds of shell scripting? > > rewriting BAT files as a series of os.system or os.popen calls isn't > exactly optimal (neither for the computer nor the programmer nor the > future user); better take an hour to skim the "generic operating system > services" section in the library reference, and use built-in functions > wherever you can: > > http://docs.python.org/lib/allos.html > > the following modules are especially useful: > > http://docs.python.org/lib/module-os.html > http://docs.python.org/lib/module-os.path.html > http://docs.python.org/lib/module-glob.html > http://docs.python.org/lib/module-shutil.html > > by using the built-in tools, you get better performance in many cases, > better error handling, and code that's a lot easier to reuse (also on > non-Windows platforms). > > > Thanks Fredrik for help. The "MD :" is just a sample. The actual script contains different commands. The actual script that I am "translating" consolidates huge table data from multiple SQL Server database into Oracle. I have to use BCP command line at the SQL server side and SQL*Loader at the Oracle side. I must capture the stdout/stderr output of command lines into log files for future inspection/troubleshooting. Beside the issue with stdout/stderror, the main stressful problem that I have is the fact that Python captures command line's output somehow differently. For example, popen captures BCP's command output completely wrong. Some part of summary is at the top and the progress percentages are at the bottom and more.! This is just stdout output. I am going to investigate other popen4 and other popen forms per your suggestion and try to fix the stdout sequence problem. Regards, Alan From shejo284 at gmail.com Sun Jun 25 12:33:02 2006 From: shejo284 at gmail.com (Sheldon) Date: 25 Jun 2006 09:33:02 -0700 Subject: array manipulation without for loops In-Reply-To: References: <1151251578.463273.24370@m73g2000cwd.googlegroups.com> Message-ID: <1151253182.496596.185420@r2g2000cwb.googlegroups.com> Hi Gary, I am really trying to cut the time down as I have 600+ arrays with dimensions (1215,1215) to compare and I do a lot more things with the arrays. If I understand you correctly, there is no way around a for loop? /Sheldon Gary Herron wrote: > Sheldon wrote: > > Hi, > > > > I have two arrays that are of the same dimension but having 3 different > > values: 255, 1 or 2. > > I would like to set all the positions in both arrays having 255 to be > > equal, i.e., where one array has 255, I set the same elements in the > > other array to 255 and visa versa. Does anyone know how to do this > > without using for loops? > > > > Sincerely, > > Sheldon > > > > > Whatever for? Have you got something against for loops? > > However... > > You could roll you own loop: > i=0 > while i < whatever: > # ... do something with i > i += 1 > > But what's the point? This does the same as a for loop but slower. > > If you don't want any kind of a loop (again, What's the point?) you > could write something recursive: > > def proc(i, ...): > # ... do something with i > if i < whatever: > proc(i+1, ...) > > But this would be even slower. > > Gary Herron From maric at aristote.info Mon Jun 5 13:42:25 2006 From: maric at aristote.info (Maric Michaud) Date: Mon, 5 Jun 2006 19:42:25 +0200 Subject: Storing nothing in a dictionary and passing it to a function In-Reply-To: <200606051940.25765.maric@aristote.info> References: <1149527899.364138.312150@j55g2000cwa.googlegroups.com> <200606051940.25765.maric@aristote.info> Message-ID: <200606051942.26021.maric@aristote.info> Le Lundi 05 Juin 2006 19:40, Maric Michaud a ?crit?: > Le Lundi 05 Juin 2006 19:18, 63q2o4i02 at sneakemail.com a ?crit?: > > Any thoughts? > oups wanted to wirte this : In [27]: a, b = (lambda : 'works like this'), (lambda *a : a) In [28]: a(*()) Out[28]: 'works like this' In [29]: b(*()) Out[29]: () -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From neelk at cs.cmu.edu Wed Jun 14 18:57:58 2006 From: neelk at cs.cmu.edu (Neelakantan Krishnaswami) Date: Wed, 14 Jun 2006 22:57:58 +0000 (UTC) Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> Message-ID: In article <4fb97sF1if8l6U1 at individual.net>, Pascal Costanza wrote: > Torben ?gidius Mogensen wrote: > >> On a similar note, is a statically typed langauge more or less >> expressive than a dynamically typed language? Some would say less, as >> you can write programs in a dynamically typed language that you can't >> compile in a statically typed language (without a lot of encoding), >> whereas the converse isn't true. > > It's important to get the levels right here: A programming language > with a rich static type system is more expressive at the type level, > but less expressive at the base level (for some useful notion of > expressiveness ;). This doesn't seem obviously the case to me. If you have static information about your program, the compiler can use this information to automate a lot of grunt work away. Haskell's system of typeclasses work this way. If you tell the compiler how to print integers, and how to print lists, then when you call a print function on a list of list of integers, then the compiler will automatically figure out the right print function using your base definitions. This yields an increase in Felleisen-expressiveness over a dynamically typed language, because you would need to globally restructure your program to achieve a similar effect. More dramatic are the "polytypic" programming languages, which let you automate even more by letting you write generic map, fold, and print functions which work at every type. > This doesn't seem to capture what I hear from Haskell programmers > who say that it typically takes quite a while to convince the > Haskell compiler to accept their programs. (They perceive this to be > worthwhile because of some benefits wrt correctness they claim to > get in return.) This is true, if you are a novice learning the language, or if you are an expert programming with good style. If you encode your invariants in the types, then type errors will signal broken invariants. But: learning how to use the type system to encode significantly complex invariants (eg, that an abstract syntax tree representing an HTML document actually satisfies all of the constraints on valid HTML) takes experience to do well. -- Neel Krishnaswami neelk at cs.cmu.edu From imcsee at gmail.com Wed Jun 14 11:39:28 2006 From: imcsee at gmail.com (imcs ee) Date: Wed, 14 Jun 2006 23:39:28 +0800 Subject: [OT] Re: Python open proxy honeypot In-Reply-To: <1150236597.152868.250740@y43g2000cwc.googlegroups.com> References: <1150236597.152868.250740@y43g2000cwc.googlegroups.com> Message-ID: On 13 Jun 2006 15:09:57 -0700, Serge Orlov wrote: > Alex Reinhart wrote: > My spam folder at gmail is not growing anymore for many months (it is > about 600-700 spams a month). Have spammers given up spamming gmail.com > only or is it global trend? Gmail said "messages that have been in Spam more than 30 days will be automatically deleted" so may be the speed of spam comes in counterbalanced to the speed spam goes out? From gbsuar at gmail.com Wed Jun 28 21:48:21 2006 From: gbsuar at gmail.com (Gabriel) Date: Wed, 28 Jun 2006 22:48:21 -0300 Subject: Correr Programas Externos Message-ID: <91906ddf0606281848p6e2a88f4hfe0a0a0824961623@mail.gmail.com> Hola a todos: Necesitar?a correr otros programas desde python. Es decir Cuando aprieto un boton que se abra el block de notas (por ejemplo) ?Alguien sabe como hacerlo? Gracias -- Gabriel From sreeram at tachyontech.net Tue Jun 6 07:34:21 2006 From: sreeram at tachyontech.net (K.S.Sreeram) Date: Tue, 06 Jun 2006 17:04:21 +0530 Subject: How to add few pictures into one In-Reply-To: <1149591704.231602.158740@c74g2000cwc.googlegroups.com> References: <1149511692.796038.155930@c74g2000cwc.googlegroups.com> <1149517433.880564.128350@h76g2000cwa.googlegroups.com> <1149529269.228019.120480@u72g2000cwu.googlegroups.com> <1149573892.526072.6770@i39g2000cwa.googlegroups.com> <1149580572.739202.110940@y43g2000cwc.googlegroups.com> <1149587802.895959.37210@f6g2000cwb.googlegroups.com> <1149591704.231602.158740@c74g2000cwc.googlegroups.com> Message-ID: <4485683D.10102@tachyontech.net> Lad wrote: > I really would like to have ALL pictures in one file. import Image def merge_images( input_files, output_file ) : img_list = [Image.open(f) for f in input_files] out_width = max( [img.size[0] for img in img_list] ) out_height = sum( [img.size[1] for img in img_list] ) out = Image.new( 'RGB', (out_width,out_height) ) y = 0 for img in img_list : w,h = img.size out.paste( img, (0,y,w,y+h) ) y += h out.save( output_file ) Use like this: >>> merge_images( ['1.jpg','2.jpg','3.jpg'], 'output.jpg' ) Regards Sreeram -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 260 bytes Desc: OpenPGP digital signature URL: From marshall.spight at gmail.com Fri Jun 23 18:12:48 2006 From: marshall.spight at gmail.com (Marshall) Date: 23 Jun 2006 15:12:48 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: <449c4826$0$657$bed64819@news.gradwell.net> References: <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <0%Wlg.3521$MF6.947@tornado.socal.rr.com> <44992e6c$0$664$bed64819@news.gradwell.net> <449aaea0$0$656$bed64819@news.gradwell.net> <449bde5e$1$663$bed64819@news.gradwell.net> <1151082956.067238.45100@b68g2000cwa.googlegroups.com> <449c4826$0$657$bed64819@news.gradwell.net> Message-ID: <1151100768.063223.120480@m73g2000cwd.googlegroups.com> Chris Uppal wrote: > Marshall wrote: > > [me:] > > > But, as a sort of half-way, semi-formal, example: consider the type > > > environment in a Java runtime. The JVM does formal type-checking of > > > classfiles as it loads them. In most ways that checking is static -- > > > it's treating the bytecode as program text and doing a static analysis > > > on it before allowing it to run (and rejecting what it can't prove to > > > be acceptable by its criteria). However, it isn't /entirely/ static > > > because the collection of classes varies at runtime in a (potentially) > > > highly dynamic way. So it can't really examine the "whole" text of the > > > program -- indeed there is no such thing. So it ends up with a hybrid > > > static/dynamic type system -- it records any assumptions it had to make > > > in order to find a proof of the acceptability of the new code, and if > > > (sometime in the future) another class is proposed which violates those > > > assumptions, then that second class is rejected. > > > > I have to object to the term "hybrid". > > > > Java has a static type system. > > Java has runtime tags and tag checks. > > It has both, agreed, but that isn't the full story. I think I explained what I > meant, and why I feel the term is justified as well as I can in the second half > of the paragraph you quoted. I doubt if I can do better. > > Maybe you are thinking that I mean that /because/ the JVM does verification, > etc, at "runtime" the system is hybrid ? > > Anyway that is /not/ what I mean. I'm (for these purposes) completely > uninterested in the static checking done by the Java to bytecode translator, > javac. I'm interested in what happens to the high-level, statically typed, OO, > language called "java bytecode" when the JVM sees it. That language has a > strict static type system which the JVM is required to check. That's a > /static/ check in my book -- it happens before the purportedly correct code is > accepted, rather than while that code is running. > > I am also completely uninterested (for these immediate purposes) in the run > time checking that the JVM does (the stuff that results in > NoSuchMethodException, and the like). In the wider context of the thread, I do > want to call that kind of thing (dynamic) type checking -- but those checks are > not why I call the JVMs type system hybrid either. > > Oh well, having got that far, I may as well take another stab at "hybrid". > Since the JVM is running a static type system without access to the whole text > of the program, there are some things that it is expected to check which it > can't. So it records preconditions on classes which might subsequently be > loaded. Those are added to the static checks on future classes, but -- as far > as the original class is concerned -- those checks happen dynamically. So part > of the static type checking which is supposed to happen, has been postponed to > a dynamic check. It's that, and /only/ that which I meant by "hybrid". That's fair, I guess. I wouldn't use the terms you do, but maybe that doesn't matter very much assuming we understand each other at this point. Marshal From johnjsal at NOSPAMgmail.com Thu Jun 8 15:31:32 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 08 Jun 2006 19:31:32 GMT Subject: wxpython: can't even create a Panel Message-ID: I'm using the sample code of the file 'simple.py' and trying to make a single window with a panel in it, but I keep getting an error. Here's my code: (I know I might need something else, like a Show() method for the panel, but the error stops on the first panel line anyway. I've tried a Layout() method but it didn't get that far). import wx class MyFrame(wx.Frame): def __init__(self, parent, title): wx.Frame.__init__(self, parent, -1, title) panel = wx.Panel(self) class MyApp(wx.App): def OnInit(self): frame = MyFrame(None, 'My Test Frame') frame.Show(True) return True app = MyApp() app.MainLoop() ----------------------- And the error: >>> Traceback (most recent call last): File "C:\Python24\myscripts\wx_tests\wxtest.py", line 4, in -toplevel- class MyFrame(wx.Frame): File "C:\Python24\myscripts\wx_tests\wxtest.py", line 9, in MyFrame panel = wx.Panel(self) NameError: name 'self' is not defined >>> ------------------ And if it helps, here is the code I'm using as a guide. It has the same panel line, but obviously something about my code is different for the 'self' reference not to work: #---------------------------------------------------------------------- # A very simple wxPython example. Just a wx.Frame, wx.Panel, # wx.StaticText, wx.Button, and a wx.BoxSizer, but it shows the basic # structure of any wxPython application. #---------------------------------------------------------------------- import wx class MyFrame(wx.Frame): """ This is MyFrame. It just shows a few controls on a wxPanel, and has a simple menu. """ def __init__(self, parent, title): wx.Frame.__init__(self, parent, -1, title, pos=(150, 150), size=(350, 200)) # Create the menubar menuBar = wx.MenuBar() # and a menu menu = wx.Menu() # add an item to the menu, using \tKeyName automatically # creates an accelerator, the third param is some help text # that will show up in the statusbar menu.Append(wx.ID_EXIT, "E&xit\tAlt-X", "Exit this simple sample") # bind the menu event to an event handler self.Bind(wx.EVT_MENU, self.OnTimeToClose, id=wx.ID_EXIT) # and put the menu on the menubar menuBar.Append(menu, "&File") self.SetMenuBar(menuBar) self.CreateStatusBar() # Now create the Panel to put the other controls on. panel = wx.Panel(self) # and a few controls text = wx.StaticText(panel, -1, "Hello World!") text.SetFont(wx.Font(14, wx.SWISS, wx.NORMAL, wx.BOLD)) text.SetSize(text.GetBestSize()) btn = wx.Button(panel, -1, "Close") funbtn = wx.Button(panel, -1, "Just for fun...") # bind the button events to handlers self.Bind(wx.EVT_BUTTON, self.OnTimeToClose, btn) self.Bind(wx.EVT_BUTTON, self.OnFunButton, funbtn) # Use a sizer to layout the controls, stacked vertically and with # a 10 pixel border around each sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(text, 0, wx.ALL, 10) sizer.Add(btn, 0, wx.ALL, 10) sizer.Add(funbtn, 0, wx.ALL, 10) panel.SetSizer(sizer) panel.Layout() def OnTimeToClose(self, evt): """Event handler for the button click.""" print "See ya later!" self.Close() def OnFunButton(self, evt): """Event handler for the button click.""" print "Having fun yet?" class MyApp(wx.App): def OnInit(self): frame = MyFrame(None, "Simple wxPython App") self.SetTopWindow(frame) print "Print statements go to this stdout window by default." frame.Show(True) return True app = MyApp(redirect=True) app.MainLoop() From digitalorganics at gmail.com Sun Jun 11 11:58:30 2006 From: digitalorganics at gmail.com (digitalorganics at gmail.com) Date: 11 Jun 2006 08:58:30 -0700 Subject: direct initialization of class attributes vs. declarations w/in __init__ Message-ID: <1150041510.139609.171120@f6g2000cwb.googlegroups.com> What's the difference between initializing class variables within the class definition directly versus initializing them within the class's __init__ method? Is there a reason, perhaps in certain situations, to choose one over the other? Thank you. From maric at aristote.info Thu Jun 8 09:55:54 2006 From: maric at aristote.info (Maric Michaud) Date: Thu, 8 Jun 2006 15:55:54 +0200 Subject: CONSTRUCT - Python's way of Ruby's "alias_method" In-Reply-To: References: Message-ID: <200606081555.54621.maric@aristote.info> Le Jeudi 08 Juin 2006 15:15, Duncan Booth a ?crit : > but the more usual way is just to call the original method directly in the > base class. > > class SqliteAdapter(BaseClass): > def create_table(self, *args) > self.table_evolve(*args) > result = BaseClass.create_table(self, *args) > return result > Yeah, this the right way to reuse ancestor's implementation of a method. > If that isn't what you are trying to achieve you'll have to explain more. I'm not a ruby programmer, but I understood it like this : the prupose is to modify the behavior of an existing third-party class, in all application (even in existing third party modules), without any code modifications (traditional patch) in those modules. Your proposal is not as good here, assuming BaseClass is defined in module toto, you can still do toto.BaseClass = SqliteAdapter, but you must ensure that this code is imported before any other where classes inherit from BaseClass. The one I porpose in my other post is robust, several packages can even patch the same method with no side effects. -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From nick.smallbone at gmail.com Tue Jun 6 13:17:22 2006 From: nick.smallbone at gmail.com (Nick Smallbone) Date: 6 Jun 2006 10:17:22 -0700 Subject: Newbie: returning dynamicly built lists (using win32com) In-Reply-To: <1149613586.862299.125070@u72g2000cwu.googlegroups.com> References: <1149613586.862299.125070@u72g2000cwu.googlegroups.com> Message-ID: <1149614241.975245.260500@h76g2000cwa.googlegroups.com> I'm afraid I don't have a Windows machine to test on, but.. Ransom wrote: > I get an error like: > [ 0x15450880>] > This isn't an error. This is a list with one element, where the element apparently represents a range of Excel cells. So by using that element you can do things like changing the formatting of the cell, as well as finding out what data is in there. It looks like you might need to use excel.ActiveSheet.Cells(32, 6).Value to get the contents of cell (32, 6). (It depends on what Excel calls it, of course, so if it's not that have a look at Excel's VBA documentation to see if it mentions anything.) Nick From aleax at mac.com Wed Jun 28 22:18:01 2006 From: aleax at mac.com (Alex Martelli) Date: Wed, 28 Jun 2006 19:18:01 -0700 Subject: Python in a nutshell - new edition ? References: <44A2C52A.6040807@skynet.be> Message-ID: <1hhnpen.1bkiv8l1d0r6puN%aleax@mac.com> Helmut Jarausch wrote: > is there a new edition of "Python in a Nutshell" > covering Python 2.5 coming soon? Yep, we're still aiming for OSCON '06 (Portland, end of July). The coverage centers on 2.4, with mentions of what was changed in that version (to make the book usable for 2.3) and in 2.5 -- since the writing had to stop by March (after that it's copyediting, indexing, etc), I couldn't really cover the substantial additions to the standard library in 2.5 (ctypes, etree, pysqlite, &c), but language-proper changes &c (with statement, new functionality in generators, new-style exception classes, ...) I think I managed to cover adequately... but, let's wait for the reviews!-) Alex From bencvt at gmail.com Thu Jun 1 20:11:16 2006 From: bencvt at gmail.com (Ben Cartwright) Date: 1 Jun 2006 17:11:16 -0700 Subject: Can Python format long integer 123456789 to 12,3456,789 ? References: <8oKfg.1621$Su3.139425@news20.bellglobal.com> Message-ID: <1149207075.954869.100130@i39g2000cwa.googlegroups.com> A.M wrote: > Is there any built in feature in Python that can format long integer > 123456789 to 12,3456,789 ? The locale module can help you here: >>> import locale >>> locale.setlocale(locale.LC_ALL, '') 'English_United States.1252' >>> locale.format('%d', 123456789, True) '123,456,789' Be sure to read the caveats for setlocale in the module docs: http://docs.python.org/lib/node323.html I'd recommend calling setlocale only once, and always at the start of your program. --Ben From scott.daniels at acm.org Wed Jun 14 13:09:25 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Wed, 14 Jun 2006 10:09:25 -0700 Subject: wxpython: how do i write this without the id parameter? In-Reply-To: References: <448e430d$1@nntp0.pdx.net> Message-ID: <44903e01$1@nntp0.pdx.net> John Salerno wrote: > Scott David Daniels wrote: > >> class InputForm(wx.Frame): >> def __init__(self, parent=None, id=-1, title=__file__): > > Also, is there a way to define parent and id with defaults, but not > title? Is it good to change the order around to do this? No, too many things know the first couple of args are parent and id. If __file__ doesn't work for you, just stick in something for title and remember to replace it. class InputForm(wx.Frame): def __init__(self, parent=None, id=-1, title='Input Form"): --Scott David Daniels scott.daniels at acm.org From reply.in.the.newsgroup at my.address.is.invalid Fri Jun 23 06:02:58 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Fri, 23 Jun 2006 12:02:58 +0200 Subject: Program slowing down with greater memory use References: Message-ID: <00fn92tg5qkkbt7n9i4k81qo6d1bop4qrr@4ax.com> Dan Stromberg: >What's the deal here? The sketchy information in your post doesn't rule out any possibility. -- Ren? Pijlman From luismgz at gmail.com Tue Jun 13 01:10:14 2006 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 12 Jun 2006 22:10:14 -0700 Subject: Very nice python IDE (windows only) In-Reply-To: <1150123984.819338.84330@u72g2000cwu.googlegroups.com> References: <1149694235.741274.325200@u72g2000cwu.googlegroups.com> <1149701880.540109.10100@y43g2000cwc.googlegroups.com> <1149704292.676501.138530@h76g2000cwa.googlegroups.com> <448d5f3d$0$815$3a628fcd@textreader.nntp.hccnet.nl> <1150123984.819338.84330@u72g2000cwu.googlegroups.com> Message-ID: <1150175414.784581.35420@c74g2000cwc.googlegroups.com> digitalorganics at gmail.com wrote: > I happen to have delphi, so if someone wants me to make small changes, > just let me know, I'll try to help.... Hmm... now that you offer, would it be possible to have the colors of text just like in IDLE? I tried configuring the colors, but some of them don't exist as options in this IDE (for example "orange"). I like how text looks in IDLE, with orange for reserved words, green for strings, etc... From bborcic at gmail.com Wed Jun 7 07:10:07 2006 From: bborcic at gmail.com (Boris Borcic) Date: Wed, 07 Jun 2006 13:10:07 +0200 Subject: Python language problem In-Reply-To: <1149678146.681370.5130@c74g2000cwc.googlegroups.com> References: <1149678146.681370.5130@c74g2000cwc.googlegroups.com> Message-ID: <4486b41b$1_3@news.bluewin.ch> ripleyfu at gmail.com wrote: >>>> class A: > ... pass > ... >>>> a = A() >>>> b = a >>>> del b >>>> a > <__main__.A instance at 0x00B91BC0> > I want to delete 'a' through 'b', why It does't? > How can I do that? del a,b From python.list at tim.thechases.com Thu Jun 15 14:43:33 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 15 Jun 2006 13:43:33 -0500 Subject: list of polynomial functions In-Reply-To: References: <1150390140.459461.169900@i40g2000cwc.googlegroups.com> Message-ID: <4491AA55.7030200@tim.thechases.com> > The `i` is the problem. It's not evaluated when the lambda > *definition* is executed but when the lambda function is > called. And then `i` is always == `n`. You have to > explicitly bind it as default value in the lambda definition: > > polys.append(lambda x, i=i: polys[i](x)*x) > > Then it works. Just to sate my curiosity, why can the lambda find "polys", but not find "i"? If what you're describing is the case, then it seems to me that the following code should work too: def make_polys(n): p = lambda x: 1 polys = [p] for i in range(n): p = polys[i] polys.append(lambda x: (p(x) * x)) return polys yet it suffers the same problem as the original. Outside the scope of make_polys, neither polys[] nor i exists. There's some subtle behavior here that I'm missing. -tkc From fredrik at pythonware.com Mon Jun 19 04:42:20 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 19 Jun 2006 10:42:20 +0200 Subject: any subway web dev experiences In-Reply-To: <44965c1f$0$22857$626a54ce@news.free.fr> References: <1150533811.911621.112430@y41g2000cwy.googlegroups.com> <1150664491.533947.61090@p79g2000cwp.googlegroups.com> <44965c1f$0$22857$626a54ce@news.free.fr> Message-ID: bruno at modulix wrote: > Nope - it's a Python MVC web framework. Like Django, Pylons and > Turborgears. And FWIW, there have been recently some discussions about > merging Subway and Turbogears. recently? was that before or after the developer picked up his marbles and went home to complain to his mother? (according to the subway wiki, only porn sites use the framework these days. hint to developers: if you're shutting down a project, make sure you lock down the project site). From steve at holdenweb.com Mon Jun 12 03:03:47 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 12 Jun 2006 08:03:47 +0100 Subject: direct initialization of class attributes vs. declarations w/in __init__ In-Reply-To: <1150082287.401522.164950@h76g2000cwa.googlegroups.com> References: <1150041510.139609.171120@f6g2000cwb.googlegroups.com> <4f2thrF1fd4r4U1@uni-berlin.de> <1150043792.136250.99770@u72g2000cwu.googlegroups.com> <1150047314.025241.260750@c74g2000cwc.googlegroups.com> <1150061669.491796.95700@g10g2000cwb.googlegroups.com> <4f3it1F1gptbcU1@uni-berlin.de> <1150082287.401522.164950@h76g2000cwa.googlegroups.com> Message-ID: digitalorganics at gmail.com wrote: [...] > Read my other post. The code was/is definitely identical. In any event, > I don't really care. It's working properly now, and if I have similarly > weird problems in future, I'll deal with them at that time. I don't > know what was up, but I understand it doesn't make sense from any > visible standpoint of logic. Thank you for your efforts Diez... > It would be nice to know where the discrepancy arose, but now I see you were using email to transfer the source code I happily withdraw my accusations of typographical error. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From cdsmith at twu.net Thu Jun 22 14:34:17 2006 From: cdsmith at twu.net (Chris Smith) Date: Thu, 22 Jun 2006 12:34:17 -0600 Subject: What is a type error? References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <7i3mg.204167$8W1.155367@fe1.news.blueyonder.co.uk> <44992e6c$2$664$bed64819@news.gradwell.net> <%Igmg.464974$xt.353729@fe3.news.blueyonder.co.uk> <449aaea0$2$656$bed64819@news.gradwell.net> Message-ID: Chris Uppal wrote: > I think we're agreed (you and I anyway, if not everyone in this thread) that we > don't want to talk of "the" type system for a given language. We want to allow > a variety of verification logics. So a static type system is a logic which can > be implemented based purely on the program text without making assumptions > about runtime events (or making maximally pessimistic assumptions -- which comes > to the same thing really). I suggest that a "dynamic type system" is a > verification logic which (in principle) has available as input not only the > program text, but also the entire history of the program execution up to the > moment when the to-be-checked operation is invoked. I am trying to understand how the above statement about dynamic types actually says anything at all. So a dynamic type system is a system of logic by which, given a program and a path of program execution up to this point, verifies something. We still haven't defined "something", though. We also haven't defined what happens if that verification fails. One or the other or (more likely) some combination of the two must be critical to the definition in order to exclude silly applications of it. Presumably you want to exclude from your definition of a dynamic "type system" which verifies that a value is non-negative, and if so executes the block of code following "then"; and otherwise, executes the block of code following "else". Yet I imagine you don't want to exclude ALL systems that allow the programmer to execute different code when the verification fails (think exception handlers) versus succeeds, nor exclude ALL systems where the condition is that a value is non-negative. In other words, I think that everything so far is essentially just defining a dynamic type system as equivalent to a formal semantics for a programming language, in different words that connote some bias toward certain ways of looking at possibilities that are likely to lead to incorrect program behavior. I doubt that will be an attractive definition to very many people. > Note that not all errors that I would want to call type errors are necessarily > caught by the runtime -- it might go happily ahead never realising that it had > just allowed one of the constraints of one of the logics I use to reason about > the program. What's known as an undetected bug -- but just because the runtime > doesn't see it, doesn't mean that I wouldn't say I'd made a type error. (The > same applies to any specific static type system too, of course.) In static type system terminology, this quite emphatically does NOT apply. There may, of course, be undetected bugs, but they are not type errors. If they were type errors, then they would have been detected, unless the compiler is broken. If you are trying to identify a set of dynamic type errors, in a way that also applies to statically typed languages, then I will read on. > But the checks the runtime does perform (whatever they are, and whenever they > happen), do between them constitute /a/ logic of correctness. In many highly > dynamic languages that logic is very close to being maximally optimistic, but > it doesn't have to be (e.g. the runtime type checking in the JMV is pretty > pessimistic in many cases). > > Anyway, that's more or less what I mean when I talk of dynamically typed > language and their dynamic type systems. So my objections, then, are in the first paragraph. > [**] Although there are operations which are not possible, reading another > object's instvars directly for instance, which I suppose could be taken to > induce a non-trivial (and static) type logic. In general, I wouldn't consider a syntactically incorrect program to have a static type error. Type systems are, in fact, essentially a tool so separate concerns; specifically, to remove type-correctness concerns from the grammars of programming languages. By doing so, we are able at least to considerably simplify the grammar of the language, and perhaps also to increase the "tightness" of the verification without risking making the language grammar context-sensitive. (I'm unsure about the second part of that statement, but I can think of no obvious theoretical reason to assume that combining a type system with a regular context- free grammar would yield another context-free grammar. Then again, formal languages are not my strong point.) -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation From nospam at nospam.com Thu Jun 8 13:13:55 2006 From: nospam at nospam.com (3c273) Date: Thu, 8 Jun 2006 10:13:55 -0700 Subject: Instead of saving text files i need as html References: <1149777499.506986.292830@j55g2000cwa.googlegroups.com> Message-ID: "3c273" wrote in message news:e69k8a01ud4 at enews2.newsguy.com... > Or is this what you mean? > -----begin----- > import urllib > urlfile = open('c:\\temp\\url.txt', 'r') > newurlfile = open('c:\\temp\\newurls.html', 'w') > newurlfile.write(' \n\n') > for lines in urlfile: > try: > if lines == '\n': > pass > else: > lines = '
'\ > + lines.strip() + '' + '
\n' > newurlfile.write(lines) > except: > pass > newurlfile.write(' \n') > urlfile.close() > newurlfile.close() > -----end----- > Louis > Oops, I guess we don't need "import urllib" anymore. Louis From npmitjans at yahoo.es Wed Jun 21 11:20:05 2006 From: npmitjans at yahoo.es (Niurka Perez) Date: Wed, 21 Jun 2006 08:20:05 -0700 (PDT) Subject: 'module' object has no attribute 'ssl' Message-ID: <20060621152005.87627.qmail@web26204.mail.ukl.yahoo.com> Hi, I have Red Hat Linux 3.2.3-54 and Python 2.4.3 (the original version downloaded from python.org) and I'm using httplib to make a request to an external server, this is the code I'm using: import httplib https = httplib.HTTPSConnection('216.220.59.211', 7989) https.debuglevel = 1 body = buildXML(data) try: https.request('POST', '/Messenger/XMLMessenger', body) response = https.getresponse() response = response.read() https.close() except: response = None import traceback traceback.print_exc() return response And I get the following error: Traceback (most recent call last): File "testPayment.py", line 14, in preAuthPayment https.request('POST', '/Messenger/XMLMessenger', body) File "/usr/local/lib/python2.4/httplib.py", line 804, in request self._send_request(method, url, body, headers) File "/usr/local/lib/python2.4/httplib.py", line 827, in _send_request self.endheaders() File "/usr/local/lib/python2.4/httplib.py", line 798, in endheaders self._send_output() File "/usr/local/lib/python2.4/httplib.py", line 679, in _send_output self.send(msg) File "/usr/local/lib/python2.4/httplib.py", line 646, in send self.connect () File "/usr/local/lib/python2.4/httplib.py", line 1073, in connect ssl = socket.ssl(sock, self.key_file, self.cert_file) AttributeError: 'module' object has no attribute 'ssl' Anybody has an idea of what migth be happening? Thank in advance. Best Regards, Niurka __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From subscriber100 at rjs.org Sat Jun 10 13:17:06 2006 From: subscriber100 at rjs.org (Ray Schumacher) Date: Sat, 10 Jun 2006 10:17:06 -0700 Subject: Python-list Digest, Vol 33, Issue 159 In-Reply-To: References: Message-ID: <6.2.3.4.2.20060610094020.02d54020@rjs.org> Thanks Larry, My depth can really only get to ~3: package module module error_module an usually not that. It is shallow, with >hundred methods (mainly serial protocol defs for LX* telescopes), but it could grow I suppose. I mainly see its use as an import for other, large apps. Speed is not an issue here , just clutter, as you said. I still also have not seen a written consensus on the "proper" usage of class variables. I define module vars (some constants), which I think is reasonable, although these modules are the type with only one class: port = LXSerial.LXSerial(...) My rationale of putting the class in its own module is to minimize giant module files with lots of long classes; there is only a remote possibility that someone would want call a class without most of the others as well. Ray Ray Schumacher wrote: > > What is the feeling on using "parent" in a class definition that class > > methods can refer to, vs. some other organization ? > > Should all relevant objects/vars just be passed into the method as needed? > > It seems like including "parent" in the class def is just like a class > > variable, which most do not recommend. > Passing parent instance into a class is perfectly legal and is > used extensively in modules like wxPython GUI. It isn't really > anything like a class variable as the instance is normally > passed not the class itself. Each instance can have different > attributes. So if you have many parents with many children this > can be an effective way to structure them. > > I think it depends on how deeply nested things get and how many > parameters need to be passed. I've used it when I want to > nest my objects more than 2 deep and I must pass around lots of > attributes. I find it is easier to just look "upwards" into the > parent to get the attribute than to clutter up my argument list > passing arguments deeper and deeper into the class hierarchy. > It can simplify the argument lists quite a bit. Maybe others can > comment with their thoughts as well. From a at tempinbox.com Sat Jun 17 04:43:31 2006 From: a at tempinbox.com (a) Date: 17 Jun 2006 01:43:31 -0700 Subject: any subway experiences Message-ID: <1150533811.911621.112430@y41g2000cwy.googlegroups.com> thanks for reading From k.retheesh at gmail.com Fri Jun 9 14:38:40 2006 From: k.retheesh at gmail.com (k.retheesh at gmail.com) Date: 9 Jun 2006 11:38:40 -0700 Subject: TypeError: unsubscriptable object In-Reply-To: References: <1149874726.470436.279200@i40g2000cwc.googlegroups.com> Message-ID: <1149878320.458373.315530@i40g2000cwc.googlegroups.com> So wat should I do ?? K.S.Sreeram wrote: > k.retheesh at gmail.com wrote: > > print template % (ID, IID, Function[:10], Description[:10], > > ErrorNumber, StatusCD) > > TypeError: unsubscriptable object > > It means either 'Function' or 'Description' is not a sequence. > Try inserting print statements to see what values they are. > > e.g: > > a = 2 > a[:10] > > will give me an 'unsubscriptable object' > > Regards > Sreeram > > > --------------enig08E562E3E8ED90BF5BC3C92B > Content-Type: application/pgp-signature > Content-Transfer-Encoding: base64 > Content-Disposition: inline; > filename="signature.asc" > Content-Description: OpenPGP digital signature > X-Google-AttachSize: 253 From neuruss at gmail.com Mon Jun 5 00:27:55 2006 From: neuruss at gmail.com (Neuruss) Date: 4 Jun 2006 21:27:55 -0700 Subject: C# equivalent to range() In-Reply-To: References: <1149468919.951745.163700@g10g2000cwb.googlegroups.com> Message-ID: <1149481675.192638.275140@c74g2000cwc.googlegroups.com> Dennis Lee Bieber wrote: > What most of us saw was a blunt request on how to implement a Python > construct in some other language that may not be familiar to us. I'm curious, who are "us"? From mvanaswegen at gmail.com Tue Jun 13 03:24:29 2006 From: mvanaswegen at gmail.com (vpr) Date: 13 Jun 2006 00:24:29 -0700 Subject: "groupby" is brilliant! In-Reply-To: <1150180151.643245.148210@y43g2000cwc.googlegroups.com> References: <1150180151.643245.148210@y43g2000cwc.googlegroups.com> Message-ID: <1150183469.756257.110890@f14g2000cwb.googlegroups.com> Hi Frank This is one of the reasons why I love Python, you can write readable code. I strive to write clean code but I find that exception handling code e.g. try: makes my code ugly and significantly harder to read. Does anyone have any good pointers for a former C++ / Perl coder. /vpr Frank Millman wrote: > Hi all > > This is probably old hat to most of you, but for me it was a > revelation, so I thought I would share it in case someone has a similar > requirement. > > I had to convert an old program that does a traditional pass through a > sorted data file, breaking on a change of certain fields, processing > each row, accumulating various totals, and doing additional processing > at each break. I am not using a database for this one, as the file > sizes are not large - a few thousand rows at most. I am using csv > files, and using the csv module so that each row is nicely formatted > into a list. > > The traditional approach is quite fiddly, saving the values of the > various break fields, comparing the values on each row with the saved > values, and taking action if the values differ. The more break fields > there are, the fiddlier it gets. > > I was going to do the same in python, but then I vaguely remembered > reading about 'groupby'. It took a little while to figure it out, but > once I had cracked it, it transformed the task into one of utter > simplicity. > > Here is an example. Imagine a transaction file sorted by branch, > account number, and date, and you want to break on all three. > > ----------------------------- > import csv > from itertools import groupby > from operator import itemgetter > > BRN = 0 > ACC = 1 > DATE = 2 > > reader = csv.reader(open('trans.csv', 'rb')) > rows = [] > for row in reader: > rows.append(row) > > for brn,brnList in groupby(rows,itemgetter(BRN)): > for acc,accList in groupby(brnList,itemgetter(ACC)): > for date,dateList in groupby(accList,itemgetter(DATE)): > for row in dateList: > [do something with row] > [do something on change of date] > [do something on change of acc] > [do something on change of brn] > ----------------------------- > > Hope someone finds this of interest. > > Frank Millman From grflanagan at yahoo.co.uk Mon Jun 5 15:02:06 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 5 Jun 2006 12:02:06 -0700 Subject: Concatenating dictionary values and keys, and further operations References: Message-ID: <1149534126.129714.131860@f6g2000cwb.googlegroups.com> Girish Sahani wrote: > I wrote the following code to concatenate every 2 keys of a dictionary and > their corresponding values. > e.g if i have tiDict1 = tiDict1 = {'a':[1,2],'b':[3,4,5]} i should get > tiDict2={'ab':[1,2][3,4,5]} and similarly for dicts with larger no. of > features. > Now i want to check each pair to see if they are connected...element of > this pair will be one from the first list and one from the second....e.g > for 'ab' i want to check if 1 and 3 are connected,then 1 and 4,then 1 and > 5,then 2 and 3,then 2 and 4,then 2 and 5. > The information of this connected thing is in a text file as follows: > 1,'a',2,'b' > 3,'a',5,'a' > 3,'a',6,'a' > 3,'a',7,'b' > 8,'a',7,'b' > . > . > This means 1(type 'a') and 2(type 'b') are connected,3 and 5 are connected > and so on. > I am not able to figure out how to do this.Any pointers would be helpful Girish It seems you want the Cartesian product of every pair of lists in the dictionary, including the product of lists with themselves (but you don't say why ;-)). I'm not sure the following is exactly what you want or if it is very efficient, but maybe it will start you off. It uses a function 'xcombine' taken from a recipe in the ASPN cookbook by David Klaffenbach (2004). (It should give every possibility, which you then check in your file) Gerard ------------------------------------------------------------------------- def nkRange(n,k): m = n - k + 1 indexer = range(0, k) vector = range(1, k+1) last = range(m, n+1) yield vector while vector != last: high_value = -1 high_index = -1 for i in indexer: val = vector[i] if val > high_value and val < m + i: high_value = val high_index = i for j in range(k - high_index): vector[j+high_index] = high_value + j + 1 yield vector def kSubsets( alist, k ): n = len(alist) for vector in nkRange(n, k): ret = [] for i in vector: ret.append( alist[i-1] ) yield ret data = { 'a': [1,2], 'b': [3,4,5], 'c': [1,4,7] } pairs = list( kSubsets(data.keys(),2) ) + [ [k,k] for k in data.iterkeys() ] print pairs for s in pairs: for t in xcombine( data[s[0]], data[s[1]] ): print "%s,'%s',%s,'%s'" % ( t[0], s[0], t[1], s[1] ) ------------------------------------------------------------------------- 1,'a',1,'c' 1,'a',4,'c' 1,'a',7,'c' 2,'a',1,'c' 2,'a',4,'c' 2,'a',7,'c' 1,'a',3,'b' 1,'a',4,'b' 1,'a',5,'b' 2,'a',3,'b' 2,'a',4,'b' 2,'a',5,'b' 1,'c',3,'b' 1,'c',4,'b' 1,'c',5,'b' 4,'c',3,'b' 4,'c',4,'b' 4,'c',5,'b' 7,'c',3,'b' 7,'c',4,'b' 7,'c',5,'b' 1,'a',1,'a' 1,'a',2,'a' 2,'a',1,'a' 2,'a',2,'a' 1,'c',1,'c' 1,'c',4,'c' 1,'c',7,'c' 4,'c',1,'c' 4,'c',4,'c' 4,'c',7,'c' 7,'c',1,'c' 7,'c',4,'c' 7,'c',7,'c' 3,'b',3,'b' 3,'b',4,'b' 3,'b',5,'b' 4,'b',3,'b' 4,'b',4,'b' 4,'b',5,'b' 5,'b',3,'b' 5,'b',4,'b' 5,'b',5,'b' From rganesan at myrealbox.com Thu Jun 15 04:27:57 2006 From: rganesan at myrealbox.com (Ganesan Rajagopal) Date: Thu, 15 Jun 2006 13:57:57 +0530 Subject: popen and password entry References: <200604141852.59515.erchamion.beren@gmail.com> <8c05f79c0606142358n5fbafc3xd859a63909f11e90@mail.gmail.com> Message-ID: >>>>> Sinan Nalkaya writes: > hi, > i have found expect method for this purpose. i`m trying to use pexpect but > following code gives me an something strange as a result. When working with pexpect, logging the entire conversation is extremely useful fro debugging > import pexpect > cmd = '/usr/bin/rsync config root at 10.1.1.2:/tmp/.' > #cmd = 'ssh root at 10.1.1.2' > child = pexpect.spawn(cmd) Add "child.logfile = sys.stdout" here and check what's going on. Ganesan -- Ganesan Rajagopal From claird at lairds.us Sun Jun 11 23:45:21 2006 From: claird at lairds.us (Cameron Laird) Date: Mon, 12 Jun 2006 03:45:21 +0000 Subject: First question on extending Python... References: <448A048B.7000007@websafe.com> Message-ID: In article <448A048B.7000007 at websafe.com>, Larry Bates wrote: >Redefined Horizons wrote: . . . >> There is a third-party application that I need to work with. It is >> closed-source, but it exposes a C API. I want to wrap this C API so >> that it is available from Python. I have no ability to modify the C >> API of the third part application. >> >> Do I the C functions that I wrap in an extensions module for Python >> need to be in a certian format? If so, I will have to write an >> intermediate DLL in C that wraps the third-party application and >> exports the functions in a form that Python can use. >> >> Or can an extension module for Python wrap any C function? If this is >> the case I think I can skip the intermediate C DLL. >> >> Are there any advantages to using the intermediate DLL written in C in >> this particular case where I will not have ability to manipulate the C >> API of the third party application directly? (For example, if the >> third-party application developers are willing to call a "call-back" >> function that must be written in C, but not Python. Could the same >> extension module export both C functions and serve as a Python >> module?) >> >> Thanks, >> >> Scott Huey > >John Machin has answered most of your questions in a separate post. All you >need is to take a look at ctypes module for Python. You can call virtually >any C based API that is stored in a .DLL using ctypes. I've called .DLL >APIs for Castelle's Faxpress, Expervision's OCR toolkit and Softrak's ADS.DLL >with no problems. The trick is creating some functions/classes that help >with the C structures that need to be passed back and forth. For that you >will probably also need to take a look at the Python struct module, but ctypes >has some built-in helper functions also. > >ctypes can be located here: http://starship.python.net/crew/theller/ctypes/ > >-Larry Bates All true. I think it's worth mentioning that some DLLs are accessible through COM; when this is possible, I find it often more convenient than ctypes. I have no idea whether COM applies in the situation at hand. From penneys at bigfoot.com Mon Jun 5 04:34:42 2006 From: penneys at bigfoot.com (MrBlueSky) Date: 5 Jun 2006 01:34:42 -0700 Subject: Pmw ScrolledCanvas: How to scroll to specific item? Message-ID: <1149496482.138396.159020@i40g2000cwc.googlegroups.com> Hi, I've got a ScrolledCanvas object (sc) and have identified an item on the canvas to which I wish to scroll. I've been reading around and experimenting but with not much success. So far I've managed to get the item's bbox using sc.bbox(item) And got the proportion of the canvas that's visible using sc.xview() and sc.yview() And established the whole canvas bbox using sc.bbox(ALL) I've even gone on to use some rudimentary maths to work out whether I need to scroll, then used: sc.xview_moveto(itemX) But this is all rather messy and I've not yet got it working. There must be an easier way?! Thanks! John From mvanaswegen at gmail.com Fri Jun 9 06:00:49 2006 From: mvanaswegen at gmail.com (vpr) Date: 9 Jun 2006 03:00:49 -0700 Subject: Amazon and Webservices Message-ID: <1149847249.123387.309650@f6g2000cwb.googlegroups.com> Hi All I've been trying to consume the webservices at Amazon using python. I have not been able to find a *good* webservices module and I've had a look at SOAPpy, etc. Yes I have googled etc, but there seems to be a lack of development in this space apart for one or two projects. Does anyone have a working webservices implementation (not pyamazon) ? /vpr From duncan.booth at invalid.invalid Mon Jun 26 04:24:54 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 26 Jun 2006 08:24:54 GMT Subject: Python taught in schools? References: <1151220913.406987.162420@u72g2000cwu.googlegroups.com> <1hhhbmb.qcvbcn14uox59N%aleax@mac.com> Message-ID: Lawrence D'Oliveiro wrote: > In article <1hhhbmb.qcvbcn14uox59N%aleax at mac.com>, > aleax at mac.com (Alex Martelli) wrote: > >>... let's try some google searches and see the number of million >>hits...: > > But how reliable are those estimates of numbers of hits, anyway? More > than once I've got a page showing something like "Results 1 - 10 of > about 36 hits", only to find that there were no more pages after the > second one. If it could get estimates so wrong with such small > numbers, how can you trust the large ones? If you read what it says at the bottom of the last page of results (this example from a claimed 90 hits, but only 27 visible): > In order to show you the most relevant results, we have omitted some > entries very similar to the 27 already displayed. If you like, you can > repeat the search with the omitted results included. Google's hit count includes all the pages which by default it filters out. In particular it only returns you two pages from each site in the initial results (grouped together and with the second one indented). If you repeat the search with filtering turned off then you should find that a small count of hits is pretty accurate). From marc.t.davies at gmail.com Mon Jun 26 05:13:42 2006 From: marc.t.davies at gmail.com (MTD) Date: 26 Jun 2006 02:13:42 -0700 Subject: style question In-Reply-To: References: Message-ID: <1151313222.382208.98390@b68g2000cwa.googlegroups.com> Hari Sekhon wrote: > Is it better to do: > > message = """This is line1. > This is line2 > This is line3\n""" > > or > > message = "This is line1.\n > message = message + "This is line2\n" > message = message + "This is line3\n" Is there any reason you can't do it in one line? message = "This is line1.\nThis is line2.\nThis is line3.\n" From Serge.Orlov at gmail.com Thu Jun 15 13:35:30 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 15 Jun 2006 10:35:30 -0700 Subject: memory leak problem with arrays References: <1150317325.614389.14770@i40g2000cwc.googlegroups.com> <1150322504.136131.139350@i40g2000cwc.googlegroups.com> <1150324059.063981.70450@u72g2000cwu.googlegroups.com> <1150327127.904461.84740@h76g2000cwa.googlegroups.com> <1150349112.780025.289480@i40g2000cwc.googlegroups.com> Message-ID: <1150392930.223307.130090@r2g2000cwb.googlegroups.com> sonjaa wrote: > Serge Orlov wrote: > > sonjaa wrote: > > > Serge Orlov wrote: > > > > sonjaa wrote: > > > > > Hi > > > > > > > > > > I'm new to programming in python and I hope that this is the problem. > > > > > > > > > > I've created a cellular automata program in python with the numpy array > > > > > extensions. After each cycle/iteration the memory used to examine and > > > > > change the array as determined by the transition rules is never freed. > > > > > I've tried using "del" on every variable possible, but that hasn't > > > > > worked. > > > > > > > > Python keeps track of number of references to every object if the > > > > object has more that one reference by the time you use "del" the object > > > > is not freed, only number of references is decremented. > > > > > > > > Print the number of references for all the objects you think should be > > > > freed after each cycle/iteration, if is not equal 2 that means you are > > > > holding extra references to those objects. You can get the number of > > > > references to any object by calling sys.getrefcount(obj) > > > > > > thanks for the info. I used this several variables/objects and > > > discovered that little counters i.e. k = k +1 have many references to > > > them, up tp 10000+. > > > Is there a way to free them? > > > > Although it's looks suspicious, even if you manage to free it you will > > gain only 12 bytes. I think you should concentrate on more fat > > objects ;) > > > Sent message to the NumPy forum as per Roberts suggestion. > An update after implimenting the suggestions: > > After doing this I see that iterative counters used to collect > occurrences > and nested loop counters (ii & jj) as seen in the code example below > are the culprits with the worst ones over 1M: That means you have over 1M integers in your program. How did it happen if you're using numpy arrays? If I allocate a numpy array of one million bytes it is not using one million integers, whereas a python list of 1M integers creates 1M integers: >>> import numpy >>> a = numpy.zeros((1000000,), numpy.UnsignedInt8) >>> import sys >>> sys.getrefcount(0) 632 >>> b=[0]*1000000 >>> sys.getrefcount(0) 1000632 >>> But that doesn't explain why your program doesn't free memory. But the way, are you sure you have enough memory for one iteration of your program? From jdhunter at ace.bsd.uchicago.edu Tue Jun 13 10:45:13 2006 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Tue, 13 Jun 2006 09:45:13 -0500 Subject: numeric/numpy/numarray References: Message-ID: <877j3lunba.fsf@peds-pc311.bsd.uchicago.edu> >>>>> "Bryan" == Bryan writes: Bryan> hi, what is the difference among numeric, numpy and Bryan> numarray? i'm going to start using matplotlib soon and i'm Bryan> not sure which one i should use. numpy is the successor to numarray and Numeric. All three do basically the same thing. You should use numpy. matplotlib works with all three, you just need to be sure to set your "numerix" setting to "numpy" in your matplotlibrc file. numerix : numpy # numpy, Numeric or numarray On unix like OSes, this file is placed in ~/.matplotlib. On windows systems, it is usually found in C:\Documents and Settings\yourname\.matplotlib JDH From gandalf at designaproduct.biz Fri Jun 16 08:14:43 2006 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Fri, 16 Jun 2006 14:14:43 +0200 Subject: Pycrypto In-Reply-To: <1150458752.342042.189650@h76g2000cwa.googlegroups.com> References: <1150446904.527285.255170@g10g2000cwb.googlegroups.com> <1150458752.342042.189650@h76g2000cwa.googlegroups.com> Message-ID: <4492A0B3.8010406@designaproduct.biz> > You can do this as follows: > > py> from Crypto.Cipher import AES > py> # key has to be 16, 24 or 32 bytes for AES > py> crypt = AES.new('abcdefghijklmnop', AES.MODE_ECB) > # we're lucky, the string to encrypt is a multiple of 16 in length > py> txt = 'ea523a664dabaa4476d31226a1e3bab0' > py> c = crypt.encrypt(txt) > py> c > 'w\x81\xe3\xdd\x066\x9eY\xc7\xce~O\x9e\xfb\xef\xfa\xb5\x8a\xac\x7f\xca\x9fl{\xe5\xfd6\x80\xe3\x81%\xb9' > py> crypt.decrypt(c) > 'ea523a664dabaa4476d31226a1e3bab0' > > see http://www.amk.ca/python/writing/pycrypt for the docs. if you have > to encrypt data which has not a multiple of length 16 you have to pad > it e.g. with spaces, and then strip the decrypt() result. > Or use CBC mode? I'm not familiar with pycrypto but I know that CBC mode can crypt/decrypt text with any size. Laszlo From fredrik at pythonware.com Fri Jun 23 05:01:42 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 23 Jun 2006 11:01:42 +0200 Subject: code is data In-Reply-To: <1150658597.272001.171840@r2g2000cwb.googlegroups.com> References: <1150574111.415068.255900@p79g2000cwp.googlegroups.com> <1150606118.456390.262620@y41g2000cwy.googlegroups.com> <1150626424.563673.175060@c74g2000cwc.googlegroups.com> <1150650852.275956.249340@p79g2000cwp.googlegroups.com> <1150658597.272001.171840@r2g2000cwb.googlegroups.com> Message-ID: Ravi Teja wrote: > You blogged on Django. Let's use that. Don't you think model creation > in Django can be represented better, given that it is done often > enough? nope, because 1) it's not done very often, and 2) the existing syntax is already very minimal, and defined in terms of a language that I already understand. there might be cognitive theories that argue that the length of the symbols used to describe something is more important than the symbols you use, and how they can be "chunked" by the brain, but sturgeon's law applies to cognitive scientists too ;-) > Since you are on thread and are a prominent and involved member of the > Python community, I would like it if you (or any such other) can > provide feedback on the rest of my previous post rather than be > dismissive by just a small portion of it. Perhaps, that will give me > some insight how these language design decisions are rationally made (I > am not strictly a programmer by profession, much less a language > designer). see Ian's posts for some excellent discussion. From subscriber100 at rjs.org Sat Jun 10 11:51:22 2006 From: subscriber100 at rjs.org (Ray Schumacher) Date: Sat, 10 Jun 2006 08:51:22 -0700 Subject: "parent" in a class __init__ def? Message-ID: <6.2.3.4.2.20060610083539.02d18150@rjs.org> What is the feeling on using "parent" in a class definition that class methods can refer to, vs. some other organization ? Should all relevant objects/vars just be passed into the method as needed? It seems like including "parent" in the class def is just like a class variable, which most do not recommend. An example: class LXSerial: def __init__(self, parent, debug=False): ... def connect(self, port, baud=9600, ptimeout=10): if self.debug: self.connectedPort = StringIO.StringIO(':A#') else: if self.parent.model=='LX200GPS': ptimeout = 240 ... Ray From fredrik at pythonware.com Wed Jun 7 16:24:24 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 07 Jun 2006 22:24:24 +0200 Subject: os.system and command output In-Reply-To: References: <8rFhg.1071$Wy.73797@news20.bellglobal.com> Message-ID: A.M wrote: > Is there anyway I can get the exit code (what os.system returns) from > os.popen? you'd rather kill yourself than read the documentation, right? http://www.python.org/doc/lib/os-newstreams.html#os-newstreams "The exit status of the command (encoded in the format specified for wait()) is available as the return value of the close() method of the file object, except that when the exit status is zero (termination without errors), None is returned." From chris.uppal at metagnostic.REMOVE-THIS.org Fri Jun 23 06:55:04 2006 From: chris.uppal at metagnostic.REMOVE-THIS.org (Chris Uppal) Date: Fri, 23 Jun 2006 11:55:04 +0100 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <0%Wlg.3521$MF6.947@tornado.socal.rr.com> <44992e6c$0$664$bed64819@news.gradwell.net> <449aaea0$0$656$bed64819@news.gradwell.net> Message-ID: <449bde5e$1$663$bed64819@news.gradwell.net> Andreas Rossberg wrote: > Chris Uppal wrote: > > > > > > It's worth noting, too, that (in some sense) the type of an object > > > > can change over time[*]. > > > > > > No. Since a type expresses invariants, this is precisely what may > > > *not* happen. If certain properties of an object may change then the > > > type of > > > the object has to reflect that possibility. Otherwise you cannot > > > legitimately call it a type. > > > > Well, it seems to me that you are /assuming/ a notion of what kinds of > > logic can be called type (theories), and I don't share your > > assumptions. No offence intended. > > OK, but can you point me to any literature on type theory that makes a > different assumption? 'Fraid not. (I'm not a type theorist -- for all I know there may be lots, but my suspicion is that they are rare at best.) But perhaps I shouldn't have used the word theory at all. What I mean is that there is one or more logic of type (informal or not -- probably informal) with respect to which the object in question has changed it categorisation. If no existing type /theory/ (as devised by type theorists) can handle that case, then that is a deficiency in the set of existing theories -- we need newer and better ones. But, as a sort of half-way, semi-formal, example: consider the type environment in a Java runtime. The JVM does formal type-checking of classfiles as it loads them. In most ways that checking is static -- it's treating the bytecode as program text and doing a static analysis on it before allowing it to run (and rejecting what it can't prove to be acceptable by its criteria). However, it isn't /entirely/ static because the collection of classes varies at runtime in a (potentially) highly dynamic way. So it can't really examine the "whole" text of the program -- indeed there is no such thing. So it ends up with a hybrid static/dynamic type system -- it records any assumptions it had to make in order to find a proof of the acceptability of the new code, and if (sometime in the future) another class is proposed which violates those assumptions, then that second class is rejected. > > I see no reason, > > even in practise, why a static analysis should not be able to see that > > the set of acceptable operations (for some definition of acceptable) > > for some object/value/variable can be different at different times in > > the execution. > > Neither do I. But what is wrong with a mutable reference-to-union type, > as I suggested? It expresses this perfectly well. Maybe I misunderstood what you meant by union type. I took it to mean that the type analysis didn't "know" which of the two types was applicable, and so would reject both (or maybe accept both ?). E..g if at instant A some object, obj, was in a state where it to responds to #aMessage, but not #anotherMessage; and at instant B it is in a state where it responds to #anotherMessage but not #aMessage. In my (internal and informal) type logic, make the following judgements: In code which will be executed at instant A obj aMessage. "type correct" obj anotherMessage. "type incorrect" In code which will be executed at instant B obj aMessage. "type incorrect" obj anotherMessage. "type correct" I don't see how a logic with no temporal element can arrive at all four those judgements, whatever it means by a union type. -- chris From ziapannocchia at gmail.com Mon Jun 12 05:07:51 2006 From: ziapannocchia at gmail.com (cloc3) Date: 12 Jun 2006 02:07:51 -0700 Subject: [mod_python] using nested blocks in psp In-Reply-To: <1150099453.868939.187030@f6g2000cwb.googlegroups.com> References: <1150027597.236379.53290@j55g2000cwa.googlegroups.com> <1150099453.868939.187030@f6g2000cwb.googlegroups.com> Message-ID: <1150103271.717249.80060@i40g2000cwc.googlegroups.com> grahamd at dscpl.com.au wrote: See: > > http://www.modpython.org/pipermail/mod_python/2005-May/018102.html > > Comment hints may still be needed in certain cases to turn off scopes > even if 8 space or tab indents are needed so it is good to understand > what they are about. > Thank you. That solves my problem. Here the good code: [code]
[/code] From raffaelcavallaro at pas-d'espam-s'il-vous-plait-mac.com Wed Jun 14 10:51:05 2006 From: raffaelcavallaro at pas-d'espam-s'il-vous-plait-mac.com (Raffael Cavallaro) Date: Wed, 14 Jun 2006 10:51:05 -0400 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> Message-ID: <2006061410510511272-raffaelcavallaro@pasdespamsilvousplaitmaccom> On 2006-06-14 09:42:25 -0400, torbenm at app-1.diku.dk (Torben ?gidius Mogensen) said: > It takes longer for the average > programmer to get the program working in the dynamically typed > language. Though I agree with much of your post I would say that many here find the opposite to be true - it takes us longer to get a program working in a statically typed language because we have to keep adding/changing things to get the compiler to stop complaining and actually compile and run a program which would be perfectly permissible in a dynamically typed language such as common lisp - for example - heterogeneous lists and forward references to as yet non-existent functions. From claudio.grondi at freenet.de Mon Jun 26 13:32:26 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Mon, 26 Jun 2006 19:32:26 +0200 Subject: Beginner Programmer Question In-Reply-To: <1151342733.742416.180370@r2g2000cwb.googlegroups.com> References: <1151342733.742416.180370@r2g2000cwb.googlegroups.com> Message-ID: kydavis77 at gmail.com wrote: > I am doing alot of reading and trying to teach myself how to program. > I can not figure out how to make "Write a program that continually > reads in numbers from the user and adds them together until the sum > reaches 100." this work. If someone could show me the correct code so i > can learn from that it would be much appreciated. Thanks > Isn't it your homework? Why can't you figure it out? What have you tried? Claudio From gamedev at fancy.org Wed Jun 28 18:06:40 2006 From: gamedev at fancy.org (Tom Plunket) Date: Wed, 28 Jun 2006 15:06:40 -0700 Subject: to py or not to py ? References: Message-ID: Carl J. Van Arsdall wrote: > Because of the GIL only one thread can actually run at a time. I've recently been wondering about this, since in the work I do, a lot of time is spent doing disk I/O. So if I want the UI to remain responsive, I could spawn an IO thread to handle requests, and do a pretty simple "just whack new requests onto the queue" without locks since I'm guaranteed to not have the IO thread read at the same time as the requestor thread? ...what exactly constitutes an atomic operation in Python, anyway? e.g. class IoThread: # ... # called from the other thread... def RequestFile(self, name): self.fileQueue.append(name) # called during the IO thread def GetNextFile(self); next = self.fileQueue[0] self.fileQueue.pop(0) return next ? -tom! From timothy.williams at nvl.army.mil Tue Jun 13 09:24:33 2006 From: timothy.williams at nvl.army.mil (timw.google) Date: 13 Jun 2006 06:24:33 -0700 Subject: pylab doesn't find numpy on Windows Message-ID: <1150205073.203361.304190@f14g2000cwb.googlegroups.com> Hi all. I installed matplotlib 0.87.3 under Python 2.4 on both Linux (FC3) and Windows XP Pro. On the linux install, I can import pylab, but when I try to do the same thing on the Windows installation, I get >>> from pylab import * Traceback (most recent call last): File "", line 1, in -toplevel- from pylab import * File "C:\Python24\Lib\site-packages\pylab.py", line 1, in -toplevel- from matplotlib.pylab import * File "C:\Python24\Lib\site-packages\matplotlib\pylab.py", line 196, in -toplevel- import cm File "C:\Python24\Lib\site-packages\matplotlib\cm.py", line 5, in -toplevel- import colors File "C:\Python24\Lib\site-packages\matplotlib\colors.py", line 33, in -toplevel- from numerix import array, arange, take, put, Float, Int, where, \ File "C:\Python24\Lib\site-packages\matplotlib\numerix\__init__.py", line 60, in -toplevel- from Numeric import * ImportError: No module named Numeric I have numpy 0.9.8 installed in both places too. Thanks for any help. From jo at durchholz.org Fri Jun 16 18:09:26 2006 From: jo at durchholz.org (Joachim Durchholz) Date: Sat, 17 Jun 2006 00:09:26 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: <_eBkg.14895$uy3.4988@tornado.socal.rr.com> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <2006061410510511272-raffaelcavallaro@pasdespamsilvousplaitmaccom> <2006061501423327544-raffaelcavallaro@pasdespamsilvousplaitmaccom> <_eBkg.14895$uy3.4988@tornado.socal.rr.com> Message-ID: Darren New schrieb: > Joachim Durchholz wrote: >> Give a heterogenous list that would to too awkward to live in a >> statically-typed language. > > Write a function that takes an arbitrary set of arguments and stores > them into a structure allocated on the heap. If the set of arguments is really arbitrary, then the software can't do anything with it. In that case, the type is simply "opaque data block", and storing it in the heap requires nothing more specific than that of "opaque data block". There's more in this. If we see a function with a parameter type of "opaque data block", and there's no function available except copying that data and comparing it for equality, then from simply looking at the function's signature, we'll know that it won't inspect the data. More interestingly, we'll know that funny stuff in the data might trigger bugs in the code - in the context of a security audit, that's actually a pretty strong guarantee, since the analysis can stop at the function't interface and doesn't have to dig into the function's implementation. >> Give a case of calling nonexistent functions that's useful. > > See the Tcl "unknown" proc, used for interactive command expansion, > dynamic loading of code on demand, etc. Not related to dynamic typing, I fear - I can easily envision alternatives to that in a statically-typed context. Of course, you can't eliminate *all* run-time type checking. I already mentioned unmarshalling data from an untyped source; another possibility is run-time code compilation (highly dubious in a production system but of value in a development system). However, that's some very specialized applications, easily catered for by doing a dynamic type check plus a thrown exception in case the types don't match. I still don't see a convincing argument for making dynamic typing the standard policy. Regards, Jo From propheci at gmail.com Wed Jun 21 03:12:51 2006 From: propheci at gmail.com (Xiaolei) Date: 21 Jun 2006 00:12:51 -0700 Subject: Initializing a set from a list In-Reply-To: References: <1150869540.796459.202330@u72g2000cwu.googlegroups.com> <1150871908.281225.61880@u72g2000cwu.googlegroups.com> Message-ID: <1150873971.810396.214000@u72g2000cwu.googlegroups.com> Sybren Stuvel wrote: > Xiaolei enlightened us with: > > from pylab import * > > You'd better not do that. Just use "import pylab". > > > If I remove the first line, I correctly get: > > > > [1, 2, 3, 3] > > > > set([1, 2, 3]) > > Pylab shadows the built-in set name, which is one of the reasons you > should generally use "import XXX" instead of "from XXX import *". Ahh. Understood. Thank you very much. From claird at lairds.us Mon Jun 19 21:20:20 2006 From: claird at lairds.us (Cameron Laird) Date: Tue, 20 Jun 2006 01:20:20 +0000 Subject: Formatting practices (was: Passing data to system command) References: <1150666037.974563.25610@i40g2000cwc.googlegroups.com> Message-ID: In article , Chris Hieronymus wrote: . . . > msg = str(x)+" "+str(y)+"\n" > p1.stdin.write(msg) . . . While Python prides itself on the clarity of its preferred style, note that the former line might just as well be written msg = "%s %s\n" % (x, y) a form which some of us prefer. From fredrik at pythonware.com Thu Jun 22 11:26:10 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 22 Jun 2006 17:26:10 +0200 Subject: Blog source code in Python In-Reply-To: <1150989366.242671.254300@g10g2000cwb.googlegroups.com> References: <1150989366.242671.254300@g10g2000cwb.googlegroups.com> Message-ID: Lad wrote: > Is there a blog application source available in Python? google down today? how many do you need ? http://newsbruiser.tigris.org/ http://pyblosxom.sourceforge.net/ http://wiki.python.org/moin/PythonBlogSoftware etc From g.farina at html.it Fri Jun 9 11:23:47 2006 From: g.farina at html.it (Gabriele Farina) Date: Fri, 09 Jun 2006 17:23:47 +0200 Subject: Thread specific singleton Message-ID: <448991d2$0$18298$4fafbaef@reader1.news.tin.it> Hi, I'm tring to implement a Singleton object that should be specific for every thread who create it, not global. I tried a solution that seems to work, but I have a very poor knowledge of concurrent programming, so I'd like someone to help me find some problems in my implementation. Here is the code: ------------------------------------------------------------- import thread class ThreadLock(object): locks = {} def __new__(cls): id = thread.get_ident() try: lock = cls.locks[id] except KeyError: lock = thread.allocate_lock() cls.locks[id] = lock return lock @classmethod def clear(cls, id=None): """ Clear the lock associated with a given id. If the id is None, thread.get_ident() is used. """ if id is None: id = thread.get_ident() try: del cls.locks[id] except KeyError: pass class ThreadedSingleton(object): pool = {} def __new__(cls, *args, **kw): lock = ThreadLock() lock.acquire() id = thread.get_ident() try: obj = cls.pool[id] except KeyError: obj = object.__new__(cls, *args, **kw) if hasattr(obj, '__init_singleton__'): obj.__init_singleton__(*args, **kw) cls.pool[id] = obj lock.release() return obj def __del__(self): id = thread.get_ident() ThreadLock.clear(id) try: del cls.pool[id] except KeyError: pass if __name__ == '__main__': import time import random class Specific(ThreadedSingleton): def __init_singleton__(self): print "Init singleton" self.a = None def test(a): s = Specific() s.a = a print "%d: %s" %(thread.get_ident(), Specific().a) time.sleep(1) print "%d: %s" %(thread.get_ident(), Specific().a) time.sleep(random.randint(1, 5)) print "%d: %s" %(thread.get_ident(), Specific().a) time.sleep(2) print "%d: %s" %(thread.get_ident(), Specific().a) for x in range(4): thread.start_new_thread(test, (x, )) time.sleep(10) ------------------------------------------------------------- using the thread module should be fine even if threads are created trought the threading module, right ? Thanks, Gabriele From richard at commonground.com.au Mon Jun 26 19:58:31 2006 From: richard at commonground.com.au (Richard Jones) Date: Tue, 27 Jun 2006 09:58:31 +1000 Subject: OSDC 2006 -- CFP closes in 2.5 weeks! Message-ID: <366AD0E8-FD7B-4858-A2C3-B4A3730EA718@commonground.com.au> http://www.osdc.com.au/papers/cfp06.html There are two and a half weeks to go to get your paper in for one of the best Australian conferences this year! The deadline for proposals is 12th July 2006. The Open Source Developers' Conference is an Australian conference designed for developers, by developers. It covers numerous programming languages across a range of operating systems. We're seeking papers on Open Source languages, technologies, projects and tools as well as topics of interest to Open Source developers. The conference will be held in Melbourne, Victoria (Monash University's Caulfield Campus) from the 6th to the 8th of December, 2006. Each day includes three streams of talks, social events and is fully catered with buffet lunch and morning, afternoon teas. For a list of conference presentations from last year visit: http://osdc2005.cgpublisher.com/proposals/ If you have any questions, or have never submitted a paper proposal before, please read our FAQ page at http://www.osdc.com.au/faq/ index.html If you don't find an answer there, please contact richard osdc.com.au To submit a proposal, follow the instructions at http://www.osdc.com.au/papers/cfp06.html This year we're also going to run a day of tutorials. See the CFP for more information. We are also seeking expressions of interest for people to be part of the OSDC 2006 Programme Committee. The Committee's primary responsibility is assessing the proposals submitted by potential speakers. Please email richard osdc.com.au if you are interested, indicating your open source development interests. We look forward to hearing from you! All the best, The OSDC 2006 committee. From enleverlesX.XmcX at XmclaveauX.com Sun Jun 4 18:53:49 2006 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI) Date: Mon, 5 Jun 2006 00:53:49 +0200 Subject: Where is the ucs-32 codec? References: <1149459785.331497.203920@c74g2000cwc.googlegroups.com> Message-ID: <4483649e$0$18311$ba4acef3@news.orange.fr> Hi! Look at: http://cjkpython.berlios.de (iconvcodec) (Serge Orlov has built a version for Python 2.4 "special for me"; thanks to him). @-salutations -- Michel Claveau From sreeram at tachyontech.net Tue Jun 20 07:30:07 2006 From: sreeram at tachyontech.net (K.S.Sreeram) Date: Tue, 20 Jun 2006 17:00:07 +0530 Subject: Specifing arguments type for a function In-Reply-To: <4497d8ef$0$29790$626a54ce@news.free.fr> References: <4fq09iF1k0h0eU1@uni-berlin.de> <4497d8ef$0$29790$626a54ce@news.free.fr> Message-ID: <4497DC3F.8000401@tachyontech.net> bruno at modulix wrote: > if type(arg) is type([]): Just a tiny nitpick.... You can just use 'list' instead of 'type([])' if type(arg) is list : # blah blah Regards Sreeram -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 260 bytes Desc: OpenPGP digital signature URL: From jo at durchholz.org Wed Jun 21 07:24:39 2006 From: jo at durchholz.org (Joachim Durchholz) Date: Wed, 21 Jun 2006 13:24:39 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: <4fsbivF1jqb81U1@individual.net> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <4fpvbvF1keed1U1@individual.net> <4fqonoF1kfkapU1@individual.net> <1150824752.799997.206210@p79g2000cwp.googlegroups.com> <4fqt33F1kfd1jU1@individual.net> <2N3mg.462963$xt.331923@fe3.news.blueyonder.co.uk> <4fsbivF1jqb81U1@individual.net> Message-ID: Pascal Costanza schrieb: > (It's really important to understand that the idea is to use this for > deployed programs - albeit hopefully in a more structured fashion - and > not only for debugging. The example I have given is an extreme one that > you would probably not use as such in a "real-world" setting, but it > shows that there is a boundary beyond which static type systems cannot > be used in a meaningful way anymore, at least as far as I can tell.) As soon as the running program can be updated, the distinction between "static" (compile time) and "dynamic" (run time) blurs. You can still erect a definition for such a case, but it needs to refer to the update process, and hence becomes language-specific. In other words, language-independent definitions of dynamic and static typing won't give any meaningful results for such languages. I'd say it makes more sense to talk about what advantages of static vs. dynamic typing can be applied in such a situation. E.g. one interesting topic would be the change in trade-offs: making sure that a type error cannot occur becomes much more difficult (particularly if the set of available types can change during an update), so static typing starts to lose some of its appeal; OTOH a good type system can give you a lot of guarantees even in such a situation, even if it might have to revert to the occasional run-time type check, so static checking still has its merits. Regards, Jo From gene.tani at gmail.com Fri Jun 16 01:45:03 2006 From: gene.tani at gmail.com (gene tani) Date: 15 Jun 2006 22:45:03 -0700 Subject: Looking for examples related to advanced python string, list and map operations In-Reply-To: References: Message-ID: <1150436703.354948.208530@p79g2000cwp.googlegroups.com> A.M wrote: > Hi, > > > > Is there any online resource that gives examples about advanced python > string, list and map operations? > http://goog-goopy.sourceforge.net/goopy.functional.html#-variance http://oakwinter.com/code/functional/documentation.html From bogus@does.not.exist.com Mon Jun 12 02:36:22 2006 From: bogus@does.not.exist.com (Morpheus) Date: Mon, 12 Jun 2006 08:36:22 +0200 Subject: wxPython: Should you use a master sizer object? References: <448b072f$0$11723$c3e8da3@news.astraweb.com> <448b25e4$0$9428$c3e8da3@news.astraweb.com> Message-ID: <448d0b66$0$28520$3b214f66@aconews.univie.ac.at> IIRC the wx dox contain stuff about sizers too. It's definitly worth to get into this stuff. Once you are used to sizers, you don't want to miss them anymore. HTH Morpheus "John Salerno" wrote in message news:448b25e4$0$9428$c3e8da3 at news.astraweb.com... > Steve Holden wrote: > > > There doesn't seem to be any really usable material to help beginners. A > > recursive design approach seems best, breaking down each grouping, but I > > have sometimes found it difficult to adapt a design to changes. > > > > Although I'm a big fan of open source I must confess that to solve this > > problem I eventually bought a copy of wxDesigner, which while not > > perfect does help quite a lot, and allows cut/copy and paste of design > > elements. > > Yeah, it would be nice to use something like wxDesigner eventually, but > right now I'd like to learn how to write it all by hand, so I can know > what's going on. > > There are a couple of screencasts about using sizers with Dabo that are > helpful, even though it's specific to that designer. It still shows how > to layout nested sizers, for example. From dodgyville at gmail.com Fri Jun 2 19:51:02 2006 From: dodgyville at gmail.com (Luke Miller) Date: Sat, 3 Jun 2006 09:51:02 +1000 Subject: Seg fault in python extension module Message-ID: Hello, I am working on my first python module based on a c program. The module builds and installs OK using dist-utils, and imports fine into python. However, when I try and use the one wrapper ("modgl.glVertex4f(1, 2, 3, 1)") in the module, it seg faults. Can anyone spot why this isn't working, or recommend a way to debug these things. Thanks, Luke #include static PyObject *_wrap_glVertex4f(PyObject *self, PyObject *args) { PyObject *resultobj = NULL; float arg1 ; float arg2 ; float arg3 ; float arg4 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; PyObject * obj3 = 0 ; if(!PyArg_ParseTuple(args,(char *)"OOOO:glVertex4f",&obj0,&obj1,&obj2,&obj3)) goto fail; { arg1 = (float)(PyFloat_AsDouble(obj0)); } { arg2 = (float)(PyFloat_AsDouble(obj1)); } { arg3 = (float)(PyFloat_AsDouble(obj2)); } { arg4 = (float)(PyFloat_AsDouble(obj3)); } glVertex4f(arg1,arg2,arg3,arg4); Py_INCREF(Py_None); resultobj = Py_None; return resultobj; fail: return NULL; }; static PyMethodDef modglMethods[] = { { (char *)"glVertex4f", _wrap_glVertex4f, METH_VARARGS, NULL}, { NULL, NULL, 0, NULL } }; PyMODINIT_FUNC modgl(void) { (void) Py_InitModule("modgl", modglMethods); }; int main(int argc, char *argv[]) { /* Pass argv[0] to the Python interpreter */ Py_SetProgramName(argv[0]); /* Initialize the Python interpreter. Required. */ Py_Initialize(); /* Add a static module */ initmodgl(); return 0; }; From pc at p-cos.net Fri Jun 23 07:46:47 2006 From: pc at p-cos.net (Pascal Costanza) Date: Fri, 23 Jun 2006 13:46:47 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: <1150988625.527780.148710@c74g2000cwc.googlegroups.com> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150902275.129780.50260@p79g2000cwp.googlegroups.com> <1150918629.818145.143220@y41g2000cwy.googlegroups.com> <4fv081F1jh4ifU1@individual.net> <1150967543.947096.72840@g10g2000cwb.googlegroups.com> <4fv84rF1kp06kU1@individual.net> <1150988625.527780.148710@c74g2000cwc.googlegroups.com> Message-ID: <4g22l7F1j8p4mU1@individual.net> Marshall wrote: > Pascal Costanza wrote: >> Consider a simple expression like 'a + b': In a dynamically typed >> language, all I need to have in mind is that the program will attempt to >> add two numbers. In a statically typed language, I additionally need to >> know that there must a guarantee that a and b will always hold numbers. > > I still don't really see the difference. > > I would not expect that the dynamic programmer will be > thinking that this code will have two numbers most of the > time but sometimes not, and fail. I would expect that in both > static and dynamic, the thought is that that code is adding > two numbers, with the difference being the static context > gives one a proof that this is so. There is a third option: it may be that at the point where I am writing this code, I simply don't bother yet whether a and b will always be numbers. In case something other than numbers pop up, I can then make a decision how to proceed from there. > In this simple example, > the static case is better, but this is not free, and the cost > of the static case is evident elsewhere, but maybe not > illuminated by this example. Yes, maybe the example is not the best one. This kind of example, however, occurs quite often when programming in an object-oriented style, where you don't know yet what objects will and will not respond to a message / generic function. Even in the example above, it could be that you can give an appropriate definition for + for objects other than numbers. Pascal -- 3rd European Lisp Workshop July 3 - Nantes, France - co-located with ECOOP 2006 http://lisp-ecoop06.bknr.net/ From aljosa.mohorovic at gmail.com Thu Jun 1 08:09:14 2006 From: aljosa.mohorovic at gmail.com (aljosa) Date: 1 Jun 2006 05:09:14 -0700 Subject: py2exe & qt4/qimage Message-ID: <1149163754.826678.95920@h76g2000cwa.googlegroups.com> i'm trying to convert python (image resizer script using PyQt4) script to exe but support for jpeg and tiff image formats is located in Qt4.1\plugins\imageformats (dll files) and when script is converted exe file doesn't support jpeg and tiff. i tryed using all file formats in script: tmp1 = QImage('images/type.bmp') tmp2 = QImage('images/type.gif') tmp3 = QImage('images/type.jpg') tmp4 = QImage('images/type.png') tmp5 = QImage('images/type.tif') but it doesn't work when i convert script to exe. any tips on howto include jpeg and tiff image formats support in exe? From 3dbernard at gmail.com Wed Jun 7 13:54:54 2006 From: 3dbernard at gmail.com (Bernard Lebel) Date: Wed, 7 Jun 2006 13:54:54 -0400 Subject: Very nice python IDE (windows only) In-Reply-To: <1149701880.540109.10100@y43g2000cwc.googlegroups.com> References: <1149694235.741274.325200@u72g2000cwu.googlegroups.com> <1149701880.540109.10100@y43g2000cwc.googlegroups.com> Message-ID: <61d0e2b40606071054y720a22f1hf1c53caa72fde3c1@mail.gmail.com> Not me. I'll probably sound pedantic but - the editor text looks awful, changing the editor options had no effect at all - there is no network access of UNC paths other than through File > Open and Python Paths..... all of my code is on a network location - expanding and collapsing directories is done with a transition effect.... that drives me nuts Bernard On 7 Jun 2006 10:38:00 -0700, sam wrote: > Very interesting, I have downloaded it,and I like what I see. > > ago wrote: > > I have just discovered Python Scripter by Kiriakos Vlahos and it was a > > pleasant surprise. I thought that it deserved to be signalled. It is > > slim and fairly fast, with embedded graphical debugger, class browser, > > file browser... If you are into graphical IDEs you are probably going > > to enjoy it. Windows only unfortunately. > > > > http://mmm-experts.com/Products.aspx?ProductId=4 > > -- > http://mail.python.org/mailman/listinfo/python-list > From steven.bethard at gmail.com Sat Jun 17 23:28:37 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 17 Jun 2006 21:28:37 -0600 Subject: add elements to indexed list locations In-Reply-To: <1150528979.036821.246410@g10g2000cwb.googlegroups.com> References: <1150478265.122559.283000@f6g2000cwb.googlegroups.com> <7rmdnTyLF8gNcw_ZnZ2dnUVZ_v2dnZ2d@comcast.com> <1150528979.036821.246410@g10g2000cwb.googlegroups.com> Message-ID: levent wrote: > Thanks for the answers. Enumerating in reverse is indeed quite a smart > idea. > > The fact is though, I overly simplified the task in the super-hero > example. In the real case, the dictionary keys are not necessarily the > indices for inserts; that is to say, the inserts do not necessarily > take place in some sorted order. > > I think I was thinking more of a linked-list idea, where you do not > store the indices as integers to some random access array but rather as > pointers into list's nodes. Then the subsequent inserts would not hurt > previously stored pointers. For those who know a bit C++/STL here is a > sketch of the idea: Sorry, I don't know C++/STL, so I don't understand the example you gave. If your dict doesn't already come with the indices, can't you just create a dict that does? >>> heros = ["super", "clark", "spider", "peter", "bat", "bruce"] >>> names = dict(clark="kent", peter="parker", bruce="wayne") >>> heros_indices = {} >>> for index, hero_word in enumerate(heros): ... if hero_word in names: ... heros_indices[index + 1] = names[hero_word] ... >>> for index in sorted(heros_indices, reverse=True): ... heros.insert(index, heros_indices[index]) ... >>> heros ['super', 'clark', 'kent', 'spider', 'peter', 'parker', 'bat', 'bruce', 'wayne'] STeVe From sreeram at tachyontech.net Fri Jun 2 14:19:17 2006 From: sreeram at tachyontech.net (K.S.Sreeram) Date: Fri, 02 Jun 2006 23:49:17 +0530 Subject: announce: DaVinci Rendering Engine Message-ID: <44808125.9050607@tachyontech.net> Hi All, I've started working on a new open source graphics library called DaVinci. DaVinci aims to provide a declarative vector graphics based framework for building GUIs. http://tachyon.in/davinci/ It is being built on top of Anti-Grain Geometry and PyQt4. Currently, dvpaint, a python wrapper around AGG is available, along with some demo code. Any and all feedback is welcome! Regards Sreeram -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 260 bytes Desc: OpenPGP digital signature URL: From pc at p-cos.net Mon Jun 26 13:41:06 2006 From: pc at p-cos.net (Pascal Costanza) Date: Mon, 26 Jun 2006 19:41:06 +0200 Subject: What is a type error? In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <7i3mg.204167$8W1.155367@fe1.news.blueyonder.co.uk> <44992e6c$2$664$bed64819@news.gradwell.net> <%Igmg.464974$xt.353729@fe3.news.blueyonder.co.uk> <4fv0v3F1kipa6U1@individual.net> Message-ID: <4gakhiF1m698cU1@individual.net> David Hopwood wrote: > Pascal Costanza wrote: >> Chris Smith wrote: >> >>> While this effort to salvage the term "type error" in dynamic >>> languages is interesting, I fear it will fail. Either we'll all have >>> to admit that "type" in the dynamic sense is a psychological concept >>> with no precise technical definition (as was at least hinted by >>> Anton's post earlier, whether intentionally or not) or someone is >>> going to have to propose a technical meaning that makes sense, >>> independently of what is meant by "type" in a static system. >> What about this: You get a type error when the program attempts to >> invoke an operation on values that are not appropriate for this operation. >> >> Examples: adding numbers to strings; determining the string-length of a >> number; applying a function on the wrong number of parameters; applying >> a non-function; accessing an array with out-of-bound indexes; etc. > > This makes essentially all run-time errors (including assertion failures, > etc.) "type errors". It is neither consistent with, nor any improvement > on, the existing vaguely defined usage. Nope. This is again a matter of getting the levels right. Consider division by zero: appropriate arguments for division are numbers, including the zero. The dynamic type check will typically not check whether the second argument is zero, but will count on the fact that the processor will raise an exception one level deeper. This is maybe better understandable in user-level code. Consider the following class definition: class Person { String name; int age; void buyPorn() { if (< this.age 18) throw new AgeRestrictionException(); ... } } The message p.buyPorn() is a perfectly valid message send and will pass both static and dynamic type tests (given p is of type Person in the static case). However, you will still get a runtime error. Pascal -- 3rd European Lisp Workshop July 3 - Nantes, France - co-located with ECOOP 2006 http://lisp-ecoop06.bknr.net/ From fredrik at pythonware.com Tue Jun 6 13:41:15 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 06 Jun 2006 19:41:15 +0200 Subject: newbie: python application on a web page In-Reply-To: <1149615269.695229.88820@j55g2000cwa.googlegroups.com> References: <1149615269.695229.88820@j55g2000cwa.googlegroups.com> Message-ID: puzz wrote: > I made this Python calculator that will take an equation as an input > and will display the computed curves on a shiny Tkinter interface well, it doesn't sound like you're quite as newbie-ish as many other newbies ;-) > Now, I'd like to make this application available on a public web > page... and all I could come up with was this post some potentially useful links: http://tkinter.unpythonic.net/wiki/ http://infogami.com/ http://pages.google.com > I'd also appreciate a link to a beginner forum assuming "beginner" implies "really wants to learn", this one's quite nice: http://mail.python.org/mailman/listinfo/tutor From fredrik at pythonware.com Wed Jun 21 09:35:17 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 21 Jun 2006 15:35:17 +0200 Subject: Search substring in a string and get index of all occurances References: <4499034A.9040306@gmail.com><200606211345.52243.maric@aristote.info> <44993B22.3040807@tachyontech.net> Message-ID: K.S.Sreeram wrote: > effbot's solution finds overlapping occurrences, whereas your solution > finds non-overlapping occurrences. So efficiency comparisons are not valid. oops. my bad. here's a fixed version: result = []; pos = 0 try: while 1: pos = mystring.index(substr, pos) result.append(pos) pos += len(substr) except ValueError: pass # done or, if you prefer the generator variant: def finditer(string, substr): pos = 0 index = string.index try: while 1: pos = index(substr, pos) yield pos pos += len(substr) except ValueError: pass # done From Kiran.Karra at gmail.com Tue Jun 6 10:31:43 2006 From: Kiran.Karra at gmail.com (Kiran) Date: 6 Jun 2006 07:31:43 -0700 Subject: Namespace problems In-Reply-To: <1149603634.391551.229700@c74g2000cwc.googlegroups.com> References: <1149603634.391551.229700@c74g2000cwc.googlegroups.com> Message-ID: <1149604303.022119.242750@h76g2000cwa.googlegroups.com> I should note that if you use the execfile command in the console, the script runs, but if you import the script, it says it cant find the module From onurb at xiludom.gro Mon Jun 26 12:36:00 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Mon, 26 Jun 2006 18:36:00 +0200 Subject: Mix-In Class Methods At Run-Time In-Reply-To: <1151327819.320233.305400@i40g2000cwc.googlegroups.com> References: <1151191406.755252.210300@i40g2000cwc.googlegroups.com> <1151193767.589325.158820@m73g2000cwd.googlegroups.com> <1151269186.710343.41210@c74g2000cwc.googlegroups.com> <1151270770.030282.237050@u72g2000cwu.googlegroups.com> <449fa027$0$24929$626a54ce@news.free.fr> <1151327819.320233.305400@i40g2000cwc.googlegroups.com> Message-ID: <44a00cf0$0$19040$636a55ce@news.free.fr> digitalorganics at gmail.com wrote: > Bruno Desthuilliers wrote: > >>digitalorganics at gmail.com wrote: (snip) >>>and 2) what's the reason to use newstyle classes >>>versus the old? >> >>All this is explained on python.org (there's a menu entry for this in >>the documentation menu). AFAICT, newstyle classes can do whatever >>oldstyle classes did, *and much more* (descriptors and usable >>metaclasses) - and they are somewhat faster too. So - compatibility with >>older Python versions (< 2.2 IIRC) set aside -, there's just no reason >>to use oldstyle classes. >> >> >>> In order to create the dynamic class "NewClass" in the >>>code above I called type() but that requires at least one new style >>>class as a base. Thus, I had to have at least one of my animals inherit >>>from "object" and this seemed a nuisance since >> >>OMG, eight more keystrokes - talk about a nuisance... > > > Like, Oh My God! *claps hand to mouth* lol You humor me. Yes, eight > more keystrokes. I follow the general rule of, if I'm going to put in > extra effort, OMG, eight more keystrokes - talk about extra effort !-) > I'd like to know why. The only reason for *not* doing it would be compat issues with pre 2.2.x versions. > So you see, it's not so much an > adversion to the eight keystrokes (multiplied by however many classes I > have mind you), Strange enough, I do write my share of Python code, and don't even notice typing the EightKeystrokes. > but to not knowing why I should use them. Because they are kind of the standard Python object model since 2.2.x ?-) Did you at least take time to read the doc on newstyle classes on python.org ? FWIW, with 2.5, even exceptions are now newstyle classes. No more oldstyle classes in the builtins. And AFAICT, no more oldstyle classes in the standard lib neither. Does that ring a bell ? > If I don't > care for descriptors or metaclasses, You *do* care for descriptors. Without descriptors, no properties, no classmethods, no staticmethods... What a desolation :( More seriously, given what you're into actually, not caring about what one can do with newstyle classes seems really strange to me - like digging a swimming-pool with a pick and a shovel when you have an excavator... (disclaimer : google translation, not sure it makes sens in english...) > I don't see why I should feel > compelled to use them. "them" -> "newstyle classes" or "descriptors and metaclasses" ? > And when I decide I want/need these features, I > can put the eight keystroke in at that time. What can I say ? That's your code, not mine... -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From fredrik at pythonware.com Wed Jun 21 11:00:32 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 21 Jun 2006 17:00:32 +0200 Subject: Search substring in a string and get index of all occurances In-Reply-To: <44993DE1.7030302@tim.thechases.com> References: <4499034A.9040306@gmail.com> <44993DE1.7030302@tim.thechases.com> Message-ID: Tim Chase wrote: > >>> indicies = [i for i in xrange(len(mystring)) if mystring.startswith(substr, i)] > >>> indicies > [4, 8, 10, 17, 22] > > is my preferred way of doing this. it's things like this that makes me wonder why I spent a week speeding up the string implementation for Python 2.5 (with special emphasis on find/index-related performance)... From marshall.spight at gmail.com Tue Jun 27 11:08:03 2006 From: marshall.spight at gmail.com (Marshall) Date: 27 Jun 2006 08:08:03 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <1151384511.223582.305760@m73g2000cwd.googlegroups.com> Message-ID: <1151420883.426116.288300@b68g2000cwa.googlegroups.com> David Hopwood wrote: > Marshall wrote: > > The real question is, are there some programs that we > > can't write *at all* in a statically typed language, because > > they'll *never* be typable? > > In a statically typed language that has a "dynamic" type, all > dynamically typed programs are straightforwardly expressible. So, how does this "dynamic" type work? It can't simply be the "any" type, because that type has no/few functions defined on it. It strikes me that *when* exactly binding happens will matter. In a statically typed language, it may be that all binding occurs at compile time, and in a dynamic language, it may be that all binding occurs at runtime. So you might have to change the binding mechanism as well. Does the "dynamic" type allow this? Marshall From pslana at gmail.com Wed Jun 21 03:52:05 2006 From: pslana at gmail.com (pierre_py) Date: 21 Jun 2006 00:52:05 -0700 Subject: wxStyledTextCtrl and sql syntax highlightning Message-ID: <1150876325.128357.129460@p79g2000cwp.googlegroups.com> Hi. I use wxPy version 2.4.2 for Python 2.3. Now I wanted to use the wxStyledTextCtrl for viewing (editing) of sql code. I have the following: self.__m_styled_text_ctrl = wxPython.stc.wxStyledTextCtrl( self, wx.NewId(), style=wxPython.wx.wxNO_FULL_REPAINT_ON_RESIZE) self.__m_styled_text_ctrl.SetLexer(wxPython.stc.wxSTC_LEX_SQL) self.__m_styled_text_ctrl.SetProperty("fold", "1") self.__m_styled_text_ctrl.SetMargins(0,0) self.__m_styled_text_ctrl.SetKeyWords(0, SQL_KEYWORDS) Where sql_keywords is string with space separated sql keywords. When i add text to the ctrl i don't get the right highlightning. What do i do wrong and what else do i have to specify? thx in advance From johnjsal at NOSPAMgmail.com Thu Jun 8 14:18:51 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 08 Jun 2006 18:18:51 GMT Subject: wxpython: where is the demo? In-Reply-To: <1149790377.609121.130860@f6g2000cwb.googlegroups.com> References: <1149790377.609121.130860@f6g2000cwb.googlegroups.com> Message-ID: vasudevram wrote: > Its a separate download. Thanks guys, I completely forgot it was separate! :) From steven.bethard at gmail.com Fri Jun 16 13:46:56 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 16 Jun 2006 11:46:56 -0600 Subject: add elements to indexed list locations In-Reply-To: <1150478265.122559.283000@f6g2000cwb.googlegroups.com> References: <1150478265.122559.283000@f6g2000cwb.googlegroups.com> Message-ID: <7rmdnTyLF8gNcw_ZnZ2dnUVZ_v2dnZ2d@comcast.com> leventyilmaz at gmail.com wrote: > # I have a list of names: > names = ['clark', 'super', 'peter', 'spider', 'bruce', 'bat'] > > # and another set of names that I want to insert into > # the names list at some indexed locations: > surnames = { 1: 'kent', 3:'parker', 5:'wayne' } > > # The thing I couldn't figure out is, after I insert a > # surname the rest of the indices are not valid. > # That is, the following won't work: > for i, x in surnames.iteritems(): > names.insert(i,surnames[i]) This seems to work (tested only with what you see below):: >>> names = ['clark', 'super', 'peter', 'spider', 'bruce', 'bat'] >>> surnames = {1:'kent', 3:'parker', 5:'wayne'} >>> for index in sorted(surnames, reverse=True): ... names.insert(index, surnames[index]) ... >>> names ['clark', 'kent', 'super', 'peter', 'parker', 'spider', 'bruce', 'wayne', 'bat'] I just did the inserts from right to left, that is, starting at the end. That way, after an insert, I don't have to adjust any indices. You may also find that if you do a lot of inserts into the list, it may be more efficient to create a new list, e.g.:: >>> names = ['clark', 'super', 'peter', 'spider', 'bruce', 'bat'] >>> surnames = {1:'kent', 3:'parker', 5:'wayne'} >>> new_names = [] >>> for i, name in enumerate(names): ... if i in surnames: ... new_names.append(surnames[i]) ... new_names.append(name) ... >>> new_names ['clark', 'kent', 'super', 'peter', 'parker', 'spider', 'bruce', 'wayne', 'bat'] STeVe From raffaelcavallaro at pas-d'espam-s'il-vous-plait-mac.com Fri Jun 16 11:49:23 2006 From: raffaelcavallaro at pas-d'espam-s'il-vous-plait-mac.com (Raffael Cavallaro) Date: Fri, 16 Jun 2006 11:49:23 -0400 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <2006061410510511272-raffaelcavallaro@pasdespamsilvousplaitmaccom> <2006061501423327544-raffaelcavallaro@pasdespamsilvousplaitmaccom> Message-ID: <2006061611492350073-raffaelcavallaro@pasdespamsilvousplaitmaccom> On 2006-06-16 05:22:08 -0400, Joachim Durchholz said: > And this is a typical dynamic type advocate's response when told that > static typing has different needs: > > "*I* don't see the usefulness of static typing so *you* shouldn't want > it, either." But I haven't made this sort of argument. I never said you shouldn't use static typing if you want to. There are indeed types of software where one wants the guarantees provided by static type checks. For example, software that controls irreplaceable or very expensive equipment such as space craft, or software that can kill people if it fails such as software for aircraft or medical devices. The problem for static typing advocates is that most software is not of this type. There is a very large class of software where user inputs are unpredictable and/or where input data comes from an untrusted source. In these cases run-time checks are going to be needed anyway so the advantages of static type checking are greatly reduced - you end up doing run-time checks anyway, precisely the thing you were trying to avoid by doing static analysis. In software like this it isn't worth satisfying a static type checker because you don't get much of the benefit anyway and it means forgoing such advantages of dynamic typing as being able to run and test portions of a program before other parts are written (forward references to as yet nonexistent functions). Ideally one wants a language with switchable typing - static where possible and necessary, dynamic elsewhere. To a certain extent this is what common lisp does but it requires programmer declarations. Some implementations try to move beyond this by doing type inference and alerting the programmer to potential static guarantees that the programmer could make that would allow the compiler to do a better job. In effect the argument comes down to which kind of typing one thinks should be the default. Dynamic typing advocates think that static typing is the wrong default. The notion that static typing can prove program correctness is flawed - it can only prove that type constraints are not violated but not necessarily that program logic is correct. It seems to me that if we set aside that class of software where safety is paramount - mostly embedded software such as aircraft and medical devices - we are left mostly with efficiency concerns. The 80-20 rule suggests that most code doesn't really need the efficiency provided by static guarantees. So static typing should be invoked for that small portion of a program where efficiency is really needed and that dynamic typing should be the default elswhere. This is how common lisp works - dynamic typing by default with static guarantees available where one needs them. From uval at rz.uni-karlsruhe.de Sun Jun 11 20:52:38 2006 From: uval at rz.uni-karlsruhe.de (=?ISO-8859-1?Q?Sch=FCle_Daniel?=) Date: Mon, 12 Jun 2006 02:52:38 +0200 Subject: @func call syntax In-Reply-To: <1150068780.001520.326910@g10g2000cwb.googlegroups.com> References: <1150068780.001520.326910@g10g2000cwb.googlegroups.com> Message-ID: this is decorator, this is how it's may be implented >>> def returns(t): ... def dec(f): ... def wrapped(*args, **kwargs): ... ret = f(*args, **kwargs) ... assert type(ret) is t ... return ret ... return wrapped ... return dec ... >>> >>> @returns(int) ... def f1(): ... return 1 ... >>> @returns(float) ... def f2(): ... return 2.0 ... >>> @returns(str) ... def f3(): ... return 1 ... >>> f1() 1 >>> f2() 2.0 >>> f3() Traceback (most recent call last): File "", line 1, in ? File "", line 5, in wrapped AssertionError >>> I can imagine that stuff like this may be extremely usefull when testing you program later one could parse and remove all such assertations easy and cut them all at once Regards, Daniel From bayazee at gmail.com Tue Jun 20 09:28:26 2006 From: bayazee at gmail.com (Bayazee) Date: 20 Jun 2006 06:28:26 -0700 Subject: =?iso-8859-1?q?Re:_comparing_of_python_GUI=B4s?= In-Reply-To: References: <1150806788.026172.140150@h76g2000cwa.googlegroups.com> <4fq979F1k6o98U1@uni-berlin.de> Message-ID: <1150810106.501767.133490@c74g2000cwc.googlegroups.com> ThanX ... any idea for choosing one of them ? best in linux & windows i must write a cross platform project . it is a chat server and client with a user end site . i started by writing a web site and creating a database in MySQL (FC4) . now i want to write a client with gui . similir to yahoo messenger or ... whats your suggest ? From austuff at gmail.com Thu Jun 15 09:07:12 2006 From: austuff at gmail.com (janama) Date: 15 Jun 2006 06:07:12 -0700 Subject: Newbie wxpython staticbitmap help please References: <1150325882.038508.122780@g10g2000cwb.googlegroups.com> <4490f8b6$0$7766$7a628cd7@news.club-internet.fr> Message-ID: <1150376832.271801.19920@f6g2000cwb.googlegroups.com> jean-michel bain-cornu wrote: > Why won't you write it yourself using the demo ? > It's clear and well documented. > Regards, > jm Hi, have been just trying for 5 hours with the timer demo in wx, i just havnt clicked with how to tie it in together, I know (think) i need the following features from the timer demo , where you can periodically call a function using the wx.timer self.Bind(wx.EVT_TIMER, self.OnTest1Timer) #---(bind to the frame ?) self.Bind(wx.EVT_BUTTON, self.OnTest3Start, t3b1) #---(this binds to a button, how do i bind to my application on load or startup instead ?) def OnTest1Timer(self, evt): self.log.write("got EVT_TIMER event\n") #---(dont think i need the logging?) def OnTest3Start(self, evt): self.t3 = NotifyTimer(self.log) self.t3.Start(1000) self.log.write("NotifyTimer timer started\n") self.t3b2.Enable() #---(the Start i guess i will work if i remap the button event to an on load type? event? def OnTest3Stop(self, evt): self.t3.Stop() self.log.write("NotifyTimer timer stoped\n") del self.t3 self.t3b2.Disable() #---(Guess i wont need to stop the timer, as i want it to trigger the 'refreshing' of the StaticBitmaps ?) # When deriving from wx.Timer you must provide a Notify method # that will be called when the timer expires. class NotifyTimer(wx.Timer): def __init__(self, log): wx.Timer.__init__(self) self.log = log def Notify(self): self.log.write("got NotifyTimer event\n") #---(dont know if i need this if i dont want to use this log feature)? Im sorry if this all seems really amatuerish, i have genuially tried hard to get my head around it , but i get error after error in boa. Somewhone couldnt append a timer and perhaps help to refresh the StaticBitmaps described, with the code, in first post). I will be able to see and learn greatly from this. Maybe some advice on where to find lists of the methods used in wxpython For example it took me hours to find methods ? like StaticBitmap.SetImage("imageName") Is there any good lists of these methods, properties etc for wxpython controls? Any good wxpython ide/editors that can "intellisense" them? boa, komodo, stani's arnt working with "intellisensing" wx for me, (maybe i cant configure them though) Thanks for any help with any of this Regards From marshall.spight at gmail.com Fri Jun 23 17:52:59 2006 From: marshall.spight at gmail.com (Marshall) Date: 23 Jun 2006 14:52:59 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <7zpshbsvjy.fsf@app-1.diku.dk><4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150902275.129780.50260@p79g2000cwp.googlegroups.com> <1150918629.818145.143220@y41g2000cwy.googlegroups.com> <4fv081F1jh4ifU1@individual.net> <1150967543.947096.72840@g10g2000cwb.googlegroups.com> <4fv84rF1kp06kU1@individual.net> <1150988625.527780.148710@c74g2000cwc.googlegroups.com> <4g22l7F1j8p4mU1@individual.net> <1151081129.290382.297530@r2g2000cwb.googlegroups.com> Message-ID: <1151099579.205144.145130@r2g2000cwb.googlegroups.com> Darren New wrote: > Marshall wrote: > > I can't see how you'd call + on a and b if you think they might > > not be numbers. > > Now substitute "<" for "+" and see if you can make the same argument. :-) If your point is about overloading, then I don't see how it affects my point. My point was, I don't see why you'd be writing code using operators that you thought might not be applicable to the operands. Marshall From wahab at chemie.uni-halle.de Mon Jun 19 17:30:31 2006 From: wahab at chemie.uni-halle.de (Mirco Wahab) Date: Mon, 19 Jun 2006 23:30:31 +0200 Subject: Seeking regex optimizer In-Reply-To: <1150750294.232093.304230@p79g2000cwp.googlegroups.com> References: <1150650439.651839.38180@y41g2000cwy.googlegroups.com> <1150750294.232093.304230@p79g2000cwp.googlegroups.com> Message-ID: Thus spoke andrewdalke at gmail.com (on 2006-06-19 22:51): > It uses Aho-Corasick for the implementation which is fast and does what > you expect it to do. Nor does it have a problem of matching more than > 99 possible strings as the regexp approach may have. If you pull the strings into (?>( ... )) (atomic groups), this would't happen. http://www.regular-expressions.info/atomic.html ... Everything between (?>) is treated as one single token by the regex engine, once the regex engine leaves the group. Because the entire group is one token, no backtracking can take place once the regex engine has found a match for the group. ... Maybe Py.2.5 will have them? Regards Mrico From max at alcyone.com Sun Jun 25 00:15:17 2006 From: max at alcyone.com (Erik Max Francis) Date: Sat, 24 Jun 2006 21:15:17 -0700 Subject: String negative indices? In-Reply-To: References: <1151054259.765401.252230@b68g2000cwa.googlegroups.com> <1151152577.661130.5690@g10g2000cwb.googlegroups.com> Message-ID: Steven D'Aprano wrote: > In mathematics, well, maybe... certainly in the Real number system, there > is no difference, and +0 and -0 are just two ways of writing the same > thing. In the hyperreals, +0 and -0 are the same, but there are > infinitesimals which are different, and signed. I don't know enough about > the surreals to comment. In matrix maths, there are an infinite number of > different matrices where all the elements are zero -- they are all > distinct, different, zeroes. What do you even mean by that? By "matrix maths," do you just mean matrices whose elements are reals, or something else? -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis My heart is pure as the driven slush. -- Tallulah Bankhead From maric at aristote.info Sat Jun 10 13:23:29 2006 From: maric at aristote.info (Maric Michaud) Date: Sat, 10 Jun 2006 19:23:29 +0200 Subject: Very newbie programming In-Reply-To: <448ae8ce_1@news.tm.net.my> References: <448ae8ce_1@news.tm.net.my> Message-ID: <200606101923.30106.maric@aristote.info> Le Samedi 10 Juin 2006 17:44, TheSaint a ?crit?: > Hello! > Hi, > Is there a more pythonic way to implement the following program: I'll try to make some suggestions. > > 8<--------------8<--------------8<--------------8<-------------- > > #! /usr/bin/env python > > import os > import sys > a = os.listdir('/media') > begin using more explicit variable names. medias = os.listdir('/media') > # no mount dirs were found, exit nicely > > if len(a) == 0: > sys.exit(0) or if not medias : sys.exit(0) and I generally avoid creating names I use only once, so : if not os.listdir('/media') : sys.exit(0) > > # Maybe collecting the arguments via command line > # will make the program more flexible > > mnt = open("/etc/mtab") > ptn = open("/proc/partitions") > dskt = '/home/user/Desktop/' > > c =[] > > # Filling the c with the list of devices which are recorded to be mounted > > d = filter((lambda a: a[:2] =='/d'),mnt.readlines()) # non /dev-mounts are > off > d = map((lambda a: a.split()[:1]),d) # only the first info column is used > > [c.append(str(a)[2:-2]) for a in d] > > # checking against /proc/partitions to see if there're mountpoints without > # corresponding partition which has been removed from the list > # ALL mountpoints with available partition will be removed from the list > There more expressive or more direct ways of doing all these, I like one liners (but a two steps can be more clear) : devices = [ e.split()[0] for e in open("/etc/mtab") if e.startswith('/d') ] > x = ptn.readlines() > for a in x[2:]: > b = a.split()[-1] > for d in c: > if b == d.rsplit('/',1)[-1]: > c.remove(d) > this time we cut in two steps but this also just filtering. partitions = [ e.split()[-1] for e in open("/proc/partitions").readlines() [2:] ] devices = [ e for e in devices if e.split('/')[-1] in partitions ] > if len(c) != 1: > sys.exit(0) # if none or more than one match exit > > cmnd = str(c)[2:-2] > err = os.system('umount ' + cmnd) why ? os.system('umount "%s"' % devices[0]) > a = os.listdir(dskt) > > #retrieve the info from the KDE desktop icons > > for i in a: > if 'desktop' not in i: continue > y = open(dskt + i) > d = y.readlines() > for x in d: > if 'URL=/media' not in x: continue > icon = i > dvc = x[11:-1] > break > this will do exactly the same for icon_file in (open(dskt + e) for e in os.listdir(dskt) if '.desktop' in e) : for line in icon_file : if 'URL=/media' in line : icon = icon.name dvc = line[11:-1] break -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From m.yanowitz at kearfott.com Tue Jun 20 15:39:07 2006 From: m.yanowitz at kearfott.com (Michael Yanowitz) Date: Tue, 20 Jun 2006 15:39:07 -0400 Subject: SWIG problems with gcc and Cygwin? Message-ID: Hello: I am just trying out SWIG, but quickly ran into problems. Using Cygwin gcc, I tried the following: 1) Created example.c (as given on http://www.swig.org/tutorial.html ) /* File : example.c */ #include double My_variable = 3.0; int fact(int n) { if (n <= 1) return 1; else return n*fact(n-1); } int my_mod(int x, int y) { return (x%y); } char *get_time() { time_t ltime; time(<ime); return ctime(<ime); } 2) Create interface file, example.i /* example.i */ %module example %{ /* Put header files here or function declarations like below */ extern double My_variable; extern int fact(int n); extern int my_mod(int x, int y); extern char *get_time(); %} extern double My_variable; extern int fact(int n); extern int my_mod(int x, int y); extern char *get_time(); 3)ran in cygwin: swig -i python example.i 4)Attempted to run on cygwin: ld -shared example.o example_wrap.o -o _example.so But got back many errors: example.o:example.c:(.text+0x55): undefined reference to `time' example.o:example.c:(.text+0x60): undefined reference to `ctime' example_wrap.o:example_wrap.c:(.text+0x9c): undefined reference to `strlen' example_wrap.o:example_wrap.c:(.text+0x12c): undefined reference to `strlen' example_wrap.o:example_wrap.c:(.text+0x1dd): undefined reference to `strcmp' example_wrap.o:example_wrap.c:(.text+0x494): undefined reference to `strcmp' example_wrap.o:example_wrap.c:(.text+0x748): undefined reference to `strlen' example_wrap.o:example_wrap.c:(.text+0x779): undefined reference to `strcpy' example_wrap.o:example_wrap.c:(.text+0x7a5): undefined reference to `strcmp' example_wrap.o:example_wrap.c:(.text+0x805): undefined reference to `strlen' example_wrap.o:example_wrap.c:(.text+0x877): undefined reference to `strncpy' example_wrap.o:example_wrap.c:(.text+0x8ab): undefined reference to `strcmp' example_wrap.o:example_wrap.c:(.text+0x8c9): undefined reference to `memset' example_wrap.o:example_wrap.c:(.text+0x948): undefined reference to `fputs' example_wrap.o:example_wrap.c:(.text+0x95d): undefined reference to `fputs' example_wrap.o:example_wrap.c:(.text+0x970): undefined reference to `fputs' example_wrap.o:example_wrap.c:(.text+0x9db): undefined reference to `PyString_Fr omFormat' example_wrap.o:example_wrap.c:(.text+0xa3a): undefined reference to `PyString_Fr omString' example_wrap.o:example_wrap.c:(.text+0xa68): undefined reference to `PyLong_From VoidPtr' example_wrap.o:example_wrap.c:(.text+0xa83): undefined reference to `PyTuple_New etc... Any idea what I am doing wrong or omitted? Of course when I then try to go into python and import example, I get: >>> import example Traceback (most recent call last): File "", line 1, in ? File "example.py", line 5, in ? import _example ImportError: No module named _example Thanks in advance: Michael Yanowitz From justin.mailinglists at gmail.com Thu Jun 15 01:05:40 2006 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: 14 Jun 2006 22:05:40 -0700 Subject: Database read and write References: Message-ID: <1150347940.257951.207770@i40g2000cwc.googlegroups.com> Stan Cook wrote: > will ope, read, and write to a Dbase 3 or 4 file? I know I have one in VB6 that I've been meaning to translate to Python but... (do not have time/am lazy/does not work with indexes) did a google search for you though http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/362715 http://www.garshol.priv.no/download/software/python/dbfreader.py From robert.kern at gmail.com Wed Jun 28 03:50:50 2006 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 28 Jun 2006 02:50:50 -0500 Subject: Immutability In-Reply-To: References: Message-ID: Nick Maclaren wrote: > The way that I read it, Python allows only values (and hence types) > to be immutable, and not class members. The nearest approach to the > latter is to use the name hiding conventions. > > Is that correct? You can also make properties that don't allow writing. class Foo(object): def __init__(self, bar): self._bar = bar @property def bar(self): return self._bar -- 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 From python.list at tim.thechases.com Sun Jun 25 13:06:04 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 25 Jun 2006 12:06:04 -0500 Subject: array manipulation without for loops In-Reply-To: <1151251578.463273.24370@m73g2000cwd.googlegroups.com> References: <1151251578.463273.24370@m73g2000cwd.googlegroups.com> Message-ID: <449EC27C.3060702@tim.thechases.com> > I have two arrays that are of the same dimension but having 3 different > values: 255, 1 or 2. > I would like to set all the positions in both arrays having 255 to be > equal, i.e., where one array has 255, I set the same elements in the > other array to 255 and visa versa. Does anyone know how to do this > without using for loops? >>> # make some sample data >>> c = 20 >>> import random, itertools >>> a1 = [(1,2,255)[random.randint(0,2)] for x in xrange(c)] >>> a2 = [(1,2,255)[random.randint(0,2)] for x in xrange(c)] >>> >>> # actually do the work >>> all = [(x==255 or y==255) and (255, 255) or (x,y) for (x,y) in itertools.izip(a1,a2)] >>> b1 = [x[0] for x in all] >>> b2 = [x[1] for x in all] >>> a1, a2 = b1, b2 # if you want them to replace the originals Seems to do what I understand that you're describing using "no" loops (other than those implied by list comprehension). There may be some nice pythonic way to "unzip" a list of tuples created by zip() but I couldn't scare up such a method, and searching for "unzip" turned up a blizzard of hits for dealing with ZIP files, not for unzipping that which was previously zip()'ed. My google-foo must be broken. :) Otherwise, you could just do >>> b1,b2 = magic_unzip([(x==255 or y==255) and (255, 255) or (x,y) for (x,y) in itertools.izip(a1,a2)]) or >>> a1,a2 = magic_unzip([(x==255 or y==255) and (255, 255) or (x,y) for (x,y) in itertools.izip(a1,a2)]) if you just want to dispose of your originals. -tkc From steve at holdenweb.com Wed Jun 7 10:35:28 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 07 Jun 2006 15:35:28 +0100 Subject: Django Quick Start with Schema Evolution Support In-Reply-To: References: <1149446706.085692.174980@h76g2000cwa.googlegroups.com> <1149505316.406428.242450@c74g2000cwc.googlegroups.com> <448429E1.90305@kered.org> <35081.132.60.240.80.1149530454.squirrel@kered.org> <4486D6F2.7000407@lazaridis.com> Message-ID: Ilias Lazaridis wrote: > Steve Holden wrote: > >>Ilias Lazaridis wrote: >> >>>[Replying to comp.lang.python, due to censorship on Django User] >>>[additional notification of poster via email, as medium is changed] >>> >> >>And yet you still don't see why people call you a troll? > > > Missing liberal qualities? > > http://dev.lazaridis.com/base/wiki/LiberalProjectDefinition > Your definition, not anyone else's. And not a very good one IMO. > >>This is completely inappropriate for comp.lang.python. Please take it >>elsewhere. > > > This is perfectly appropriate for comp.lang.python, as it is the closest > usenet group for django. > Nope, the Django group is that. This is *not* a substitute, and it is *not* acceptable to post to "the closest usenet group" to one that won't tolerate your actions. > >>This newsgroup is not a proxy for any other group who may have tired of >>your postings, and is not an arbitration forum for disputes. > > > no. > > It's a place to discuss python. > > And it's a place to continue discussions which were censored within > other media of the python domain. > Sorry, that's exactly what it isn't. Kindly stop. > - > > sidenote: > > I forgot to post the link to the original article: > > http://groups.google.com/group/django-users/msg/710f456a3c1f1ee5 > I repeat: and yet you still don't see why people call you a troll? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From dieter at handshake.de Fri Jun 23 16:13:59 2006 From: dieter at handshake.de (Dieter Maurer) Date: 23 Jun 2006 22:13:59 +0200 Subject: need helping tracking down weird bug in cPickle References: <449833A4.7000905@mvista.com> Message-ID: [Carl J. Van Arsdall] > Hey everyone, cPickle is raising an ImportError that I just don't quite > understand. When I get in such a situation, I replace "cPickle" with Python's "pickle". Usually, I get the same exception -- but this time with a traceback that can be analysed with "pdb.pm()". Usually, this lets me understand... Dieter From deets at nospam.web.de Tue Jun 27 12:37:22 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 27 Jun 2006 18:37:22 +0200 Subject: What is Expressiveness in a Computer Language References: <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <1151384511.223582.305760@m73g2000cwd.googlegroups.com> <1151425350.679754.278820@i40g2000cwc.googlegroups.com> Message-ID: <4gd56eF1n07dbU1@uni-berlin.de> >> The C++ type system is Turing complete, although in practical terms >> it limits how much processing power it will spend on types at >> compile time. > > I think templates only have to expand to seven levels, so you are > severely limited here. You can adjust the iteration-depth. However, as turing-complete implies the potential to create infinite loops - it enforces _some_ boundary. Otherwise the user hitting C-c will do :) Diez From brian at sweetapp.com Fri Jun 2 11:54:59 2006 From: brian at sweetapp.com (Brian Quinlan) Date: Fri, 02 Jun 2006 17:54:59 +0200 Subject: Sampling a population Message-ID: <44805F53.6090409@sweetapp.com> This is less a Python question and more a optimization/probability question. Imaging that you have a list of objects and there frequency in a population e.g. lst = [(a, 0.01), (b, 0.05), (c, 0.50), (d, 0.30), (e, 0.04), (f, 0.10)] and you want to drawn n items from that list (duplicates allowed), with that probability distribution. The fastest algorithm that I have been able to devise for doing so is: O(n * log(len(lst))). Can anyone think or a solution with a better time complexity? If not, is there an obviously better way to do this (assuming n is big and the list size is small). Here is the code: from random import random from bisect import bisect def draw(n, lst): ps = [] last = 0 for p in lst: ps.append(last + p) last += p # ps = [0.01, 0.06, 0.56, 0.86, 0.90, 1.00] chosen = [0] * len(lst) # track frequency for i in range(n): r = random() chosen[bisect(ps, r)] += 1 # binary search and increment result = [] # rescale probability based on frequency for c in chosen: result.append(float(c) / n) return result lst = [0.01, 0.05, 0.50, 0.30, 0.04, 0.10] print draw(10000, lst) From *firstname*nlsnews at georgea*lastname*.com Thu Jun 15 15:34:08 2006 From: *firstname*nlsnews at georgea*lastname*.com (Tony Nelson) Date: Thu, 15 Jun 2006 19:34:08 GMT Subject: Trace KeyboardInterrupt exception? References: <*firstname*nlsnews-B3800F.13431013062006@news.verizon.net> <1150293702.090195.324550@y43g2000cwc.googlegroups.com> <*firstname*nlsnews-04EFB8.13261714062006@news.verizon.net> <1150357101.984761.63310@u72g2000cwu.googlegroups.com> Message-ID: <*firstname*nlsnews-6916F2.15342215062006@news.verizon.net> In article <1150357101.984761.63310 at u72g2000cwu.googlegroups.com>, "yairchu at gmail.com" wrote: > if you want to interrupt the code to find out where it is, > you can instead connect to it in gdb and get the python traceback of > each thread. > if you're interested I'll post the necesary gdb-macro for that (didn't > put it on the net yet) I think I've found the problem, using Python's Bugzilla. This appears to be unresolved Python bug 926423, unresolved proposed patch 1102879, don't know if anything ever came of it. See other thread. ________________________________________________________________________ TonyN.:' *firstname*nlsnews at georgea*lastname*.com ' From fairwinds at eastlink.ca Fri Jun 2 19:17:02 2006 From: fairwinds at eastlink.ca (David Pratt) Date: Fri, 02 Jun 2006 20:17:02 -0300 Subject: Initializing an attribute that needs the object In-Reply-To: <4480be5b$0$27367$626a54ce@news.free.fr> References: <4480be5b$0$27367$626a54ce@news.free.fr> Message-ID: <4480C6EE.1090909@eastlink.ca> Hi Bruno. This is certainly what I was missing. Thank you. I am afraid I am behind the times with use of object. Will I only use object when I am not subclassing? Where will I find a document that provides info on the use of object in new style classes? Many thanks. Regards, David Bruno Desthuilliers wrote: > David Pratt a ?crit : >> Hi. I want to have different handlers to do perform logic. The problem >> is the Handler requires an instance of the factory since it will use its >> own methods in conjunction with methods of the factory. >> >> Once I have got a Factory instance I can give it a new handler (see >> below). It would be more flexible if I could provide a handle in >> constructor - but how to do this when it requires the object itself. > > Hint : Python classes are objects too. > >> class Factory: > > Do yourself a favour : use new-style classes. > > class Factory(object): > def __init__(self, handler_class): > self.handler = handler_class(self) > > class SomeHandler(object): > def __init__(self, factory): > self.factory = factory > > f = Factory(SomeHandler) From digitalorganics at gmail.com Mon Jun 26 16:37:39 2006 From: digitalorganics at gmail.com (digitalorganics at gmail.com) Date: 26 Jun 2006 13:37:39 -0700 Subject: Replace Whole Object Through Object Method In-Reply-To: <44a041a6$0$17612$636a55ce@news.free.fr> References: <1151337453.804750.293180@b68g2000cwa.googlegroups.com> <44a0132d$0$21282$626a54ce@news.free.fr> <1151342941.256085.243000@p79g2000cwp.googlegroups.com> <44a041a6$0$17612$636a55ce@news.free.fr> Message-ID: <1151354259.082966.25820@p79g2000cwp.googlegroups.com> Bruno Desthuilliers wrote: > digitalorganics at gmail.com a ?crit : > > Bruno Desthuilliers wrote: > (snip) > >> > >>Instead of exposing problems with your solution, you may want to expose > >>the real use case ? > > > > > > I'm working with a team that's doing social modeling, and for example, > > I need to model workers that at some point in the program may or may > > not also become employers. > > If I understand correctly, only some of the existing workers will become > employers ? > > > Now, I want the workers to take on all > > behaviors and attributes of an employer in addition to their > > pre-existing "worker" behaviors and attributes. > > wrt/ behaviors, it's easy as pie. Attributes (I mean instance > attributes) are another problem, but I don't have enough informations to > deal with this problem here. > > > Also, as I'm sure you > > guessed, the workers' attributes need to retain their values at that > > point in the program, so a brand new worker-employer object wouldn't in > > itself do the trick. > > Here's a simple stupid possible solution: > > class Worker(object): > def __init__(self, ...) > # init code here > > # behaviours here > > def becomeEmployer(self): > self.___class__ = Employer > > class Employer(Worker): > # behaviours here > > > w = Worker(...) > w.becomeEmployer() > > Note that there's no initializer in the Employer class - it wouldn't get > called anyway (not automatically at least). Won't work because there will be employers that aren't workers. And yes, only some workers will become employers, but also only some employers will also be workers (at some point in program). Let me be more clear: workers --> subset of workers --become--> employers employers --> subset of employers --become--> workers It is very important that both should maintain attribute values, regardless of whether they take on new "roles". Furthermore, this is a very simple case and ultimately in my program an object should be able to dynamically take on a multitude of roles (classes of behavior) without mucking at all with their pre-existing states. From raathm at gmail.com Tue Jun 27 09:21:47 2006 From: raathm at gmail.com (Mike) Date: 27 Jun 2006 06:21:47 -0700 Subject: "no module named win32api" using PyWin32-208 Message-ID: <1151414507.408944.291850@c74g2000cwc.googlegroups.com> Hi. I have Python 2.4 installed on my local machine in c:\Python24. I have also downloaded the python for windows extensions installer pywin32-208.win32-py2.4.exe and installed this to C:\Python24\Lib\site-packages Trying to run a python script through a C# console app is causing me problems: the last line of code in the following block results in a no module named win32ap error. I'm not sure if this is because there is no win32api.py in the win32 fikder off site-packages, just a win32api.pyc file. m_engine = new PythonEngine(); m_engine.AddToPath("C:\\Python24\\DLLs"); m_engine.AddToPath("C:\\Python24\\lib"); m_engine.AddToPath("C:\\Python24\\lib\\plat-win"); m_engine.AddToPath("C:\\Python24\\lib\\lib-tk"); m_engine.AddToPath("C:\\Python24\\Lib\\site-packages\\pythonwin"); m_engine.AddToPath("C:\\Python24"); m_engine.AddToPath("C:\\Python24\\lib\\site-packages"); m_engine.AddToPath("C:\\Python24\\lib\\site-packages\\win32"); m_engine.AddToPath("C:\\Python24\\lib\\site-packages\\win32\\lib"); m_engine.Execute("from win32api import win32api"); I have added all the addtopaths to get the path to match the sys.path I see in a normal python console which can successfully import the module. Incidentally, I have tried making the last line m_engine.Execute("import win32api"); with no luck. Can the win32 extensions handle compiled python modules? If not how can I get it to work? Thanks, Mike From bnblazer at gmail.com Thu Jun 1 18:27:22 2006 From: bnblazer at gmail.com (Brian) Date: 1 Jun 2006 15:27:22 -0700 Subject: TSV to HTML In-Reply-To: <7f5u721mhaauqak62krrb4p9ruhicaus45@4ax.com> References: <1149098823.979329.9220@f6g2000cwb.googlegroups.com> <447e268a$0$3699$4d3efbfe@news.sover.net> <1149126509.984331.306530@h76g2000cwa.googlegroups.com> <1149157775.490474.173970@y43g2000cwc.googlegroups.com> <7f5u721mhaauqak62krrb4p9ruhicaus45@4ax.com> Message-ID: <1149200842.674309.323930@g10g2000cwb.googlegroups.com> Dennis Lee Bieber wrote: > On 1 Jun 2006 03:29:35 -0700, "Brian" declaimed the > following in comp.lang.python: > > > Thank you for that response. Your code was very helpful to me. I > > think that actually seeing how it should be done in Python was a lot > > more educational than spending hours with trial and error. > > > It's not the best code around -- I hacked it together pretty much > line-for-line from an assumption of what the Ruby was doing (I don't do > Ruby -- too much PERL idiom in it) > > > One question (and this is a topic that I still have trouble getting my > > arms around). Why is the text in STYLEBLOCK tripple quoted? > > > Triple quotes allow: 1) use of single quotes within the block > without needing to escape them; 2) allows the string to span multiple > lines. Plain string quoting must be one logical line to the parser. > > I've practically never seen anyone use a line continuation character > in Python. And triple quoting looks cleaner than parser concatenation. > > The alternatives would have been: > > Line Continuation: > STYLEBLOCK = '\n\ > \n\ > ' > Note the \n\ as the end of each line; the \n is to keep the > formatting on the generated HTML (otherwise everything would be one long > line) and the final \ (which must be the physical end of line) > signifying "this line is continued". Also note that I used ' rather than > " to avoid escaping the " on text/css. > > Parser Concatenation: > STYLEBLOCK = ( > '\n" > ) > > Note the use of ( ) where the original had """ """. Also note that > each line has quotes at start/end (the first has ' to avoid escaping > text/css). There are no commas separating each line (and the \n is still > for formatting). Using the ( ) creates an expression, and Python is nice > enough to let one split expressions inside () or [lists], {dicts}, over > multiple lines (I used that feature in a few spots to put call arguments > on multiple lines). Two strings that are next to each other > > "string1" "string2" > > are parsed as one string > > "string1string2" > > Using """ (or ''') is the cleanest of those choices, especially if > you want to do preformatted layout of the text. It works similar to the > Ruby/PERL construct that basically said: Copy all text up to the next > occurrence of MARKER_STRING. Thank you for your explanation, now it makes sense. Brian From jhefferon at smcvt.edu Fri Jun 16 16:51:09 2006 From: jhefferon at smcvt.edu (Jim) Date: 16 Jun 2006 13:51:09 -0700 Subject: Cross-site scripting (XSS) defense In-Reply-To: <1150480621.563312.134500@c74g2000cwc.googlegroups.com> References: <1150480621.563312.134500@c74g2000cwc.googlegroups.com> Message-ID: <1150491069.401736.40780@f6g2000cwb.googlegroups.com> Have a look at http://feedparser.org/docs/html-sanitization.html . Jim From avelldiroll at yahoo.fr Wed Jun 21 15:52:57 2006 From: avelldiroll at yahoo.fr (Avell Diroll) Date: Wed, 21 Jun 2006 21:52:57 +0200 Subject: OS specific command in Python In-Reply-To: <1150896882.746722.95200@u72g2000cwu.googlegroups.com> References: <1150781429.090359.148560@c74g2000cwc.googlegroups.com> <1150783324.258644.65770@u72g2000cwu.googlegroups.com> <4498dcd5$0$25503$626a54ce@news.free.fr> <1150896882.746722.95200@u72g2000cwu.googlegroups.com> Message-ID: <4499a392$0$12391$626a54ce@news.free.fr> diffuser78 at gmail.com wrote: > I have a question on getpass. Since I am a newbie you might find it a > little dumb. > > By using the getpass, are u trying to retrieve the username and > password of remote mahcine or local ? > the module getpass contains 2 functions, getuser() and getpass() : getuser() returns the username of the user executing the python script on the machine where the script is executed. getpass() prompts the user for a password and returns it in a string whitout printing it on screen (just as the text mode login on linux or ssh). By the way this is better explained in the official python documentation. http://docs.python.org/lib/module-getpass.html From jmdeschamps at gmail.com Wed Jun 14 19:58:38 2006 From: jmdeschamps at gmail.com (jmdeschamps at gmail.com) Date: 14 Jun 2006 16:58:38 -0700 Subject: found a swftools for 2.4 - Docs anyone? Message-ID: <1150329518.458325.108560@f6g2000cwb.googlegroups.com> New to swf - interesting technology for dynamic web graphic effects stemming from user input. I found a working windows pre-compiled binary (0.6.2) for Python 2.4 of rfxswf library from swftools to generate swf files. (flash compiled files(?)). No source of documentation of that api. There are a few python examples that I managed to make work, from swftools site but only covers partly the api. help(SWF) only tells of the main classes - nothings on arguments I tried reading the C source, but I'm not very fluent in C so that didn't amount to much. Any help appreciated in finding help on this API. Thanks in advance Jean-Marc Ref: http://www.swftools.org/ python binary : http://lists.gnu.org/archive/html/swftools-common/2005-01/msg00066.html (Thanks to Daichi .) From sreeram at tachyontech.net Sat Jun 3 10:21:35 2006 From: sreeram at tachyontech.net (K.S.Sreeram) Date: Sat, 03 Jun 2006 19:51:35 +0530 Subject: image lib & Qt4 In-Reply-To: References: <1149173540.470829.34940@c74g2000cwc.googlegroups.com> <4e8haiF1dp2heU1@uni-berlin.de> <1149180814.585713.209640@i39g2000cwa.googlegroups.com> <44818202.8060607@tachyontech.net> <448191A5.1050502@tachyontech.net> Message-ID: <44819AEF.6040609@tachyontech.net> thanks! so does that mean the BGRA raw mode is supported in PIL 1.1.6? Regards Sreeram Fredrik Lundh wrote: > K.S.Sreeram wrote: > >> I was hacking the code trying to support RGBA mode images, and >> inadvertently i tried im.tostring("raw","BGRX") on the RGBA mode image. >> >> So BGRX does indeed work for RGB mode images. >> >> While trying to support RGBA mode images, i realized that a BGRA raw >> mode is needed for working with QImage. It doesn't seem to be supported >> by PIL. Any workarounds? > > sure! here's a patch: > > Index: ImageQt.py > =================================================================== > --- ImageQt.py (revision 342) > +++ ImageQt.py (working copy) > @@ -58,6 +61,14 @@ > elif im.mode == "RGB": > data = im.tostring("raw", "BGRX") > format = QImage.Format_RGB32 > + elif im.mode == "RGBA": > + try: > + data = im.tostring("raw", "BGRA") > + except SystemError: > + # workaround for earlier versions > + r, g, b, a = im.split() > + im = Image.merge("RGBA", (b, g, r, a)) > + format = QImage.Format_ARGB32 > else: > raise ValueError("unsupported image mode %r" % im.mode) > > > -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 260 bytes Desc: OpenPGP digital signature URL: From frank at chagford.com Mon Jun 26 05:34:34 2006 From: frank at chagford.com (Frank Millman) Date: 26 Jun 2006 02:34:34 -0700 Subject: style question In-Reply-To: <1151314163.701348.195370@u72g2000cwu.googlegroups.com> References: <1151314163.701348.195370@u72g2000cwu.googlegroups.com> Message-ID: <1151314474.696043.201250@b68g2000cwa.googlegroups.com> Frank Millman wrote: > > How about > > message = ("This is line1. " > "This is line2 " > "This is line3\n") > > The brackets mean that the lines are automatically treated as > continuous, without the need for the ugly '\' continuation character. > > The opening/closing quotes on each line mean that the strings are > contatenated into one long string. > > Frank Millman Don't know what happened there - Google seems to have messed up my indentation. My intention was that each of the three leading quote marks line up vertically, but when I read it back via Google Groups, the second two lines were pushed over to the right. Frank From dnew at san.rr.com Fri Jun 16 12:59:41 2006 From: dnew at san.rr.com (Darren New) Date: Fri, 16 Jun 2006 16:59:41 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: <_eBkg.14895$uy3.4988@tornado.socal.rr.com> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <2006061410510511272-raffaelcavallaro@pasdespamsilvousplaitmaccom> <2006061501423327544-raffaelcavallaro@pasdespamsilvousplaitmaccom> <_eBkg.14895$uy3.4988@tornado.socal.rr.com> Message-ID: <1sBkg.14897$uy3.4884@tornado.socal.rr.com> Joachim Durchholz wrote: > Give a heterogenous list that would to too awkward to live in a > statically-typed language. Printf()? -- Darren New / San Diego, CA, USA (PST) My Bath Fu is strong, as I have studied under the Showerin' Monks. From dnew at san.rr.com Fri Jun 16 12:45:46 2006 From: dnew at san.rr.com (Darren New) Date: Fri, 16 Jun 2006 16:45:46 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <2006061410510511272-raffaelcavallaro@pasdespamsilvousplaitmaccom> <2006061501423327544-raffaelcavallaro@pasdespamsilvousplaitmaccom> Message-ID: <_eBkg.14895$uy3.4988@tornado.socal.rr.com> Joachim Durchholz wrote: > Give a heterogenous list that would to too awkward to live in a > statically-typed language. Write a function that takes an arbitrary set of arguments and stores them into a structure allocated on the heap. > Give a case of calling nonexistent functions that's useful. See the Tcl "unknown" proc, used for interactive command expansion, dynamic loading of code on demand, etc. -- Darren New / San Diego, CA, USA (PST) My Bath Fu is strong, as I have studied under the Showerin' Monks. From rossberg at ps.uni-sb.de Thu Jun 29 17:10:08 2006 From: rossberg at ps.uni-sb.de (rossberg at ps.uni-sb.de) Date: 29 Jun 2006 14:10:08 -0700 Subject: What is Expressiveness in a Computer Language [correction] In-Reply-To: <1151521689.654605.261320@p79g2000cwp.googlegroups.com> References: <1151384511.223582.305760@m73g2000cwd.googlegroups.com> <1151425350.679754.278820@i40g2000cwc.googlegroups.com> <7bjog.229500$8W1.29971@fe1.news.blueyonder.co.uk> <1151521689.654605.261320@p79g2000cwp.googlegroups.com> Message-ID: <1151615408.920886.237600@y41g2000cwy.googlegroups.com> Joe Marshall wrote: > Andreas Rossberg wrote: > > > > Which is why this actually is a very bad example to chose for dynamic > > typing advocacy... ;-) > > Actually, this seems a *good* example. The problem seems to be that > you end up throwing the baby out with the bathwater: your static type > system stops catching the errors you want once you make it powerful > enough to express certain programs. That is not the case: you can still express these programs, you just need to do an indirection through a datatype. - Andreas From iainking at gmail.com Mon Jun 5 04:11:14 2006 From: iainking at gmail.com (Iain King) Date: 5 Jun 2006 01:11:14 -0700 Subject: Trying to get FreeImagePy to work. In-Reply-To: References: <1148651668.578852.3160@i40g2000cwc.googlegroups.com> <7fEdg.13375$cX1.201311@twister2.libero.it> <1148655611.990937.322350@j73g2000cwa.googlegroups.com> <1149166096.176405.22780@i40g2000cwc.googlegroups.com> <3PCfg.20835$cX1.315781@twister2.libero.it> <1149174938.337973.85950@g10g2000cwb.googlegroups.com> <1149192520.959302.250840@j55g2000cwa.googlegroups.com> <1149235836.646855.164110@i40g2000cwc.googlegroups.com> Message-ID: <1149495074.808694.273010@j55g2000cwa.googlegroups.com> Michele Petrazzo wrote: > Iain King wrote: > >> I'll try out FIPY's resizing tomorrow too. OTOH, I have functions > >> to convert between PIL and wxPython, and functions to convert > >> betweem PIL and FIPY, but I don't see a function to convert FIPY to > >> wxPython? > >> > > > > Image at: http://www.snakebomb.com/misc/example.tif > > > > Iain > > > > Yes it's min-is-white:: > > michele:~$ tiffinfo example.tif > TIFFReadDirectory: Warning, example.tif: unknown field with tag 37680 > (0x9330) encountered. > TIFF Directory at offset 0x1520 (5408) > Subfile Type: (0 = 0x0) > Image Width: 1696 Image Length: 1162 > Resolution: 200, 200 pixels/inch > Bits/Sample: 1 > Compression Scheme: CCITT Group 4 > Photometric Interpretation: min-is-white # <------ > FillOrder: msb-to-lsb > Samples/Pixel: 1 > Rows/Strip: 1162 > Planar Configuration: single image plane > ImageDescription: DS > michele:~$ > > So you *need* to invert it to work correctly with PIL! > > P.s. Added the convertToWx function, that return a wx.Image, to the > Image class. > > Michele Most excellent! Iain From saketh.bhamidipati at gmail.com Sun Jun 11 15:46:57 2006 From: saketh.bhamidipati at gmail.com (Saketh) Date: 11 Jun 2006 12:46:57 -0700 Subject: wxPython: Keyboard events and TreeCtrl Message-ID: <1150055217.354043.135340@h76g2000cwa.googlegroups.com> Hello, everyone. I am a writing an application that I want to make a stripped-down framework of Leo for Cornell note-taking. I have one TreeCtrl, a menu, and a status bar. There are two classes currently - the Application class and the Frame class. The Frame class contains all of the event handling, such as OnAbout and OnExit. I am trying to add keyboard shortcuts. When someone hits Ctrl-I, I want a new node to be added at the bottom level - if you've ever used Leo, you know what I am talking about. Like in Leo, when the new node is created, I want the title to be highlighted so that you can type in the title of the node. For some reason, the way I am doing it is not working. It's probably because OnKeyDown is not attached to anything, but I am not sure. Anyway, here is what my OnKeyDown method looks like: def OnKeyDown(self, e): key = e.KeyCode() controlDown = e.ControlDown() altDown = e.AltDown() elif (controlDown and key == WXK_I): # I want the "Node Title" to be editable upon its creation self.tree.AppendItem(root, 'Node Title') Am I supposed to connect the method to the Frame somehow? Or does it automatically get called when the user hits Ctrl-I, regardless of the fact that no other methods call OnKeyDown? Thank you for the assistance. From steven.bethard at gmail.com Fri Jun 2 13:01:43 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 02 Jun 2006 11:01:43 -0600 Subject: grouping a flat list of number by range In-Reply-To: <1149196642.001466.53990@c74g2000cwc.googlegroups.com> References: <1149196642.001466.53990@c74g2000cwc.googlegroups.com> Message-ID: joh12005 at yahoo.fr wrote: > i'm looking for a way to have a list of number grouped by consecutive > interval, after a search, for example : > > [3, 6, 7, 8, 12, 13, 15] > > => > > [[3, 4], [6,9], [12, 14], [15, 16]] Know your itertools. From the examples section[1]: """ # Find runs of consecutive numbers using groupby. The key to the # solution is differencing with a range so that consecutive numbers all # appear in same group. >>> data = [ 1, 4,5,6, 10, 15,16,17,18, 22, 25,26,27,28] >>> for k, g in groupby(enumerate(data), lambda (i,x):i-x): ... print map(operator.itemgetter(1), g) ... [1] [4, 5, 6] [10] [15, 16, 17, 18] [22] [25, 26, 27, 28] """ So I think something like this should work: >>> import itertools >>> def intervals(numbers): ... def key((i, n)): ... return i - n ... for key, group in itertools.groupby(enumerate(numbers), key): ... group = list(group) ... _, first_n = group[0] ... _, last_n = group[-1] ... yield first_n, last_n + 1 ... >>> list(intervals([3, 6, 7, 8, 12, 13, 15])) [(3, 4), (6, 9), (12, 14), (15, 16)] If you really need lists instead of tuples, just put brackets around the terms in the yield statement. [1] http://docs.python.org/lib/itertools-example.html STeVe From robert.thorpe at antenova.com Mon Jun 19 04:48:10 2006 From: robert.thorpe at antenova.com (Rob Thorpe) Date: 19 Jun 2006 01:48:10 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: <7zslm58ggp.fsf@app-1.diku.dk> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> Message-ID: <1150706890.543243.284430@h76g2000cwa.googlegroups.com> Torben ?gidius Mogensen wrote: > "Rob Thorpe" writes: > > > Torben ?gidius Mogensen wrote: > > > > That's the point: Bugs that in dynamically typed languages would > > > require testing to find are found by the compiler in a statically > > > typed language. So whil eit may take onger to get a program thatgets > > > past the compiler, it takes less time to get a program that works. > > > > In my experience the opposite is true for many programs. > > Having to actually know the precise type of every variable while > > writing the program is not necessary, it's a detail often not relevant > > to the core problem. The language should be able to take care of > > itself. > > > > In complex routines it can be useful for the programmer to give types > > and for the compiler to issue errors when they are contradicted. But > > for most routines it's just an unnecessary chore that the compiler > > forces on the programmer. > > Indeed. So use a language with type inference. Well, for most purposes that's the same as dynamic typing since the compiler doesn't require you to label the type of your variables. I occasionally use CMUCL and SBCL which do type inference, which is useful at improving generated code quality. It also can warn the programmer if they if they reuse a variable in a context implying that it's a different type which is useful. I see type inference as an optimization of dynamic typing rather than a generalization of static typing. But I suppose you can see it that way around. From deets at nospam.web.de Wed Jun 14 07:15:17 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 14 Jun 2006 13:15:17 +0200 Subject: determining file type In-Reply-To: <1150281704.342529.206640@u72g2000cwu.googlegroups.com> References: <1150276935.270798.5550@i40g2000cwc.googlegroups.com> <1150281704.342529.206640@u72g2000cwu.googlegroups.com> Message-ID: <4fa9e3F1icbhnU1@uni-berlin.de> Ritesh Raj Sarraf schrieb: > Also, > f = file ('some_file.jpg') > > throws an error. > "str object is not callable" I bet you have rebound "file" to a string, like this: file = "some name" And PLEASE don't top-quote: http://www.redballoon.net/~snorwood/quote-rant.shtml Diez From fredrik at pythonware.com Fri Jun 30 07:34:37 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 30 Jun 2006 13:34:37 +0200 Subject: Way for see if dict has a key References: <6V6pg.21624$_J1.271925@twister2.libero.it><44a5041f$0$29637$636a55ce@news.free.fr><4F7pg.21676$_J1.272665@twister2.libero.it> <1151666867.604260.116320@h44g2000cwa.googlegroups.com> Message-ID: "Andr?" wrote: > Perhaps Bruno meant this: > > try: > ... my_dict[key] ... > except: > ... > > when we expect that the key will most often be in my_dict so that >exception will be raised rarely, otherwise use on my machine, "key in dict" is about twice as fast as the full try/getitem con- struct when the key is present in the dict, so that's not a very good optimization. now, if the OP had been interested in the associated value, things might have been a bit different. From scott.daniels at acm.org Thu Jun 15 17:15:08 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Thu, 15 Jun 2006 14:15:08 -0700 Subject: Which compiler will Python 2.5 / Windows (Intel) be built with? In-Reply-To: References: <1150367139.495114.148550@g10g2000cwb.googlegroups.com> <44917535$1@nntp0.pdx.net> <1150391891.130185.4640@f6g2000cwb.googlegroups.com> <4491b9e1$1@nntp0.pdx.net> Message-ID: <4491c90f$1@nntp0.pdx.net> Jarek Zgoda wrote: > Sorry, gals and guys, but if you force us to buy something irrelevant > like VC2003, you will not get our sympathy. Oh, no. And just when our bank account was getting full from your appreciation of our efforts. --Scott David Daniels scott.daniels at acm.org From pablo at decode.com.ar Fri Jun 16 17:01:05 2006 From: pablo at decode.com.ar (Pablo Ziliani) Date: Fri, 16 Jun 2006 18:01:05 -0300 Subject: [OT] Python Argentina T-shirt to exchange Message-ID: <44931C11.6030302@decode.com.ar> Hi guys, sorry for this _very_ off-topic message. I'll be in Paris, France next week and I thought someone there might be interested to exchange this http://www.python.com.ar/moin/Remeras T-shirt (size M) with me? I'd really like to take home a py-french (or wherever) one instead. Thanks and sorry again if this has been an inappropriate place to make the request. Pablo From steve at holdenweb.com Mon Jun 12 07:21:26 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 12 Jun 2006 12:21:26 +0100 Subject: Function to remove elements from a list working, but Python Hangs :(( In-Reply-To: <49961.10.209.4.1.1150110600.squirrel@10.105.1.3> References: <49543.10.209.4.1.1150100717.squirrel@10.105.1.3><200606121041.01792.maric@aristote.info><36394.10.209.4.1.1150103178.squirrel@10.105.1.3> <200606121237.04032.maric@aristote.info> <49961.10.209.4.1.1150110600.squirrel@10.105.1.3> Message-ID: Girish Sahani wrote: >>I guess it's already the case with lst = [ e for e in lst if e in pairs ] >> >> >>In [1]: lst = (1,2,3,4) >> >>In [2]: pairs=(5,) >> >>In [3]: lst=[e for e in lst if e in pairs] >> >>In [4]: lst >>Out[4]: [] > > Yes its working. I realized that i was giving an input which didnt satisfy > the condition. > Now if you could please check out this new problem i'm facing,related to > this.In my code,l4 is a list of lists, and these lists contain such pairs. > e.g. l4 = > [[[4,2],[4,7],[4,10],[4,12],[9,2],[9,7],[9,10],[9,12],[11,2],[11,10]],[[1,2],[3,5],[7,8]]] > which is a list of 2 lists (having 13 pairs) > Now when l4 has 50 pairs, and i run the code, python just hangs, and i'm > quite sure its because of this. Is there any way to rectify this??? > Yes: use standard debugging techniques. You might try adding "print" statements to show you the value of various names as you run through the code: frequently this is good enough to explain what's going wrong (although you *do* need enough confidence to be able to predict what the values should be). If all else fails try the "stuffed bear" technique: sit an inanimate object in front of you and explain the code, and exactly why it can't possibly be going wrong. Amazingly often, halfway through your explanation you realise what your error is. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From fredrik at pythonware.com Mon Jun 5 03:12:33 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 05 Jun 2006 09:12:33 +0200 Subject: attribute error using fnmatch In-Reply-To: References: <1149489751.258496.259540@c74g2000cwc.googlegroups.com> Message-ID: > did you verify that the code you posted really has the problem (it does > use the 'os' module which isn't important message.replace("important", "imported") From sreeram at tachyontech.net Sun Jun 25 10:22:12 2006 From: sreeram at tachyontech.net (K.S.Sreeram) Date: Sun, 25 Jun 2006 19:52:12 +0530 Subject: error with string (beginner) In-Reply-To: <1151240297.725336.305960@i40g2000cwc.googlegroups.com> References: <1151240297.725336.305960@i40g2000cwc.googlegroups.com> Message-ID: <449E9C14.7030601@tachyontech.net> Alex Pavluck wrote: > String: Source for exec/eval is unavailable I'm not able to find this message anywhere in the Python-2.4.3 sources. What python version are you using? What input did you enter when the prompt appeared? and copy&paste the *exact* exception you got including the full traceback. Regards Sreeram -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 260 bytes Desc: OpenPGP digital signature URL: From bearophileHUGS at lycos.com Fri Jun 2 04:19:15 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 2 Jun 2006 01:19:15 -0700 Subject: after del list , when I use it again, prompt 'not defined'.how could i delete its element, but not itself? In-Reply-To: <1149235087.256704.309360@g10g2000cwb.googlegroups.com> References: <1149235087.256704.309360@g10g2000cwb.googlegroups.com> Message-ID: <1149236355.221540.136120@y43g2000cwc.googlegroups.com> python wrote: > after del list , when I use it again, prompt 'not defined'.how could i > delete its element,but not itself? This is a way: >>> a = range(10) >>> del a[:] >>> a [] >>> a.append(20) >>> a [20] Bye, bearophile From sjmachin at lexicon.net Wed Jun 7 07:53:02 2006 From: sjmachin at lexicon.net (John Machin) Date: Wed, 07 Jun 2006 21:53:02 +1000 Subject: tempfile Question In-Reply-To: References: <4486161D.6060102@lexicon.net> Message-ID: <4486BE1E.5070107@lexicon.net> On 7/06/2006 3:57 PM, Dennis Lee Bieber wrote: > On Wed, 07 Jun 2006 09:56:13 +1000, John Machin > declaimed the following in comp.lang.python: > >> The dir, prefix and suffix parameters are passed to mkstemp(). > >> So I'd be thinking about using the (deprecated) mktemp() instead, > > I think you passed over the mkstemp() variation. Granted, it, too, > returns an opened file, along with the full pathname of the file, but it > requires the caller to handle eventual disposal of the file. > > Merely close the opened file; pass the pathname to the subprocess, > await completion of subprocess, reopen the file for use in Python... > Then at the end, close the file and use the pathname to delete the file > from the system. I passed over mkstemp() because (according to my reading of the manual), mkstemp() requires an *extra* step (close the file), leaving the situation then *exactly* the same as with mktemp() i.e. some pirate process may molest the file before the caller's child process can open the file. Cheers, John From bdesth.quelquechose at free.quelquepart.fr Tue Jun 20 20:30:38 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 21 Jun 2006 02:30:38 +0200 Subject: Newbie Question In-Reply-To: <1150771029.756430.19960@p79g2000cwp.googlegroups.com> References: <1150750938.973049.114780@y41g2000cwy.googlegroups.com> <129e55eahc35f00@corp.supernews.com> <1150753085.332654.283270@f6g2000cwb.googlegroups.com> <1150767309.831092.188530@h76g2000cwa.googlegroups.com> <1150767801.754519.165440@y41g2000cwy.googlegroups.com> <1150771029.756430.19960@p79g2000cwp.googlegroups.com> Message-ID: <4498631b$0$5392$626a54ce@news.free.fr> Saint Malo a ?crit : > BTW my program isn't about red blue yellow etc. I'm just using it as > an example. I guess i didn't asked the question correctly or am not > expressing myself correctly. Let me try one more. > > Ok. > > Contents of text file follow: > > red blue purble > yellow blue green > > > > Now lets imagine i wrote some code to look for the word red. Once the > program has found red i want it to print something like the following > line. > > > If you add red and blue you obtain the color purple... > > > How do i turn each color in the line into a separate string? Now is > that possible? > Here's a possible solution - documenting it is left as an exercice to the reader... # data.txt red blue purple yellow blue green # color.py def read_data(path): f = open(path, 'r') try: return [tuple(line.strip().split()) for line in f] finally: f.close() class ColorComboLookup(object): def __init__(self, data, search_in_results=True): index = dict() indices = range(search_in_results and 3 or 2) for combo in data: for i in indices: index.setdefault(combo[i], []).append(combo) self._index = index def __call__(self, color): try: return self._index[color] except KeyError: return [] def main(data_path): data = read_data(data_path) lookup = ColorComboLookup(data) for color in ['red', 'blue', 'yellow', 'green', 'pink']: print "looking for color", color combos = lookup(color) if combos: for combo in combos: print "If you add %s and %s you obtain the color %s..." % combo else: print "nothing found..." return 0 if __name__ == '__main__': import sys import os try: data_path = sys.argv[1] except IndexError: data_path = 'data.txt' # look in current dir if not os.path.is_file(data_path): sys.exit("data file %s not found" % data_path) sys.exit(main(data_path)) NB : not tested, but should work. From steve at holdenweb.com Wed Jun 14 16:19:25 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 14 Jun 2006 21:19:25 +0100 Subject: better Python IDE? Mimics Maya's script editor? In-Reply-To: <1150313824.937532.22780@g10g2000cwb.googlegroups.com> References: <1149810048.765664.107820@i40g2000cwc.googlegroups.com> <1150313824.937532.22780@g10g2000cwb.googlegroups.com> Message-ID: warpcat wrote: > I'm not sure where you got "pythonwin sucks" from my text (none of > those words are there). Saying one aspect of a piece of software is > clunky to "me" (if that's what you're refering too?) or saying the > whole software "sucks" are pretty different IMO. All I stated is that > it's very different from how I'm used to working. I didn't mean any > disrespect, but I do appreciate your info! > No offence taken - I was clearly reading too much into your words. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From filipwasilewski at gmail.com Sat Jun 24 08:36:17 2006 From: filipwasilewski at gmail.com (Filip Wasilewski) Date: 24 Jun 2006 05:36:17 -0700 Subject: String negative indices? References: <1151054259.765401.252230@b68g2000cwa.googlegroups.com> Message-ID: <1151152577.661130.5690@g10g2000cwb.googlegroups.com> Steven D'Aprano wrote: > On Fri, 23 Jun 2006 02:17:39 -0700, Filip Wasilewski wrote: > > > drtimhill at comcast.net wrote: > > > >> Logically, I should be able to enter x[-2:-0] to get the last and next to last characters. However, since Python doesn't distinguish between positive and negative zero, this doesn't work. Instead, I have to enter x[-2:]. > > > > Hooray! Logically there is no such thing as positive or negative zero, > > or did I miss something in the primary? > > No, not in the primary, or even in the secondary, but possibly in the > tertiary. > > For many purposes, it doesn't make sense to distinguish +0 from -0. But > for other purposes, it does. I believe you will agree that this is mostly a matter of notation of some fact rather than really trying to sign zero. For example I use to denote numbers that approach zero from "the right side" by x -> [0 uppercase +], which is definitely harder to type and display in poor man's text editor than x -> +0. Otherwise I should also rethink the meaning of positive (>0) and negative (<0) numbers (at least where such relations are defined). [...] > In statistical mechanics, some systems can have negative absolute > temperatures, including negative zero. Counter-intuitively, negative > absolute temperatures aren't colder than absolute zero, but hotter than > any positive temperature. So, strangely enough, a temperature of -0K is > hotter than a infinitely hot temperature! Yeah, this is really cool ;-) -- Filip "During board meeting: We have great news. Our earnings reached highest value ever - a positive 0." From Serge.Orlov at gmail.com Sat Jun 10 06:14:48 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 10 Jun 2006 03:14:48 -0700 Subject: Intermittent Failure on Serial Port References: Message-ID: <1149934488.780566.265600@j55g2000cwa.googlegroups.com> H J van Rooyen wrote: > Traceback (most recent call last): > File "portofile.py", line 232, in ? > ret_val = main_routine(port, pollstruct, pfifo) > File "portofile.py", line 108, in main_routine > send_nak(port, timeout) # so bad luck - comms error > File "/home/hvr/Polling/lib/readerpoll.py", line 125, in send_nak > port.flush() > IOError: [Errno 29] Illegal seek > close failed: [Errno 29] Illegal seek > > Where can I find out what the Errno 29 really means? > Is this Python, the OS or maybe hardware? It is from kernel: grep -w 29 `locate errno` /usr/include/asm-generic/errno-base.h: #define ESPIPE 29 /* Illegal seek */ man lseek: ERRORS: ESPIPE fildes is associated with a pipe, socket, or FIFO. RESTRICTIONS: Linux specific restrictions: using lseek on a tty device returns ESPIPE. From cfc at shell01.TheWorld.com Mon Jun 26 18:13:16 2006 From: cfc at shell01.TheWorld.com (Chris F Clark) Date: 26 Jun 2006 18:13:16 -0400 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> Message-ID: I wrote: > These informal systems, which may not prove what they claim to prove > are my concept of a "type system". Chris Smith replied: > Okay, that works. I'm not sure where it gets us, though.... Ok, we'll get there. First, we need to step back in time, to when there was roughly algol, cobol, fortran, and lisp. Back then, at least as I understood things, there were only a few types that generally people understood integer, real, and (perhaps) pointer. Now, with algol or fortran things were generally only of the first two types and variables were statically declared to be one or the other. With lisp any cell could hold any one of the 3, and some clever implementor added "tag bits" to distinguish which the cell held. As I understood it, the tag bits weren't originally for type correctness, so much as they facilitated garbage collection. The garbage collector didn't know what type of data you put in a cell and had to determine which cells contained pointers, so that the mark-and-sweep algorithms could sweep by following the pointers (and not following the integers that looked like pointers). Still, these tag bits did preserve the "dynamic" type, in the sense that we knew types from the other languages. As I remember it, sophistication with type really didn't occur as a phenomena for the general programmer until the introduction of Pascal (and to a lesser extent PL/I). Moreover, as I recall it, perhaps because I didn't learn the appropriate dialect was that lisp dialects kept with the more general notion of type (lists and tuples) and eschewed low-level bit-fiddling where we might want to talk about a 4 bit integer representing 0 .. 15 or -8 .. 7. The important thing is the dynamicism of lisp allowed one to write polymorphic programs, before most of us knew the term. However, we still had a notion of type: integers and floating point numbers were still different and one could not portably use integer operations on floating pointer values or vice versa. However, one could check the tag and "do the right thing" and many lisp primitives did just that, making them polymorphic. The way most of us conceived (or were taught to conceive) of the situation was that there still were types, they were just associated with values and the type laws we all knew and loved still worked, they just worked dynamically upon the types of the operand values that were presented at the time. Can this be made rigorous? Perhaps. Instead of viewing the text of the program staticly, let us view it dynamicly, that is by introducing a time (or execution) dimension. This is easier if you take an imperative view of the dynamic program and imagine things having an operational semantics, which is why we stepped back in time in the first place, so that we are in a world where imperative programming is the default model for most programmers. Thus, as we traverse a list, the first element might be an integer, the second a floating point value, the third a sub-list, the fourth and fifth, two more integers, and so on. If you look statically at the head of the list, we have a very wide union of types going by. However, perhaps there is a mapping going on that can be discerned. For example, perhaps the list has 3 distinct types of elements (integers, floating points, and sub-lists) and it circles through the types in the order, first having one of each type, then two of each type, then four of each type, then eight, and so on. The world is now patterned. However, I don't know how to write a static type annotation that describes exactly that type. That may just be my lack of experience in writing annotations. However, it's well within my grasp to imagine the appropriate type structure, even though **I** can't describe it formally. More importantly, I can easily write something which checks the tags and sees whether the data corresponds to my model. And, this brings us to the point, if the data that my program encounters doesn't match the model I have formulated, then something is of the wrong "type". Equally importantly, the dynamic tags, have helped me discover that type error. Now, the example may have seemed arbitrary to you, and it was in some sense arbitrary. However, if one imagines a complete binary tree with three kinds elements stored in memory as rows per depth, one can get exactly the structure I described. And, if one were rewriting that unusual representation to a more normal one, one might want exactly the "type check" I proposed to validate that the input binary tree was actually well formed. Does this help explain dynamic typing as a form of typing? -Chris From grante at visi.com Thu Jun 15 12:46:58 2006 From: grante at visi.com (Grant Edwards) Date: Thu, 15 Jun 2006 16:46:58 -0000 Subject: Numerics, NaNs, IEEE 754 and C99 References: <12917f6jp7u90f8@corp.supernews.com> <44912058$0$29674$636a55ce@news.free.fr> <1292p7s46ef5off@corp.supernews.com> <1292tvei30ahhd4@corp.supernews.com> <12930879vah1k12@corp.supernews.com> Message-ID: <12933o2thjji9da@corp.supernews.com> On 2006-06-15, Tim Peters wrote: > [Grant] >> Am I remebering incorrectly? > > Mostly but not entirely. > >> Didn't the old fixed-width integers operate modulo-wordsize? > > Not in Python. > >> I distinctly remember having to rewrite a bunch of checksum code when >> fixed-width integers went away. > > Best guess is that you're working on a 32-bit box, and remember this > Python <= 2.2 behavior specific to the left shift operator: > >>>> 1 << 31 > -2147483648 >>>> 1 << 32 > 0 That's probably it. I've also spent some time on/off fighting with 32-bit constants that have the high-order bit set. You've got to jump through hoops when you need to pass a value like 0xC0000000 to an extension that demands a 32-bit value. > + - * / on short ints always complained about overflow before > int-long unification, I was definitely mis-remembering things. I had to have been the left shift that caused the problems. -- Grant Edwards grante Yow! I'm CONTROLLED by at the CIA!! EVERYONE is visi.com controlled by the CIA!! From marshall.spight at gmail.com Wed Jun 21 11:09:06 2006 From: marshall.spight at gmail.com (Marshall) Date: 21 Jun 2006 08:09:06 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150749670.053433.242210@p79g2000cwp.googlegroups.com> <1150754918.338770.89870@i40g2000cwc.googlegroups.com> Message-ID: <1150902546.400454.219430@i40g2000cwc.googlegroups.com> Joachim Durchholz wrote: > > On a semantic level, the tag is always there - it's the type (and > definitely part of an axiomatic definition of the language). > Tag elimination is "just" an optimization. I see what you're saying, but the distinction is a bit fine for me. If the language has no possible mechanism to observe the it-was-only-eliminated-as-an-optimization tag, in what sense is it "always there?" E.g. The 'C' programming language. Marshall From gene.tani at gmail.com Sat Jun 24 09:22:28 2006 From: gene.tani at gmail.com (gene tani) Date: 24 Jun 2006 06:22:28 -0700 Subject: search engine In-Reply-To: <1151151361.359777.269130@y41g2000cwy.googlegroups.com> References: <1151151361.359777.269130@y41g2000cwy.googlegroups.com> Message-ID: <1151155348.609074.92740@p79g2000cwp.googlegroups.com> George Sakkis wrote: > vinodh kumar wrote: > > hai all, > > i am student of computer science dept. i have planned to > > design a search engine in python. i am seeking info about how to > > proceed further. > > i need to know what r the modules that can be used. > > There is not a "search engine module" around AFAIK. You should do your > homework first and learn about search engines in a language-independent > way from some good textbook such as "Mining the Web" > (http://http.cs.berkeley.edu/~soumen/mining-the-web/), There are python bindings for lucene, swish, Xapian, etc. As well as a Zcatalog. There *was* Pyndex, from Divmod, maybe they'll send you the source. More books: Manning and Schuetze "Statistical NLP", Berry and Browne's "Understanding Search Engines" http://www.ec-securehost.com/SIAM/SE17.html From diffuser78 at gmail.com Tue Jun 20 12:13:14 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 20 Jun 2006 09:13:14 -0700 Subject: OS specific command in Python References: <1150781429.090359.148560@c74g2000cwc.googlegroups.com> <1150783324.258644.65770@u72g2000cwu.googlegroups.com> Message-ID: <1150819994.389614.66800@b68g2000cwa.googlegroups.com> When you connect (via ssh or telnet) to a remote machine, you need to > type (manually) > your username and your password. Programming that is never easy. I have setup the public keys to AUTO LOGIN so that it doesn't ask the password. From ptmcg at austin.rr._bogus_.com Fri Jun 30 10:07:28 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 30 Jun 2006 14:07:28 GMT Subject: Way for see if dict has a key References: <6V6pg.21624$_J1.271925@twister2.libero.it> <44a5041f$0$29637$636a55ce@news.free.fr> <4F7pg.21676$_J1.272665@twister2.libero.it> <1151666867.604260.116320@h44g2000cwa.googlegroups.com> Message-ID: "Michele Petrazzo" wrote in message news:zZ7pg.21792$zy5.445667 at twister1.libero.it... > > when we expect that the key will most often be in my_dict so that > > exception will be raised rarely > > I didn't thought this because if I think that a key aren't in a dict, I > use dict.get(key, default) > Another factor to consider is if "default" is not something simple like 0 or None, but is an object constructed and initialized with some expensive initialization code (like access to a database). In this case: dict.get(key, ExpensiveObjectToCreate()) always creates the default value, and if the key does not exist, then promptly drops it on the floor. In such a case you'd be better off with one of the "check for existence" patterns, which only creates the default value if you *know* you're going to need it. -- Paul From marcelo.gosling at gmail.com Fri Jun 23 17:51:38 2006 From: marcelo.gosling at gmail.com (Marcelo Gosling) Date: 23 Jun 2006 14:51:38 -0700 Subject: Trouble including Python.h Message-ID: <1151099498.381282.64590@b68g2000cwa.googlegroups.com> Hi, everyone. This is on WinXP SP2, with Python 2.4.3 and DJGPP gcc 4.1.0. I'm having trouble including Python.h in a C file. The following C code: #include "Python.h" int main() { return 0; } when compiled with "gcc -I..\Python2.4\include\", gives more than 1000 lines of errors, beginning with: c:/documents and settings/marcelo.gosling/my documents/djgpp/bin/as.exe: BFD 2.16.1 assertion fail ../../bfd/coff-i386.c:576 c:/documents and settings/marcelo.gosling/my documents/djgpp/tmp/ccACtxBR.s: Assembler messages: c:/documents and settings/marcelo.gosling/my documents/djgpp/tmp/ccACtxBR.s:28: Error: cannot represent relocation type BFD_RELOC_386_PLT32 In file included from ../../Python2.4/include/Python.h:74, from example_wrap.c:112: ../../Python2.4/include/pymem.h: In function '__declspec': ../../Python2.4/include/pymem.h:51: error: expected declaration specifiers before '__declspec' ../../Python2.4/include/pymem.h:52: error: expected declaration specifiers before '__declspec' In file included from ../../Python2.4/include/Python.h:76, from example_wrap.c:112: ../../Python2.4/include/object.h:104: error: storage class specified for parameter 'PyObject' ../../Python2.4/include/object.h:108: error: storage class specified for parameter 'PyVarObject' ../../Python2.4/include/object.h:126: error: expected '=', ',', ';', 'asm' or '__attribute__' before '*' token ../../Python2.4/include/object.h:127: error: expected '=', ',', ';', 'asm' or '__attribute__' before '*' token ../../Python2.4/include/object.h:128: error: expected '=', ',', ';', 'asm' or '__attribute__' before '*' token ../../Python2.4/include/object.h:129: error: expected ')' before '*' token ../../Python2.4/include/object.h:130: error: expected ')' before '*' token Am I missing something important here? Thanks in advance, Marcelo From george.sakkis at gmail.com Fri Jun 23 10:40:35 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 23 Jun 2006 07:40:35 -0700 Subject: Flight search automation References: <1151069276.861472.292270@r2g2000cwb.googlegroups.com> <1151070415.237973.265400@c74g2000cwc.googlegroups.com> Message-ID: <1151073635.181128.15460@m73g2000cwd.googlegroups.com> mkPyVS wrote: > Is there an http page redirect call to the client once the java > releases it's wait que? Sorry, I've no idea.. not even sure if they use java or whether this matters. Can you guess by trying, say, http://www.travelocity.com/ ? Expedia and Orbitz have also a waiting page, hopefully I can figure them out once I have one working. George > George Sakkis wrote: > > I'm trying to use mechanize to fill in a "find a flight" form and then > > get back the results, but I'm not sure how to make it wait until the > > results page appears; the response after submitting the form is the > > "please wait while we are searching for your flights" page. Any ideas ? > > > > George From gdamjan at gmail.com Fri Jun 30 11:00:32 2006 From: gdamjan at gmail.com (Damjan) Date: Fri, 30 Jun 2006 17:00:32 +0200 Subject: Chapter 9 Tutorial for Classes Not Working References: Message-ID: <44a53c91$0$15781$14726298@news.sunsite.dk> > class MyClass: > "A simple example class" > i = 12345 > def f(self): > return 'hello world' > > > From here I run: > x = MyClass Did you mean x = MyClass() > xf = x.f > while True: > print xf() > > This gives the following error: > > Traceback (most recent call last): > File "", line 2, in ? > TypeError: unbound method f() must be called with MyClass instance as > first argument (got nothing instead) > > Please help...this is killing me! What you are really calling is MyClass.f without any arguments. -- damjan From fredrik at pythonware.com Thu Jun 15 07:05:13 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 15 Jun 2006 13:05:13 +0200 Subject: Python in Windows ng References: <449131ab$0$10456$afc38c87@news.optusnet.com.au> Message-ID: "veritas" wrote: > Can anyone tell me of a good newsgroup for running/programming Python on Windows OS ? as long as your posts include at least some Python, this is a perfectly appropriate forum. From johnjsal at NOSPAMgmail.com Wed Jun 14 10:11:39 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 14 Jun 2006 14:11:39 GMT Subject: wxpython: bringing up a dialog box with a button In-Reply-To: <448f1e04$0$7763$7a628cd7@news.club-internet.fr> References: <448f1e04$0$7763$7a628cd7@news.club-internet.fr> Message-ID: jean-michel bain-cornu wrote: > When your button gives an event, wx send two arguments : the object > itself and an event object. So you can't bind directly. Ah, that explains it! Thank you! From s99999999s2003 at yahoo.com Mon Jun 5 02:42:31 2006 From: s99999999s2003 at yahoo.com (s99999999s2003 at yahoo.com) Date: 4 Jun 2006 23:42:31 -0700 Subject: attribute error using fnmatch Message-ID: <1149489751.258496.259540@c74g2000cwc.googlegroups.com> hi i have script like this: from fnmatch import fnmatch from glob import glob .... ... f = ['file1','file2','file3'] r = "d:\\somepath" pat = "*.bat" listof_files = [i for i in f if not fnmatch(os.path.join(r,i),pat) and os.path.isfile(os.path.join(r,i))] ... .. I get this error: File "C:\Python24\Lib\fnmatch.py", line 37, in fnmatch pat = os.path.normcase(pat) File "C:\Python24\lib\ntpath.py", line 42, in normcase return s.replace("/", "\\").lower() AttributeError: replace But when i do everything in interactive, there is no problem.. What could be wrong with the script? My purpose is to find a list of files that does not match pat... thanks From digitalorganics at gmail.com Mon Jun 26 10:28:26 2006 From: digitalorganics at gmail.com (digitalorganics at gmail.com) Date: 26 Jun 2006 07:28:26 -0700 Subject: DictProxy? What is this? In-Reply-To: References: <1151328077.677523.57820@b68g2000cwa.googlegroups.com> <1151330771.142051.312380@b68g2000cwa.googlegroups.com> Message-ID: <1151332106.330791.107830@b68g2000cwa.googlegroups.com> All right. Thanks for explaining that Maric. Maric Michaud wrote: > Le lundi 26 juin 2006 16:06, digitalorganics at gmail.com a ?crit : > > Fredrik Lundh wrote: > > > digitalorganics at gmail.com wrote: > > > > When I tried to update a class's __dict__, I got an error saying that > > > > there is no 'update' attribute for dictproxy object. What is a > > > > dictproxy object? > > > > > > a CPython implementation detail, used to protect an internal data > > > structure used by new-style objects from unexpected modifications. > > > > > > > > > > Ah, so I'm not suppose to be able to change a class's __dict__? Thanks > > Fredrik. > > Of course, yes : > > In [1]: class a(object) : pass > ...: > > In [2]: a.__dict__ > Out[2]: > > In [3]: a.__dict__.items() > Out[3]: > [('__dict__', ), > ('__module__', '__main__'), > ('__weakref__', ), > ('__doc__', None)] > > In [4]: a.__dict__['foo'] = lambda s : True > --------------------------------------------------------------------------- > exceptions.TypeError... > > TypeError: object does not support item assignment > > hmmm, not this way, but : > > In [5]: a.foo = lambda s : True > > In [6]: a.__dict__.items() > Out[6]: > [('__dict__', ), > ('__module__', '__main__'), > ('foo', at 0xa79528ec>), > ('__weakref__', ), > ('__doc__', None)] > > In [7]: a().foo() > Out[7]: True > > or : > > In [9]: setattr(a, 'bar', lambda s : False) > > In [10]: a().bar() > Out[10]: False > > > -- > _____________ > > Maric Michaud > _____________ > > Aristote - www.aristote.info > 3 place des tapis > 69004 Lyon > Tel: +33 426 880 097 From david.nospam.hopwood at blueyonder.co.uk Tue Jun 27 13:17:23 2006 From: david.nospam.hopwood at blueyonder.co.uk (David Hopwood) Date: Tue, 27 Jun 2006 17:17:23 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: <1151420883.426116.288300@b68g2000cwa.googlegroups.com> References: <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <1151384511.223582.305760@m73g2000cwd.googlegroups.com> <1151420883.426116.288300@b68g2000cwa.googlegroups.com> Message-ID: Marshall wrote: > David Hopwood wrote: >>Marshall wrote: >> >>>The real question is, are there some programs that we >>>can't write *at all* in a statically typed language, because >>>they'll *never* be typable? >> >>In a statically typed language that has a "dynamic" type, all >>dynamically typed programs are straightforwardly expressible. > > So, how does this "dynamic" type work? > It can't simply be the "any" type, because that type has no/few > functions defined on it. It isn't. From the abstract of the above paper: [...] even in statically typed languages, there is often the need to deal with data whose type cannot be determined at compile time. To handle such situations safely, we propose to add a type Dynamic whose values are pairs of a value v and a type tag T where v has the type denoted by T. Instances of Dynamic are built with an explicit tagging construct and inspected with a type safe typecase construct. "Gradual typing" as described in is another alternative. The difference between gradual typing and a "dynamic" type is one of convenience rather than expressiveness -- gradual typing does not require explicit tagging and typecase constructs. -- David Hopwood From jon+usenet at unequivocal.co.uk Thu Jun 8 14:58:57 2006 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: 8 Jun 2006 18:58:57 GMT Subject: Select hangs after some reads References: <1149737234.816833.177710@j55g2000cwa.googlegroups.com> <1149764138.868847.326250@i39g2000cwa.googlegroups.com> <128g8uvi6aj4240@corp.supernews.com> <1149779056.498540.46620@f6g2000cwb.googlegroups.com> Message-ID: In article , Steve Holden wrote: >> I don't think that's right. You are confusing the PSH flag (which is >> basically unused in Unix networking I think) and the URG flag (which >> is extremely rarely used, but is indeed used by FTP to get abort >> requests to 'jump the queue' as it were). > > Nope. I'm sorry, but you're definitely mistaken. > The URG flag indicates that a packet contains out-of-band data, > whihc is what you describe above. "out-of-band" is just way the sockets interface slightly mis-describes it. Either way, it causes (in Unix) the FTP server process to receive a SIGURG; the signal handler sets a flag and the data-transfer loop stops. > The PSH flag indicates that the data stream must be flushed right > through to the other end. That's sort-of true, but irrelevant. The PSH flag, when received, means that the networking layer should unbuffer any data and ensure it is released to the receiving application. *However*, BSD sockets never wait before allowing the application to receive incoming data, so the incoming PSH flag is unnecessary and ignored. In addition, the sockets interface simply doesn't provide a method for applications to set the PSH flag on output. The networking system simply sets the PSH flag by default whenever the output buffer empties. > This is essential for interactive protocols such as FTP: without it > the server has no way to know that the client has sent a complete > command, and vice versa. I'm afraid that's completely wrong. The FTP server knows it has received a complete command because it sees the CRLF sequence in the data stream. I must admit it's refreshingly unusual to find someone who is more familiar with TCP/IP as described theoretically in the 1981 RFCs than the realities of the sockets interface ;-) From bussieremaillist at gmail.com Wed Jun 28 03:33:41 2006 From: bussieremaillist at gmail.com (bussiere) Date: Wed, 28 Jun 2006 09:33:41 +0200 Subject: documentation for the change of Python 2.5 In-Reply-To: <44a0f4d9$0$9022$626a54ce@news.free.fr> Message-ID: <002101c69a85$31eb2620$1a0aa8c0@Iris> I've read thsi documentation n: http://docs.python.org/dev/whatsnew/whatsnew25.html is there a way to have it in a more printable form ? Regards Bussiere From conkerll at gmail.com Sun Jun 11 00:08:04 2006 From: conkerll at gmail.com (conkerll at gmail.com) Date: 10 Jun 2006 21:08:04 -0700 Subject: learning python idioms Message-ID: <1149998884.261678.299860@u72g2000cwu.googlegroups.com> After several years developing in Java, I've begun to switch to Python for several of my new projects as I have found the language quite interesting. I've read several tutorials and implemented a few sample programs and I've found that Python enables one to program in a variety of different styles (I'm not sure if this was the original intention or not). Thus, I find myself occaisionally slipping into the "Java" mindset when writing Python code and I wonder if this is not optimal. Python is not Java and there must be more "correct" ways of doing this in Python that simply writing Java code with different syntax. Is there a good reference on the internet about Python-specific idioms and just good Python style in general. Which language constructs are efficient and which aren't? Thanks in advance, Ben From alanalan at newsgroup.nospam Thu Jun 15 19:00:07 2006 From: alanalan at newsgroup.nospam (A.M) Date: Thu, 15 Jun 2006 19:00:07 -0400 Subject: Looking for examples related to advanced python string, list and map operations Message-ID: Hi, Is there any online resource that gives examples about advanced python string, list and map operations? Today I saw this and I found that I have to work more on mentioned topics: numbers = [72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33] print filter(lambda n: n % 2 == 0, numbers) numbers = [72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33] print reduce(lambda x, y: x+y, numbers) Thank you, Alan From cfc at shell01.TheWorld.com Sat Jun 24 21:01:36 2006 From: cfc at shell01.TheWorld.com (Chris F Clark) Date: 24 Jun 2006 21:01:36 -0400 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> Message-ID: Chris Smith writes: > Unfortunately, I have to again reject this idea. There is no such > restriction on type theory. Rather, the word type is defined by type > theorists to mean the things that they talk about. Do you reject that there could be something more general than what a type theorist discusses? Or do you reject calling such things a type? Let you write: > because we could say that anything that checks types is a type system, > and then worry about verifying that it's a sound type system without > worrying about whether it's a subset of the perfect type system. I'm particularly interested if something unsound (and perhaps ambiguous) could be called a type system. I definitely consider such things type systems. However, I like my definitions very general and vague. Your writing suggests the opposite preference. To me if something works in an analogous way to how a known type system, I tend to consider it a "type system". That probably isn't going to be at all satisfactory to someone wanting a more rigorous definition. Of course, to my mind, the rigorous definitions are just an attempt to capture something that is already known informally and put it on a more rational foundation. > So what is the domain of a function? (Heck, what is a function? ... > (I need a word here that implies something like a set, but I don't care > to verify the axioms of set theory. I'm just going to use set. Hope > that's okay.) Yes, I meant the typical HS algebra definition of domain, which is a set, same thing for function. More rigorous definitions can be sustituted as necessary and appropriate. > 1. The domain is the set of inputs to that expression which are going to > produce a correct result. > > 2. The domain is the set of inputs that I expected this expression to > work with when I wrote it. > > 3. The domain is the set of inputs for which the expression has a > defined result within the language semantics. > > So the problem, then, more clearly stated, is that we need something > stronger than #3 and weaker than #1, but #2 includes some psychological > nature that is problematic to me (though, admittedly, FAR less > problematic than the broader uses of psychology to date.) Actually, I like 2 quite well. There is some set in my mind when I'm writing a particular expression. It is likely an ill-defined set, but I don't notice that. That set is exactly the "type". I approximate that set and it's relationships to other sets in my program with the typing machinery of the language I am using. That is the static (and well-founded) type. It is however, only an approximation to the ideal "real" type. If I could make that imaginary mental set concrete (and well-defined), that would be exactly my concept of type. Now, that overplays the conceptual power in my mind. My mental image is influenced by my knowledge of the semantics of the language and also any implementations I may have used. Thus, I will weaken 2 to be closer to 3, because I don't expect a perfectly ideal type system, just an approximation. To the extent that I am aware of gotchas in the language or a relavent implementation, I amy write extra code to try and limit things to model 1. Note that in my fallible mind, 1 and 2 are identical. In my hubris, I expect that the extra checks I have made have restricted my inputs to where model 3 and 1 coincide. Expanding that a little. I expect the language to catch type errors where I violate model 3. To the extent model 3 differs from model 1 and my code hasn't added extra checks to catch it, I have bugs resulting from undetected type errors or perhaps modelling errors. To me they are type errors, because I expect that there is a typing system that captures 1 for the program I am writing, even though I know that that is not generally true. As I reflect on this more, I really do like 2 in the sense that I believe there is some abstract Platonic set that is an ideal type (like 1) and that is what the type system is approximating. to the sense that languages approximate either 1 or 2, those facilites are type facilities of a language. That puts me very close to your (rejected) definition of type as the well-defined semantics of the language. Except I think of types as the sets of values that the language provides, so it isn't the entire semantics of the language, just that part which divides values into discrete sets which are approriate to different operations (and detect inaapropriate values). -Chris From fredrik at pythonware.com Fri Jun 9 15:39:26 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 09 Jun 2006 21:39:26 +0200 Subject: Deep copy of XML elements from one document to another In-Reply-To: <1149875641.306311.40680@i40g2000cwc.googlegroups.com> References: <1149875641.306311.40680@i40g2000cwc.googlegroups.com> Message-ID: pesachzon wrote: > In case anyone is wondering how to do this, here's a short explanation: > http://eugene.eggkeg.com/?p=16 "Sorry, no posts matched your criteria." forgot to click "publish" before you clicked "send" ? From gregory.petrosyan at gmail.com Thu Jun 15 13:44:59 2006 From: gregory.petrosyan at gmail.com (Gregory Petrosyan) Date: 15 Jun 2006 10:44:59 -0700 Subject: nested functions In-Reply-To: <1150319279.865335.323530@u72g2000cwu.googlegroups.com> References: <1150319279.865335.323530@u72g2000cwu.googlegroups.com> Message-ID: <1150393499.201391.197520@y41g2000cwy.googlegroups.com> Thanks everybody for your help! From eval.apply at gmail.com Wed Jun 28 14:56:37 2006 From: eval.apply at gmail.com (Joe Marshall) Date: 28 Jun 2006 11:56:37 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <1151384511.223582.305760@m73g2000cwd.googlegroups.com> <1151425350.679754.278820@i40g2000cwc.googlegroups.com> <1151450513.458623.139460@b68g2000cwa.googlegroups.com> Message-ID: <1151520997.731688.193710@p79g2000cwp.googlegroups.com> David Hopwood wrote: > Joe Marshall wrote: > > > > The point is that there exists (by construction) programs that can > > never be statically checked. > > I don't think you've shown that. I would like to see a more explicit > construction of a dynamically typed [*] program with a given specification, > where it is not possible to write a statically typed program that meets > the same specification using the same algorithms. I think we're at cross-purposes here. It is trivial to create a static type system that has a `universal type' and defers all the required type narrowing to runtime. In effect, we've `turned off' the static typing (because everything trivially type checks at compile time). However, a sufficiently powerful type system must be incomplete or inconsistent (by Godel). A type system proves theorems about a program. If the type system is rich enough, then there are unprovable, yet true theorems. That is, programs that are type-safe but do not type check. A type system that could reflect on itself is easily powerful enough to qualify. > AFAIK, it is *always* possible to construct such a statically typed > program in a type system that supports typerec or gradual typing. The > informal construction you give above doesn't contradict that, because > it depends on reflecting on a [static] type system, and in a dynamically > typed program there is no type system to reflect on. A static type system is usually used for universal proofs: For all runtime values of such and such... Dynamic checks usually provide existential refutations: This particular value isn't a string. It may be the case that there is no universal proof, yet no existential refutation. > > Note that I'm not claiming that you can check any desirable property of > a program (that would contradict Rice's Theorem), only that you can > express any dynamically typed program in a statically typed language -- > with static checks where possible and dynamic checks where necessary. Sure. And I'm not saying that you cannot express these programs in a static language, but rather that there exist programs that have desirable properties (that run without error and produce the right answer) but that the desirable properties cannot be statically checked. The real question is how common these programs are, and what sort of desirable properties are we trying to check. From laura at voipro.nl Thu Jun 1 03:08:32 2006 From: laura at voipro.nl (Laura van Tuin) Date: Thu, 1 Jun 2006 09:08:32 +0200 Subject: Python Programmerwanted Message-ID: Python programmer wanted Our fast-growing team of software developers is currently looking for a (junior) Python programmer to assist in the development of our core technology. To extend the core team we're looking for a talented individual with specifically: thorough knowledge of Linux and Python experience with Zope and Plone is recommended knowledge of VoIP including open standards such as SIP at least HBO/academic education fluent in English, preferably also in Dutch Working at Voipro is about team work and sharing in the success of the company. Our compensation is highly competitive and our organization has room for entrepreneurial professionals with experience in the telecommunication and technology markets. Professionalism, relationship management, and creativity are our core values and inherent strengths in our team. Voipro extends its founders tradition of delivering technological solutions in the technology and telecommunication markets successfully. Our fast growing team is motivated to deliver success to its investors, customers, and partners. If you are interested please contact Voipro Nederland BV - Laura van Tuin +31 20 7884000 / laura at voipro.nl -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Tue Jun 6 01:18:08 2006 From: sjmachin at lexicon.net (John Machin) Date: Tue, 06 Jun 2006 15:18:08 +1000 Subject: Reading from a file and converting it into a list of lines: code not working In-Reply-To: References: <1149534126.129714.131860@f6g2000cwb.googlegroups.com> <1149535195.763340.220010@y43g2000cwc.googlegroups.com> Message-ID: <44851010.6070503@lexicon.net> On 6/06/2006 2:10 PM, Girish Sahani wrote: > I have a text file in the following format: > > 1,'a',2,'b' > 3,'a',5,'c' > 3,'a',6,'c' > 3,'a',7,'b' > 8,'a',7,'b' Check out the csv module. > . > . > . > Now i need to generate 2 things by reading the file: > 1) A dictionary with the numbers as keys and the letters as values. > e.g the above would give me a dictionary like > {1:'a', 2:'b', 3:'a', 5:'c', 6:'c' ........} > 2) A list containing pairs of numbers from each line. > The above formmat would give me the list as > [[1,2],[3,5],[3,6][3,7][8,7]......] > > I wrote the following codes for both of these but the problem is that > lines returns a list like ["1,'a',2,'b'","3,'a',5,'c","3,'a',6,'c'".....] > Now due to the "" around each line,it is treated like one object > and i cannot access the elements of a line. You managed to split the file contents into lines using lines = open(filename).read().split("\n") Same principle applies to each line: |>>> lines = ["1,'a',2,'b'","3,'a',5,'c","3,'a',6,'c'"] |>>> lines[0].split(',') ['1', "'a'", '2', "'b'"] |>>> lines[1].split(',') ['3', "'a'", '5', "'c"] |>>> > > [code] > #code to generate the dictionary > def get_colocations(filename): > lines = open(filename).read().split("\n") > colocnDict = {} > i = 0 > for line in lines: > if i <= 2: > colocnDict[line[i]] = line[i+1] > i+=2 > continue > return colocnDict The return is indented too far; would return after 1st line. > [/code] > > [code] > def genPairs(filename): > lines = open(filename).read().split("\n") > pairList = [] > for line in lines: > pair = [line[0],line[2]] > pairList.append(pair) > i+=2 i is not defined. This would cause an exception. Please *always* post the code that you actually ran. > continue > return pairList dedented too far!! > [/code] > Please help :(( def get_both(filename): lines = open(filename).read().split("\n") colocnDict = {} pairList = [] for line in lines: n1, b1, n2, b2 = line.split(",") n1 = int(n1) n2 = int(n2) a1 = b1.strip("'") a2 = b2.strip("'") colocnDict[n1] = a1 colocnDict[n2] = a2 pairList.append([n1, n2]) return colocnDict, pairList def get_both_csv(filename): import csv reader = csv.reader(open(filename, "rb"), quotechar="'") colocnDict = {} pairList = [] for n1, a1, n2, a2 in reader: n1 = int(n1) n2 = int(n2) colocnDict[n1] = a1 colocnDict[n2] = a2 pairList.append([n1, n2]) return colocnDict, pairList HTH, John From bdesth.quelquechose at free.quelquepart.fr Fri Jun 2 20:09:17 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 03 Jun 2006 02:09:17 +0200 Subject: New to Python: Do we have the concept of Hash in Python? In-Reply-To: <_qOfg.1685$Su3.148290@news20.bellglobal.com> References: <1149206685.768210.71990@i39g2000cwa.googlegroups.com> <1149212030.851030.257180@c74g2000cwc.googlegroups.com> <_qOfg.1685$Su3.148290@news20.bellglobal.com> Message-ID: <4480a39f$0$20871$626a54ce@news.free.fr> A.M a ?crit : > Well the work is done now. I arrived home at 10:30 PM. > (snip) > > > Now that I finished the 1st part of the application, I have to admit that > choosing Python was an excellent decision. Python is an awesome programming > language with comprehensive library and great community support. > > I am not that new to Python anymore.. But the better is yet to come !-) (FWIW, I use Python since the 1.5.2 days, and still learn new things almost everyday). > I had a productive day. Thanks > everybody for help. Welcome. From crazymykl at gmail.com Sat Jun 10 14:58:15 2006 From: crazymykl at gmail.com (crazymykl at gmail.com) Date: 10 Jun 2006 11:58:15 -0700 Subject: Killing a thread In-Reply-To: References: <7c8a9a970606091338t174fbcb0wc73cdb8b385f8ccd@mail.gmail.com> <7c8a9a970606091354u73308bf8o2758eea5ef690c39@mail.gmail.com> <1149889827.2754.6.camel@kenshin.CASA> <448A0D8A.4000008@mvista.com> Message-ID: <1149965895.702667.3970@u72g2000cwu.googlegroups.com> Fredrik Lundh wrote: > Carl J. Van Arsdall wrote: > > > Are there any plans in the future to add the capability to kill threads > > from the outside? > > it cannot be done in a portable way, so that's not very likely. > import sys, trace, threading class KThread(threading.Thread): """A subclass of threading.Thread, with a kill() method.""" def __init__(self, *args, **keywords): threading.Thread.__init__(self, *args, **keywords) self.killed = False def start(self): """Start the thread.""" self.__run_backup = self.run self.run = self.__run # Force the Thread to install our trace. threading.Thread.start(self) def __run(self): """Hacked run function, which installs the trace.""" sys.settrace(self.globaltrace) self.__run_backup() self.run = self.__run_backup def globaltrace(self, frame, why, arg): if why == 'call': return self.localtrace else: return None def localtrace(self, frame, why, arg): if self.killed: if why == 'line': raise SystemExit() return self.localtrace def kill(self): self.killed = True From xah at xahlee.org Sun Jun 25 12:08:56 2006 From: xah at xahlee.org (Xah Lee) Date: 25 Jun 2006 09:08:56 -0700 Subject: languages with full unicode support Message-ID: <1151251736.590910.36050@u72g2000cwu.googlegroups.com> Languages with Full Unicode Support As far as i know, Java and JavaScript are languages with full, complete unicode support. That is, they allow names to be defined using unicode. (the JavaScript engine used by FireFox support this) As far as i know, here's few other lang's status: C ? No. Python ? No. Perl ? No. Haskell ? Yes by the spec, but no on existing compilers. JavaScript ? No in general. Firefox's engine do support it. Lisps ? No. unix shells (bash) ? No. (this probably applies to all unix shells) Java ? Yes and probably beats all. However, there may be a bug in 1.5 compiler. Also, there appears to be a bug with Java 1.5's unicode support. The following code compiles fine in 1.4, but under 1.5 the compiler complains about the name x1.str?. class ? { String str? = "?????,??????\n?????,??????\n?????????\n??????"; String str?="?????????? ????????? ?????? ??????? ???? ?? ??? ??????? ??"; } class UnicodeTest { public static void main(String[] arg) { ? x1 = new ?(); System.out.println( x1.str? ); System.out.println( x1.str? ); } } If you know a lang that does full unicode support, please let me know. Thanks. Xah xah at xahlee.org ? http://xahlee.org/ From ilias at lazaridis.com Thu Jun 8 13:57:40 2006 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Thu, 08 Jun 2006 20:57:40 +0300 Subject: CONSTRUCT - Python's way of Ruby's "alias_method" In-Reply-To: <1149771935.391193.147360@h76g2000cwa.googlegroups.com> References: <1149771935.391193.147360@h76g2000cwa.googlegroups.com> Message-ID: Tim N. van der Leeuw wrote: [...] http://case.lazaridis.com/wiki/Please . -- http://lazaridis.com From jcb at iteris.com Thu Jun 1 14:03:01 2006 From: jcb at iteris.com (Metalone) Date: 1 Jun 2006 11:03:01 -0700 Subject: Python for Visual Basic or C# programmers References: Message-ID: <1149184981.184143.63160@f6g2000cwb.googlegroups.com> A.M wrote: > Hi, > > > > I am trying to find the equivalent functions such as vb's str or asc in > Python. Is there any resource that help me to find these kinds of functions > in Python faster? > > > > Thank you, > > Alan > > Alan Python has a str() function that is close to vb's str. The Python version does not produce a leading space. str(123) --> '123' If you want to control the formatting to mimick vb or create different formatting you can use. " %d" % 123 --> ' 123' The format specifier is just like 'C's printf format strings. A tuple should follow the % sign if formatting more than 1 number. "%d %d" % (123, 456) Python has a similar function to vb's asc. It is ord(). ord() accepts a single character, whereas asc operates on the first character of a string. To mimick vb you could do s = 'hello' ord(s[0]) --> 104 I am unaware of any reference associating vb functionality with Python functionality. Then again, I never looked for one. From scott.daniels at acm.org Sat Jun 17 05:50:12 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Sat, 17 Jun 2006 02:50:12 -0700 Subject: python texts? In-Reply-To: References: Message-ID: <4493cb7c$1@nntp0.pdx.net> Dave Cook wrote: > On 2006-06-17, nate wrote: >> reading Learning Python 2nd edition by O'Reilly. I am enjoying it at the > I'd get the Python Cookbook, next. There's a jump. The Cookbook is quite advanced. I'd write code next. Then, I'd read through the docs for all the provided modules (fast, the idea is to know where to go back for detail, not to understand each module in depth), and write more code. If you want paper for going through the modules, next I'd read either Beazley's "Python Essential Reference" or Alex Martelli's "Python in a Nutshell." Choosing between P.E.R. and Nutshell is really quite individual. They are both great, thorough jobs that leave you with a wonderful reference work after you've read them. I'd say P.E.R. is terser, going for density and brevity, while the Nutshell is a bit more elaborative on what it covers. The choice between Martelli and Beazley is, I suspect, one of your learning style. Find somewhere to look at each (any edition) and read twenty pages from the middle. One of them will seem much better than the other, and it has everything to do with what you prefer. The Cookbook comes later. As does getting all the way through the challenge, but for puzzle lovers, it can be great fun. --Scott David Daniels scott.daniels at acm.org From rganesan at myrealbox.com Wed Jun 14 05:25:43 2006 From: rganesan at myrealbox.com (Ganesan Rajagopal) Date: Wed, 14 Jun 2006 14:55:43 +0530 Subject: popen and password entry References: <200604141214.51754.erchamion.beren@gmail.com> Message-ID: >>>>> sinan nalkaya writes: > i want to use rsync for remote file transfer via popen, but couldnt pass > the Password yet. For interactive input try the pexpect module instead of popen (see http://pexpect.sf.net). Ganesan -- Ganesan Rajagopal From johnjsal at NOSPAMgmail.com Wed Jun 7 14:45:24 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 07 Jun 2006 18:45:24 GMT Subject: tkinter: native look to windows? Message-ID: <89Fhg.2258$No6.47844@news.tufts.edu> I'm a little confused. I was under the impression (perhaps incorrectly) that Tkinter will create GUI widgets that are native to your OS, so I should have an XPish looking application. But when I create buttons (and even the text fields look a bit different), they are not the 'fancy' Windows buttons that are rectangular with rounded edges and have a blueish border around the active button, but instead are just square buttons. Is this normal behavior? Why don't I get the XP type of buttons, and is it possible to get them? From python at hope.cz Mon Jun 5 08:48:12 2006 From: python at hope.cz (Lad) Date: 5 Jun 2006 05:48:12 -0700 Subject: How to add few pictures into one Message-ID: <1149511692.796038.155930@c74g2000cwc.googlegroups.com> Hello , is it possible to add( with PYTHON language) several image files into one? Thanks for reply L. From elbertlev at hotmail.com Fri Jun 9 14:31:45 2006 From: elbertlev at hotmail.com (elbertlev at hotmail.com) Date: 9 Jun 2006 11:31:45 -0700 Subject: PAMIE save an image Message-ID: <1149877905.129068.274440@i40g2000cwc.googlegroups.com> Hi, all! I'm writing a web page tester. The page is designed in such a way, that every time it creates an image file and displays it on the page. As soon as the file is downoladed it is deleted from the server. Using PAMIE I can download the page (by controlling an instance of IE) then images = ie.imagesGet() #list of images src = images[0].getAttribute('src') #sorce of the image Is it possible to save the image(s) in the local file? From donn at u.washington.edu Fri Jun 2 13:52:41 2006 From: donn at u.washington.edu (Donn Cave) Date: Fri, 02 Jun 2006 10:52:41 -0700 Subject: os.chdir doesn't accept variables sometimes References: <1149267516.348440.60290@u72g2000cwu.googlegroups.com> Message-ID: In article <1149267516.348440.60290 at u72g2000cwu.googlegroups.com>, "dannycolligan at gmail.com" wrote: > #!/usr/bin/python > > from os import * > > chdir("/home/chainlynx/Desktop/Music") > for artist in listdir(getcwd()): > print "===ARTIST: "+artist > chdir(artist) > for album in listdir(getcwd()): > print "---ALBUM: "+album > print "CWD: " + getcwd() > chdir(album) ######ERROR ON THIS > LINE > for string in listdir(album): ... > Traceback (most recent call last): > File "/home/chainlynx/workspace/PyTest/src/pypack/__init__.py", line > 12, in ? > for string in listdir(album): > OSError: [Errno 2] No such file or directory: 'Album1' To start with, note that your traceback implicates the listdir() on line 12, not the chdir() before it. This listdir() uses the same parameter as that preceding chdir(), that appears to be your problem. One of your problems, anyway. You're doing a lot of downwards chdirs, but no upwards, which is going to limit the extent of your directory traversal. The "from os import *" is a terrible idea, where did you get that? "os" has a lot of identifiers in it that tend to collide with other namespaces. "open" is a classic example. Don't do that, with "os" or generally any module. As a more general direction, it would be a good idea to look into standard library functions, e.g., os.path.walk > P.S. Bonus points: is there any way to bash shell script this on the > command line instead (recursively)? Depends on what you want it to do, but maybe something like find . -name \*.mp3 -exec $HOME/bin/cvt .mp4 {} \; where cvt would be something like #!/bin/sh case $1:$2 in .mp4:*.mp3) mp3_to_mp4 $2 ${2%.mp3}.mp4 ;; ... You'd have to think about it. Donn Cave, donn at u.washington.edu From bjourne at gmail.com Sat Jun 17 22:09:46 2006 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Sun, 18 Jun 2006 04:09:46 +0200 Subject: code is data In-Reply-To: <1150574111.415068.255900@p79g2000cwp.googlegroups.com> References: <1150574111.415068.255900@p79g2000cwp.googlegroups.com> Message-ID: <740c3aec0606171909y3b058ce9x195e2bc1ae7496b6@mail.gmail.com> > Personally, I would like to see macros in Python (actually Logix > succeeding is good enough). But I am no language designer and the > community has no interest in it. When I absolutely need macros, I will > go elsewhere. One must wonder, when is that? When do you absolutely need macros? -- mvh Bj?rn From paddy3118 at netscape.net Fri Jun 2 02:18:26 2006 From: paddy3118 at netscape.net (Paddy) Date: 1 Jun 2006 23:18:26 -0700 Subject: grouping a flat list of number by range In-Reply-To: <127ut85lpcmoa5b@corp.supernews.com> References: <1149196642.001466.53990@c74g2000cwc.googlegroups.com> <1149201416.196975.123370@c74g2000cwc.googlegroups.com> <127urvnrbvjgr07@corp.supernews.com> <1149202780.780252.242110@f6g2000cwb.googlegroups.com> <127ut85lpcmoa5b@corp.supernews.com> Message-ID: <1149229106.062837.139960@j55g2000cwa.googlegroups.com> Jim Segrave wrote: > In article <1149202780.780252.242110 at f6g2000cwb.googlegroups.com>, > Paddy wrote: > > > >What I ran was more like the version below, but i did a quick > >separation of the line that has the ';' in it and goofed. > > > >>>> def interv2(inlist): > >... for i,val in enumerate(inlist): > >... if i==0: > >... tmp = val > >... elif val != valinc: > >... yield [tmp, valinc]; tmp = val > >... valinc = val+1 > >... yield [tmp, valinc] > >... > >>>> list(interv2(inlist)) > >[[3, 4], [6, 9], [12, 14], [15, 16]] > > Fails on an empty list, as tmp is not defined when it hits the yield > > > -- > Jim Segrave (jes at jes-2.demon.nl) Yep, I still, purposfully, decided not to put any guard checks in because: Its very easy to add. It detracts from the algorithm. It might never be called with an empty list in-situ. It is correct for the original posters testcases. Yah gotta leave-em something to do ;-) But you-too are right. Don't just cut-n-paste newsgroup solutions. they need testing for your particular use. I doubt anyone on C.L.P. would be malicious, but your actual use of a function having a wider scope to inputs than mentioned might be fairy common. (Damn, I wanted to use 'caveat emptor', but it does not apply as nothing is being bought. Oh well :-) -- Pad. From steve at holdenweb.com Wed Jun 7 10:08:37 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 07 Jun 2006 15:08:37 +0100 Subject: Django Quick Start with Schema Evolution Support In-Reply-To: <4486D6F2.7000407@lazaridis.com> References: <1149446706.085692.174980@h76g2000cwa.googlegroups.com> <1149505316.406428.242450@c74g2000cwc.googlegroups.com> <448429E1.90305@kered.org> <35081.132.60.240.80.1149530454.squirrel@kered.org> <4486D6F2.7000407@lazaridis.com> Message-ID: Ilias Lazaridis wrote: > [Replying to comp.lang.python, due to censorship on Django User] > [additional notification of poster via email, as medium is changed] > And yet you still don't see why people call you a troll? This is completely inappropriate for comp.lang.python. Please take it elsewhere. This newsgroup is not a proxy for any other group who may have tired of your postings, and is not an arbitration forum for disputes. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From Serge.Orlov at gmail.com Wed Jun 14 19:18:47 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 14 Jun 2006 16:18:47 -0700 Subject: memory leak problem with arrays References: <1150317325.614389.14770@i40g2000cwc.googlegroups.com> <1150322504.136131.139350@i40g2000cwc.googlegroups.com> <1150324059.063981.70450@u72g2000cwu.googlegroups.com> Message-ID: <1150327127.904461.84740@h76g2000cwa.googlegroups.com> sonjaa wrote: > Serge Orlov wrote: > > sonjaa wrote: > > > Hi > > > > > > I'm new to programming in python and I hope that this is the problem. > > > > > > I've created a cellular automata program in python with the numpy array > > > extensions. After each cycle/iteration the memory used to examine and > > > change the array as determined by the transition rules is never freed. > > > I've tried using "del" on every variable possible, but that hasn't > > > worked. > > > > Python keeps track of number of references to every object if the > > object has more that one reference by the time you use "del" the object > > is not freed, only number of references is decremented. > > > > Print the number of references for all the objects you think should be > > freed after each cycle/iteration, if is not equal 2 that means you are > > holding extra references to those objects. You can get the number of > > references to any object by calling sys.getrefcount(obj) > > thanks for the info. I used this several variables/objects and > discovered that little counters i.e. k = k +1 have many references to > them, up tp 10000+. > Is there a way to free them? Although it's looks suspicious, even if you manage to free it you will gain only 12 bytes. I think you should concentrate on more fat objects ;) From ak at silmarill.org Sat Jun 17 21:10:49 2006 From: ak at silmarill.org (ak at silmarill.org) Date: 17 Jun 2006 18:10:49 -0700 Subject: Tkinter question. In-Reply-To: <1150591728.235667.319230@p79g2000cwp.googlegroups.com> References: <1150591728.235667.319230@p79g2000cwp.googlegroups.com> Message-ID: <1150593049.361117.77730@g10g2000cwb.googlegroups.com> Update: I found a way to do what I want with RadioButton with option indicatoron=0 which creates a bunch of what looks like regular buttons except that when one is pressed the other one is depressed and the value of the same variable is changed. Thanks dear me. ak at silmarill.org wrote: > Hi, I'd like to create buttons on the fly that will call the same > function, and the function in question has to know what was the name of > the button that called it. Unless there is a preferred way for doing > this.. Perhaps creating a new function on the fly along with the new > button? Please help.. thanks! From paddy3118 at netscape.net Sun Jun 18 06:27:04 2006 From: paddy3118 at netscape.net (Paddy) Date: 18 Jun 2006 03:27:04 -0700 Subject: code is data In-Reply-To: <1150606118.456390.262620@y41g2000cwy.googlegroups.com> References: <1150574111.415068.255900@p79g2000cwp.googlegroups.com> <1150606118.456390.262620@y41g2000cwy.googlegroups.com> Message-ID: <1150626424.563673.175060@c74g2000cwc.googlegroups.com> Ravi Teja wrote: > BJ?rn Lindqvist wrote: > > > Personally, I would like to see macros in Python (actually Logix > > > succeeding is good enough). But I am no language designer and the > > > community has no interest in it. When I absolutely need macros, I will > > > go elsewhere. > > > > One must wonder, when is that? When do you absolutely need macros? > > Whenever there is significant boiler plate code that functions and > classes cannot eliminate alone. > Whenever there is a more elegant way to express your code. > Me, I am torn. I should now better. I have listened to the arguments against Macros in Python and the ones that struck home were the argument for maintainability: Without macros, Python is Python. Statements do what you expect. And the argument against DSLs altogether: Make Python your DSL! If you design your own DSL before long you start to embellish it with more statements or datatypes and before long it becomes complex. If you used Python from the beginning then you would have a community for support. I know the arguments, but every once in a while I think if only I could craft my own ??? statement or .... Don't go their Paddy. ;-) From Michael.Coll-Barth at VerizonWireless.com Wed Jun 28 11:07:41 2006 From: Michael.Coll-Barth at VerizonWireless.com (Michael.Coll-Barth at VerizonWireless.com) Date: Wed, 28 Jun 2006 11:07:41 -0400 Subject: How do you use this list ? Message-ID: <20060628150746.D32CE1E4021@bag.python.org> -----Original Message----- From: Grant Edwards >>> Actually having mailing lists send you mail is insane. Once upon a time, I would have agreed. However, it is becoming increasingly difficuilt to get to the newgroups directly from the workplace. The only recourse is to use the mailing lists, such as those provided by various sites, such as python.org. This might also account for why so many folks top post rather than bottom post as postings look like email. And in a corporate setting, most people use top posting for email, pushing the history down and out of the way. The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you. From aleax at mac.com Thu Jun 1 22:16:16 2006 From: aleax at mac.com (Alex Martelli) Date: Thu, 1 Jun 2006 19:16:16 -0700 Subject: An oddity in list comparison and element assignment References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> <447f152f@nntp0.pdx.net> <1149194434.528648.148860@u72g2000cwu.googlegroups.com> Message-ID: <1hg9onn.p25evr18a09f9N%aleax@mac.com> Slawomir Nowaczyk wrote: > On Thu, 01 Jun 2006 13:40:34 -0700 > michael.f.ellis at gmail.com wrote: > > #> Scott David Daniels wrote: > #> > Would you say that envelope containing five $100 bills is equal to > #> > an envelope containing five $100 bills with different serial numbers? > > #> Yes (unless I was testing the assertion that the second envelope did > #> not contain counterfeits of the first) > > So, what if Bank of America later decided that bills with serial > numbers containing "7" are no longer valid? Then Wachowia would no doubt be happy to take my business away from BoA;-). I suspect you believe BoA is some kind of "official" body -- it isn't, just like Deutschebank is not one in Germany (rather, Bundesbank is). Just to share some tidbits (about which, as an Italian now living between San Francisco and San Jose, I'm sort of proud of...!-)...: Bank of America is a private bank, founded in San Francisco more than 100 years ago by an Italian-American guy (Amadeo Giannini, born in San Jose, CA, but to Italian-born parents) as "Bank of Italy", then renamed in 1930 in part because the Italian State bank "Banca d'Italia" objected. It rose to prominence right after the SF earthquake of 100 years ago, by opening and staffing a temporary branch to ensure depositors could access their money when they most needed it, while most other banks were staying closed. > In other word, *if* you assume equality must be preserved by future > modifications, than no two different (modifiable) objects can ever be > really equal. Yes, apart from the (slight and understandable!) mistake about BoA's role, this is an excellent example. Here, a global change (to the rule about what banknotes are "equal" to each other, by making some of them invalid and thus unequal to others) perturbs Michaels' desired "strong equality definition" -- to preserve it, equality must degenerate to identity. A Python example would be a change to the default encoding (not officially supported but achievable through a reload(sys), hint;-) which could easily make a bytestring equal, or not, to a Unicode string! Alex From torbenm at app-3.diku.dk Mon Jun 19 04:19:05 2006 From: torbenm at app-3.diku.dk (=?iso-8859-1?q?Torben_=C6gidius_Mogensen?=) Date: 19 Jun 2006 10:19:05 +0200 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <2006061410510511272-raffaelcavallaro@pasdespamsilvousplaitmaccom> <2006061501423327544-raffaelcavallaro@pasdespamsilvousplaitmaccom> <2006061611492350073-raffaelcavallaro@pasdespamsilvousplaitmaccom> <2006061618250975249-raffaelcavallaro@pasdespamsilvousplaitmaccom> Message-ID: <7zhd2himme.fsf@app-3.diku.dk> Raffael Cavallaro writes: > This is purely a matter of programming style. For explorative > programming it is easier to start with dynamic typing and add static > guarantees later rather than having to make decisions about > representation and have stubs for everything right from the start. I think you are confusing static typing with having to write types everywhere. With type inference, you only have to write a minimum of type information (such as datatype declarations), so you can easily do explorative progrmming in such languages -- I don't see any advantage of dynamic typing in this respect. > The > lisp programming style is arguably all about using heterogenous lists > and forward references in the repl for everything until you know what > it is that you are doing, then choosing a more appropriate > representation and filling in forward references once the program > gels. Having to choose representation right from the start and needing > working versions (even if only stubs) of *every* function you call may > ensure type correctness, but many programmers find that it also > ensures that you never find the right program to code in the first > place. If you don't have definitions (stubs or complete) of the functions you use in your code, you can only run it up to the point where you call an undefined function. So you can't really do much exploration until you have some definitions. I expect a lot of the exploration you do with incomplete programs amount to the feedback you get from type inference. > This is because you don't have the freedom to explore possible > solutions without having to break your concentration to satisfy the > nagging of a static type checker. I tend to disagree. I have programmed a great deal in Lisp, Scheme, Prolog (all dynamically typed) and SML and Haskell (both statically typed). And I don't find that I need more stubs etc. in the latter. In fact, I do a lot of explorative programming when writing programs in ML and Haskell. And I find type inference very helpful in this, as it guides the direction of the exploration, so it is more like a safari with a local guide than a blindfolded walk in the jungle. Torben From gajownik at gmail.com Tue Jun 13 16:17:02 2006 From: gajownik at gmail.com (Dawid Gajownik) Date: Tue, 13 Jun 2006 22:17:02 +0200 Subject: [pysqlite] [ANN] pysqlite 2.3.0 In-Reply-To: <448F14A1.7020503@ghaering.de> References: <448F0982.70906@ghaering.de> <448F1178.7060407@gmail.com> <448F14A1.7020503@ghaering.de> Message-ID: <448F1D3E.7090707@gmail.com> Dnia 06/13/2006 09:40 PM, U?ytkownik Gerhard H?ring napisa?: > I've uploaded a fixed source tarball now. Thanks! BTW new packages for Fedora should be available tomorrow on mirrors :) -- ^_* From maric at aristote.info Wed Jun 21 13:27:47 2006 From: maric at aristote.info (Maric Michaud) Date: Wed, 21 Jun 2006 19:27:47 +0200 Subject: How to override the doc of an object instance. In-Reply-To: References: Message-ID: <200606211927.48167.maric@aristote.info> Le Mercredi 21 Juin 2006 17:00, Paul McGuire a ?crit?: > No need to, just assign your special docstrings to w.x.__doc__, and print > w.x.__doc__. ?Instances that have special docstrings will print their > instance-specific versions; instances without instance-specific docstrings > will print the class-level version. ?See below. I think this is about to make IPython find the proper docstring of properties without modifying existing code. > >>> z.__doc__ ?= "instance-level docstring, just for z" > >>> z.__doc__ > > 'instance-level docstring, just for z' > > >>> zz = W() > >>> print zz.__doc__ > > Class-level docstring for W > > >>> print z.__doc__ > > instance-level docstring, just for z Won't work for properties, as z.prop.__doc__ is in fact z._prop.__doc__, so future assignment to prop qil lose the docstring. Le Mercredi 21 Juin 2006 18:32, David Huard a ?crit : > I looked into the internals of IPython and I can't say I understood much... This function wil do the job, not roughly tested but seems ok, call it at any moment (startup ?) in the IPython shell. def make_pinfo() : """replace the standard magic_pinfo of itpython This one will insert __class__. before the last element if it is a property.""" if not hasattr(__IPYTHON__, 'old_pinfo') : __IPYTHON__._old_pinfo = __IPYTHON__.magic_pinfo def new_pinfo(obj) : """obj param is the string typed in the interpreter, ie a.b.c it will be evaluated in magic_pinfo""" path = obj.split('.') if len(path) == 1 : return __IPYTHON__._old_pinfo(obj) else : new_eval_string = '.'.join(path[:-1]) # get the last attribute by the mean of the __class__ of its owner target = __IPYTHON__.user_ns[path[0]] # user_ns is the globals of the interpreter for attr in path[1:-1] : target=getattr(target, attr) target = getattr(target.__class__, path[-1], None) if isinstance(target, property) : new_eval_string += '.__class__' return __IPYTHON__._old_pinfo(new_eval_string + '.' + path[-1]) __IPYTHON__.magic_pinfo = new_pinfo Hope this help. regards. -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From spam.noam at gmail.com Fri Jun 9 09:00:01 2006 From: spam.noam at gmail.com (spam.noam at gmail.com) Date: 9 Jun 2006 06:00:01 -0700 Subject: Allowing zero-dimensional subscripts References: <1149801040.936452.26270@i40g2000cwc.googlegroups.com> Message-ID: <1149858001.419451.260670@f6g2000cwb.googlegroups.com> Hello, Sybren Stuvel wrote: > I think it's ugly to begin with. In math, one would write simply 'x' > to denote an unsubscribed (ubsubscripted?) 'x'. And another point, why > would one call __getitem__ without an item to call? I think that in this case, mathematical notation is different from python concepts. If I create a zero-dimensional array, with the value 5, like this: >>> a = array(5) I refer to the array object as "a", and to the int it stores as "a[]". For example, I can change the value it holds by writing >>> a[] = 8 Writing "a = 8" would have a completely different meaning - create a new name, a, pointing at a new int, 8. Noam From jurgenex at hotmail.com Sun Jun 11 01:40:30 2006 From: jurgenex at hotmail.com (Jürgen Exner) Date: Sun, 11 Jun 2006 05:40:30 GMT Subject: Xah Lee network abuse References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148495974.975395.12920@i40g2000cwc.googlegroups.com> <1149998343.493200.144990@h76g2000cwa.googlegroups.com> Message-ID: Mallor wrote: > I know I'm coming late to the barbeque. That's why you are missing the history > In passing, I ask: do you > have an objective, impartial perspective on the subject of committing > crimes? Because libel is a crime. It all depends on whether what you > state about Xah is provably true or not. I haven't followed his > posts, Had you done so, then you wouldn't ask this question. jue From timr at probo.com Sun Jun 25 23:19:06 2006 From: timr at probo.com (Tim Roberts) Date: Mon, 26 Jun 2006 03:19:06 GMT Subject: Python in HTML References: <1151077239.840572.175120@y41g2000cwy.googlegroups.com> Message-ID: brochu121 at gmail.com wrote: > >Does anyone know of a way to embed python scripts into html, much like >you would javascript or php? I do not want to use this to connect to a >database, but rather for a functional script to be called when a user >clicks on a link to open a page. If you are running Windows, and you have Python installed, and you have the Python-Win32 extensions installed, then there is a script you can run which installs Python as one of the "Windows scripting languages". After that, you can run Python code in HTML just like Javascript: However, it is considered a security risk which is why it is no longer enabled by default. Plus, it will only work on systems that have it installed. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From rossberg at ps.uni-sb.de Thu Jun 22 07:53:26 2006 From: rossberg at ps.uni-sb.de (Andreas Rossberg) Date: Thu, 22 Jun 2006 13:53:26 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: <4fv84rF1kp06kU1@individual.net> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150902275.129780.50260@p79g2000cwp.googlegroups.com> <1150918629.818145.143220@y41g2000cwy.googlegroups.com> <4fv081F1jh4ifU1@individual.net> <1150967543.947096.72840@g10g2000cwb.googlegroups.com> <4fv84rF1kp06kU1@individual.net> Message-ID: Pascal Costanza wrote: > > Consider a simple expression like 'a + b': In a dynamically typed > language, all I need to have in mind is that the program will attempt to > add two numbers. In a statically typed language, I additionally need to > know that there must a guarantee that a and b will always hold numbers. I'm confused. Are you telling that you just write a+b in your programs without trying to ensure that a and b are in fact numbers?? - Andreas From jmcmonagle at velseis.com.au Thu Jun 22 20:08:14 2006 From: jmcmonagle at velseis.com.au (John McMonagle) Date: Fri, 23 Jun 2006 10:08:14 +1000 Subject: Mouse wheel event for Canvas In-Reply-To: <1150950286.5055.12.camel@kuepper.vels-int.com.au> References: <1150950286.5055.12.camel@kuepper.vels-int.com.au> Message-ID: <1151021294.5055.18.camel@kuepper.vels-int.com.au> On Thu, 2006-06-22 at 14:24 +1000, John McMonagle wrote: > I tried binding mouse wheel events (, ) to a Tkinter > Canvas widget with the hope of using the event.delta value to > subsequently scroll the Canvas. > > However, it seems that event.delta always returns 0. > > For example, > > from Tkinter import * > > r = Tk() > c = Canvas(r, scrollregion=(0,0,500,500), height=200, width=200) > s = Scrollbar(r, command=c.yview) > c.pack(side=LEFT) > s.pack(side=RIGHT, fill=Y) > c.configure(yscrollcommand=s.set) > c.create_rectangle(10,10,100,100) > c.create_rectangle(10,200,100,300) > > def rollWheel(event): > print event.delta > > c.bind('', rollWheel) > c.bind('', rollWheel) > > c.focus_set() > > r.mainloop() > > > Has anyone successfully managed to wheel scroll a Tkinter Canvas > widget ? > > Regards, > > John > > > I worked it out. c.bind('', lambda event: event.widget.yview_scroll(-1, UNITS)) c.bind('', lambda event: event.widget.yview_scroll(1, UNITS)) I also changed the yscrollincrement to '5p'. The default moved a bit too much. -- This message has been scanned for viruses and dangerous content by MailScanner, and is believed to be clean. From maric at aristote.info Thu Jun 1 17:54:51 2006 From: maric at aristote.info (Maric Michaud) Date: Thu, 1 Jun 2006 23:54:51 +0200 Subject: An oddity in list comparison and element assignment In-Reply-To: <1149177617.985251.74560@c74g2000cwc.googlegroups.com> References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> Message-ID: <200606012354.52702.maric@aristote.info> Le Jeudi 01 Juin 2006 18:00, michael.f.ellis at gmail.com a ?crit?: > Perhaps the most fundamental notion is mathematics is that the left and > right sides of an equation remain identical after any operation applied > to both sides. IMHO, you are not aware that the '=' symbol of mathematics exists in python, it's the 'is' assertion. a is b and then, do what you want with a (or b), a is b remains True. THIS is the meaning of expr1 = expr2, but in computer science, this is not as important as it is in pure logic (most languages do not even provide the 'is' assertion). -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From akameswaran at gmail.com Fri Jun 9 10:25:10 2006 From: akameswaran at gmail.com (akameswaran at gmail.com) Date: 9 Jun 2006 07:25:10 -0700 Subject: removing dictionary key-pair In-Reply-To: <128j0r7tla1qi12@corp.supernews.com> References: <128j0r7tla1qi12@corp.supernews.com> Message-ID: <1149863109.848800.278970@c74g2000cwc.googlegroups.com> JD wrote: > Hello, > > I try to remove a dictionary key-pair (remove an entry), > but I'm unsuccessful. Does anyone know how to achieve this? > > Thanks Assuming you know the key: d = {"foo":1,"bar":2} print d del(d["foo"]) print d From defcon8 at gmail.com Sat Jun 24 10:20:59 2006 From: defcon8 at gmail.com (defcon8) Date: 24 Jun 2006 07:20:59 -0700 Subject: Python and cellular automata (It works this time!) Message-ID: <1151158859.422817.239810@y41g2000cwy.googlegroups.com> I thought people would be interested in this little script I wrote to reproduce the 256 simple automata that is shown in the first chapters of "A New Kind of Science". You can see a few results without running the script, at http://cooper-j.blogspot.com . And here is the code (You will need PIL (Python Imaging Library)): import Image # Contract: # To simulate simple cellular automata. class calculations: def __init__(self,which): self.against = self.array_maker_2()[which] self.check = self.array_maker_1() self.array = self.array_maker_3(311) self.calculator() def binary(self, n, size): ## This is the Int -> str(BINARY) converter assert n >= 0 bits = [] while n: bits.append('01'[n&1]) n >>= 1 bits.reverse() result = ''.join(bits) or '0' for iteration in range(len(result),size): result = "0" + result return result def array_maker_1(self): # This makes the array that represents the 8 different permutations of 3 cells. Itself, its left and its right. return [self.binary(n, 3) for n in range(8)] def array_maker_2(self): # This makes the array that represents every single different rule. If for instance the second element in one # of these rules is 1, then the corresponding permutation that may be found in the result array (array_maker_3), will be 1 (black). return [self.binary(n, 8) for n in range(256)] def array_maker_3(self, y): # This is the array for all the results. The automaton starts from the middle of the first row x = [["0" for x in range((2*y)+1)] for n in range(y)] x[0][(2*y+1)/2] = "1" return x def calculator(self): # This cycles over all of the cells, and scans one row at a time, and changes the next row according to the current cell. self.buff_result = ["0","0","0"] # This is the current permutation buffer to be checked against the corresponding arrays. for i in range(len(self.array)-1): for j in range(1, len(self.array[0])-1): self.step1(j,i) self.step2(j,i) self.step3(j,i) y = self.check.index(''.join(self.buff_result)) self.array[i+1][j] = self.against[y] # The steps update the result buffer. def step1(self, step, y): self.buff_result[0] = self.array[y][step-1] def step2(self, step, y): self.buff_result[1] = self.array[y][step] def step3(self, step, y): self.buff_result[2] = self.array[y][step+1] for number in range(256): objo = calculations(number) x = objo.array y = [] for num,zo in enumerate(x): for com,wo in enumerate(zo): x[num][com] = int(wo) nim = Image.new("1", (623,311)) for n in x: #converting the array of arrays into a single array so putdata can take it. for p in n: y.append(p) nim.putdata(y) nim.resize((6230/2,3110/2)).save("output" + str(number) + ".png") print number From jeethu at tachyontech.net Wed Jun 7 07:15:40 2006 From: jeethu at tachyontech.net (Jeethu Rao) Date: Wed, 07 Jun 2006 16:45:40 +0530 Subject: secure xmlrpc server? In-Reply-To: <4486B02E.70705@designaproduct.biz> References: <4486B02E.70705@designaproduct.biz> Message-ID: <4486B55C.3030509@tachyontech.net> Using Twisted on the server side for xmlrpc doesn't restrict your options to using only Twisted on the client side. Nothing prevents you from using xmlrpclib.ServerProxy on the client side. Jeethu Rao Laszlo Nagy wrote: > Hello, > > I'm trying to create a simple XMLRPC server and a client. It is a small > application, but the connection needs to be secure. I would like the > client to be as thin as possible. Ideally, the client should only > require the basic python library, nothing else. I found many examples on > the net. But I could not find secure ones (except twisted/xmlrpc, but I > would like to use the basic python lib on the client side, if possible). > I know that python supports HTTPS. In theory, this could be used to > bulild a secure xmlrpc server. I think that the client would work with > this code: > > # Connect to server > server = ServerProxy("https://myserver.com:8000") > > But I do not know how to create an XML RPC server in Python that uses > HTTPS for XML transports. (The server may use other libraries, just the > client needs to be thin.) > Can you help me please? > > Thanks, > > Laszlo > > From jo at durchholz.org Wed Jun 21 10:15:45 2006 From: jo at durchholz.org (Joachim Durchholz) Date: Wed, 21 Jun 2006 16:15:45 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: <44992e6c$3$664$bed64819@news.gradwell.net> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <44992e6c$3$664$bed64819@news.gradwell.net> Message-ID: Chris Uppal schrieb: > Chris Smith wrote: >> I think Marshall got this one right. The two are accomplishing >> different things. In one case (the dynamic case) I am safeguarding >> against negative consequences of the program behaving in certain non- >> sensical ways. In the other (the static case) I am proving theorems >> about the impossibility of this non-sensical behavior ever happening. > > And so conflating the two notions of type (-checking) as a kind of category > error ? If so then I see what you mean, and it's a useful distinction, but am > unconvinced that it's /so/ helpful a perspective that I would want to exclude > other perspectives which /do/ see the two as more-or-less trivial variants on > the same underlying idea. It is indeed helpful. Just think of all the unit tests that you don't have to write. Regards, Jo From sekhon.hari at googlemail.com Wed Jun 21 11:41:17 2006 From: sekhon.hari at googlemail.com (Hari Sekhon) Date: Wed, 21 Jun 2006 16:41:17 +0100 Subject: memory error with zipfile module In-Reply-To: References: <446e07ab$0$12795$636a55ce@news.free.fr> <1148072514.207383.26370@j55g2000cwa.googlegroups.com> <446e51e6$0$6831$636a55ce@news.free.fr> Message-ID: <4499689D.1000206@gmail.com> Fredrik Lundh wrote: > Hari Sekhon wrote: > > >> Is it me or is having to use os.system() all the time symtomatic of a >> deficiency/things which are missing from python as a language? >> > > it's you. > > > > I take it that it's still a work in progress to be able to pythonify everything, and until then we're just gonna have to rely on shell and those great C coded coreutils and stuff like that. Ok, I'm rather fond of Bash+coreutils, highest ratio of code lines to work I've ever seen.... it's the real strength of Linux. Shame about Windows... -------------- next part -------------- An HTML attachment was scrubbed... URL: From and-google at doxdesk.com Tue Jun 27 23:51:57 2006 From: and-google at doxdesk.com (and-google at doxdesk.com) Date: 27 Jun 2006 20:51:57 -0700 Subject: getting POST vars from BaseHTTPRequestHandler In-Reply-To: References: Message-ID: <1151466717.164729.15710@b68g2000cwa.googlegroups.com> Christopher J. Bottaro wrote: > When I make a post, it just hangs (in self.rfile.read()). I don't know about BaseHTTPRequestHandler in particular, but in general you don't want to call an unlimited read() on an HTTP request - it will try to read the entire incoming stream, up until the stream is ended by the client dropping the connection (by which point it's too late to send a response). Instead you'll normally want to read the request's Content-Length header (int(os.environ['CONTENT_LENGTH']) under CGI) and read(that many) bytes. -- And Clover mailto:and at doxdesk.com http://www.doxdesk.com/ From onurb at xiludom.gro Tue Jun 20 08:04:02 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 20 Jun 2006 14:04:02 +0200 Subject: Specifing arguments type for a function In-Reply-To: References: <4fq09iF1k0h0eU1@uni-berlin.de> <4497d8ef$0$29790$626a54ce@news.free.fr> Message-ID: <4497e439$0$9024$626a54ce@news.free.fr> K.S.Sreeram wrote: > bruno at modulix wrote: > >> if type(arg) is type([]): > > > Just a tiny nitpick.... > You can just use 'list' instead of 'type([])' I know. Note that I wrote "*A* right way to write this", not "*The* right way..." And FWIW, you could also use arg.__class__ instead of type(arg). -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From sreeram at tachyontech.net Sun Jun 11 15:46:36 2006 From: sreeram at tachyontech.net (K.S.Sreeram) Date: Mon, 12 Jun 2006 01:16:36 +0530 Subject: math.pow(x,y) In-Reply-To: References: <1150049976.916474.186580@j55g2000cwa.googlegroups.com> Message-ID: <448C731C.5030405@tachyontech.net> Raymond L. Buvel wrote: > I just tried this and it is taking an extremely long time even on a fast > machine with 4 Gb of RAM. Killed it after a couple of minutes. Thats odd. 34564323**456356 completed on my laptop in 28 seconds. [Python 2.4.3, Celeron-M 1.3GHz, WinXP], and max memory consumption during the whole process was about 11megs. What python version are you using? Regards Sreeram -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 260 bytes Desc: OpenPGP digital signature URL: From tim.peters at gmail.com Mon Jun 5 10:52:22 2006 From: tim.peters at gmail.com (Tim Peters) Date: Mon, 5 Jun 2006 10:52:22 -0400 Subject: Large Dictionaries In-Reply-To: References: <1147699064.107490@teuthos> <1147772420.405097@teuthos> <1147818548.532882.94180@i39g2000cwa.googlegroups.com> <1147874585.728471@teuthos> <1148514158.790760.205630@i40g2000cwc.googlegroups.com> <447af556$1@nntp0.pdx.net> Message-ID: <1f7befae0606050752t7d2b0403m872aed970da30401@mail.gmail.com> [Scott David Daniels] >> For example, time timsort (Python's internal sort) on pre-sorted >> data; you'll find it is handled faster than random data. O(N) vs O(N log N), in fact. [Lawrence D'Oliveiro] > But isn't that how a reasonable sorting algorithm should behave? Less > work to do if the data is already sorted? For example, the O(N log N) heapsort is unreasonable compared to the O(N**2) bubblesort by that reasoning (pre-sorted is actually a bad case for heapsort, but a good case for bubblesort)? O(N log N) sorting algorithms helped by pre-existing order are uncommon, unless they do extra work to detect and exploit pre-existing order. Python's current sorting algorithm exploits pre-existing order of many kinds. For example, take a sorted list, "cut it in half, and riffle shuffle the two halves together"; e.g., [0, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15] That turns out to be a supernaturally good case too. From fredrik at pythonware.com Thu Jun 8 09:50:49 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 08 Jun 2006 15:50:49 +0200 Subject: 10GB XML Blows out Memory, Suggestions? In-Reply-To: <1149773399.508514.223910@f6g2000cwb.googlegroups.com> References: <1149594519.098115.8980@u72g2000cwu.googlegroups.com> <4eleh3F1eguosU1@uni-berlin.de> <1149648187.891942.258300@i40g2000cwc.googlegroups.com> <1149694031.712812.304940@u72g2000cwu.googlegroups.com> <1149696078.984114.51880@h76g2000cwa.googlegroups.com> <1149773399.508514.223910@f6g2000cwb.googlegroups.com> Message-ID: fuzzylollipop wrote: > SAX style or a pull-parser has to be used when the data is "large" or > when you don't really need to process every element and attribute. > > This problem looks like it is just a data export / import problem. In > that case you will either have to use a sax style parser and parse the > 10GB file. Or as I suggested in another reply, export the data in > smaller chunks or use a parser that can do the chunking for you, on the way in... in Python, incremental parsers like cET's iterparse and the one in Amara gives you *better* performance than SAX (including "raw" pyexpat) in many cases, and offers a much simpler programming model. From max at alcyone.com Tue Jun 6 00:39:03 2006 From: max at alcyone.com (Erik Max Francis) Date: Mon, 05 Jun 2006 21:39:03 -0700 Subject: the most efficient method of adding elements to the list In-Reply-To: References: Message-ID: alf wrote: > Would it be .append()? Does it reallocate te list with each apend? > > l=[] > for i in xrange(n): > l.append(i) No, it doesn't. It expands the capacity of the list if necessary. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis It isn't important to come out on top, what matters is to be the one who comes out alive. -- Bertolt Brecht, 1898-1956 From deets at nospam.web.de Fri Jun 9 10:56:29 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 09 Jun 2006 16:56:29 +0200 Subject: Interacting with a process that I ran with subprocess module In-Reply-To: <1149864190.134947.178000@g10g2000cwb.googlegroups.com> References: <1149864190.134947.178000@g10g2000cwb.googlegroups.com> Message-ID: <4etgguF1fef6aU1@uni-berlin.de> py.adriano at gmail.com schrieb: > Hi folks, > > I'm trying to use the nmap runtime interaction feature while using it > with the subprocess module. For those not familiar with nmap, the > runtime interaction feature allow users to get informations about the > scan stats during the nmap execution. More at: > http://www.insecure.org/nmap/man/man-runtime-interaction.html > If someone want to try, just run nmap and try to type some keys to see > what happens. This only works with nmap 4.00 and above. > > Ok.. What I've tried is shown below: > > from subprocess import Popen, PIPE > nmap = Popen("nmap -T3 -A 10.0.0.1-254", stdin=PIPE, stdout=PIPE, > stderr=PIPE, shell=True, bufsize=1) > > To interact with nmap, I tried: > > nmap.communicate("?") > > And I tried this, also: > > nmap.stdin.write("?") > nmap.stdout.read() > > What's wrong? Is that suposed to be this way? Is there a better way to > interact with it that I've missed? Any help is very welcome. Thanks in > advance! Programs that interact with users usually require a terminal to be run from. This is not the case when using pipes. Use pexpect. Diez From reply.in.the.newsgroup at my.address.is.invalid Mon Jun 12 02:31:43 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Mon, 12 Jun 2006 08:31:43 +0200 Subject: An error ? References: Message-ID: Bo Yang: >[Fri Jun 16 14:06:45 2006] [error] [client 10.10.110.17] malformed >header from script. Bad header=Hello World!: a.py "The output of a CGI script should consist of two sections, separated by a blank line. The first section contains a number of headers, telling the client what kind of data is following." http://docs.python.org/lib/cgi-intro.html -- Ren? Pijlman From max at alcyone.com Wed Jun 14 03:11:41 2006 From: max at alcyone.com (Erik Max Francis) Date: Wed, 14 Jun 2006 00:11:41 -0700 Subject: curses module bug in windows python? In-Reply-To: <448FB38F.8040106@tundraware.com> References: <1150267132.986057.226690@i40g2000cwc.googlegroups.com> <448FB38F.8040106@tundraware.com> Message-ID: Tim Daneliuk wrote: > Nope - this module is not supported under Windows ... There's at least one Python curses module for Windows: http://adamv.com/dev/python/curses/ -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Whom God has put asunder, why should man put together? -- Ralph Waldo Emerson From olsongt at verizon.net Thu Jun 29 16:23:14 2006 From: olsongt at verizon.net (olsongt at verizon.net) Date: 29 Jun 2006 13:23:14 -0700 Subject: Bug reporting impossible In-Reply-To: <1151601890.184738.108590@x69g2000cwx.googlegroups.com> References: <1151598979.369897.140770@x69g2000cwx.googlegroups.com> <1151601890.184738.108590@x69g2000cwx.googlegroups.com> Message-ID: <1151612594.078002.242930@i40g2000cwc.googlegroups.com> > > I usually refrain from posting if I don't have anything to add to the > discussion, but that struck me as perverse and I was curious. > I certainly have no objection to having that bug fixed. : ) > If you find that sort of perversity strangely exciting, I would like to refer you to pages 67-69 of the Unix Hater's Handbook: http://www.simson.net/ref/ugh.pdf From tim.leeuwvander at nl.unisys.com Mon Jun 19 09:59:53 2006 From: tim.leeuwvander at nl.unisys.com (Tim N. van der Leeuw) Date: 19 Jun 2006 06:59:53 -0700 Subject: Tix Tree / HList widget? Message-ID: <1150725593.777722.115290@y41g2000cwy.googlegroups.com> Hi, I need to display some hierarchical data, and because I don't want to force users to install too many things beyond Python itself, I'm hoping to use Tix which is at least included with Python. I've managed to use the Tix HList widget to display a tree of items (at least in a proof-of-concept miniprogram) but I actually need to display 2 columns -- perhaps more. I figured out that I can specify the number of columns and the headers of the columns, but I haven't yet figured out how to set the values of the columns independantly. I tried using a tuple for the value of 'text' attribute, but that doesn't really seem to work. My second column never seems to be filled - all text goes into the first column. Also, the header for the second column never shows. I must be overlooking something rather basic in the manuals but for the moment I'm stumped. I'm also trying to figure out how to create a Tix 'Tree' widget instead of a HList, and make it do the same, but I don't know how to pass it the option for 2 columns: the 'Tree' widget refuses the option 'columns'. The samples in the Tix manual are for Tcl. I don't know how to translate their samples into Python/TkInter. How should I tell the Tix 'Tree' mega-widget that I need to pass an option to it's sub-widget? (At creation-time of that sub-widget, because that's the only time you can set the nr. of columns) Any clues? Anyone who can help? Are there any samples -- there's supposed to be a 'Demo' directory but I can't find it in my (windows) Python installation. Cheers, --Tim From jstroud at ucla.edu Wed Jun 21 18:41:55 2006 From: jstroud at ucla.edu (James Stroud) Date: Wed, 21 Jun 2006 15:41:55 -0700 Subject: tkMessagebox.askyesno always returns False In-Reply-To: <1150922362.746933.276430@i40g2000cwc.googlegroups.com> References: <1150922362.746933.276430@i40g2000cwc.googlegroups.com> Message-ID: peter wrote: > I have a weird problem in some code I am writing. The user selects a > number of files from a list and then can select an option which will > rename the selected files. Before the process starts, a yes/no dialog > box pops up just to confirm. > > Most of the time this works fine, but occasionally it seem the dialog > box gets into a state where it always returns False, irrespective of > the button clicked. > > I must be doing something wrong, but I just can't see it! Any > suggestions? > > > > import tkMessageBox as mb > : > : > if action=='Rename': > yn=mb.askyesno(file_list[0],'Ok to rename %d selected > file(s)' % file_count) > print 'Response: ',yn # Debug only > if not yn: exit_flag=1 > > > This problem seems to be beyond the code you provide. Is this part of a larger program? Is it possible to show the entire script? James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From luismgz at gmail.com Tue Jun 13 14:12:53 2006 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 13 Jun 2006 11:12:53 -0700 Subject: Combining The Best Of Python, Ruby, & Java?????? In-Reply-To: <4f7todF1har97U1@uni-berlin.de> References: <1150181049.815883.138580@c74g2000cwc.googlegroups.com> <4f7todF1har97U1@uni-berlin.de> Message-ID: <1150222373.368622.121050@h76g2000cwa.googlegroups.com> Diez B. Roggisch wrote: > > But semantically it is a proper functional language. The features may > > not attract Python users who might prefer Boo/Jython/IronPython. But it > > does offer something to disillusioned Groovy users. > > Are they disillusioned? Just wondering. > > Diez Whay talking about disillutioned programmers? These are tools, not religions... I love python, and I like it more everyday. And with the advent of Pypy, its future looks brighter than ever. But I also find very interesting these new options that are coming up. Although I'm not a professional programmer (not even a serious aficionado), I love to be able to translate my python skills very easily to .NET through Boo, for example. I even find it more appealing than Ironpython, because it was created from the ground up to take advantage of the CLR. On the other hand, porting pure python to .NET is in many aspects like trying to fit a square on a circle (I don't know if this sentence makes sense in english...). Because many of the design choices taken by GvR back in the early nineties were surely conditioned by the platform he chose to write python, which is the c language. The good thing is that python is having a lot of influence in these new languages. As far as I could see, even C# 3.0 is showing up some pythonic traits. From grante at visi.com Fri Jun 30 17:53:52 2006 From: grante at visi.com (Grant Edwards) Date: Fri, 30 Jun 2006 21:53:52 -0000 Subject: How to control permission of file? References: <12aavvb7vc58b48@corp.supernews.com> Message-ID: <12ab7bgti9us73@corp.supernews.com> On 2006-06-30, Sch?le Daniel wrote: >> When one open()s a file (that doesn't exist) for writing , how >> does one control that file's permissions (it's "mode" in Unix >> terms). > > what do you mean by "contor file's mode"? Are you asking what a file's mode is? Under Unix, it's a bitmapped value that determines what the access permissions are for the file. There are individual bits that enable permissions for user-read, user-write, user-execute, group-read, group-write, group-execute, other-read, other-write, other-execute, etc. If you look at os.open() there's a "mode" parameter (the same as the mode parameter in Unix's libc open()). I wanted to know how to control a file's mode when it was created by the builtin open(). I'm afraid I don't know how else to say it. > usually you try to open and if you are not allowed you will > get the exception > > >>> try: > ... f = file("/etc/shadow") > ... print f.read() > ... except IOError, e: > ... print e > ... > [Errno 13] Permission denied: '/etc/shadow' > >>> True, but I don't see what it has to do with my question. > if you want to know more about file attributes Um, thanks. I know all about file attributes. -- Grant Edwards grante Yow! Inside, I'm already at SOBBING! visi.com From george.sakkis at gmail.com Sat Jun 10 21:12:53 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 10 Jun 2006 18:12:53 -0700 Subject: Algorithm for Labels like in Gmail References: <1149985001.668803.121260@c74g2000cwc.googlegroups.com> Message-ID: <1149988373.769406.305720@i40g2000cwc.googlegroups.com> rhcarvalho at gmail.com wrote: > Hello there! > > I'm trying to make a simple Contact Manager using python (console > only), however i'm having trouble implementing a division by "Groups" > or "Labels" just like in Gmail. I don't have any real code to post > because all i got now is a raw TXT file holding the names and phones of > my contacts. > > The only idea I could figure out until now seems too weak, so that's > why i'm asking for help. I thought of making a separate list (in a text > file) holding all the possible groups, where each group hold the names > of the contacts. Then if i access a group, i'll be able to see all > contacts related to that group. On the other hand, i'll also need to > attach to the contact instance a list of every group it is present. > I think it's a bad idea because it seems to be very easy to get things > messed up. Like I can get things corrupted or bad linked, and i'll > always need to run functions to check all the realations between > contact names and groups... > > I like the way i can "label" emails on Gmail, does anyone know how I > can implement such kind of feature? What's the best/broadly used > algorithm? > > Sorry for the long message, and thanks in advance > > Rodolfo Carvalho Google for "many-to-many relationships". In short, you have two entity classes (say emails and labels) where each instance of one entity may be associated to zero or more instances of the other entity. In databases you implement this by having three tables, one for each entity and one for their association: Email RelEmailLabel Label ---------- -------------- --------- ID <--- EmailID ID subject LabelID ---> name ... ... Then you can associate mails to labels by joining all three tables together on the IDs. Of course you can implement this in memory as well but you should probably want to store them in some persistent area anyway, so an rdbms the way to go. Sqlite (with pysqlite) would meet your needs just fine. HTH, George From python.list at tim.thechases.com Mon Jun 26 14:17:05 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 26 Jun 2006 13:17:05 -0500 Subject: Beginner Programmer Question In-Reply-To: <1151343473.722970.251360@r2g2000cwb.googlegroups.com> References: <1151342733.742416.180370@r2g2000cwb.googlegroups.com> <1151343383.139891.219270@u72g2000cwu.googlegroups.com> <1151343473.722970.251360@r2g2000cwb.googlegroups.com> Message-ID: <44A024A1.5030604@tim.thechases.com> > bigone = 100 > > number = input("Whats the first number?") > number2 = input ("Whats the second number?") > nu3 = number+number2 > while nu3 < bigone: > print ("Not there yet, next number please") > > print "Finally there!" > > thats what i thought maybe it was...but after the first two numbers it > just continually scrolls on the screen with finally there Gaak! it's doing exactly what you told it to do! Bad program! :) Inside the loop it neither 1) gets further input from the user nor 2) reassigns/sums nu3 Thus, neither of the elements of your condition (nu3 < bigone) change, so you're stuck in an infinite loop of printing "not there yet..." Here's some sample code that works and does about what you describe. Tweak accordingly. :) total = 0 target = 3600 values = [ 82, 69, 87, 83, 78, 65, 0, 89, 83, 85, 79, 76, 0, 83, 73, 72, 84, 0, 83, 65, 87, 0, 84, 79, 71, 0, 41, 0, 76, 76, 65, 0, 68, 78, 65, 0, 78, 79, 72, 84, 89, 80, 14, 71, 78, 65, 76, 14, 80, 77, 79, 67, 0, 78, 79, 0, 78, 79, 73, 84, 83, 69, 85, 81, 0, 75, 82, 79, 87, 69, 77, 79, 72, 0, 65, 0, 68, 69, 75, 83, 65, 0, 41 ] while total < target: # still haven't found the value value = values.pop() # so we get another number print chr(value+32), #h have a little fun total += value #accumulate our total # and do it until we've accumlated more than target print "Hey...we're over %s" % target -tkc From pc at p-cos.net Fri Jun 23 08:01:51 2006 From: pc at p-cos.net (Pascal Costanza) Date: Fri, 23 Jun 2006 14:01:51 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: <1151026856.064429.36460@c74g2000cwc.googlegroups.com> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150998222.352746.65520@i40g2000cwc.googlegroups.com> <1151026856.064429.36460@c74g2000cwc.googlegroups.com> Message-ID: <4g23hgF1l4434U1@individual.net> Marshall wrote: > Joe Marshall wrote: >> That's the important point: I want to run broken code. > > I want to make sure I understand. I can think of several things > you might mean by this. It could be: > 1) I want to run my program, even though I know parts of it > are broken, because I think there are parts that are not broken > and I want to try them out. > 2) I want to run my program, even though it is broken, and I > want to run right up to a broken part and trap there, so I can > use the runtime facilities of the language to inspect what's > going on. > > >> I want to run >> as much of the working fragments as I can, and I want a `safety net' to >> prevent me from performing undefined operations, but I want the safety >> net to catch me at the *last* possible moment. > > This statement is interesting, because the conventional wisdom (at > least as I'm used to hearing it) is that it is best to catch bugs > at the *first* possible moment. But I think maybe we're talking > about different continua here. The last last last possible moment > is after the software has shipped to the customer, and I'm pretty > sure that's not what you mean. I think maybe you mean something > more like 2) above. Nowadays, we have more options wrt what it means to "ship" code. It could be that your program simply runs as a (web) service to which you have access even after the customer has started to use the program. See http://www.paulgraham.com/road.html for a good essay on this idea. Pascal -- 3rd European Lisp Workshop July 3 - Nantes, France - co-located with ECOOP 2006 http://lisp-ecoop06.bknr.net/ From nmm1 at cus.cam.ac.uk Thu Jun 15 05:10:50 2006 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 15 Jun 2006 09:10:50 GMT Subject: Numerics, NaNs, IEEE 754 and C99 References: <12904mjhl493t49@corp.supernews.com> <1290aik50hmk94a@corp.supernews.com> <4490329e$0$12356$636a55ce@news.free.fr> <12917f6jp7u90f8@corp.supernews.com> <44912058$0$29674$636a55ce@news.free.fr> Message-ID: In article <44912058$0$29674$636a55ce at news.free.fr>, Christophe writes: |> |> > Now, can you explain why 1/0 => -Inf wouldn't work as well? I.e. why |> > are ALL of your zeroes, INCLUDING those that arise from subtractions, |> > are known to be positive? |> |> I would say that the most common reason people assume 1/0 = Inf is |> probably because they do not make use of negative numbers or they forgot |> they exist at all. Usually the latter :-( Yes, if you are working with the non-negative real numbers (or even non-negative integers), then the best result of 1/0 is +infinity. Thus, if you are working with events, a count of zero is a true zero, but its inverse can reasonably be said to be +infinity. However, it is common for non-experts to assume that they are working in the non-negative real domain, because numbers are conventionally measured that way, but in fact that is not so. The use of elapsed times is one such "gotcha". I have seen quite a few programs that have assumed that elapsed times were always positive, and which have blown up when applied to real problems, where the measurement of an elapsed time may be negative. Hence, the SAFE approach is to make the inverse of all zeros a NaN. Regards, Nick Maclaren. From czajnik at czajsoft.pl Mon Jun 12 09:22:52 2006 From: czajnik at czajsoft.pl (czajnik at czajsoft.pl) Date: 12 Jun 2006 06:22:52 -0700 Subject: (pre)forking server framework? Message-ID: <1150118572.252707.57460@i40g2000cwc.googlegroups.com> Hi! I'm quite new to Python development. Can someone advise me a framework useful for building (pre-)forking or threaded TCP servers, other than SocketServer ? I've seen source code of a few python-based app servers, all of theme seem to reinvent the wheel, eventually reusing SocketServer. I'd appreciate a framework with logging, process/thread pool, signal handling etc. Just plug-in a protocol implementation and go ! Yes, I know Twisted, but asynchronous model is an overkill for me in this particular project. I do not need high performance, simple forking suites my needs better. BR, Przemek From ycoci0 at gmail.com Sun Jun 11 23:01:28 2006 From: ycoci0 at gmail.com (ycoci0 at gmail.com) Date: 11 Jun 2006 20:01:28 -0700 Subject: Evaluating a Function After X Seconds: Python Equivalent to JavaScript's SetTimeout() Function Message-ID: <1150081288.699325.105850@j55g2000cwa.googlegroups.com> Hi all, Not exactly new to Python, just have not programmed a time dependent function using it before. I imagine that many of you may also program some JavaScript and may be familiar with JavaScript's SetTimeout( expression, after time interval in milliseconds) function. Does Python have an equivalent to this? A SetTimeout-like Python function would be ideal for my application. Best, Y-coci From steve at holdenweb.com Wed Jun 28 03:08:49 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 28 Jun 2006 08:08:49 +0100 Subject: to py or not to py ? In-Reply-To: References: Message-ID: Serge Orlov wrote: > On 6/27/06, Chandrashekhar kaushik wrote: [...] >>also is it actually a good idea to write high perf applications in python ? > > > Take a look at Mercurial sources. > It's a high performance python application. Or watch Bryan > O'Sullivan's Mercurial presentation > he > talks briefly how they made it work fast. > > But writing high performance application in python requires > self-discipline and attention to details, looking at the way you spell > I think it will be a challenge ;) This doesn't distinguish Python: are there any languages that you can write high-performance applications in *without* self-discipline and attention to details? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From deets at nospam.web.de Wed Jun 7 12:11:13 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 07 Jun 2006 18:11:13 +0200 Subject: 10GB XML Blows out Memory, Suggestions? References: <1149594519.098115.8980@u72g2000cwu.googlegroups.com> <4eleh3F1eguosU1@uni-berlin.de> <1149648187.891942.258300@i40g2000cwc.googlegroups.com> <1149694031.712812.304940@u72g2000cwu.googlegroups.com> Message-ID: <4eoc54F1f5irsU1@uni-berlin.de> fuzzylollipop wrote: > > Fredrik Lundh wrote: >> fuzzylollipop wrote: >> >> > you got no idea what you are talking about, anyone knows that something >> > like this is IO bound. >> >> which of course explains why some XML parsers for Python are a 100 times >> faster than other XML parsers for Python... >> > > dependes on the CODE and the SIZE of the file, in this case > > processing 10GB of file, unless that file is heavly encrypted or > compressed will, the process will be IO bound PERIOD! Why so? IO-bounds will be hit when the processing of the fetched data is faster than the fetching itself. So if I decide to read 10GB a 4Kb block per second, I'm possibly a very patient fella, but no IO-bounds are hit. So no PERIOD here - without talking about _what_ actually happens. > Anyone saying that using C instead of Python will be faster when 99% of > the time in this case is just waiting on the disk to feed a buffer, has > no idea what they are talking about. Which is true - but the chances for C performing whatever I want to in the 1% of time are a few times better than to do so in Python. Mind you: I don't argue that the statements of Mr. Sreeram are true, either. This discussion can only be hold with respect to the actual use case (which is certainly more that just parsing XML, but also processing it) > I work with TeraBytes of files, and all our Python code is just as fast > as equivelent C code for IO bound processes. Care to share what kind of processing you perfrom on these files? Regards, Diez From no at address.spam Fri Jun 16 06:10:17 2006 From: no at address.spam (Sacha) Date: Fri, 16 Jun 2006 10:10:17 GMT Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <2006061410510511272-raffaelcavallaro@pasdespamsilvousplaitmaccom> <2006061501423327544-raffaelcavallaro@pasdespamsilvousplaitmaccom> Message-ID: "Joachim Durchholz" wrote in message news:e6tt7j$b41$1 at online.de... > Raffael Cavallaro schrieb: >> On 2006-06-14 15:04:34 -0400, Joachim Durchholz said: >> >>> Um... heterogenous lists are not necessarily a sign of expressiveness. >>> The vast majority of cases can be transformed to homogenous lists >>> (though these might then contain closures or OO objects). >>> >>> As to references to nonexistent functions - heck, I never missed these, >>> not even in languages without type inference :-) >>> >>> [[snipped - doesn't seem to relate to your answer]] >> > Give a heterogenous list that would to too awkward to live in a > statically-typed language. Many lists are heterogenous, even in statically typed languages. For instance lisp code are lists, with several kinds of atoms and sub-lists.. A car dealer will sell cars, trucks and equipment.. In a statically typed language you would need to type the list on a common ancestor... What would then be the point of statical typing , as you stilll need to type check each element in order to process that list ? Sure you can do this in a statically-typed language, you just need to make sure some relevant ancestor exists. In my experience you'll end up with the base object-class more often than not, and that's what i call dynamic typing. > Give a case of calling nonexistent functions that's useful. I might want to test some other parts of my program before writing this function. Or maybe will my program compile that function depending on user input. As long as i get a warning for calling a non-existing function, everything is fine. Sacha From almondb at gmail.com Thu Jun 1 18:53:37 2006 From: almondb at gmail.com (Brian) Date: 1 Jun 2006 15:53:37 -0700 Subject: Replace one element of a tuple (LONG) In-Reply-To: <127upu8k63qnu10@corp.supernews.com> References: <127ulhn6h7hvj22@corp.supernews.com> <1149198946.567904.260480@f6g2000cwb.googlegroups.com> <127upu8k63qnu10@corp.supernews.com> Message-ID: <1149202416.959127.71620@i39g2000cwa.googlegroups.com> Captain Dondo wrote: > What I'd like to do is build the correct selectlist in the first place, > rather than build the wrong one and then rebuild a correct one. This is sounding more like a SQL/DB problem and less like a Python one. If you have a field that is being pulled from the database that you would like to do a substitution on, I'm fairly sure MySQL includes a CASE statement in their flavor of SQL. Instead of performing a SELECT * in your script you could select the individual fields you want, and instead of just pulling the problematic column as is, you could pull it as something like "select case when sourcehost = x then y else sourcehost end case, ...". Naturally if an entire column needs to be replaced with a static value, you won't even need to use CASE. HTH From aum at spam.me.please Mon Jun 19 00:24:41 2006 From: aum at spam.me.please (aum) Date: Mon, 19 Jun 2006 16:24:41 +1200 Subject: ANN: pyfcp Message-ID: Hi all, pyfcp is a suite of tools, including a package, modules and applications, for accessing the Freenet network. What is freenet? Freenet - www.freenetproject.org - is a 'darknet' which supports anonymous publication and retrieval of websites and other media, in a way that makes it extremely expensive, if not impossible, for Big Brother to find out the source or requesters of any given files. pyfcp empowers python programmers to write applications which access the freenet network. Note that pyfcp only works with the new-generation 0.7 alpha freenet - it will not work with the current stable 0.5 version. But that is most certainly a plus :) pyfcp is available on the freenet website (downloads section), but also has its own website on the mainstream web: http://www.python.org/pyfcp as well as within freenet: freenet:USK at T4gW1EvwSrR9AOlBT2hFnWy5wK0rtd5rGhf6bp75tVo,E9uFCy0NhiTbR0jVQkY77doaWtxTrkS9kuMrzOtNzSQ,AQABAAE/pyfcp/50/ Enjoy! -- Cheers aum From vbgunz at gmail.com Thu Jun 29 01:32:39 2006 From: vbgunz at gmail.com (vbgunz) Date: 28 Jun 2006 22:32:39 -0700 Subject: Python in a nutshell - new edition ? References: <44A2C52A.6040807@skynet.be> <1hhnpen.1bkiv8l1d0r6puN%aleax@mac.com> <1151551938.499099.162520@75g2000cwc.googlegroups.com> <1hhnvof.1apknoe1v7zz8aN%aleax@mac.com> Message-ID: <1151559159.220511.68150@m73g2000cwd.googlegroups.com> > Let me assure you that it _won't_ be on paper this coming Saturday (two > days from now). I am absolutely certain it will be worth the wait. The Python in a Nutshell book that covers 2.2 is so well written, it's practically amazing the author was able to cram so much in so little space. Although I wish a bit more detailed examples were part of the book it undoubtedly does it's job as the perfect desktop reference. I'll get the latest and maybe donate my 2.2 to the local library. I hope Alex doesn't mind :) From janencarl at aznex.net Thu Jun 15 11:39:30 2006 From: janencarl at aznex.net (Carl Trachte) Date: Thu, 15 Jun 2006 08:39:30 -0700 (MST) Subject: Python is fun (useless social thread) ;-) Message-ID: <26519.198.176.208.75.1150385970.squirrel@admintool.trueband.net> ---------------------------- Original Message ---------------------------- Subject: Re: Python is fun (useless social thread) ;-) From: "Carl Trachte" Date: Thu, June 15, 2006 8:21 am To: -------------------------------------------------------------------------- > > So out of curiosity, I'm just wondering how everyone else came to learn it. If you feel like responding, I'll ask my questions for easy quoting: > > Did you have to learn it for a job? Yes. I was a production geologist in a copper mine in the mid 90's. Our mine planning software vendor Mintec (www.mintec.com) had chosen it as their API for programmatic access to the three dimensional geologic block model and two dimensional polygons that defined geologic shapes on a level bench or in vertical cross section. > > Or did you just like what you saw and decided to learn it for fun? That too. I had been using Visual Basic. For what I was doing (mine engineering), there was just a lot more functionality available in Python and its external modules (numeric, for example). Organizing a lot of engineering data dumped as text is easier in Python than it is in VB (IMO), because of the way Python handles lists and dictionaries. > > Also, how did you go about learning it? (i.e., like I described above, I started with the main stuff then moved on to the different available frameworks) I started with Mintec's mine planning software API, then realized that a lot of stuff was easier in Python. VB was great for making GUI's quickly. Python (Tkinter) is harder because you have to code your windows (although once I got over that initial hump, it got a lot easier - there's decent documentation for Tkinter on the web, and it doesn't cost a thing!). My employer was good enough to send me to M. Lutz' 3 day course on Python in Colorado. This was helpful. Up until that time I had been coding VB in Python (a lot of it was "translating" code from one language to the other). After that course I started to think in Python and make better use of the features Python had (OO, exception handling, etc.). > > Was there any necessity in the specifics you learned, or did you just dabble in something (e.g. wxPython) for fun? As I mentioned with the Tkinter example above, there was almost always necessity. Fortunately the stuff we do necessitates a lot of different language features and modules. The datetime module was something I didn't know about until I bought the latest version of the Python cookbook. The thing is a huge productivity boost, especially for the stuff I do (daily/monthly/yearly production reports). > > Are there still some things you feel you need to learn or improve? Always. Always. Always. Extending to Fortran and C are things I'd like to accomplish. There is a lot of old, but useful Fortran code around. If you can marry it with Python instead of trying to rewrite it, that's a lot of coding time (and money) saved. There are accounts of this sort of thing out on the web, but I'm yet to accomplish it myself. Langtangen's scientific Python book offers a start. I've got a copy and have read through it, but I've got to work on some real examples before I have any success with it. I'm not there yet. > > Additional comments/complains here: :) Life's too short to use and enjoy everything Python's got to offer. :-) > -- > http://mail.python.org/mailman/listinfo/python-list > -Carl Trachte From jweida at gmail.com Sat Jun 10 20:48:55 2006 From: jweida at gmail.com (Jerry) Date: 10 Jun 2006 17:48:55 -0700 Subject: Algorithm for Labels like in Gmail In-Reply-To: <1149985001.668803.121260@c74g2000cwc.googlegroups.com> References: <1149985001.668803.121260@c74g2000cwc.googlegroups.com> Message-ID: <1149986935.735704.283380@j55g2000cwa.googlegroups.com> I would probably go with an SQLite database to store your information. You can have the contacts listed in a table with unique ids, then a table of labels. Finally, create a table that links one or more labels with each contact. Then you can just keep adding more labels. From grante at visi.com Wed Jun 14 09:44:51 2006 From: grante at visi.com (Grant Edwards) Date: Wed, 14 Jun 2006 13:44:51 -0000 Subject: Numerics, NaNs, IEEE 754 and C99 References: Message-ID: <12904mjhl493t49@corp.supernews.com> On 2006-06-14, Nick Maclaren wrote: > > The numerical robustness of Python is very poor - this is not its fault, > but that of IEEE 754 and (even more) C99. In particular, erroneous > numerical operations often create apparently valid numbers, and the > NaN state can be lost without an exception being raised. For example, > try int(float("nan")). > > Don't even ASK about complex, unless you know FAR more about numerical > programming than 99.99% of programmers :-( > > Now, I should like to improve this, but there are two problems. The > first is political, and is whether it would be acceptable in Python to > restore the semantics that were standard up until about 1980 in the > numerical programming area. I.e. one where anything that is numerically > undefined or at a singularity which can deliver more than one value is > an error state (e.g. raises an an exception or returns a NaN). That's fine as long as the behavior is selectable. I almost always want a quiet NaN. While you're at it, the pickle modules need to be fixed so they support NaN and Inf. ;) -- Grant Edwards grante Yow! Yow! at visi.com From news at andmc.com Sun Jun 25 14:57:51 2006 From: news at andmc.com (Andrew McDonagh) Date: Sun, 25 Jun 2006 19:57:51 +0100 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <7zpshbsvjy.fsf@app-1.diku.dk> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <0%Wlg.3521$MF6.947@tornado.socal.rr.com> <44992e6c$0$664$bed64819@news.gradwell.net> <1151010139.960608.122470@b68g2000cwa.googlegroups.com> Message-ID: Chris Smith wrote: > Andrew McDonagh wrote: >> I haven't read all of this thread, I wonder, is the problem to do with >> Class being mistaken for Type? (which is usually the issue) > > Hi Andrew! Hi Chris > > Not much of this thread has to do with object oriented languages... so > the word "class" would be a little out of place. Glad to here. > However, it is true > that the word "type" is being used in the dynamically typed sense to > include classes from class-based OO languages (at least those that > include run-time type features), as well as similar concepts in other > languages. Some of us are asking for, and attempting to find, a formal > definition to justify this concept, and are so far not finding it. > Others are saying that the definition is somehow implicitly > psychological in nature, and therefore not amenable to formal > definition... which others (including myself) find rather unacceptable. > > I started out insisting that "type" be used with its correct formal > definition, but I'm convinced that was a mistake. Asking someone to > change their entire terminology is unlikely to succeed. I'm now > focusing on just trying to represent the correct formal definition of > types in the first place, and make it clear when one or the other > meaning is being used. > > Hopefully, that's a fair summary of the thread to date. > Cheers much appreciated! Andrew From martin at v.loewis.de Fri Jun 16 01:27:40 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 16 Jun 2006 07:27:40 +0200 Subject: Which compiler will Python 2.5 / Windows (Intel) be built with? In-Reply-To: <1150391891.130185.4640@f6g2000cwb.googlegroups.com> References: <1150367139.495114.148550@g10g2000cwb.googlegroups.com> <44917535$1@nntp0.pdx.net> <1150391891.130185.4640@f6g2000cwb.googlegroups.com> Message-ID: <4492414C.10505@v.loewis.de> meyer at mesw.de wrote: > the problem is not the ABI, but the runtime libraries. From what you're > saying, it looks like we will have to standardize on VS2003. As I said, > we need to buy VS anyway because of the MFC support. On the other hand, > I really worry about all those people that want to build open source > extensions for Python 2.5. It is really possible that there will be no > legal, free way to do that soon if you don't have an old installation > of the 2003 toolkit lying around somewhere... As others have pointed out already: This is not true. You can build Python extensions with GCC just fine; gcc provides an import library for msvcr71.dll. It might be possible to integrate an msvcr71.dll import library with VS 2005, in which case you could use VS 2005 to create Python extensions as well. Regards, Martin From onurb at xiludom.gro Mon Jun 12 05:01:24 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Mon, 12 Jun 2006 11:01:24 +0200 Subject: "parent" in a class __init__ def? In-Reply-To: References: Message-ID: <448d2d65$0$23267$626a54ce@news.free.fr> Ray Schumacher wrote: > What is the feeling on using "parent" in a class definition "parent" is just a name. What is the semantic for this name ? Parent class (ie: superclass) ? Container ? Else ? > that class > methods Takes care, "class method" has a very defined meaning in Python - a class method is a method that takes the class object - not the instance - as first param. > can refer to, vs. some other organization ? > Should all relevant objects/vars just be passed into the method as needed? There's no absolute rule about this - at most some guidelines : - What constitutes the state of an object should be an attribute of the object. - What is not part of the state and is only used for a given operation should be passed as param. > It seems like including "parent" in the class def is just like a class > variable, Here again, "class variable" has a well defined meaning in Python: it's an attribute of the class object itself, that is shared by all instances of the class. > which most do not recommend. > > An example: > class LXSerial: do yourself a favour : use new-style classes whenever possible. > def __init__(self, parent, debug=False): > ... > def connect(self, port, baud=9600, ptimeout=10): > if self.debug: > self.connectedPort = StringIO.StringIO(':A#') > else: > if self.parent.model=='LX200GPS': ptimeout = 240 > ... We still don't know what's the semantic for this 'parent'. But anyway, having this test on self.parent.model smells of a design error. If the timeout value depends on the 'parent' object, then it's clearly a responsability of this parent object to know that value. Your code here should read: def connect(self, ....) # ... ptimeout = self.parent.timeout # ... You may also want to have a look at the strategy pattern, to avoid cluttering your code with "if self.debug"... wrt/ your original question, I don't see how one could give a sound answer without knowing more about this "parent" object and it's relationship with the LXSerial class/instance of. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From rpdooling at gmail.com Fri Jun 23 12:46:12 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 23 Jun 2006 09:46:12 -0700 Subject: Opening a file with system default application In-Reply-To: <1151080644.805513.257140@r2g2000cwb.googlegroups.com> References: <1151077662.598370.214490@c74g2000cwc.googlegroups.com> <1151080343.917275.296520@g10g2000cwb.googlegroups.com> <1151080644.805513.257140@r2g2000cwb.googlegroups.com> Message-ID: <1151081172.418493.190730@i40g2000cwc.googlegroups.com> >> It would probably break like mad under *nix I bet it would work the same way on linux or os x; it's the equivalent of double-clicking on the file. rd From david.nospam.hopwood at blueyonder.co.uk Thu Jun 22 17:35:35 2006 From: david.nospam.hopwood at blueyonder.co.uk (David Hopwood) Date: Thu, 22 Jun 2006 21:35:35 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: <1150991074.705803.211570@m73g2000cwd.googlegroups.com> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150908952.804184.218990@r2g2000cwb.googlegroups.com> <1150991074.705803.211570@m73g2000cwd.googlegroups.com> Message-ID: Rob Thorpe wrote: > David Hopwood wrote: > >>As far as I can tell, the people who advocate using "typed" and "untyped" >>in this way are people who just want to be able to discuss all languages in >>a unified terminological framework, and many of them are specifically not >>advocates of statically typed languages. > > Its easy to create a reasonable framework. My earlier posts show simple > ways of looking at it that could be further refined, I'm sure there are > others who have already done this. > > The real objection to this was that latently/dynamically typed > languages have a place in it. You seem to very keen to attribute motives to people that are not apparent from what they have said. > But some of the advocates of statically > typed languages wish to lump these languages together with assembly > language a "untyped" in an attempt to label them as unsafe. A common term for languages which have defined behaviour at run-time is "memory safe". For example, "Smalltalk is untyped and memory safe." That's not too objectionable, is it? (It is actually more common for statically typed languages to fail to be memory safe; consider C and C++, for example.) -- David Hopwood From dingbat at codesmiths.com Wed Jun 21 13:51:14 2006 From: dingbat at codesmiths.com (Andy Dingley ) Date: 21 Jun 2006 10:51:14 -0700 Subject: Iterating a list in reverse ? In-Reply-To: References: <1150909005.604896.122290@m73g2000cwd.googlegroups.com> Message-ID: <1150912274.457642.151070@u72g2000cwu.googlegroups.com> Fredrik Lundh wrote: > for item in reversed(listOfThings): Thanks! I was staring so hard at reverse() that I'd completely missed reversed() I think I prefer this to listOfThings[::-1]: as it's a little more readable. Not that I'm reacting to past bad experience of Perl, you understand 8-) From deets at nospam.web.de Sun Jun 11 10:47:26 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 11 Jun 2006 16:47:26 +0200 Subject: TypeError: unsubscriptable object In-Reply-To: <1149874726.470436.279200@i40g2000cwc.googlegroups.com> References: <1149874726.470436.279200@i40g2000cwc.googlegroups.com> Message-ID: <4f2ontF1h7gb1U1@uni-berlin.de> k.retheesh at gmail.com schrieb: > Can anybody tell me why am I getting this error message while trying to > print a part of a string. Is there a better approach for this... Because you don't use a string? The error message is pretty clear: TypeError: unsubscriptable object So - what are Function[:10], Description[:10] ? You _assume_ they are strings, seems not to be the case. Diez From rossberg at ps.uni-sb.de Thu Jun 22 11:21:31 2006 From: rossberg at ps.uni-sb.de (Andreas Rossberg) Date: Thu, 22 Jun 2006 17:21:31 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: <87ejxh9xoq.fsf@thalassa.informatimago.com> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150902275.129780.50260@p79g2000cwp.googlegroups.com> <1150918629.818145.143220@y41g2000cwy.googlegroups.com> <4fv081F1jh4ifU1@individual.net> <1150967543.947096.72840@g10g2000cwb.googlegroups.com> <4fv84rF1kp06kU1@individual.net> <4fvfuiF1kncqtU1@individual.net> <87ejxh9xoq.fsf@thalassa.informatimago.com> Message-ID: Pascal Bourguignon wrote: > > For example, sort doesn't need to know what type the objects it sorts > are. It only needs to be given a function that is able to compare the > objects. Sure. That's why any decent type system supports polymorphism of this sort. (And some of them can even infer which comparison function to pass for individual calls, so that the programmer does not have to bother.) - Andreas From fuzzyman at gmail.com Wed Jun 7 16:55:52 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 7 Jun 2006 13:55:52 -0700 Subject: [ANN] Firedrop 0.2.2 Message-ID: <1149713752.087334.269320@f6g2000cwb.googlegroups.com> `Firedrop 2 0.2.2 `_ is now available. You can download it from : `Firedrop-0.2.2.zip `_ This is an important release with several new features, and contributions from new developers joining the team. What is Firedrop2 ? ============== **Firedrop2** is a free, cross-platform blogging tool written in `Python `_. It keeps your blog source files on your computer, making it a *clientside* tool. This means you control your blog, and can easily move it from one server to another, with no risk of losing data. It also means you can manage your blog *offline*. It is fully open source, and has all the features you expect from a modern blogging program : * {acro;RSS;Really Simple Syndication} feed generation * Categories * Automatic archive generation * A powerful set of plugins, including spellchecker, emailer, and themes * Entries can be made in text, {acro;HTML}, {acro;ReST}, textile, sextile or markdown markup * HTML templating system and macros for all sorts of tricks * Built-in {acro;FTP} capability for uploading your blog to a server * Integrated blog comments support (Through Haloscan_) * Because it's written in Python, it is easy to extend Firedrop or create new plugins for it What's New ? ========== This release has a lot of bugfixes and changes. Hopefully I've remembered the important ones. {sm;:-)} * Fixed a bug with categories and the unicode wxPython * Added the Themes plugin by Stewart Midwinter [#]_ * RSS feeds can be generated for all the categories, by Davy Mitchell * Firedrop now saves user data in the users home (checking sensibly for directories where it has write permissions) * Now includes support for the `Haloscan `_ comments system. * Addition of the Firedrop2 banner by Stewart Midwinter. Plus other code improvements and bug fixes. Their is already work being done on the next release. This will include features like : * Faster build time through entry HTML caching * Blog statistics report generation * Tagging * A Podcast plugin * Extension to the plugin protocol for extra plugin capabilities .. [#] The Themes plugin requires version 0.3.32 of `Wax `_, or more recent. From goofball at vapornet.com Mon Jun 19 14:21:56 2006 From: goofball at vapornet.com (Yet Another Dan) Date: Mon, 19 Jun 2006 18:21:56 +0000 (UTC) Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> Message-ID: Chris Smith wrote in news:MPG.1f007f6a483b5e7d9896c6 at news.altopia.net: > Rob Thorpe wrote: >> A language is latently typed if a value has a property - called it's >> type - attached to it, and given it's type it can only represent >> values defined by a certain class. > > Now I define a class of values called "correct" values. I define > these to be those values for which my program will produce acceptable > results. Clearly there is a defined class of such values: (1) they > are immediately defined by the program's specification for those lines > of code that produce output; ... > I'm not trying to poke holes in your definition for fun. I am > proposing that there is no fundamental distinction between the kinds > of problems that are "type problems" and those that are not. That sounds like a lot to demand of a type system. It almost sounds like it's supposed to test and debug the whole program. In general, defining the exact set of values for a given variable that generate acceptable output from your program will require detailed knowledge of the program and all its possible inputs. That goes beyond simple typing. It sounds more like contracts. Requiring an array index to be an integer is considered a typing problem because it can be checked based on only the variable itself, whereas checking whether it's in bounds requires knowledge about the array. -- YAD From xah at xahlee.org Wed Jun 14 16:54:39 2006 From: xah at xahlee.org (Xah Lee) Date: 14 Jun 2006 13:54:39 -0700 Subject: Interactive Find and Replace String Patterns on Multiple Files In-Reply-To: <1150245399.967427.190300@c74g2000cwc.googlegroups.com> References: <1150245399.967427.190300@c74g2000cwc.googlegroups.com> Message-ID: <1150318478.994113.140820@g10g2000cwb.googlegroups.com> Interactive Find and Replace String Patterns on Multiple Files Xah Lee, 2006-06 Suppose you need to do find and replace of a string pattern, for all files in a directory. However, you do not want to replace all of them. You need to look at it in a case-by-case basis. What can you do? Answer: emacs. Here's how you do it. Select Target Files Start emacs by typing ?emacs? in the command line interface prompt. Now you need to locate the directory and files you want to find/replace. Type ?esc x find-dired?. (then press Enter) Then, give a directory name, e.g. ?/Users/mary/myfiles? Emacs will ask you with the prompt ?Run find (with args): ?. If you need to do the replacement on all html files, then give ?-name "*html"?. If you don't care about what kind of file but simply all files under that dir, then give ?-type f?. Now, you will be shown the list of files, and now you need to ?mark? the files you want the regex find-replace to work on. You mark a file by moving the cursor to the file you want, then press m. Unmark it by pressing u. To mark all files by a regex, type ?% m?, then give your pattern. Suppose you want to mark all html files, then type ?% m html$?. Interactive Find & Replace Now, you are ready to do the interactive find replace. For simplicity, let's say you just want to replace the word ?quick? by ?super? depending on the context. Now, type ?esc x dired-do-query-replace-regexp?. It will prompt you for the regex string and the replacement string. Type ?quick? then ?super?. Now, emacs will use your pattern and check the files, and stop and show you whenever a match occurred. When this happens, emacs will prompt you, and you have a choice of making the change or skip the change. To make the change, type y. To skip, type n. If you simply want emacs to go ahead and make all such changes to the current files, type ?!?. If you want to cancel the whole operation, type control-g. Saving the Changed Files Now, after you went through the above ordeal. There is one more step you need to do, and that is saving the changed files. This you can do, by typing ?esc x list-buffer?, then move the cursor to the file you want to save and press s. It will mark the file for later save action. Type u to unmark. Once you are done, type x to execute the saving of all S marked files. (in emacs, opened file is called ?buffer?. Disregard ohter things there.) Alternatively, you can also type ?esc x save-some-buffers?. Then emacs will show each buffer for you and ask if you want it saved. If you have emacs version 22, you can use ?M-x ibuffer? to mark all files you want to save by a regex. ---- PS if anyone know any tool or perl/python/lisp program that can also do this, i'd be interested to know. Thanks. ---- This post is archived at: http://xahlee.org/emacs/find_replace_inter.html Xah xah at xahlee.org ? http://xahlee.org/ From scott at bogusaddress.com Thu Jun 29 07:57:23 2006 From: scott at bogusaddress.com (scott at bogusaddress.com) Date: Thu, 29 Jun 2006 11:57:23 GMT Subject: Passing a Cookie with httplib References: Message-ID: <4nf7a2h89hg1an775hv2rvf8pjbk63f7ad@4ax.com> On Thu, 29 Jun 2006 21:42:50 +1200, Lawrence D'Oliveiro wrote: >According to , >you can pass additional "body" and "headers" args to >HTTPConnection.request. How about trying something like this in place of >the last line above: > > Headers = {"Cookie" : >"auth=buster%3A12345678901234567890exZ9rzMqgtxa5A"} > conn.request('GET',WP_PATH % uservalue, None, Headers) Perfect! Thanks so much. I appreciate your help. I looked through the docs before, but didn't spot this nugget because I was focused on searching for the text "cookie". Obviously, it pays to read... :-) Scott From smithj at rpath.com Tue Jun 6 16:52:35 2006 From: smithj at rpath.com (Jonathan Smith) Date: Tue, 06 Jun 2006 16:52:35 -0400 Subject: subprocesses, stdin/out, ttys, and beating insubordinate processes into the ground Message-ID: <4485EB13.1030106@rpath.com> First a bit about what I'm trying to do. I need a function which takes a patchfile and patches a source directory. Thats it. However, I need to be able to do so no matter what the patchlevel (-px) of the diff is. So, my solution is to just try to patch until it works or you try a level more than 3. However, if you have a reversed patch, or patch can't find the right file, GNU patch tries to ask for input and I don't want that. I know that patch will run non-interactively when backgrounded in a shell (no controlling tty). This is what I've tried so far: def patchme(self, provides, f, destDir, patchlevels): for patchlevel in patchlevels: patchArgs = ['patch', '-d', destDir, '-p%s'%patchlevel, ] if self.backup: patchArgs.append(['-b', '-z', self.backup]) if self.extraArgs: patchArgs.append(self.extraArgs) log.info('attempting to patch the source with file %s and patchlevel %s' % (f,patchlevel)) p1 = subprocess.Popen([provides, f], stdout=subprocess.PIPE, shell=False) p2 = subprocess.Popen(patchArgs, stdin=p1.stdout, shell=False) message = p2.communicate()[0] # patch seems to use stdout for everything, even errors if message != None and self.patcherror.search(message): os.kill(p2.pid, signal.SIGTERM) elif p2.wait(): log.info('patch did not apply with path level %s' % patchlevel) print message else: return log.error('could not apply the patch to your build dir') However, I still get an interactive prompt, no matter what I try! Using shell=False did not help, nor did trying to kill the pid if python sees a line from patch which isn't saying what its patching or giving info on a specific hunk. Any suggestions? -smithj PS: if you're a maintainer for GNU patch, a --non-interactive would be really nice ;-) (and no, -f and -t aren't good enough as they force other things that I don't want) From yairchu at gmail.com Mon Jun 19 04:46:22 2006 From: yairchu at gmail.com (yairchu at gmail.com) Date: 19 Jun 2006 01:46:22 -0700 Subject: Tetris In-Reply-To: <1150647716.792057.283860@u72g2000cwu.googlegroups.com> References: <1150647716.792057.283860@u72g2000cwu.googlegroups.com> Message-ID: <1150706782.642885.275100@u72g2000cwu.googlegroups.com> pygame.org is what you need it has tutorials it's cool From rabkinDELETE at mweb.co.za Thu Jun 1 15:58:38 2006 From: rabkinDELETE at mweb.co.za (Max) Date: Thu, 01 Jun 2006 21:58:38 +0200 Subject: Python for Visual Basic or C# programmers In-Reply-To: <1149188503.783262.132870@h76g2000cwa.googlegroups.com> References: <1149184981.184143.63160@f6g2000cwb.googlegroups.com> <1149188503.783262.132870@h76g2000cwa.googlegroups.com> Message-ID: Metalone wrote: > > This might be a little too tricky. > [" %d", "%d][n < 0] % n --> selects list[0] or list[1] based upon sign > of number > ("%+d" % 123).replace("+", " ") is slightly longer but instantly comprehensible, although I for one think your boolean indexing trick is cool. --Max From mensanator at aol.com Sun Jun 18 12:19:19 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 18 Jun 2006 09:19:19 -0700 Subject: maximum integer length? References: Message-ID: <1150647558.938537.180580@c74g2000cwc.googlegroups.com> nate wrote: > Hey everyone, > > I am trying to figure out what is the largest integer I can. Lets say > for 400 megabytes of memory at my disposal. > > I have tried a few things > c = 2**1000000 > d = 2**2000000 > print c**d > > Obviously I didn't have enough memory for that, but I was able to c**3. > (I think anyways, it is still trying to display the result) Don't print, takes too long. Do e=c**3. > > So I am just wondering how long an integer can be with 400 megabytes of > memory. > > I guess this is a question of logic? > each integer takes up a byte right? If I have 400 megabytes that would > mean I could have a long integer with up to 419,430,400,000 integers? > > Really I am not sure on this one and that is why I am asking. Because it > is just bugging me I am not sure how it works... > > I know this probably seems trivial and just a stupid question, but I > find this type of stuff interesting... Using gmpy (and I don't know if it stores large ints different from Python ints) and only 192M on my laptop, I can get to billion bit numbers, but not much larger. Switching to Python ints ran out of memory trying gen 11. It also ran out of memory trying to calculate gen 10, which gmpy was able to do successfully, so maybe gmpy is better for such things: Closed form: Type12MH(k,i) Find ith, kth Generation Type [1,2] Mersenne Hailstone using the closed form equation 2**(6*((i-1)*9**(k-1)+(9**(k-1)-1)/2+1)-1)-1 2**5-1 generation: 1 2**29-1 generation: 2 2**245-1 generation: 3 2**2189-1 generation: 4 2**19685-1 generation: 5 2**177149-1 generation: 6 2**1594325-1 generation: 7 2**14348909-1 generation: 8 2**129140165-1 generation: 9 2**1162261469-1 generation:10 Traceback (most recent call last): File "C:\python24\user\user_home\gmpy ver 1.01\MHtest.py", line 41, in -toplevel- a = Type12MH(k,1) File "C:\python24\lib\collatz_functions.py", line 595, in Type12MH return TWO**(SIX*a - ONE) - ONE ValueError: mpz.pow outrageous exponent >>> >>> i=1 >>> k=11 >>> a = 2**(6*((i-1)*9**(k-1)+(9**(k-1)-1)/2+1)-1)-1 Traceback (most recent call last): File "", line 1, in -toplevel- a = 2**(6*((i-1)*9**(k-1)+(9**(k-1)-1)/2+1)-1)-1 MemoryError From fcorreia at gmail.com Wed Jun 28 10:55:10 2006 From: fcorreia at gmail.com (Filipe) Date: 28 Jun 2006 07:55:10 -0700 Subject: handling unicode data Message-ID: <1151506510.391856.207460@y41g2000cwy.googlegroups.com> Hi all, I'm starting to learn python but am having some difficulties with how it handles the encoding of data I'm reading from a database. I'm using pymssql to access data stored in a SqlServer database, and the following is the script I'm using for testing purposes. ----------------------------------------------------------------------------- import pymssql mssqlConnection = pymssql.connect(host='localhost',user='sa',password='password',database='TestDB') cur = mssqlConnection.cursor() query="Select ID, Term from TestTable where ID > 200 and ID < 300;" cur.execute(query) row = cur.fetchone() results = [] while row is not None: term = row[1] print type(row[1]) print term results.append(term) row = cur.fetchone() cur.close() mssqlConnection.close() print results ----------------------------------------------------------------------------- In the console output, for a record where I expected to see "Fran?a" I'm getting the following: "" - When I print the type (print type(row[1])) "Fran+a" - When I print the "term" variable (print term) "Fran\xd8a" - When I print all the query results (print results) The values in "Term" column in "TestTable" are stored as unicode (the column's datatype is nvarchar), yet, the python data type of the values I'm reading is not unicode. It all seems to be an encoding issue, but I can't see what I'm doing wrong.. Any thoughts? thanks in advance, Filipe From kent at kentsjohnson.com Fri Jun 9 09:51:58 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Fri, 09 Jun 2006 09:51:58 -0400 Subject: secure xmlrpc server? In-Reply-To: <448976aa$1_2@newspeer2.tds.net> References: <448976aa$1_2@newspeer2.tds.net> Message-ID: <44897bda$1_3@newspeer2.tds.net> Kent Johnson wrote: > Laszlo Nagy wrote: >> But I do not know how to create an XML RPC server in Python that uses >> HTTPS for XML transports. > > This recent recipe seems to do exactly what you want: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496786 It was gently pointed out to me that the OP is the author of the recipe...well I guess he figured it out! That will teach me to get two days behind on reading c.l.py... From bj_666 at gmx.net Sat Jun 17 02:42:06 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 17 Jun 2006 08:42:06 +0200 Subject: Date Subtraction References: Message-ID: In , rsutradhar_python wrote: > How to subtract date which is stored in string variable? > > Example: > > date1="2006-01-10" > date2="2005-12-15" > date = date1 - date2 > should give me 25 but problem is that date1 and date2 datatype is > string which need to be conerted into date fromat which i am not able > to do so please help me. from datetime import date date_str_1 = '2006-01-10' date_str_2 = '2005-12-15' date_1 = date(*map(int, date_str_1.split('-'))) date_2 = date(*map(int, date_str_2.split('-'))) print (date_1 - date_2).days - 1 Ciao, Marc 'BlackJack' Rintsch From redefined.horizons at gmail.com Mon Jun 12 23:45:40 2006 From: redefined.horizons at gmail.com (Redefined Horizons) Date: Mon, 12 Jun 2006 20:45:40 -0700 Subject: Extending Python - Understanding Flags... Message-ID: I'm trying to understand the argument flags that are used in the method table of an extension module written in C. First let me ask this question about the method table. Is it an C array named "PyMethodDef"? Now, onto my questions about the arguments: [1] I see that even when the Python function we are supplying takes no arguments, (the argument flag is METH_NOARGS), that we still pass the C function a reference to "self". Is this "self" actually a pointer to the section of memory that represents the object in Python that is calling the method? [2] What is the difference between "positional" arguments indicated by the METH_VARARGS argument flag, and "keyword" arguments that are indicated by the METH_KEYWORDS argument flag? Does one determine the identity of an argument based on the order or position in which the arguments are passed to the C function, while the other uses keys in a dictionary to identify the arguments? That should be the start of my customization questions... :] If it is any consolation I hope to take what I learn and put together a tutorial on expanding Python for those that only have a little experience with C programming, like myself. I plan to explain everything like I was teaching a 6-year old. :] I was just going to put this on a wiki, but is there a way to include with other Python documentation on an "official" site? Thanks for the help. Scott Huey From bearophileHUGS at lycos.com Thu Jun 8 12:48:51 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 8 Jun 2006 09:48:51 -0700 Subject: How to generate k+1 length strings from a list of k length strings? In-Reply-To: <44883789$1_4@news.bluewin.ch> References: <44883789$1_4@news.bluewin.ch> Message-ID: <1149785331.109164.208340@i39g2000cwa.googlegroups.com> Boris Borcic: > I'd favor the following, that I find most readable > sets = map(set,list_of_strings) > res = set(''.join(sorted(s1|s2)) for s1 in sets for s2 in sets if len(s1^s2)==2) I think there can be written more readable code. For my programs I usually prefer simpler code, that (if possible) even a children can understand. So I can debug, modify and improve it better & faster. Bye, bearophile From cvanarsdall at mvista.com Tue Jun 20 13:43:00 2006 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Tue, 20 Jun 2006 10:43:00 -0700 Subject: need helping tracking down weird bug in cPickle Message-ID: <449833A4.7000905@mvista.com> Hey everyone, cPickle is raising an ImportError that I just don't quite understand. Before I paste the code, let me explain the application. Basically the part of the application that failed is a function that loads a list of objects from a file using cPickle. This list is a queue of requests. I've done some research and it looks like cPickle tries to load some modules as some kind of test. From what I can tell the module that cPickle is trying to load is a concatenation of the module that it exists in and part of the string that was sent in the orignal request. It looks like something where memory is getting overwritten, but I'm not really doing anything too fancy, so i'm not sure how to approach this problem. I'm using python2.2. Does anyone know how I might go about trying to troubleshoot something like this? Is there a good tool or a better method of error handling I can use to try and track this down? Or is it better to give up troubleshooting and just upgrade to 2.4? Here's the code where the error occured: def initQueue(): global masterQueue try: queueFPtr = open("/home/build/bin/resourceManager/queue.rm","rb") except IOError: raise ResourceError,"Error Opening Queue for Reading" except: traceback.print_exc() raise ResourceError, "Unknown Error Opening Queue" try: pickledList = cPickle.load(queueFPtr) except EOFError: masterQueue = [[],[],[]] #empty file, set to empty list for construction #there exist 3 blank lists in the master list, these list refer to various priorities 0, 1, and 2 queueFPtr.close() return except: traceback.print_exc() raise ResourceError, "Unknown Error loading Queue" queueFPtr.close() masterQueue = pickledList return Here's the traceback: Traceback (most recent call last): File "/home/build/bin/resourceManager/resourceQueue.py", line 50, in initQueue pickledList = cPickle.load(queueFPtr) ImportError: No module named resourcepmdb' Traceback (most recent call last): File "./installimage.py", line 443, in ? rpmdb = getResource(buildtag,buildid,"dumborpmdb","Installing installer rpms") File "/home/build/bin/resourceManager/resourceManager.py", line 39, in getResource resourceQueue.initQueue() File "/home/build/bin/resourceManager/resourceQueue.py", line 58, in initQueue raise ResourceError, "Unknown Error loading Queue" resourceError.ResourceError: Unknown Error loading Queue -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From bencvt at gmail.com Thu Jun 1 18:33:38 2006 From: bencvt at gmail.com (Ben Cartwright) Date: 1 Jun 2006 15:33:38 -0700 Subject: argmax In-Reply-To: References: Message-ID: <1149201218.659046.64030@u72g2000cwu.googlegroups.com> David Isaac wrote: > 2. Is this a good argmax (as long as I know the iterable is finite)? > def argmax(iterable): return max(izip( iterable, count() ))[1] Other than the subtle difference that Peter Otten pointed out, that's a good method. However if the iterable is a list, it's cleaner (and more efficient) to use seq.index(max(seq)). That way you won't be creating and comparing all those tuples. def argmax(it): try: it.index except AttributeError: it = list(it) # Or if it would too expensive to convert it to list: #return -max((v, -i) for i, v in enumerate(it))[1] return it.index(max(it)) --Ben From steve at holdenweb.com Wed Jun 7 15:26:05 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 07 Jun 2006 20:26:05 +0100 Subject: os.system and command output In-Reply-To: <8rFhg.1071$Wy.73797@news20.bellglobal.com> References: <8rFhg.1071$Wy.73797@news20.bellglobal.com> Message-ID: A.M wrote: > Hi, > > > > How can I run an OS command and have the command's output (to stdout) in my > string variable? > > > > For example in windows, this command should return a list of files within > directory: > > > > os.system("DIR") > > > > I am looking for an alternative function that returns the DIR command output > in a string > Try: s = os.popen("DIR").read() regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From dmharvey at math.harvard.edu Fri Jun 30 06:51:01 2006 From: dmharvey at math.harvard.edu (David Harvey) Date: Fri, 30 Jun 2006 06:51:01 -0400 Subject: efficiency question Message-ID: <6AD91BEE-08AF-446D-AE17-B2FB5532E7FE@math.harvard.edu> Hi, Suppose I write if x in ("abc", "def", "xyz"): doStuff() elif x in ("pqr", "tuv", "123"): doOtherStuff() elif ... etc. When is python building the tuples? Does it need to build the tuple every time it comes through this code? Or does it somehow recognise that they are constant and cache them? In other words, is anything gained (efficiency-wise) by first putting say tuple1 = ("abc", "def", "xyz") tuple2 = ("pqr", "tuv", "123") somewhere where I know it's executed once, and then writing if x in tuple1: doStuff() elif x in tuple2: doOtherStuff() elif ... ???? (The tuples I have in mind are of course much longer than three elements) Many thanks David From a at tempinbox.com Wed Jun 28 23:59:51 2006 From: a at tempinbox.com (a) Date: 28 Jun 2006 20:59:51 -0700 Subject: how do i make an array global References: <1151472238.400461.42350@p79g2000cwp.googlegroups.com> <1151553485.378000.203760@p79g2000cwp.googlegroups.com> Message-ID: <1151553591.615096.212030@d56g2000cwd.googlegroups.com> please tell me how to do it if i should not make it global like you guys worry i m not comfortable making it global and mutating it in every subblock thanks for reading and helping out From warspir at gmail.com Fri Jun 23 11:41:28 2006 From: warspir at gmail.com (warspir) Date: Fri, 23 Jun 2006 11:41:28 -0400 Subject: Python profiler and decorators Message-ID: Hi I was wondering about this while working on profiling my program using the profile module. Say we have the following: @dec def func: blah blah blah When profiling the whole program, what would the total time for func represent? The time spent just in the original function or the time spent spent in the function along with the execution of the decorator's code? Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From no at spam.please Sun Jun 4 10:07:34 2006 From: no at spam.please (D H) Date: Sun, 04 Jun 2006 09:07:34 -0500 Subject: Python less error-prone than Java In-Reply-To: References: Message-ID: Christoph Zwerschke wrote: > > See the following web page if you dont find it ;-) > http://googleresearch.blogspot.com/2006/06/extra-extra-read-all-about-it-nearly.html The point of that is that it did fail. It threw an ArrayIndexOutOfBoundsException exception. But it was just luck that happened. Unfortunately I don't think java and C# have integer overflow checking turned on by default. Take this longArithmetic benchmark here: http://www.cowell-shah.com/research/benchmark/code and a story about it here: http://www.osnews.com/story.php?news_id=5602&page=3 The java and C# versions are fast (15 seconds for me), BUT, they give the incorrect result because of an overflow error. The python version gives the correct result because it transparently changes the underlying types to handle the larger numbers, BUT this causes it to run over 20X slower than Java or C#. It takes 10 minutes to complete in python, not 15 seconds. With psyco, it takes 5 minutes. So to say the story you pointed out shows that python is superior is a matter of perspective. Yes, python gave the correct result by silently changing the underlying types to longs, and that is what I would expect of a scripting language. But the price is speed. In both these cases, I would rather be made aware of the error in the code and fix it so I didn't have to suffer slowdowns. That is why in boo ( http://boo.codehaus.org/ ) luckily overflow checking is enabled by default, and it throws a overflow exception at runtime to tell you something is wrong with your code. When you then fix for that, you get the same 15 second time just like java and C#. From alanalan at newsgroup.nospam Thu Jun 1 12:35:20 2006 From: alanalan at newsgroup.nospam (A.M) Date: Thu, 1 Jun 2006 12:35:20 -0400 Subject: Python for Visual Basic or C# programmers Message-ID: Hi, I am trying to find the equivalent functions such as vb's str or asc in Python. Is there any resource that help me to find these kinds of functions in Python faster? Thank you, Alan From no at spam.please Thu Jun 1 23:16:38 2006 From: no at spam.please (D H) Date: Thu, 01 Jun 2006 22:16:38 -0500 Subject: Can Python format long integer 123456789 to 12,3456,789 ? In-Reply-To: <8oKfg.1621$Su3.139425@news20.bellglobal.com> References: <8oKfg.1621$Su3.139425@news20.bellglobal.com> Message-ID: A.M wrote: > Hi, > > Is there any built in feature in Python that can format long integer > 123456789 to 12,3456,789 ? Apparently you need to use the locale module. This is the example they give online to print a simple number with commas: import locale locale.setlocale(locale.LC_ALL, 'English_United States.1252') print locale.format("%d", 123456789, grouping=True) Someone should make a module that uses .NET or Java's formmating. You just use {0:n} or ###,### instead of all the above. http://blog.stevex.net/index.php/string-formatting-in-csharp/ http://java.sun.com/docs/books/tutorial/i18n/format/decimalFormat.html From userprogoogle-139 at yahoo.co.uk Sun Jun 18 17:00:45 2006 From: userprogoogle-139 at yahoo.co.uk (rodmc) Date: 18 Jun 2006 14:00:45 -0700 Subject: USB support References: <1150222139.721785.268830@f14g2000cwb.googlegroups.com> Message-ID: <1150664445.317749.305880@u72g2000cwu.googlegroups.com> Thanks for this, I have managed to build PyUSB and install it in the relevant directory. However I get bus errors when I try the PlugUSB.py example. Does anyone know why this is likely to be the case? I am using Macpython 2.4, Libusb 0.1.12 and PyUSB 0.3.3 on an Intel based mac. Thanks in advance. Rod Tim Roberts wrote: > "rodmc" wrote: > > > >I need to write a program which can access the USB ports on Mac and > >Linux, is there a library available for Python? > > The "stable" version of Libusb includes a Python binding. The version in > development does not yet. > -- > - Tim Roberts, timr at probo.com > Providenza & Boekelheide, Inc. From ldo at geek-central.gen.new_zealand Thu Jun 29 05:47:45 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 29 Jun 2006 21:47:45 +1200 Subject: Python docs bug Message-ID: One long-standing irritation I have with the table of contents for the Python Library Reference , is that there is one very important section, "String Methods" , which does not appear there. That's because it is section 2.3.6.1, and the table of contents only goes to 3 levels. From marco.giusti at gmail.com Fri Jun 2 17:28:19 2006 From: marco.giusti at gmail.com (Marco Giusti) Date: Fri, 2 Jun 2006 23:28:19 +0200 Subject: Initializing an attribute that needs the object In-Reply-To: <4480AA70.2020804@eastlink.ca> References: <4480AA70.2020804@eastlink.ca> Message-ID: <20060602212819.GA2688@localdomain> On Fri, Jun 02, 2006 at 06:15:28PM -0300, David Pratt wrote: >Hi. I want to have different handlers to do perform logic. The problem >is the Handler requires an instance of the factory since it will use its >own methods in conjunction with methods of the factory. > >Once I have got a Factory instance I can give it a new handler (see >below). It would be more flexible if I could provide a handle in >constructor - but how to do this when it requires the object itself. >Would I use a super for this sort of thing? Many thanks when __init__ is called the object already exists. >class Factory: > > def __init__(self): > self.some_handler = Handler(self) > >f = Factory() >f.some_handler = AnotherHandler(f) try this, should works: class Factory: def __init__(self): self._some_handler = AnotherHandler(self) maybe a class hierarchy is good for you ciao m. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From xivulon at gmail.com Thu Jun 1 15:10:54 2006 From: xivulon at gmail.com (ago) Date: 1 Jun 2006 12:10:54 -0700 Subject: win32com: how to connect to a specific instance of a running object? Message-ID: <1149189054.311477.309250@g10g2000cwb.googlegroups.com> Is it possible to use win32com.client to connect to a specific instance of a running application? In particular I am interested in finding the instance of excel which has a particular spreadsheet opened considering that there might be more instances of excel running at the same time. I need to take a "snapshot" of the spreadsheet which contains live feeds. From rdh at new.rr.com Fri Jun 2 15:54:15 2006 From: rdh at new.rr.com (DataSmash) Date: 2 Jun 2006 12:54:15 -0700 Subject: os.chdir doesn't accept variables sometimes In-Reply-To: References: <1149267516.348440.60290@u72g2000cwu.googlegroups.com> Message-ID: <1149278055.629113.47350@c74g2000cwc.googlegroups.com> A simple way to get all the files throughout the directory sturcture... You may have to rewrite the "CONVERTING" part. import os, glob for root, dirs, files in os.walk(os.getcwd()): for file in files: if file.endswith(".mp3"): print "File: " + os.path.abspath(os.path.join(root, file)) print "CONVERTING "+file+" to "+file[:file.index(".")]+".mp3" file = file[:file.index(".")]+".mp3" Donn Cave wrote: > In article <1149267516.348440.60290 at u72g2000cwu.googlegroups.com>, > "dannycolligan at gmail.com" wrote: > > > #!/usr/bin/python > > > > from os import * > > > > chdir("/home/chainlynx/Desktop/Music") > > for artist in listdir(getcwd()): > > print "===ARTIST: "+artist > > chdir(artist) > > for album in listdir(getcwd()): > > print "---ALBUM: "+album > > print "CWD: " + getcwd() > > chdir(album) ######ERROR ON THIS > > LINE > > for string in listdir(album): > ... > > > Traceback (most recent call last): > > File "/home/chainlynx/workspace/PyTest/src/pypack/__init__.py", line > > 12, in ? > > for string in listdir(album): > > OSError: [Errno 2] No such file or directory: 'Album1' > > To start with, note that your traceback implicates the listdir() > on line 12, not the chdir() before it. This listdir() uses the > same parameter as that preceding chdir(), that appears to be your > problem. > > One of your problems, anyway. You're doing a lot of downwards > chdirs, but no upwards, which is going to limit the extent of > your directory traversal. > > The "from os import *" is a terrible idea, where did you get that? > "os" has a lot of identifiers in it that tend to collide with other > namespaces. "open" is a classic example. Don't do that, with "os" > or generally any module. > > As a more general direction, it would be a good idea to look > into standard library functions, e.g., os.path.walk > > > P.S. Bonus points: is there any way to bash shell script this on the > > command line instead (recursively)? > > Depends on what you want it to do, but maybe something like > > find . -name \*.mp3 -exec $HOME/bin/cvt .mp4 {} \; > > where cvt would be something like > #!/bin/sh > case $1:$2 in > .mp4:*.mp3) mp3_to_mp4 $2 ${2%.mp3}.mp4 ;; > ... > > You'd have to think about it. > > Donn Cave, donn at u.washington.edu From grante at visi.com Tue Jun 27 14:27:07 2006 From: grante at visi.com (Grant Edwards) Date: Tue, 27 Jun 2006 18:27:07 -0000 Subject: Questions about OSS projects. References: <1151431692.418333.123060@y41g2000cwy.googlegroups.com> Message-ID: <12a2u3r6kgjrrf1@corp.supernews.com> On 2006-06-27, bio_enthusiast wrote: > I was wondering how to go about starting an open source > project for doing routine biological problems? Generally you either start writing code to fulfill a need of yours, or you pay somebody else to write it for you. > There is a plethora of scripts and a fairly large biopython > project to back up anyone who tried, these however cater to > the bioinformatics community and it loses the vast majority of > the wet-lab scientists. How can someone who is used to writing > small scripts and doing wet-lab work contribute to the open > source community? For existing projects, you can help a lot by submitting good bug reports, documentation enhancements or translations, patches, etc. > Starting software projects seems to be the domain of people > with much more experience and skill but there are some serious > needs by people who do not have the skills to upkeep any > software based project. That's what money is for. People with no need for (or interest in) program X (and indeed don't even know about the need) aren't going to write program X unless you pay them to. You could try to recruit some SW types to write the code for free, but they're probably already busy working on OSS projects that they need/want. There are sites where you can offer "bounties" as incentives for people to work on the OSS you want them to work on. -- Grant Edwards grante Yow! Are you still at SEXUALLY ACTIVE? Did you visi.com BRING th' REINFORCEMENTS? From belred at gmail.com Wed Jun 7 23:52:00 2006 From: belred at gmail.com (Bryan) Date: Wed, 07 Jun 2006 20:52:00 -0700 Subject: language-x-isms Message-ID: does anyone know if there is a collection somewhere of common python mistakes or inefficiencies or unpythonic code that java developers make when first starting out writing python code? if not, maybe we could start a thread on this. for example, i've noticed several java developers i know write python code like this: foo_list = [...] for i in range(len(foo_list)): print '%d %s' % (i, foo_list[i]) of course, one way to do this would be to use enumerate: for i, foo in enumerate(foo_list): print '%d %s' % (i, foo) i'm guessing there is a lot of these language-x-isms that people on this list have seen. i think it would be helpful to both the new java-to-python developer and python developers in general to be aware of these. just an idea. feel free to discuss any language-x-isms, not necessarily just java-isms. bryan From eval.apply at gmail.com Tue Jun 27 17:26:31 2006 From: eval.apply at gmail.com (Joe Marshall) Date: 27 Jun 2006 14:26:31 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: <1151432002.905190.152470@y41g2000cwy.googlegroups.com> References: <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <1151384511.223582.305760@m73g2000cwd.googlegroups.com> <1151425350.679754.278820@i40g2000cwc.googlegroups.com> <1151432002.905190.152470@y41g2000cwy.googlegroups.com> Message-ID: <1151443591.286204.16620@x69g2000cwx.googlegroups.com> Marshall wrote: > Joe Marshall wrote: > > Looking back in comp.lang.lisp, I see these examples: > > > > (defun noisy-apply (f arglist) > > (format t "I am now about to apply ~s to ~s" f arglist) > > (apply f arglist)) > > > > (defun blackhole (argument) > > (declare (ignore argument)) > > #'blackhole) > > > > But wait a sec. It seems that these were examples I invented in > > response to the same question from you! > > Ah, how well I remember that thread, and how little I got from it. > > My memories of that thread are > 1) the troll who claimed that Java was unable to read two numbers from > standard input and add them together. > 2) The fact that all the smart people agreed the blackhole > function indicated something profound. > 3) The fact that I didn't understand the black hole function. > > The noisy-apply function I think I understand; it's generic on the > entire arglist. In fact, if I read it correctly, it's even generic > on the *arity* of the function, which is actually pretty impressive. > True? Yes. > This is an issue I've been wrestling with in my own type > system investigations: how to address genericity across arity. > > Does noisy-apply get invoked the same way as other functions? > That would be cool. Yes, but in testing I found an incompatability. Here's a better definiton: (defun noisy-apply (f &rest args) (format t "~&Applying ~s to ~s." f (apply #'list* args)) (apply f (apply #'list* args))) CL-USER> (apply #'+ '(2 3)) 5 CL-USER> (noisy-apply #'+ '(2 3)) Applying # to (2 3). 5 The internal application of list* flattens the argument list. The Common Lisp APPLY function has variable arity and this change makes my NOISY-APPLY be identical. > As to the black hole function, could you explain it a bit? It is a function that takes any argument and returns the function itself. > I apologize > for my lisp-ignorance. I am sure there is a world of significance > in the # ' on the third line, but I have no idea what it is. The #' is a namespace operator. Since functions and variables have different namespaces, I'm indicating that I wish to return the function named blackhole rather than any variable of the same name that might be around. From grante at visi.com Sat Jun 3 13:18:21 2006 From: grante at visi.com (Grant Edwards) Date: Sat, 03 Jun 2006 17:18:21 -0000 Subject: integer to binary... References: <1149189570.376091.319890@j55g2000cwa.googlegroups.com> <127ugf9jgu7av18@corp.supernews.com> <4480a084$0$6172$626a54ce@news.free.fr> <12839b8doin7mff@corp.supernews.com> Message-ID: <1283h2t81mdn697@corp.supernews.com> On 2006-06-03, Tim Chase wrote: >> The fact that they impliment the xor operator is pretty much >> proof that integers are stored in binary format -- xor is only >> defined for binary numbers. > > Um...let's not use bad logic/proofs for evidencing this... > > >>> hasattr(set(), "__xor__") > True Sets aren't numbers. Perhaps I should have phrased it better: xor is only defined for numbers if they are represented in binary. If numbers were represented in something other than binary, then an xor operation on those numbers wouldn't make sense. -- Grant Edwards grante Yow! .. I want to perform at cranial activities with visi.com Tuesday Weld!! From larry.bates at websafe.com Thu Jun 1 10:03:46 2006 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 01 Jun 2006 09:03:46 -0500 Subject: Best way to do data source abstraction In-Reply-To: References: Message-ID: <447EF3C2.9060804@websafe.com> Arthur Pemberton wrote: > What is the best way to do data source abtraction? For example have > different classes with the same interface, but different > implementations. > > I was thinking of almost having classA as my main class, and have > classA dynamically "absorb" classFood into to based on the extension > of the input file received by classA. But this doesn't seem possible. > > Please advise. > > Thank you. > The best method I've found is to have a class that abstracts the data and presents the values from the data source via class attributes. If you also implement it as an iterator (e.g. give it __iter__ and __next__ methods), you can easily iterate over the resultset from each data source. With this method I've abstracted data in CSV files, fixed ASCII files, SQL tables, Excel Spreadsheets, tab delimited files that are members of a .ZIP archive, you name it. Short example (not tested): class foo: ''' Class to abstract tab delimited files ''' def __init__(self, filepath, columnnames): self.fp=open(filepath, 'r') self.columnnames=columnnames return def __iter__(self): return self def next(self): # # Try to get the next line from file # try: line=self.fp.next() except StopIteration: self.fp.close() raise # # Decode the tab delimited line into its parts # line=line.rstrip() if not line: raise StopIteration values=line.split('\t') print "values=", values l=zip(self.columnnames, values) print l for column, value in l: setattr(self, column, value) return if __name__ == "__main__": obj=foo('abc.txt', ['name', 'address1', 'address2', 'city', 'state', 'zip']) for entry in obj: print "" print "Name........", obj.name print "Address1....", obj.address1 print "Address2....", obj.address2 print "City........", obj.city print "State.......", obj.state print "Zip.........", obj.zip -Larry Bates From defcon8 at gmail.com Mon Jun 26 08:35:49 2006 From: defcon8 at gmail.com (defcon8) Date: 26 Jun 2006 05:35:49 -0700 Subject: About python 2.5 and its try statement. Message-ID: <1151325349.040404.77730@i40g2000cwc.googlegroups.com> I can't remember the proposal number, but many of you reading will have probably read the features that will be added to python 2.5. The actual part I wanted to talk about was the finally part of try. Isn't it totally defeating a compiler's job by executing the finally part even if there is an error in the previous statements? Or have I understood something wrong? From sreeram at tachyontech.net Mon Jun 5 10:03:17 2006 From: sreeram at tachyontech.net (K.S.Sreeram) Date: Mon, 05 Jun 2006 19:33:17 +0530 Subject: is it possible to find which process dumped core In-Reply-To: <1149514829.032643.193890@h76g2000cwa.googlegroups.com> References: <1149514829.032643.193890@h76g2000cwa.googlegroups.com> Message-ID: <448439A5.7050909@tachyontech.net> su wrote: > from this command we know 'soffice.bin' process dumped core. Now can i > do the same using python i.e. finding which process dumped core? if so > how can i do it? You're best bet would be to run the 'file' program using the subprocess module and parse the output that it generates. Regards Sreeram -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 260 bytes Desc: OpenPGP digital signature URL: From yan at NsOeSiPnAeMr.com Thu Jun 1 18:19:38 2006 From: yan at NsOeSiPnAeMr.com (Captain Dondo) Date: Thu, 01 Jun 2006 15:19:38 -0700 Subject: Replace one element of a tuple (LONG) In-Reply-To: <1149198946.567904.260480@f6g2000cwb.googlegroups.com> References: <127ulhn6h7hvj22@corp.supernews.com> <1149198946.567904.260480@f6g2000cwb.googlegroups.com> Message-ID: <127upu8k63qnu10@corp.supernews.com> BartlebyScrivener wrote: >>>I've looked at various search-and-replace snippets but none that address >>>what I am trying to do.... > > > I think you need to tell more about what you're trying to do. You say > it's in a database? Is that why you can't just put the whole blob in > your text editor and do search-and-replace? > > And is that also why you can't turn it into a giant string and do > giantstring.replace('unwanted','wanted') > > rd > Fair enough. I am trying to pull records from one database (on tooth.seiner.lan) and create a smaller table with only selected elements in another database (on localhost aka hermes). My code so far: import MySQLdb import sys, os, os.path, time, string, dialog masterBackend="tooth.seiner.lan" toGoBackend="hermes.seiner.lan" masterDB=MySQLdb.connect(host=masterBackend,user="mythtv",passwd="mythtv",db="mythconverg") # pull recordings from masterDB c=masterDB.cursor() c.execute("""SELECT title, subtitle, starttime FROM recorded""") # build our dialog checkbox d = dialog.Dialog(dialog="dialog") d.add_persistent_args(["--backtitle", "Myth2Go"]) recordings=[] for listing in c.fetchall(): recordings.append( (listing[0]+'|'+listing[2].isoformat(), listing[1],0)) recordings.sort() (retcode, itemlist) = d.checklist(text="", height=15, width=70, list_height=7, choices=recordings, title="Which recordings do you want to transfer?") selectlist=[] for listing in itemlist: print listing (rectitle, recdate) = listing.split('|',1) c.execute("""SELECT * FROM recorded WHERE title=%s AND starttime=%s""",(rectitle,recdate)) selectlist.append(c.fetchone()) ======================================================== The problem is the last line. I am creating a bunch of tuples that are, for my purposes, incorrect. I would like to create them with masterBackend replaced by toGoBackend. Currently (I corrected a small bug based on another post) after a user selects what recordings s/he wants, selectlist contains: [ (1028L, datetime.datetime(2006, 5, 26, 7, 0), datetime.datetime(2006, 5, 26, 7, 30), 'Arthur', "What's Cooking?; Buster's Special Delivery", '', 'Children', 'tooth.seiner.lan', None, 0L, None, 1L, 1L, 'Default', 9L, 'SH044107', 'EP0441070207', datetime.datetime(2006, 5, 26, 7, 31, 1), 1162899392L, 0.0, 0, datetime.date(2006, 5, 26), 0, 0L, 0), (1028L, datetime.datetime(2006, 5, 27, 9, 0), datetime.datetime(2006, 5, 27, 9, 30), 'Arthur', 'Unfinished; D.W., Bossy Boots', '', 'Children', 'tooth.seiner.lan', None, 0L, None, 1L, 1L, 'Default', 9L, 'SH044107', 'EP0441070204', datetime.datetime(2006, 5, 27, 9, 31, 26), 1164783552L, 0.0, 0, datetime.date(2006, 5, 23), 0, 0L, 0), (1028L, datetime.datetime(2006, 5, 30, 7, 0), datetime.datetime(2006, 5, 30, 7, 30), 'Arthur', 'Prunella Sees the Light; Return of the Snowball', 'Prunella prepares for a sleepover with Marina; D.W. protects a snowball.', 'Children', 'tooth.seiner.lan', None, 0L, None, 1L, 1L, 'Default', 9L, 'SH044107', 'EP0441070123', datetime.datetime(2006, 5, 30, 7, 31, 24), 1164179392L, 0.0, 1, datetime.date(2002, 11, 28), 0, 0L, 0) ] which is the correct format to insert into the new database. What I'd like to do is build the correct selectlist in the first place, rather than build the wrong one and then rebuild a correct one. I can't find a replace method that would work on a tuple (not surprising since they're immutable) but I also can't find a replace function that would replace an element of a tuple and return a new tuple. --Yan From edreamleo at charter.net Sat Jun 3 10:24:06 2006 From: edreamleo at charter.net (Edward K. Ream) Date: Sat, 3 Jun 2006 09:24:06 -0500 Subject: Leo 4.4.1 beta 1 released Message-ID: Leo 4.4.1 beta 1 is now available at: http://sourceforge.net/project/showfiles.php?group_id=3458&package_id=29106 Leo is a text editor, data organizer, project manager and much more. See: http://webpages.charter.net/edreamleo/intro.html The highlights of Leo 4.4.1: ---------------------------- - A new colorizer plugin controlled by jEdit language description files. At present this plugin only reliably colors @language python code. - Multiple editors in Leo's body pane. - Search commands now support regex replace patterns: \1, \2, etc. - Support for external debuggers: see http://webpages.charter.net/edreamleo/debuggers.html - The scripting plugin now creates a Debug Script button. - Several new commands including run-unit-test, python-help and toggle-invisibles. - The help-for-command commands now contains information for almost all commands. - A new shortcut_button plugin. Links: ------ Leo: http://webpages.charter.net/edreamleo/front.html Home: http://sourceforge.net/projects/leo/ Download: http://sourceforge.net/project/showfiles.php?group_id=3458 CVS: http://leo.tigris.org/source/browse/leo/ Quotes: http://webpages.charter.net/edreamleo/testimonials.html -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From aleax at mac.com Wed Jun 14 11:27:03 2006 From: aleax at mac.com (Alex Martelli) Date: Wed, 14 Jun 2006 08:27:03 -0700 Subject: Extending Python - Understanding Flags... References: <448E4918.3050105@lexicon.net> Message-ID: <1hgwxwu.1db6wglsffkkoN%aleax@mac.com> John Machin wrote: ... > > If it is any consolation I hope to take what I learn and put together > > a tutorial on expanding Python for those that only have a little > > experience with C programming, like myself. I plan to explain > > everything like I was teaching a 6-year old. :] > > > > I was just going to put this on a wiki, but is there a way to include > > with other Python documentation on an "official" site? > > The manual is in fact written as a tutorial. You may prefer to propose > changes to the manual, rather than to publish yet another document. I don't think the manual even TRIES to address "those that only have a little experience with C programming", nor should it -- there's a vast niche for a truly tutorial document based on learn-by-doing, which takes somebody with a "C 101" course as their only C experience, and a good knowledge of Python, and turns them into writers of C extension modules for Python. I suggest to the OP that he starts this effort as a wiki, publicize it widely but with good taste to try and attract willing helpers, and think about possibly get it included on Python's official site only if and when it becomes more mature and well-accepted. Best of luck: I think it's a worthwhile project and I hope I can be of help (I have published a number of shorter documents on this subject, and I'd be happy to allow them to be shared in as much as I retain copyright on most of them -- alas, can't do that for the chapter of Python in a Nutshell that deals with writing Python extensions in C, since that's (C) O'Reilly!-). Alex From duncan.booth at invalid.invalid Wed Jun 7 10:33:07 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 7 Jun 2006 14:33:07 GMT Subject: THE IMPORTANCE OF MAKING THE GOOGLE INDEX DOWNLOADABLE References: <1149689482.372450.13210@i39g2000cwa.googlegroups.com> Message-ID: gen_tricomi wrote: > Currently application programmers using the Google web search API are > limited to 1000 queries a day. This on the one hand is a reasonable > decision by Google because; limiting the queries will prevent harm on > the Google system by unnecessary automated queries; but it is also > limiting us programmers severely. The query limit limits the usefulness > of whatever applications we decide to craft out and even limits our > imagination on what is possible with a handful of indexes. > If you know which sites you are interested in searching then you can already license hardware from Google which will let you index up to 15 million documents and an api to search the indexed content without restriction. If you simply want to compete with Google on searching the entire internet then they are unlikely to want to help you. If you fall somewhere in between what can be done with a Google Search Appliance and competing with Google then you are talking about paying Google sufficient money that they ought to be interested in sitting round a table with you. As it says on their website: "For larger deployments, contact us and we?ll be happy to talk to you about building a custom search solution for your environment." From phil at riverbankcomputing.co.uk Sun Jun 11 11:41:29 2006 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Sun, 11 Jun 2006 16:41:29 +0100 Subject: ANN: PyQt v4.0 Released - Python Bindings for Qt v4 Message-ID: <200606111641.29759.phil@riverbankcomputing.co.uk> Riverbank Computing is pleased to announce the release of PyQt v4.0 available from http://www.riverbankcomputing.co.uk/pyqt/. The main change from v4.0beta1 is the inclusion of comprehensive HTML documentation based on the Qt documentation. PyQt is a comprehensive set of Qt bindings for the Python programming language and supports the same platforms as Qt (Windows, Linux and MacOS/X). Like Qt, PyQt is available under the GPL and a commercial license. PyQt v4 supports Qt v4 (http://www.trolltech.com/products/qt/index.html). PyQt v3 is still available to support earlier versions of Qt. PyQt v4 is implemented as a set of 8 extension modules containing approximately 400 classes and 6,000 functions and methods. QtCore The non-GUI infrastructure including event loops, threads, i18n, Unicode, signals and slots, user and application settings. QtGui A rich collection of GUI widgets. QtNetwork A set of classes to support TCP and UDP socket programming and higher level protocols (eg. HTTP). QtOpenGL A set of classes that allows PyOpenGL to render onto Qt widgets. QtSql A set of classes that implement SQL data models and interfaces to industry standard databases. Includes an implementation of SQLite. QtSvg A set of classes to render SVG files onto Qt widgets. QtXML A set of classes that implement DOM and SAX parsers. QtAssistant A set of classes that enables the Qt Assistant online help browser to be integrated with an application. A Windows installer is provided for the GPL version of PyQt to be used with the GPL version of Qt v4 (http://www.trolltech.com/download/qt/windows.html). It enabes a complete PyQt environment to be installed on Windows without the need for a C++ compiler. PyQt includes the pyuic utility which generates Python code to implement user interfaces created with Qt Designer in the same way that the uic utility generates C++ code. It is also able to load Designer XML files dynamically. From Kiran.Karra at gmail.com Tue Jun 20 17:08:03 2006 From: Kiran.Karra at gmail.com (Kiran) Date: 20 Jun 2006 14:08:03 -0700 Subject: socket programming question Message-ID: <1150837683.338093.8960@y41g2000cwy.googlegroups.com> Hello All, My question is, is it possible to make python do some other processing while it is waiting for a socket to timeout? thanks a lot! Kiran From sjmachin at lexicon.net Wed Jun 14 19:27:54 2006 From: sjmachin at lexicon.net (John Machin) Date: Thu, 15 Jun 2006 09:27:54 +1000 Subject: Negative hex to int In-Reply-To: References: <1150326597.327669.222640@r2g2000cwb.googlegroups.com> Message-ID: <44909B7A.60404@lexicon.net> On 15/06/2006 9:24 AM, Wojciech Mu?a wrote: > andreas.lydersen at gmail.com wrote: >> The problem is negative values. If the unit returns the hex value 'e7', >> it means -25, but python says it's 231: >> --------------------------- >>>>> int('e7', 16) >> 231 >> --------------------------- >> >> Does anyone have a clue a to what I need to do? > > def u2(x): > if x & 0x80: # MSB set -> neg. > return -((~x & 0xff) + 1) Holy obfuscation, Batman! > else: > return x > >>>> u2(int('e7', 16)) > -25 >>>> u2(int('12', 16)) > 18 > > w. From klaus at seistrup.dk Sat Jun 3 07:44:55 2006 From: klaus at seistrup.dk (Klaus Alexander Seistrup) Date: Sat, 3 Jun 2006 11:44:55 +0000 (UTC) Subject: Missing unicode data? References: Message-ID: Fredrik Lundh skrev: > I'm pretty sure unicodename.name() doesn't look in the Unicode- > Data file on your machine, nor in the latest file from unicode.org. I am pretty sure of that, too. I was only using those files as a reference against the unicode data that comes with my python interpreter. > in other words, you get whatever version that was used to create > the Unicode data set in your Python distribution. I see. > iirc, 2.4 uses Unicode 3.2, and 2.5 uses Unicode 4.1. to update, > use the tools under Tools/unicode. Thanks for the hint. Mvh, -- Klaus Alexander Seistrup SubZeroNet, Copenhagen, Denmark http://magnetic-ink.dk/ From micklee74 at hotmail.com Sun Jun 18 08:05:20 2006 From: micklee74 at hotmail.com (micklee74 at hotmail.com) Date: 18 Jun 2006 05:05:20 -0700 Subject: mapping None values to '' Message-ID: <1150632320.443681.42640@r2g2000cwb.googlegroups.com> hi i wish to map None or "None" values to "". eg a = None b = None c = "None" map( , [i for i in [a,b,c] if i in ("None",None) ]) I can't seem to find a way to put all values to "". Can anyone help? thanks From aleax at mac.com Tue Jun 6 23:48:42 2006 From: aleax at mac.com (Alex Martelli) Date: Tue, 6 Jun 2006 20:48:42 -0700 Subject: what are you using python language for? References: Message-ID: <1hgj2iu.1d8nheb1wn5c0zN%aleax@mac.com> hacker1017 wrote: > im just asking out of curiosity. At work, since about 16 months ago, mostly for maintaining and enhancing many programs that control, monitor, and ensure the smooth working of, many large clusters of servers (plus, all the persnickety extra little things that keep coming up...). At home, mostly to orchestrate my long-standing research into the theoretical roots of the game of contract bridge (plus, the even more numerous persnickety big and small things that come up even more often, at least with a wife and stepson both being students at demanding Palo Alto teaching institutions which both happen to be named Stanford;-)... they're both decent Python programmers [my wife more than just decent... she's the only woman member of the PSF!-)] but I'm still happy to lend a hand when needed -- for my stepdaughter too, who lives thousands of miles away... she's a budding artist and often uses Poser, which lets users write Python programs to drive the positioning and rendering...). As a freelance consultant in Europe, before I crossed an ocean and a continent to come work for my current employer, I used Python for a huge variety of tasks for clients, including a multi-tier enterprise-class workflow framework cum several specialized applications (I mostly helped out with middleware tiers and web interfaces, but the Qt-based GUI and the DB-interfacing backend were also Python), a tivo-like DVR system's wide variety of programs, a web-based system to farm out photo retouching from customers to professional consultants, a system controlling the UI of a mechanical engineering bill-of-materials system to either GUI or Web interfaces, and so forth. Alex From alainpoint at yahoo.fr Tue Jun 20 08:38:25 2006 From: alainpoint at yahoo.fr (alainpoint at yahoo.fr) Date: 20 Jun 2006 05:38:25 -0700 Subject: =?iso-8859-1?q?Re:_comparing_of_python_GUI=B4s?= In-Reply-To: <1150806788.026172.140150@h76g2000cwa.googlegroups.com> References: <1150806788.026172.140150@h76g2000cwa.googlegroups.com> Message-ID: <1150807105.706972.167490@h76g2000cwa.googlegroups.com> Bayazee wrote: > Hi > i want some info ... > plz tell me the benefit (or any data) of each gui (pyqt , pyqtk , > wxpython , tkinter ..) > in the other hand wich one you offer (and why ?) ? Open the following url: http://www.google.com Enter the following: "google tutorial" Choose a link and follow the instructions. Alain From fredrik at pythonware.com Thu Jun 8 11:48:12 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 08 Jun 2006 17:48:12 +0200 Subject: cos: "Integer Required"?!?!?!? In-Reply-To: <1149780685.768525.276850@h76g2000cwa.googlegroups.com> References: <1149777499.262577.318070@u72g2000cwu.googlegroups.com> <2aqdnQ8uYZLpoxXZnZ2dnUVZ_qadnZ2d@comcast.com> <1149780685.768525.276850@h76g2000cwa.googlegroups.com> Message-ID: moonman wrote: > print self.ACphi, type(self.ACphi) yields: > 19412557 > > value = XPLMGetDataf(self.ACphi); print value type(value ) yields: > -0.674469709396 > > print math.radians(XPLMGetDataf(self.ACphi)), > type(math.radians(XPLMGetDataf(self.ACphi))) yields: > > TypeError > : > an integer is required > > Am I totally missing something about 'math'. Does it really expect an > int? nope. >>> import math >>> math.radians(-0.6744) -0.011770500475449759 >>> math.cos(-0.1177) 0.99308134771019019 when you end up with exceptions that make no sense at all, and C extensions are involved, the problem is quite often that some code in the extension forgets to check for errors, or forgets to reset the exception status when it has handled an error. do you get any further if you do: value = XPLMGetDataf(self.ACphi) hasattr(value, "foo") # reset the exception status print math.radians(value) ? From austuff at gmail.com Mon Jun 19 11:39:12 2006 From: austuff at gmail.com (janama) Date: 19 Jun 2006 08:39:12 -0700 Subject: Formatted string to object Message-ID: <1150731552.799052.47320@r2g2000cwb.googlegroups.com> Hi, can such a thing be done somehow? aaa = self.aaa bbb = %s.%s % ('parent', 'bbb') Can you use strings or %s strings like in the above or aaa = 'string' aaa.%s() % 'upper' Somehow? Thanks for taking a look at this Regards Janama From robert.thorpe at antenova.com Fri Jun 23 13:20:39 2006 From: robert.thorpe at antenova.com (Rob Thorpe) Date: 23 Jun 2006 10:20:39 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150908952.804184.218990@r2g2000cwb.googlegroups.com> <1150991074.705803.211570@m73g2000cwd.googlegroups.com> Message-ID: <1151083239.829296.33030@i40g2000cwc.googlegroups.com> Andreas Rossberg wrote: > Rob Thorpe wrote: > > > > Its easy to create a reasonable framework. > > Luca Cardelli has given the most convincing one in his seminal tutorial > "Type Systems", where he identifies "typed" and "safe" as two orthogonal > dimensions and gives the following matrix: > > | typed | untyped > -------+-------+---------- > safe | ML | Lisp > unsafe | C | Assembler > > Now, jargon "dynamically typed" is simply untyped safe, while "weakly > typed" is typed unsafe. Consider a langauge something like BCPL or a fancy assembler, but with not quite a 1:1 mapping with machine langauge. It differs in one key regard: it has a variable declaration command. This command allows the programmer to allocate a block of memory to a variable. If the programmer attempts to index a variable outside the block of memory allocated to it an error will occur. Similarly if the programmer attempts to copy a larger block into a smaller block an error would occur. Such a language would be truly untyped and "safe", that is safe according to many peoples use of the word including, I think, yours. But it differs from latently typed languages like python, perl or lisp. In such a language there is no information about the type the variable stores. The programmer cannot write code to test it, and so can't write functions that issue errors if given arguments of the wrong type. The programmer must use his or her memory to substitute for that facility. As far as I can see this is a significant distinction and warrants a further category for latently typed languages. As a sidenote: the programmer may also create a tagging system to allow the types to be tracked. But this is not the same as saying the language supports types, it is akin to the writing of OO programs in C using structs. From bj_666 at gmx.net Wed Jun 14 07:21:58 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 14 Jun 2006 13:21:58 +0200 Subject: determining file type References: <1150276935.270798.5550@i40g2000cwc.googlegroups.com> <1150281704.342529.206640@u72g2000cwu.googlegroups.com> Message-ID: In <1150281704.342529.206640 at u72g2000cwu.googlegroups.com>, Ritesh Raj Sarraf wrote: > Also, > f = file ('some_file.jpg') > > throws an error. > "str object is not callable" This happens if you rebind names of builtins. In this case to a string. Don't do that! In [5]:file Out[5]: In [6]:file = 'foo.txt' In [7]:file Out[7]:'foo.txt' In [8]:file('x') --------------------------------------------------------------------------- exceptions.TypeError Traceback (most recent call last) /home/bj/ TypeError: 'str' object is not callable Ciao, Marc 'BlackJack' Rintsch From artur_spruce at yahoo.com Mon Jun 5 07:29:36 2006 From: artur_spruce at yahoo.com (AdSR) Date: 5 Jun 2006 04:29:36 -0700 Subject: ANN: PQRC - Python Quick Reference Card - v 0.55 References: <4481b8ff$0$19687$ba4acef3@news.orange.fr> Message-ID: <1149506976.002410.207870@y43g2000cwc.googlegroups.com> Laurent Pointal wrote: > [for those who dont read clp.announce] > > The Python Quick Reference Card (PQRC) aims to provide a printable quick > reference documentation for the Python language and some of its main > standard libraries (currently for Python 2.4). > [etc.] Great job, Laurent! If this is version 0.55, I can't wait for 1.0. Keep up the good work. BTW, it would be great if something like this came with Python installation. No more sifting through library TOC/index, "where did I see this stuff" :) AdSR From rhcarvalho at gmail.com Sun Jun 11 09:33:11 2006 From: rhcarvalho at gmail.com (Rodolfo) Date: 11 Jun 2006 06:33:11 -0700 Subject: Algorithm for Labels like in Gmail In-Reply-To: <1150026354.741489.273420@g10g2000cwb.googlegroups.com> References: <1149985001.668803.121260@c74g2000cwc.googlegroups.com> <1150026354.741489.273420@g10g2000cwb.googlegroups.com> Message-ID: <1150032791.583273.82730@g10g2000cwb.googlegroups.com> Thanks to you all. I'll start trying the buzhug solution, which seems more pythonic. But I feel like I gotta learn how to use databases... once I studied SQL a litle bit, but don't remember much. I'll play around with Python and then I show what I got. Bye Rodolfo P.S: Is there a way to do a "clear screen" on a Python program? I mean something like the "cls" command in MS-DOS.... From phleum_nospam at chello.se Thu Jun 1 14:59:13 2006 From: phleum_nospam at chello.se (Carl) Date: Thu, 01 Jun 2006 20:59:13 +0200 Subject: Starting New Process References: <1149172463.881528.131290@j55g2000cwa.googlegroups.com> <1149185284.820789.321130@y43g2000cwc.googlegroups.com> Message-ID: D wrote: > Thanks, Jean-Paul - is there any way to do it without using Twisted, > since I am not very familiar with it? (i.e. just using the os library) > Thanks. > > Jean-Paul Calderone wrote: >> On 1 Jun 2006 07:34:23 -0700, D wrote: >> >Hello, I need to write a server program that performs the following >> >tasks: >> > >> >1) Listens on TCP port 5555 for a connection >> >2) When client connects, launches application (for example, vi), then >> >closes connection with client >> >3) Goes back to listening on TCP port 5555 for an incoming connection >> >> Untested: >> >> from twisted.internet import protocol, reactor >> >> class ViRunner(protocol.Protocol): >> def connectionMade(self): >> reactor.spawnProcess( >> None, >> '/usr/bin/setsid', >> ['setsid', '/usr/bin/vi']) >> self.transport.loseConnection() >> >> f = protocol.ServerFactory() >> f.protocol = ViRunner >> reactor.listenTCP(5555, f) >> reactor.run() >> >> Jean-Paul Use import socket ifyou don't want to use twisted (which is incredibly good). Google for "+socket +python +server" and you will find what you are looking for. See, for example, http://floppsie.comp.glam.ac.uk/Glamorgan/gaius/wireless/5.html Carl From nmm1 at cus.cam.ac.uk Wed Jun 14 07:46:20 2006 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 14 Jun 2006 11:46:20 GMT Subject: Numerics, NaNs, IEEE 754 and C99 Message-ID: The numerical robustness of Python is very poor - this is not its fault, but that of IEEE 754 and (even more) C99. In particular, erroneous numerical operations often create apparently valid numbers, and the NaN state can be lost without an exception being raised. For example, try int(float("nan")). Don't even ASK about complex, unless you know FAR more about numerical programming than 99.99% of programmers :-( Now, I should like to improve this, but there are two problems. The first is political, and is whether it would be acceptable in Python to restore the semantics that were standard up until about 1980 in the numerical programming area. I.e. one where anything that is numerically undefined or at a singularity which can deliver more than one value is an error state (e.g. raises an an exception or returns a NaN). This is heresy in the C99 and Java camps, and is none too acceptable in the IEEE 754R one. My question here is would such an attempt be opposed tooth and nail in the Python context, the way it was in C99? The second is technical. I can trivially provide options to select between a restricted range of behaviours, but the question is how. Adding a method to an built-in class doesn't look easy, from my investigations of floatobject.c, and it is very doubtful that is the best way, anyway - one of the great problems with "object orientation" is how it handles issues that occur at class conversions. A run-time option or reading an environment variable has considerable merit from a sanity point of view, but calling a global function is also possible. Any ideas? Regards, Nick Maclaren. From grflanagan at yahoo.co.uk Mon Jun 12 09:36:53 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 12 Jun 2006 06:36:53 -0700 Subject: Searching and manipulating lists of tuples In-Reply-To: <1150117632.693617.45310@c74g2000cwc.googlegroups.com> References: <1150117632.693617.45310@c74g2000cwc.googlegroups.com> Message-ID: <1150119413.937822.199020@g10g2000cwb.googlegroups.com> MTD wrote: > Hello, > > I'm wondering if there's a quick way of resolving this problem. > > In a program, I have a list of tuples of form (str,int), where int is a > count of how often str occurs > > e.g. L = [ ("X",1),("Y",2)] would mean "X" occurs once and "Y" occurs > twice > > If I am given a string, I want to search L to see if it occurs already. > If it does, I find the corresponding tuple and increment the integer > part. If not, I append the new element with int = 1. > > e.g. > > algorithm(L, "X") would produce output L = [("X",2),("Y",2)] > algorithm(L,"Z") would produce L = [("X",1),("Y",2),("Z",1)] > just a thought: class MyList(object): def __init__(self): self._items = [] self._counts = [] def append(self, value): try: i = self._items.index(value) self._counts[i] += 1 except ValueError: self._items.append(value) self._counts.append(1) def __getitem__(self, index): return self._items[index], self._counts[index] def __repr__(self): return str(zip(self._items, self._counts)) m = MyList() print m m.append('K') print m m.append('K') print m m.append('Z') print m ----------------------------------- Gerard From aljosa.mohorovic at gmail.com Wed Jun 7 09:21:01 2006 From: aljosa.mohorovic at gmail.com (aljosa) Date: 7 Jun 2006 06:21:01 -0700 Subject: capture video from camera In-Reply-To: <1149618799.409008.33060@h76g2000cwa.googlegroups.com> References: <1149598946.182874.121650@c74g2000cwc.googlegroups.com> <1149603488.012417.269760@j55g2000cwa.googlegroups.com> <1149618799.409008.33060@h76g2000cwa.googlegroups.com> Message-ID: <1149686461.261815.81670@i39g2000cwa.googlegroups.com> i had no intention to say that videocapture is bad but it's not what i'm looking for. concerning docs, everybody has their own view on how docs should look like. that said, i should have written more clearly what i'm looking for. From yaru22 at gmail.com Sat Jun 10 17:26:23 2006 From: yaru22 at gmail.com (yaru22) Date: 10 Jun 2006 14:26:23 -0700 Subject: infinite loop executed in emacs Message-ID: <1149974783.869457.231020@h76g2000cwa.googlegroups.com> Hi. I'm using python-mode in emacs. I happened to execute the code that contains an infinite loop. The system is hung and it doesn't stop at all. lol How do I manually stop it in emacs? For Eclipse, in java programming, if i happen to fall into an infinite loop, i could juse press ctrl+c to stop it. What keys do I have to press in emacs? From pipedreamergrey at gmail.com Tue Jun 6 10:01:34 2006 From: pipedreamergrey at gmail.com (PipedreamerGrey) Date: 6 Jun 2006 07:01:34 -0700 Subject: Expanding Search to Subfolders In-Reply-To: <1149526866.681348.273590@c74g2000cwc.googlegroups.com> References: <1149526866.681348.273590@c74g2000cwc.googlegroups.com> Message-ID: <1149602494.670254.48660@h76g2000cwa.googlegroups.com> Here's the final working script. It opens all of the text files in a directory and its subdirectories and combines them into one Rich text file (index.rtf): #! /usr/bin/python import glob import fileinput import os import string import sys index = open("index.rtf", 'w') class DirectoryWalker: # a forward iterator that traverses a directory tree, and # returns the filename def __init__(self, directory): self.stack = [directory] self.files = [] self.index = 0 def __getitem__(self, index): while 1: try: file = self.files[self.index] self.index = self.index + 1 except IndexError: # pop next directory from stack self.directory = self.stack.pop() self.files = os.listdir(self.directory) self.index = 0 else: # get a filename, eliminate directories from list fullname = os.path.join(self.directory, file) if os.path.isdir(fullname) and not os.path.islink(fullname): self.stack.append(fullname) else: return fullname for file in DirectoryWalker("."): # divide files names into path and extention path, ext = os.path.splitext(file) # choose the extention you would like to see in the list if ext == ".txt": print file # print the contents of each file into the index file = open(file) fileContent = file.readlines() for line in fileContent: if not line.startswith("\n"): index.write(line) index.write("\n") index.close() From k.retheesh at gmail.com Fri Jun 9 13:38:46 2006 From: k.retheesh at gmail.com (k.retheesh at gmail.com) Date: 9 Jun 2006 10:38:46 -0700 Subject: TypeError: unsubscriptable object Message-ID: <1149874726.470436.279200@i40g2000cwc.googlegroups.com> Can anybody tell me why am I getting this error message while trying to print a part of a string. Is there a better approach for this... Traceback (most recent call last): File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "Q:\PythonScripts\InventoryCompareCase.py", line 276, in ? main() File "Q:\PythonScripts\InventoryCompareCase.py", line 167, in main print template % (ID, IID, Function[:10], Description[:10], ErrorNumber, StatusCD) TypeError: unsubscriptable object Thanks Retheesh From greg at cosc.canterbury.ac.nz Sat Jun 3 05:05:31 2006 From: greg at cosc.canterbury.ac.nz (greg) Date: Sat, 03 Jun 2006 21:05:31 +1200 Subject: Selection in Tkinter Text widget. In-Reply-To: <1149251859.630518.248760@y43g2000cwc.googlegroups.com> References: <1149246483.809582.8310@i39g2000cwa.googlegroups.com> <1149251859.630518.248760@y43g2000cwc.googlegroups.com> Message-ID: <4ed1mjF1eao0mU1@individual.net> Ant wrote: > Strange behaviour though (IMHO), that the selection is only shown if > the widget has focus. It's only strange if you're used to certain platforms. This is normal behaviour in the Macintosh world. One of the original Apple UI Guidelines was that there should only be one selection visible at a time, so that it's always clear what you're operating on. (They seem to be breaking that now in MacOSX, which I think is a backward step...) -- Greg From JKolstad71HatesSpam at yahoo.com Thu Jun 1 19:27:22 2006 From: JKolstad71HatesSpam at yahoo.com (Joel Kolstad) Date: Thu, 1 Jun 2006 16:27:22 -0700 Subject: Recommendations for CD/DVD-based or on-line Python classes? Message-ID: <127uturbd73g5ca@corp.supernews.com> Just curious... I have plenty of programming background (C++ being the closest to Python), and I have a copy of Lutz's "Learning Python," but before I dive head-first into that tome, does anyone know of a web-based or CD/DVD-based training class that's priced for individuals? Example of what I'm looking for: Something like 6 or 7 years ago Ziff-Davis had a bunch of on-line instructor-lead courses, where you'd read a chapter in a book, read the instructor's take on the chapter (just a few pages), perform the programming assignments, and ask the instructor if you had any difficulties. There was a solid schedule (ch. 1 this week, ch. 2 the next, etc. -- courses repeated every quarter or somesuch) as well. Ziff-Davis charged something like $99 or $199/year for this service (all the courses you wanted to sign up for -- quite reasonable, IMO) and also made money by requiring the use of their own books (which were often someone else's book that they'd just put their own name on) -- which were usually cheap enough at something like $30/ea. That whole setup worked quite well for me... anyone know of something similar? If not I probably will have to force myself to spend an hour a day or something going through Lutz's book... Thanks, ---Joel Kolstad From tundra at tundraware.com Wed Jun 14 02:54:36 2006 From: tundra at tundraware.com (Tim Daneliuk) Date: 14 Jun 2006 02:54:36 EDT Subject: curses module bug in windows python? In-Reply-To: <1150267132.986057.226690@i40g2000cwc.googlegroups.com> References: <1150267132.986057.226690@i40g2000cwc.googlegroups.com> Message-ID: <448FB38F.8040106@tundraware.com> kernel1983 wrote: > when I type command below in windows python: > import curses > > it gives the error msg! It can't find _curses.pyd > > Is this a bug? > Nope - this module is not supported under Windows ... -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From michele.petrazzo at TOGLIunipex.it Sat Jun 3 05:13:46 2006 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Sat, 03 Jun 2006 09:13:46 GMT Subject: Trying to get FreeImagePy to work. In-Reply-To: <1149235836.646855.164110@i40g2000cwc.googlegroups.com> References: <1148651668.578852.3160@i40g2000cwc.googlegroups.com> <7fEdg.13375$cX1.201311@twister2.libero.it> <1148655611.990937.322350@j73g2000cwa.googlegroups.com> <1149166096.176405.22780@i40g2000cwc.googlegroups.com> <3PCfg.20835$cX1.315781@twister2.libero.it> <1149174938.337973.85950@g10g2000cwb.googlegroups.com> <1149192520.959302.250840@j55g2000cwa.googlegroups.com> <1149235836.646855.164110@i40g2000cwc.googlegroups.com> Message-ID: Iain King wrote: >> I'll try out FIPY's resizing tomorrow too. OTOH, I have functions >> to convert between PIL and wxPython, and functions to convert >> betweem PIL and FIPY, but I don't see a function to convert FIPY to >> wxPython? >> > > Image at: http://www.snakebomb.com/misc/example.tif > > Iain > Yes it's min-is-white:: michele:~$ tiffinfo example.tif TIFFReadDirectory: Warning, example.tif: unknown field with tag 37680 (0x9330) encountered. TIFF Directory at offset 0x1520 (5408) Subfile Type: (0 = 0x0) Image Width: 1696 Image Length: 1162 Resolution: 200, 200 pixels/inch Bits/Sample: 1 Compression Scheme: CCITT Group 4 Photometric Interpretation: min-is-white # <------ FillOrder: msb-to-lsb Samples/Pixel: 1 Rows/Strip: 1162 Planar Configuration: single image plane ImageDescription: DS michele:~$ So you *need* to invert it to work correctly with PIL! P.s. Added the convertToWx function, that return a wx.Image, to the Image class. Michele From duncan.booth at invalid.invalid Wed Jun 7 06:39:42 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 7 Jun 2006 10:39:42 GMT Subject: Bug in list comprehensions? References: <1149675723.118917.276940@j55g2000cwa.googlegroups.com> Message-ID: Iain King wrote: >>>> [x for x in y for y in beta] > ['C', 'C', 'C'] >>>> [y for y in beta] > [['one', 'two', 'three'], ['one', 'two', 'three'], ['one', 'two', > 'three']] >>>> [x for x in y for y in beta] > ['one', 'one', 'one', 'two', 'two', 'two', 'three', 'three', 'three'] > > Shoudn't both lines '[x for x in y for y in beta]' produce the same > list? [x for x in y for y in beta] is a shorthand for: tmp = [] for x in y: for y in beta: tmp.append(x) So x iterates over whatever y is before the loop starts, and y iterates over beta (but that doesn't affect what x is iterating over). The important thing is to remember that the order of 'for' and 'if' statements is the same as though you had written the for loop out in full. From kent at kentsjohnson.com Mon Jun 5 13:33:38 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Mon, 05 Jun 2006 13:33:38 -0400 Subject: Storing nothing in a dictionary and passing it to a function In-Reply-To: <1149527899.364138.312150@j55g2000cwa.googlegroups.com> References: <1149527899.364138.312150@j55g2000cwa.googlegroups.com> Message-ID: <448469ed_3@newspeer2.tds.net> 63q2o4i02 at sneakemail.com wrote: > Hi, > > I'm writing a hand-written recursive decent parser for SPICE syntax > parsing. In one case I have one function that handles a bunch of > similar cases (you pass the name and the number of tokens you're > looking for). In another case I have a function that handles a > different set of tokens and so it can't use the same arguments as the > first one, and in fact takes no arguments. However, these functions > are semantically similar and are called from the same place one right > after the other. > > I'd like to have a dictionary (actually a nested dictionary) to call > these functions so I can avoid if-then-elsing everything. Eath > dictionary item has three things in it: the function to be called, a > string to pass to the function (which is also the key to the dict), and > a tuple to pass to the function. In the case of the function with no > arguments, obviously I'd like not to pass anything. > > I'm trying to do this 'functionally' (i guess), by avoiding > if-then-elses and just calling out the functions by accessing them and > their arguments from the dictionary. > > something like this: > alldict = \ > {'pulse': {'func': self.arbtrandef, 'args':(2,5)},\ > 'sin' : {'func': self.arbtrandef, 'args':(2,3)},\ > 'exp' : {'func': self.arbtrandef, 'args':(2,4)},\ > 'pwl' : {'func': self.pwldef , 'args': (None,)},\ <------- how > do I store "no" arguments? > 'sffm' : {'func': self.arbtrandef, 'args':(5,0)}} > > for it in alldict.items(): > name = it[0] > args = (name,) + it[1]['args'] > it[1]['func'](*args) > > So basically this doesn't work. > > Any thoughts? You could omit the 'args' entry completely and test for this in the dispatch: 'pwl' : {'func': self.pwldef},\ for name, params in alldict.items(): try args = (name,) + params['args'] except KeyError: args = () params['func'](*args) Or include the 'name' parameter in the arg list and use an empty tuple for the arg to pwldef: 'exp' : {'func': self.arbtrandef, 'args':('exp', 2,4)},\ 'pwl' : {'func': self.pwldef , 'args': ()},\ for name, params in alldict.items(): params['func'](*args) Kent From dadapapa at googlemail.com Thu Jun 8 09:30:39 2006 From: dadapapa at googlemail.com (Harold Fellermann) Date: 8 Jun 2006 06:30:39 -0700 Subject: how to switch from os.tmpnam to os.tmpfile Message-ID: <1149773439.534989.54450@i40g2000cwc.googlegroups.com> Hi, I need to create a temporary file and I need to retrieve the path of that file. os.tmpnam() would do the job quite well if it wasn't for the RuntimeWarning "tmpnam is a potential security risk to your program". I would like to switch to os.tmpfile() which is supposed to be safer, but I do not know how to get the path information from the file object returned by tmpfile(). any clues? thanks! - harold - From greg.kujawa at gmail.com Tue Jun 6 21:05:36 2006 From: greg.kujawa at gmail.com (gregarican) Date: 6 Jun 2006 18:05:36 -0700 Subject: what are you using python language for? References: Message-ID: <1149642336.575362.113320@c74g2000cwc.googlegroups.com> Currently I am using Python for a CRM client application that runs on Win32, ARM Linux, and WinCE platforms. It pushes and pulls contact data using XMLRPC calls so that it doesn't lock the client into having to use CDO for communicating with the Exchange Server and ADO for communicating with the SQL Server. hacker1017 wrote: > im just asking out of curiosity. From jstroud at ucla.edu Wed Jun 14 15:55:27 2006 From: jstroud at ucla.edu (James Stroud) Date: Wed, 14 Jun 2006 12:55:27 -0700 Subject: "groupby" is brilliant! In-Reply-To: <1hgww3q.88ib5jyqo5hcN%aleax@mac.com> References: <1150180151.643245.148210@y43g2000cwc.googlegroups.com> <1hgww3q.88ib5jyqo5hcN%aleax@mac.com> Message-ID: Alex Martelli wrote: > James Stroud wrote: > ... > >>def doit(rows, doers, i=0): >> for r, alist in groupby(rows, itemgetter(i)): >> if len(doers) > 1: >> doit(alist, doers[1:], i+1) >> doers[0](r) > > > Isn't this making N useless slices (thus copies, for most kinds of > sequences) for a doers of length N? Since you're passing i anyway, it > seems to me that: > > def doit(rows, doers, i=0): > for r, alist in groupby(rows, itemgetter(i)): > if len(doers) > i+1: > doit(alist, doers, i+1) > doers[i](r) > > is equivalent to your code, but avoids these slices (thus copies). > > > Alex Actually, I remember why I wrote it that way--because the itemgetter argument may not start at zero (admitting that I haven't yet played with itemgetter at all). Maybe pop(0) is better than a copy? def doit(rows, doers, i=0): for r, alist in groupby(rows, itemgetter(i)): doer = doers.pop(0) if doers: # empty list tests as False doit(alist, doers, i+1) doer(r) James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From sjmachin at lexicon.net Wed Jun 14 19:23:43 2006 From: sjmachin at lexicon.net (John Machin) Date: Thu, 15 Jun 2006 09:23:43 +1000 Subject: Negative hex to int In-Reply-To: <1150326597.327669.222640@r2g2000cwb.googlegroups.com> References: <1150326597.327669.222640@r2g2000cwb.googlegroups.com> Message-ID: <44909A7F.7000408@lexicon.net> On 15/06/2006 9:09 AM, andreas.lydersen at gmail.com wrote: > Hi! > > While communicating with a monitoring unit, I get some hex values > representing degrees celcius from its probes. The values can be > something like '19' or '7d'. To convert it to int, I do the following: > --------------------------- > Python 2.4.2 (#1, Sep 28 2005, 10:25:47) > [GCC 3.4.3 20041212 (Red Hat 3.4.3-9.EL4)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> int('7d', 16) > 125 >>>> int('19', 16) > 25 > --------------------------- > > The problem is negative values. If the unit returns the hex value 'e7', > it means -25, but python says it's 231: > --------------------------- >>>> int('e7', 16) > 231 > --------------------------- > The Da Vinci code it aint :-) |>> readings = ['19', 'e7'] |>> for reading in readings: ... intval = int(reading, 16) ... if intval >= 128: ... intval -= 256 ... print intval ... 25 -25 From duncan.booth at invalid.invalid Thu Jun 22 11:02:18 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 22 Jun 2006 15:02:18 GMT Subject: Registry of Methods via Decorators References: <1150983145.387222.5600@c74g2000cwc.googlegroups.com> Message-ID: Stephan Diehl wrote: > replace '@collect_methods' with '@decorated.collect_methods' > and this will do what you want. That is unlikely as it will keep a single list of methods for all classes derived from decorated: calling decorated.collect_methods will pass decorated as the cls parameter. What the OP wants it a separate list for each subclass. The way to do that of course is as others have suggested, just stick an attribute on each decorated function and then collect_methods goes through the class dict when it is called and picks out the correct methods. It could even build a list cached on the class at that time if it needs to (although the speedup is unlikely to be significant over just iterating through all the methods picking out the marked ones). From anton at appsolutions.com Mon Jun 26 02:20:20 2006 From: anton at appsolutions.com (Anton van Straaten) Date: Mon, 26 Jun 2006 06:20:20 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <1151199196.870389.81960@p79g2000cwp.googlegroups.com> <_xrng.108673$H71.2451@newssvr13.news.prodigy.com> Message-ID: Chris Smith wrote: > What makes static type systems interesting is not the fact that these > logical processes of reasoning exist; it is the fact that they are > formalized with definite axioms and rules of inference, performed > entirely on the program before execution, and designed to be entirely > evaluatable in finite time bounds according to some procedure or set of > rules, so that a type system may be checked and the same conclusion > reached regardless of who (or what) is doing the checking. All that, > and they still reach interesting conclusions about programs. There's only one issue mentioned there that needs to be negotiated w.r.t. latent types: the requirement that they are "performed entirely on the program before execution". More below. > If > informal reasoning about types doesn't meet these criteria (and it > doesn't), then it simply doesn't make sense to call it a type system > (I'm using the static terminology here). It may make sense to discuss > some of the ways that programmer reasoning resembles types, if indeed > there are resemblances beyond just that they use the same basic rules of > logic. It may even make sense to try to identify a subset of programmer > reasoning that even more resembles... or perhaps even is... a type > system. It still doesn't make sense to call programmer reasoning in > general a type system. I'm not trying to call programmer reasoning in general a type system. I'd certainly agree that a programmer muddling his way through the development of a program, perhaps using a debugger to find all his problems empirically, may not be reasoning about anything that's sufficiently close to types to call them that. But "latent" means what it implies: someone who is more aware of types can do better at developing the latent types. As a starting point, let's assume we're dealing with a disciplined programmer who (following the instructions found in books such as the one at htdp.org) reasons about types, writes them in his comments, and perhaps includes assertions (or contracts in the sense of "Contracts for Higher Order Functions[1]), to help check his types at runtime (and I'm talking about real type-checking, not just tag checking). When such a programmer writes a type signature as a comment associated with a function definition, in many cases he's making a claim that's provable in principle about the inputs and outputs of that function. For example, if the type in question is "int -> int", then the provable claim is that given an int, the function cannot return anything other than an int. Voila, assuming we can actually prove our claim, then we've satisfied the requirement in Pierce's definition of type system, i.e. "proving the absence of certain program behaviors by classifying phrases according to the kinds of values they compute." The fact that the proof in question may not be automatically verified is no more relevant than the fact that so many proofs in mathematics have not been automatically verified. Besides, if the proof turns out to be wrong, we at least have an automated mechanism for finding witnesses to the error: runtime tag checks will generate an error. Such detection is not guaranteed, but again, "proof" does not imply "automation". What I've just described walks like a type and talks like a type, or at least it appears to do so according to Pierce's definition. We can classify many terms in a given dynamically-typed program on this basis (although some languages may be better at supporting this than others). So, on what grounds do you reject this as not being an example of a type, or at the very least, something which has clear and obvious connections to formal types, as opposed to simply being arbitrary programmer reasoning? Is it the lack of a formalized type system, perhaps? I assume you recognize that it's not difficult to define such a system. Regarding errors, we haven't proved that the function in question can never be called with something other than an int, but we haven't claimed to prove that, so there's no problem there. I've already described how errors in our proofs can be detected. Another possible objection is that I'm talking about local cases, and not making any claims about extending it to an entire program (other than to observe that it can be done). But let's take this a step at a time: considered in isolation, if we can assign types to terms at the local level in a program, do you agree that these are really types, in the type theory sense? If you were to agree, then we could move on to looking at what it means to have many local situations in which we have fairly well-defined types, which may all be defined within a common type system. As an initial next step, we could simply rely on the good old universal type everywhere else in the program - it ought to be possible to make the program well-typed in that case, it would just mean that the provable properties would be nowhere near as pervasive as with a traditional statically-typed program. But the point is we would now have put our types into a formal context. > In the same post here, you simultaneously suppose that there's something > inherently informal about the type reasoning in dynamic languages; and > then talk about the type system "in the static sense" of a dynamic > language. How is this possibly consistent? The point about inherent informality is just that if you fully formalize a static type system for a dynamic language, such that entire programs can be statically typed, you're likely to end up with a static type system with the same disadvantages that the dynamic language was trying to avoid. However, that doesn't preclude type system being defined which can be used to reason locally about dynamic programs. Some people actually do this, albeit informally. >>So we actually have quite a bit of evidence about the presence of static >>types in dynamically-typed programs. > > > No. What we have is quite a bit of evidence about properties remaining > true in dynamically typed programs, which could have been verified by > static typing. Using my example above, at least some of those properties would have been verified by manual static typing. So those properties, at least, seem to be types, at least w.r.t. the local fragment they're proved within. >>We're currently discussing something that so far has only been captured >>fairly informally. If we restrict ourselves to only what we can say >>about it formally, then the conversation was over before it began. > > > I agree with that statement. However, I think the conversation > regarding static typing is also over when you decide that the answer is > to weaken static typing until the word applies to informal reasoning. > If the goal isn't to reach a formal understanding, then the word "static > type" shouldn't be used Well, I'm trying to use the term "latent type", as a way to avoid the ambiguity of "type" alone, to distinguish it from "static type", and to get away from the obvious problems with "dynamic type". But I'm much less interested in the term itself than in the issues surrounding dealing with "real" types in dynamically-checked programs - if someone had a better term, I'd be all in favor of it. > and when that is the goal, it still shouldn't > be applied to process that aren't formalized until they manage to become > formalized. This comes back to the phrase I highlighted at the beginning of this message: "performed entirely on the program before execution". Formalizing local reasoning about types is pretty trivial, in many cases. It's just that there are other cases where that's less straightforward. So when well-typed program fragments are considered as part of a larger untyped program, you're suggesting that this so radically changes the picture, that we can no longer distinguish the types we identified as being anything beyond programmer reasoning in general? All the hard work we did figuring out the types, writing them down, writing assertions for them, and testing the program to look for violations evaporates into the epistemological black hole that exists outside the boundaries of formal type theory? > Hopefully, this isn't perceived as too picky. I've already conceded > that we can use "type" in a way that's incompatible with all existing > research literature. Not *all* research literature. There's literature on various notions of dynamic type. > I would, however, like to retain some word with > actually has that meaning. Otherwise, we are just going to be > linguistically prevented from discussing it. For now, you're probably stuck with "static type". But I think it was never likely to be the case that type theory would succeed in absconding with the only technically valid use of the English word "type". Although not for want of trying! Besides, I think it's worth considering why Bertrand Russell used the term "types" in the first place. His work had deliberate connections to the real world. Type theory in computer science unavoidably has similar connections. You could switch to calling it Zoltar Theory, and you'd still have to deal with the fact that a zoltar would have numerous connections to the English word "type". In CS, we don't have the luxury of using the classic mathematician's excuse when confronted with inconvenient philosophical issues, of claiming that type theory is just a formal symbolic game, with no meaning outside the formalism. Anton [1] http://people.cs.uchicago.edu/~robby/pubs/papers/ho-contracts-techreport.pdf From flupke at nonexistingdomain.com Tue Jun 27 20:11:26 2006 From: flupke at nonexistingdomain.com (flupke) Date: Wed, 28 Jun 2006 00:11:26 GMT Subject: logging error with RotatingFileHandler In-Reply-To: <1151391562.198586.249130@m73g2000cwd.googlegroups.com> References: <_asng.501715$x64.12701762@phobos.telenet-ops.be> <1151391562.198586.249130@m73g2000cwd.googlegroups.com> Message-ID: Vinay Sajip wrote: > flupke wrote: > > >> File "C:\Python24\lib\logging\handlers.py", line 134, in doRollover >> self.handleError(record) >>NameError: global name 'record' is not defined > > > There's a bug in doRollover's exception handling, which is masking the > true error - which is most probably an exception being thrown in > os.rename. > > I'll look at fixing this bug asap. Most likely, it'll be done by let > the exception propagate up from doRollover to its caller. > > Regards, > > Vinay Sajip > OK Vinjay, thanks for the info. If this bug is fixed, where will i find a fixed version and how do i install it? Also, more important to me, what am i doing wrong to get this error message in the first place? I could reproduce the error with this program: import logging import logging.config LOGFILE = r"logconf.ini" logging.config.fileConfig(LOGFILE) class TypeA(object): def __init__(self): #logging.config.fileConfig(LOGFILE) self.log = logging.getLogger('logfile') self.dolog("Starting the program") def dolog(self,text): self.log.debug(text) class TypeB(TypeA): def __init__(self): super(TypeB,self).__init__() # put this line in comment to prevent the error logging.config.fileConfig(LOGFILE) #self.log = logging.getLogger('logfile') self.log.debug("Starting class B") for nr_of_lognr in range(0,2000): b = TypeB() b.dolog("This is a test to see if logging works and more specifically the RotatingFileHandler functionallity") It seemed as if the "logging.config.fileConfig(LOGFILE)" line in Type B is to blame. I changed the code of my big program to reflect this change yet i still get this error. I didn't get this with an earlier version of python. Regards, Benedict From marc.t.davies at gmail.com Tue Jun 20 05:24:41 2006 From: marc.t.davies at gmail.com (MTD) Date: 20 Jun 2006 02:24:41 -0700 Subject: How to truncate/round-off decimal numbers? In-Reply-To: References: Message-ID: <1150795481.361532.310790@b68g2000cwa.googlegroups.com> > >>> a = 2 > >>> b = 3 > >>> round(a*1.0 / b,2) > 0.67000000000000004 > > Inspite of specifying 2 in 2nd attribute of round, it outputs all the > digits after decimal. This is because of floating point inaccuracy. The system cannot accurately represent some integers, however it does its best to approximate them. Notice this: >>> x = 2.0/3 >>> x 0.66666666666666663 >>> round(x,2) 0.67000000000000004 >>> s = str(round(x,2)) >>> s '0.67' From onurb at xiludom.gro Sat Jun 17 12:29:11 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Sat, 17 Jun 2006 18:29:11 +0200 Subject: Legitimate use of the "is" comparison operator? In-Reply-To: <1150530591.422197.304300@p79g2000cwp.googlegroups.com> References: <1150530591.422197.304300@p79g2000cwp.googlegroups.com> Message-ID: <44942dd8$0$29810$626a54ce@news.free.fr> Mike Duffy wrote: > I just recently realized that the comparison operator "is" actually > works for comparing numeric values. It's only an implementation detail of CPython (and is only true for small integers - you'll find the limit in the CPython source code), not part of the language specifications. You should *not* relie on this behaviour. > Now, I know that its intended use > is for testing object identity, but I have used it for a few other > things, such as type checking, Don't use it for this neither unless you know exactly what you do. Use isinstance(obj, klass) instead - and yet better, don't check type at all if you can avoid it. > and I was just wondering whether or not > it is considered bad practice in the Python Community to use it for > numerics as well. It's even worse than a bad practice : it's an error. > Example: > > a = range(5) > b = range(5) > > if len(a) is len(b): > print "They're the same size!" > else: > print "They're not the same size!" > >>> a = range(32000) >>> b = range(32000) >>> len(a) is len(b) False -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From foster at home.nl Wed Jun 7 16:23:07 2006 From: foster at home.nl (Maarten van Veen) Date: Wed, 07 Jun 2006 22:23:07 +0200 Subject: creating and naming objects References: <1149696358.065614.76150@h76g2000cwa.googlegroups.com> Message-ID: In article <1149696358.065614.76150 at h76g2000cwa.googlegroups.com>, "Brian" wrote: > I have a question that some may consider silly, but it has me a bit > stuck and I would appreciate some help in understanding what is going > on. > > For example, lets say that I have a class that creates a student > object. > > Class Student: > def setName(self, name) > self.name = name > def setId(self, id) > self.id = id > > Then I instantiate that object in a method: > > def createStudent(): > foo = Student() > /add stuff > > Now, suppose that I want to create another Student. Do I need to name > that Student something other than foo? What happens to the original > object? If I do not supplant the original data of Student (maybe no id > for this student) does it retain the data of the previous Student > object that was not altered? I guess I am asking how do I > differentiate between objects when I do not know how many I need to > create and do not want to hard code names like Student1, Student2 etc. > > I hope that I am clear about what I am asking. > > Thanks, > Brian Hi Brian, If you would do it like this: Class Student: def setName(self, name) self.name = name def setId(self, id) self.id = id def createStudent(): foo = Student() foo.setName("Brian") foo = Student() print foo.getName() You would get an error here, because foo now equals the second Student object which has no name. And you can't get to the first one. Perhaps you could do something like this. Class Student: def setName(self, name) self.name = name def setId(self, id) self.id = id listWithStudents = [] def createStudent(): listWithStudent.append(Student()) Now every student you create is put in the list with students so you can access them but don't have to give them names. You could do something to all of them like this: for student in listWithStudent: student.doSomething() Or change just one student: listWithStudent[23].doSomething() # this is the 24th student though!!! Hope this is what you're looking for. Maarten From chris at kateandchris.net Thu Jun 1 17:39:16 2006 From: chris at kateandchris.net (Chris Lambacher) Date: Thu, 1 Jun 2006 17:39:16 -0400 Subject: Add file to zip, or replace file in zip In-Reply-To: <447D417D.000005.13553@bj163app13.163.com> References: <447D417D.000005.13553@bj163app13.163.com> Message-ID: <20060601213916.GA912@kateandchris.net> Skip over the file in question when you first are zipping the directory. Unfortunately you cannot replace or remove a file from a zip without unzipping and rezipping all the contents. -Chris On Wed, May 31, 2006 at 03:10:53PM +0800, majj81 wrote: > hi: > Good afternoon. > Has this problem solved in the URL > [1]http://mail.python.org/pipermail/python-list/2006-April/338849.html . > Now I have the same problem to deal with. If you have any suggestion > please tell me. > Thanks. > Johnny Ma > come from China > > > > > ?? ?? ?? ?? ?? 1/2? ?? ?? ?????? ?? ?? ?? ?? ?? > [2]?? ? ?? ?? '? ?? ?? ?? ?? ?? 1/2? ?? ?? ?? 1/4 1/4 ?? ????'' ?? Ajax > 1/4 1/4 ????126 ??D 1/4? ?????? ?? ?? ?? ?? ?? > > References > > Visible links > 1. http://mail.python.org/pipermail/python-list/2006-April/338849.html > 2. http://www.126.com/ > -- > http://mail.python.org/mailman/listinfo/python-list From fredrik at pythonware.com Wed Jun 7 02:27:47 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 07 Jun 2006 08:27:47 +0200 Subject: 10GB XML Blows out Memory, Suggestions? In-Reply-To: <1149648710.179563.274320@c74g2000cwc.googlegroups.com> References: <1149594519.098115.8980@u72g2000cwu.googlegroups.com> <2Qfhg.18186$0v4.787@tornado.texas.rr.com> <1149623638.736338.185320@h76g2000cwa.googlegroups.com> <1149648710.179563.274320@c74g2000cwc.googlegroups.com> Message-ID: fuzzylollipop wrote: >> Is it possible to read an XML document in compressed format? > > compressing the footprint on disk won't matter, you still have 10GB of > data that you need to process and it can only be processed uncompressed. didn't you just claim that this was an I/O bound problem ? From tim.peters at gmail.com Mon Jun 5 14:24:41 2006 From: tim.peters at gmail.com (Tim Peters) Date: Mon, 5 Jun 2006 14:24:41 -0400 Subject: Large Dictionaries In-Reply-To: <1288rq2mkj9r40b@corp.supernews.com> References: <1147699064.107490@teuthos> <447af556$1@nntp0.pdx.net> <1288rq2mkj9r40b@corp.supernews.com> Message-ID: <1f7befae0606051124m1cde1096m1e021c53124437d5@mail.gmail.com> [Jim Segrave] > Actually, presorted lists are not a bad case for heapsort - it's quite > immune to any existing order or lack thereof, Write a heapsort and time it. It's not a difference in O() behavior, but more memory movement is required for a sorted list because transforming the list into a max-heap at the start requires shuffling the largest elements from the end of the list to its start. Initially reverse-sorted is a "good case" for heapsort in the same sense (because the list is already a max-heap then; initially sorted is as far from being a max-heap as is possible). "good" and "bad" are both O(N log N) here, though. BTW, most people have never heard of Smoothsort, which was Dijkstra's excruciating attempt to make heapsort exploit pre-existing order: http://www.cs.utexas.edu/users/EWD/ewd07xx/EWD796.PDF That's one of a hundred algorithms I rejected for Python ;-) > whereas some other sorts, quicksort being a prime example, require > great care to avoid pathological cases. Indeed, Python gave up on quicksort for that reason. While the samplesort hybrid that came between quicksort and the current sort also had theoretical O(N**2) worst-case behavior, it was exceedingly difficult to create such an input, and (unlike as for every quicksort variant Python tried) no real-life case of undue sloth was ever reported against it. From david at boddie.org.uk Wed Jun 7 09:25:25 2006 From: david at boddie.org.uk (David Boddie) Date: 7 Jun 2006 06:25:25 -0700 Subject: pyqt show wizard References: Message-ID: <1149686724.992518.104290@i39g2000cwa.googlegroups.com> Yves Glodt wrote: > I have a mainwindow in my pyqt application, and on click of a button I > want to start an assistant (wizard). > > I have create the wizard with the Qt Designer, generated the python code > with pyuic, imported it "from assistant import *", and subclassed it as > usual. > > To show it, the onclick method of the button does: > > w = Wizard() > w.show() > > bot nothing happens... If this is within a method that returns immediately after the show() call, the wizard will go out of scope and be deleted. I suspect that you really want to call w.exec_loop() intead, since this will only return control to the method after the user has finished interacting with the wizard. Take a look at the QWizard documentation for more information: http://doc.trolltech.com/3.3/qwizard.html David From robert.kern at gmail.com Thu Jun 1 19:24:29 2006 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 01 Jun 2006 18:24:29 -0500 Subject: Conditional Expressions in Python 2.4 In-Reply-To: References: Message-ID: A.M wrote: > Do we have the conditional expressions in Python 2.4? No. -- 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 From ziapannocchia at gmail.com Sun Jun 11 08:06:37 2006 From: ziapannocchia at gmail.com (cloc3) Date: 11 Jun 2006 05:06:37 -0700 Subject: [mod_python] using nested blocks in psp Message-ID: <1150027597.236379.53290@j55g2000cwa.googlegroups.com> I'm a newbie in python, and I'm fighting against nested blocks in psp. Thats a little example with a funny behaviour: [code]
[/code] In my intention, the for instruction have to run two operation: first: the if instruction second: to print the option tag on the html page. Instead, the real behaviour is depending on the result of the control in the if: if the control is true, the option tag is not printed, and the for instruction goes to the successive step. if the control is false, the option is correctly printed. I don't understand the reason of this behaviour. Which is the right way to control the nested block instructions in psp? From emanuele.aina at gmail.com Thu Jun 15 08:46:29 2006 From: emanuele.aina at gmail.com (Emanuele Aina) Date: 15 Jun 2006 05:46:29 -0700 Subject: __lt__ slowing the "in" operator even if not called References: <1150318630.203249.191250@r2g2000cwb.googlegroups.com> <1150373671.227640.50910@f6g2000cwb.googlegroups.com> Message-ID: <1150375588.963040.235590@f6g2000cwb.googlegroups.com> Maric Michaud continu?: > > But I hoped in a more exaustive answer: why python has to do this > > lookup when the __lt__ method is not involved at all? > > It is not the case, that's what my program shows : > > > > in operator at the beginning of list: 173 > in operator at the end of list: 28249 <- here > > converting to dict : 79 > in operator for a dict for 60000 elements: 14 > > > > in operator at the beginning of list: 202 > in operator at the end of list: 30472 <- and here It is very obvious that these two have similiar timings, as both call __eq__. I asked why the State and StateLT don't give similar results, but StateLT is noticeably slower. From serge.orlov at gmail.com Tue Jun 27 16:29:51 2006 From: serge.orlov at gmail.com (Serge Orlov) Date: Tue, 27 Jun 2006 13:29:51 -0700 Subject: Python UTF-8 and codecs In-Reply-To: References: Message-ID: On 6/27/06, Mike Currie wrote: > I'm trying to write out files that have utf-8 characters 0x85 and 0x08 in > them. Every configuration I try I get a UnicodeError: ascii codec can't > decode byte 0x85 in position 255: oridinal not in range(128) > > I've tried using the codecs.open('foo.txt', 'rU', 'utf-8', errors='strict') > and that doesn't work and I've also try wrapping the file in an utf8_writer > using codecs.lookup('utf8') > > Any clues? Use unicode strings for non-ascii characters. The following program "works": import codecs c1 = unichr(0x85) f = codecs.open('foo.txt', 'wU', 'utf-8') f.write(c1) f.close() But unichr(0x85) is a control characters, are you sure you want it? What is the encoding of your data? From dnew at san.rr.com Wed Jun 21 13:43:37 2006 From: dnew at san.rr.com (Darren New) Date: Wed, 21 Jun 2006 17:43:37 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <0%Wlg.3521$MF6.947@tornado.socal.rr.com> <44992e6c$0$664$bed64819@news.gradwell.net> Message-ID: Andreas Rossberg wrote: > AFAICT, ADT describes a type whose values can only be accessed by a > certain fixed set of operations. No. AFAIU, an ADT defines the type based on the operations. The stack holding the integers 1 and 2 is the value (push(2, push(1, empty()))). There's no "internal" representation. The values and operations are defined by preconditions and postconditions. Both a stack and a queue could be written in most languages as "values that can only be accessed by a fixed set of operations" having the same possible internal representations and the same function signatures. They're far from the same type, because they're not abstract. The part you can't see from outside the implementation is exactly the part that defines how it works. Granted, it's a common mistake to write that some piece of C++ code implements a stack ADT. For example, an actual ADT for a stack (and a set) is shown on http://www.cs.unc.edu/~stotts/danish/web/userman/umadt.html Note that the "axia" for the stack type completely define its operation and semantics. There is no other "implementation" involved. And in LOTOS (which uses ACT.1 or ACT.ONE (I forget which)) as its type, this is actually how you'd write the code for a stack, and then the compiler would crunch a while to figure out a corresponding implementation. I suspect "ADT" is by now so corrupted that it's useful to use a different term, such as "algebraic type" or some such. > Classes qualify for that, as long as they provide proper encapsulation. Nope. > OK, I admit that I exaggerated slightly. Although currently I'm indeed > able to mostly work with the more pleasant among languages. :-) Yah. :-) > (Btw, Pascal did not have it either, AFAIK) I'm pretty sure in Pascal you could say Type Apple = Integer; Orange = Integer; and then vars of type apple and orange were not interchangable. -- Darren New / San Diego, CA, USA (PST) My Bath Fu is strong, as I have studied under the Showerin' Monks. From diffuser78 at gmail.com Thu Jun 22 15:02:14 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 22 Jun 2006 12:02:14 -0700 Subject: Network Programming in Python Message-ID: <1151002934.586359.174540@m73g2000cwd.googlegroups.com> I am a newbie in python. I want to learn and implement a small networking concept. Please help me. Every help is appreciated. I have one Linux Box and one Windows PC. I want to have a daemon running on Windows PC which listens on some specicif port number. I want to send a TCP/IP or UDP/IP packet from Linux box to Windows PC to start some application. As Windows PC recieves such a packet from Linux Box it executes a certain .exe file. I want to implement this concept. In short I want to remotely send command from Linux to Windows PC to start a particular application. Thanks, Every help is appreciated. From vaikings at gmail.com Mon Jun 26 02:48:40 2006 From: vaikings at gmail.com (vaibhav) Date: 25 Jun 2006 23:48:40 -0700 Subject: list problem 4 newbie References: <1151302228.249512.277690@p79g2000cwp.googlegroups.com> Message-ID: <1151304520.885954.124450@p79g2000cwp.googlegroups.com> Hi, if u check the id's of a and b lists and also its elements, you will obeserve that the id's of a and b have changed but id's of their elements have not changed. If you make a deep copy of the list a and then make your changes in that list, it shud work. this can be done using the copy module. hope that helps, vaibhav >>> id(a) -1208622388 >>> id(b) -1208622324 >>> for el in a: ... print id(el) ... -1208622836 -1208622708 -1208622772 -1208622420 >>> for el in b: ... print id(el) ... -1208622836 -1208622708 -1208622772 -1208622420 >>> import copy >>> c = copy.deepcopy(a) >>> id(c) -1208464564 >>> for el in c: ... print id(el) ... -1208465172 -1208464276 -1208464180 -1208463988 From gandalf at designaproduct.biz Thu Jun 8 07:48:31 2006 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Thu, 08 Jun 2006 13:48:31 +0200 Subject: Terminateable thread Message-ID: <44880E8F.5080804@designaproduct.biz> I wote a TThread class that is 'soft terminateable'. For example: class MyProcessor(TThread): def run(self): while not self.terminated(): self.process_one_item() My question is that, do I really need to use events for this? Because of the GIL, assignments are atomic. Is it okay to use a simple '_terminated' attribute instead of the Event object (see below)? It would be much better to use a simple 'mythread.terminated' attribute instead of 'mythread.terminated()' and 'mythread.terminated=True' instead of 'mythread.terminate()'. Please advise. Laszlo -------------------------- from thread import * from threading import * class TermMixIn(object): """Terminateable thread mixin class. Methods in this class are thread safe and can be used to implement softly terminateable threads. This class can also be used to create a main synchronization object.""" def __init__(self): """Create a TermMixIn instance. Default state is not terminated.""" self._terminated = Event() def terminated(self): """ @return: if the thread is terminated.""" return self._terminated.isSet() def terminate(self): """Set the terminate flag. Can be called from any thread.""" self._terminated.set() def checkterminated(self): """Check if the thread was terminated. This sould be periodically called from the softly terminateable thread itself. Will raise a L{TerminatedException} if the thread is terminated.""" if self.terminated(): raise TerminatedException() class TThread(Thread,TermMixIn): """Terminateable thread. See the L{TermMixIn} class for details.""" def __init__(self,group=None, target=None, name=None, args=(), kwargs={}): TermMixIn.__init__(self) Thread.__init__(self,group,target,name,args,kwargs) From bborcic at gmail.com Fri Jun 9 11:13:19 2006 From: bborcic at gmail.com (Boris Borcic) Date: Fri, 09 Jun 2006 17:13:19 +0200 Subject: [noob question] References and copying In-Reply-To: References: Message-ID: <44899021$1_4@news.bluewin.ch> zefciu wrote: > Hello! > > Where can I find a good explanation when does an interpreter copy the > value, and when does it create the reference. I thought I understand > it, but I have just typed in following commands: > >>>> a=[[1,2],[3,4]] >>>> b=a[1] >>>> b=[5,6] >>>> a > [[1, 2], [3, 4]] >>>> b > [5, 6] > > And I don't understand it. I thought, that b will be a reference to a, > so changing b should change a as well. It would if you had written "b[:]=[5,6]" > What do I do wrong. And a > second question - can I create a reference to element of a list of > floating points and use this reference to change that element? not like that. > > Greets to all PyFans > zefciu From scott.daniels at acm.org Tue Jun 20 16:27:17 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Tue, 20 Jun 2006 13:27:17 -0700 Subject: need helping tracking down weird bug in cPickle In-Reply-To: References: Message-ID: <44985535$1@nntp0.pdx.net> Carl J. Van Arsdall wrote: > Hey everyone, cPickle is raising an ImportError that I just don't quite > understand. Before I paste the code, let me explain the application. > Basically the part of the application that failed is a function that > loads a list of objects from a file using cPickle.... Loading and unloading Floating Point NaNs (Not a Numbers) is often the source of such problems. I'd look for something like that. They can displays as: (Inf, Ind, NaN, SNaN, QNaN) w/ or w/o a sign. Depending on your runtimes, processor, OS, and sometimes program history (flag manipulation), you can get these values in different ways. --Scott David Daniels scott.daniels at acm.org From anton.vredegoor at gmail.com Fri Jun 23 07:54:30 2006 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Fri, 23 Jun 2006 13:54:30 +0200 Subject: code is data In-Reply-To: <1151013151.902103.32800@g10g2000cwb.googlegroups.com> References: <44965f53$0$12743$636a55ce@news.free.fr> <4496b29f$0$27412$626a54ce@news.free.fr> <4496e9c9$0$14868$626a54ce@news.free.fr> <4fokj4F1ihat3U1@uni-berlin.de> <4497c20e$0$29656$636a55ce@news.free.fr> <4fpuh5F1i9bl1U1@uni-berlin.de> <4497d72d$0$30964$636a55ce@news.free.fr> <4fq5fkF1k346bU1@uni-berlin.de> <44982637$0$29812$626a54ce@news.free.fr> <1151013151.902103.32800@g10g2000cwb.googlegroups.com> Message-ID: Paul Boddie wrote: > Anton Vredegoor wrote: >> Yes, but also what some other posters mentioned, making Pythons internal >> parsing tree available to other programs (and to Python itself) by using >> a widely used standard like XML as its datatype. > > http://pysch.sourceforge.net/ast.html Very interesting, it led me to some sxml describing pages and it also tricked me into reading some Python documentation that I had always considered to be hiding some arcane deep Python magic. I guess now that Python is officially entering tree territory (as opposed to providing third party functionality) it seems unavoidable that Python's officially endorsed tree datatype will also be used for some of its internal structures, thereby making it more accessible to programmers like me and to outside programmers. > I was going to write a long reply to one of your previous messages, but > the above link references a project which may intersect with some of > your expectations. Meanwhile, it should be noted that the availability Somehow I get the impression of getting away with my posts luckily, while you now are duping other interested readers into not reading your innermost feelings about this subject. Let's get it in the open, don't spare me :-) > of Python AST processing tools is not a recent thing: the compiler > module has been around for a long time, and it is possible to modify > the AST and to generate bytecode from it; my own experiments have > centred on producing other representations from the AST, and other more > successful projects (eg. ShedSkin) produce other languages (eg. C++) > from the AST. Well maybe this trick of vehemently denying the existence of something on Usenet worked again, by materializing the thing as a reaction. However, I knew of the existence of such languages but I am mostly interested in standardized code interchange, like for example with JSONP which fetches some external javascriptcode from another server using JSON and places the translated javascript into a webpage at the request of the clients browser or so it seems. Maybe a Python webserver could also emit pieces of javascript code by getting them from a *Python* code library after translating Python code on the fly? That would open up the web to Python programmers without browsers needing to understand Python. Like Jython, but now as separately distributed functions from different servers. Anton From aleax at mac.com Sun Jun 25 12:41:17 2006 From: aleax at mac.com (Alex Martelli) Date: Sun, 25 Jun 2006 09:41:17 -0700 Subject: array manipulation without for loops References: <1151251578.463273.24370@m73g2000cwd.googlegroups.com> <1151253182.496596.185420@r2g2000cwb.googlegroups.com> Message-ID: <1hhhes5.1hw0kbeniihqiN%aleax@mac.com> Sheldon wrote: > Hi Gary, > > I am really trying to cut the time down as I have 600+ arrays with > dimensions (1215,1215) to compare and I do a lot more things with the > arrays. If I understand you correctly, there is no way around a for > loop? In pure Python (w/o extension packages) there are no 2-D arrays; so either you're using lists of lists (and I wonder how you fit even one of them in memory, if they're 1215 by 1215, much less 600!) or you're already using some extension (Numeric, numarray, numpy) and aren't telling us which one. If you're using pure Python add your extension of choice, if you're using an extension already tell us which one, and in each case there will be ways to perform your manipulation tasks faster than Python-level for loops would afford. Alex From fredrik at pythonware.com Thu Jun 8 05:41:21 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 08 Jun 2006 11:41:21 +0200 Subject: simplexmlrpcserver and allow_none In-Reply-To: <4487EE87.9060106@designaproduct.biz> References: <4487EE87.9060106@designaproduct.biz> Message-ID: Laszlo Nagy wrote: > I ran in the same problem again. Many others have the same problem. Just > Google for this: "SimpleXMLRPCServer allow_none site:python.org". > Looks like the 'allow_none' patch was commited to trunk on 2005 Dec ( > http://mail.python.org/pipermail/python-checkins/2005-December/048289.html ) > > I just upgraded to Python 2.4.3 (it was released on March 29, 2006) and > SimpleXMLRPCServer.py still has the old code. once a major release is done, the trunk becomes the development version for the next major release (2.5, at this time). bugfix releases are not based on the trunk. > I can work around this by coping the whole file into a new file and > patch it, but I hate to do that. > I wonder why it has not been commited to the standard library yet. Does > anyone know if it will be in the next bugfix release? not likely, because it's a new feature, not a bug fix. From stanc at al.com.au Tue Jun 6 01:26:54 2006 From: stanc at al.com.au (Astan Chee) Date: Tue, 06 Jun 2006 15:26:54 +1000 Subject: using custom cookies in http Message-ID: <4485121E.2090503@al.com.au> Hi, Im attemtping to set values of custom cookies and use it to gain access to certain web-pages that require these custom cookies. What I've done so far is creating the cookies like so: import Cookie C = Cookie.SmartCookie() C["__user_name"] = "foob" And Im trying to open a url that requires this cookie: import urllib f = urllib.urlopen("http://example.com/page/lies/here") print f.read() Now all Im missing is loading the cookie to urllib. How do I do this? Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From luismgz at gmail.com Wed Jun 28 23:55:00 2006 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 28 Jun 2006 20:55:00 -0700 Subject: Correr Programas Externos In-Reply-To: <1151552434.864745.268550@j72g2000cwa.googlegroups.com> References: <1151552434.864745.268550@j72g2000cwa.googlegroups.com> Message-ID: <1151553300.191673.191320@d56g2000cwd.googlegroups.com> La lista en espa?ol esta ac?: http://listas.aditel.org/listinfo/python-es Saludos, Luis From justin.azoff at gmail.com Thu Jun 22 09:22:57 2006 From: justin.azoff at gmail.com (Justin Azoff) Date: 22 Jun 2006 06:22:57 -0700 Subject: smtplib problem for newbie In-Reply-To: References: Message-ID: <1150982577.699670.316750@g10g2000cwb.googlegroups.com> Noah Gift wrote: [snip] > a = long(time.time() * 256) # use fractional seconds > TypeError: 'module' object is not callable Part of your program includes a file or directory that you called 'long'. You should not re-use names of built-ins in your programs.. they cause you to get errors like the above. see: >>> long('12') 12L >>> open("long.py",'w') >>> import long >>> long('12') Traceback (most recent call last): File "", line 1, in ? TypeError: 'module' object is not callable >>> -- - Justin From grante at visi.com Thu Jun 15 11:47:19 2006 From: grante at visi.com (Grant Edwards) Date: Thu, 15 Jun 2006 15:47:19 -0000 Subject: Numerics, NaNs, IEEE 754 and C99 References: <12904mjhl493t49@corp.supernews.com> <1290aik50hmk94a@corp.supernews.com> <4490329e$0$12356$636a55ce@news.free.fr> <12917f6jp7u90f8@corp.supernews.com> <44912058$0$29674$636a55ce@news.free.fr> <1292p7s46ef5off@corp.supernews.com> <1292tvei30ahhd4@corp.supernews.com> Message-ID: <12930879vah1k12@corp.supernews.com> On 2006-06-15, Fredrik Lundh wrote: > Grant Edwards wrote: > >>> Firstly, a FAR more common assumption is that integers wrap in twos' >>> complement - Python does not do that. >> >> It used to > > for integers ? what version was that ? Am I remebering incorrectly? Didn't the old fixed-width integers operate modulo-wordsize? I distinctly remember having to rewrite a bunch of checksum code when fixed-width integers went away. -- Grant Edwards grante Yow! My uncle Murray at conquered Egypt in 53 visi.com B.C. And I can prove it too!! From rhymes at myself.com Thu Jun 29 03:33:43 2006 From: rhymes at myself.com (Lawrence Oluyede) Date: Thu, 29 Jun 2006 09:33:43 +0200 Subject: mmap as a sequence behavior References: <1hho1x1.1ntwxi3z2hdzhN%rhymes@myself.com> <44a31620$1@nntp0.pdx.net> Message-ID: <1hhoss2.plvqdo1jmnlbwN%rhymes@myself.com> Scott David Daniels wrote: > That is sequence behavior. The convention of -1 for last, -2 for > second-to-last, ... is done before it gets to your C code. I suspect > if you don't define a __len__ method, you'd suppress this. I defined a __len__ method but I get the index "plain" without any kind of conversion before entering the method -- Lawrence - http://www.oluyede.org/blog "Nothing is more dangerous than an idea if it's the only one you have" - E. A. Chartier From bdesth.quelquechose at free.quelquepart.fr Sun Jun 4 22:49:45 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 05 Jun 2006 04:49:45 +0200 Subject: Using print instead of file.write(str) In-Reply-To: <1d5482dibl4b4or8d4fkd90pd17ml3st2p@4ax.com> References: <2Iq*Jzbir@news.chiark.greenend.org.uk> <44809e93$0$13657$636a55ce@news.free.fr> <1d5482dibl4b4or8d4fkd90pd17ml3st2p@4ax.com> Message-ID: <44836c2c$0$13039$626a54ce@news.free.fr> Tim Roberts a ?crit : > Bruno Desthuilliers wrote: > > >>Sion Arrowsmith a ?crit : >> (snip) >>>"more flexible"? More convenient, yes. More powerful, maybe. But I >>>don't see more flexible. Everything print can to stdout.write() can >>>do. The reverse isn't true. eg (this appears to be a FAQ on this >>>group, although I can't find it in the FAQ): >>> >>>for x in range(10): >>> sys.stdout.write(str(x)) >>> >>>to print: >>> >>>0123456789 >> >>The reverse isn't true ??? >> >> print "".join(str(x) for x in range(10)) > > What he meant it that it is impossible to produce "0123456789" using 10 > separate print statements, while it IS possible with 10 separate writes. why on earth would someone try to use 10 consecutive I/O operations on the same stream when it can be done with 1 ??? From shejo284 at gmail.com Mon Jun 19 08:49:41 2006 From: shejo284 at gmail.com (Sheldon) Date: 19 Jun 2006 05:49:41 -0700 Subject: comparing two arrays Message-ID: <1150721380.948808.231760@h76g2000cwa.googlegroups.com> Hi, I have two arrays that are identical and contain 1s and zeros. Only the ones are valid and I need to know where both arrays have ones in the same position. I thought logical_and would work but this example proves otherwise: >>> a = [0,1,2,5,6,6] >>> b = [5,4,1,6,4,6] >>> Numeric.logical_and(a==6,b==6) 0 >>> Numeric.where(a==b,1,0) 0 >>> Numeric.where(a==6 and b==6,1,0) 0 The where() statement is also worhtless here. Does anyone have any suggestion on how to do this? Thanks in advance, Sheldon From praveenkumar.117 at gmail.com Tue Jun 6 02:29:47 2006 From: praveenkumar.117 at gmail.com (praveenkumar.117 at gmail.com) Date: 5 Jun 2006 23:29:47 -0700 Subject: Python.h Message-ID: <1149575387.027832.115870@i39g2000cwa.googlegroups.com> Hi, I am running python to c converter application. It throws an error saying python.h file not found. Can somebody plz suggest how to resolve this problem. Regards, Praveen Kumar From onurb at xiludom.gro Tue Jun 27 04:30:19 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Tue, 27 Jun 2006 10:30:19 +0200 Subject: Replace Whole Object Through Object Method In-Reply-To: References: <1151337453.804750.293180@b68g2000cwa.googlegroups.com> <44a041a6$0$17612$636a55ce@news.free.fr> <1151354259.082966.25820@p79g2000cwp.googlegroups.com> Message-ID: <44a0ec9c$0$20889$626a54ce@news.free.fr> Maric Michaud wrote: > Le lundi 26 juin 2006 22:37, digitalorganics at gmail.com a ?crit : > >>Won't work because there will be employers that aren't workers. >>And yes, only some workers will become employers, but also only some >>employers will also be workers (at some point in program). Let me be >>more clear: >> >>workers >>--> subset of workers --become--> employers >>employers >>--> subset of employers --become--> workers >> >>It is very important that both should maintain attribute values, >>regardless of whether they take on new "roles". Furthermore, this is a >>very simple case and ultimately in my program an object should be able >>to dynamically take on a multitude of roles (classes of behavior) >>without mucking at all with their pre-existing states. > > > This seem to be a OO design problem Obviously. > and you clearly make a misuse of > inheritance, Chapter and verse, please ? s/misuse/creative use/ > if a person can eventually have many roles, but doesn't have > this role for all his lifetime, then the person *is* not his roles. And ? In a dynamically typed language, inheritance is about implementation, not subtyping. The class of an object is nothing more than an attribute, and as such is not necessarily fixed for the lifetime of the object. > That the meaning of inheritance, class B(A) means a B is a A. > The association between a person and his roles is obviously a 1-n association, > which can be rendered by different patterns (delegation, composition, > strategy, etc.). You've learned your lessons well. That's fine. Now please understand that there's a huge difference between the book (usually based on static some static language) and dynamic OOPLs. IOW : free your mind. In Python, you can dynamically change the class of an object at runtime. And the attribute lookup rule is to first lookup the object, then the class (which is itself an object FWIW). So you can see the object/class relationship as a somewhat specialised composition/delegation relationship. In fact, in Python, a class is both an object factory and delegatee. > You should google on "design patterns" and make your choice. FWIW, a good part of the canonical design patterns are mostly workaround the lack of flexibility in languages like C++ and Java. The Strategy pattern's simplest Python implementation is to dynamically replace a method on a per-object basis. The State pattern's simplest implementation in Python is to dynamically change the class of an object. Of course, one of the canonical solutions to the OP's problem is to use composition/delegation. But doing it the canonical way would imply creating instances of the role objects and passing them the instance as param so they can access it's attributes. It works, but it creates a cyclic dependancy between the object and it's roles, so you would have to use weakrefs. Dynamically creating new classes with the appropriate bases and assigning them to the object's __class__ attribute is another way to achieve the same result, and it's perfectly legal. Now I do agree that it can become tricky to manage correctly wrt/ mro rules !-) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From sjmachin at lexicon.net Mon Jun 19 08:56:32 2006 From: sjmachin at lexicon.net (John Machin) Date: Mon, 19 Jun 2006 22:56:32 +1000 Subject: Seeking regex optimizer In-Reply-To: <1150708003.681073.296430@f6g2000cwb.googlegroups.com> References: <1150650439.651839.38180@y41g2000cwy.googlegroups.com> <1150708003.681073.296430@f6g2000cwb.googlegroups.com> Message-ID: <44969F00.30203@lexicon.net> On 19/06/2006 7:06 PM, Kay Schluehr wrote: > Mirco, > > with "special characters" I mentioned control characters of regular > expressions i.e. one of ".^$()?[]{}\|+*" but not non ascii-127 > characters. > > For a workaround you simply have to "mangle" those using an escape > control character: > > REGEXCHAR = ".^$()?[]{}\\|+*" > def mangle(s): > pattern = [] > for c in s: > if c in REGEXCHAR: > pattern.append("\\") > pattern.append(c) > return "".join(pattern) > What's wrong with re.escape()? Have you not read (a) my response to Paddy's first posting (b) the manual? From onurb at xiludom.gro Fri Jun 16 10:29:17 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 16 Jun 2006 16:29:17 +0200 Subject: Python is fun (useless social thread) ;-) In-Reply-To: <1150387471.341026.260090@c74g2000cwc.googlegroups.com> References: <1150381872.958342.180420@p79g2000cwp.googlegroups.com> <44917776$1@nntp0.pdx.net> <1150387471.341026.260090@c74g2000cwc.googlegroups.com> Message-ID: <4492c03e$0$9271$636a55ce@news.free.fr> BartlebyScrivener wrote: >>>I'd like something a bit like a module, >>>but I'd like to make several of them, >>>and not have them interfere with each other." > > > Thank you. I sense what you are saying, but at this point I'd be > thinking, "Why not just make several modules?" :) Because you want an unknown number of the *same* module ?-) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From david.nospam.hopwood at blueyonder.co.uk Mon Jun 26 10:49:12 2006 From: david.nospam.hopwood at blueyonder.co.uk (David Hopwood) Date: Mon, 26 Jun 2006 14:49:12 GMT Subject: What is Expressiveness in a Computer Language [off-topic] In-Reply-To: References: <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150908952.804184.218990@r2g2000cwb.googlegroups.com> <1150991074.705803.211570@m73g2000cwd.googlegroups.com> <1151244628.566060.40500@p79g2000cwp.googlegroups.com> <1151252226.104247.62960@b68g2000cwa.googlegroups.com> <1151257480.183097.165640@b68g2000cwa.googlegroups.com> Message-ID: Matthias Blume wrote: > I agree with Bob Harper about safety being language-specific and all > that. But, with all due respect, I think his characterization of C is > not accurate. [...] > AFAIC, C is C-unsafe by Bob's reasoning. Agreed. > Of course, C can be made safe quite easily: > > Define a state "undefined" that is considered "safe" and add a > transition to "undefined" wherever necessary. I wouldn't say that was "quite easy" at all. C99 4 #2: # If a "shall" or "shall not" requirement that appears outside of a constraint # is violated, the behavior is undefined. Undefined behavior is otherwise # indicated in this International Standard by the words "undefined behavior" # *or by the omission of any explicit definition of behavior*. [...] In other words, to fix C to be a safe language (compatible with Standard C89 or C99), you first have to resolve all the ambiguities in the standard where the behaviour is *implicitly* undefined. There are a lot of them. -- David Hopwood From grante at visi.com Thu Jun 15 11:43:12 2006 From: grante at visi.com (Grant Edwards) Date: Thu, 15 Jun 2006 15:43:12 -0000 Subject: Numerics, NaNs, IEEE 754 and C99 References: <12904mjhl493t49@corp.supernews.com> <1290aik50hmk94a@corp.supernews.com> <4490329e$0$12356$636a55ce@news.free.fr> <12917f6jp7u90f8@corp.supernews.com> <44912058$0$29674$636a55ce@news.free.fr> <1292p7s46ef5off@corp.supernews.com> Message-ID: <129300g5np02c8a@corp.supernews.com> On 2006-06-15, Nick Maclaren wrote: >|>> Firstly, a FAR more common assumption is that integers wrap in twos' >|>> complement - Python does not do that. >|> >|> It used to, and I sure wish there was still a way to get that >|> behavior back. Now I have to do all sorts of bitwise ands that >|> I didn't use to. > > Given that it is perhaps THE most common cause of severe > failure in large scientific codes, I don't agree that it > should be the default. A 'twos complement' class would be > quite reasonable. Since Python went to non-fixed-length integers, a couple of those classes have been written. I tried one of them and it was rather clumsy. There was no conversion/coercion between different widths or between fixed-width integers and "regular" integers. That mean you had to call a constructor even if all you wanted to do was add 2 to a value. >|> > Secondly, it is NOT incompatible with IEEE 754, which is a >|> > pure hardware standard. All it does is to trap the exception >|> > and take appropriate action (as permitted by that standard). >|> >|> There are two allowed (selectable?) behaviors for 1/0: trap and >|> Inf. > > Er, no. The second is REQUIRED to set an exception flag, But it's not required to generate a trap according to my reading of the spec. > which IEEE 754 assumes that the code will test and take > appropriate action (which can be anything, including aborting > the program and replacing it by a NaN). See > http://www.cs.berkeley.edu/~wkahan/JAVAhurt.pdf IEEE Std 754-1985, subclause 7.2 - Division by Zero "If the divisor is zero and the dividend is a finite nonzero number, then the division by zero shall be signaled. The result, when no trap occurs, shall be a correctly signed (infinity symbol)(6.3)." To me it looks like the spec specifically allows for a case where "no trap occurrs" and the result is Inf. >|> As long as I can get IEEE 754 results, that's cool. I'd prefer >|> if Python just let the HW do it's thing when possible. > > Including crash and burn? No. :) > Seriously. I don't think that you realise just how many > layers of fixup there are on a typical "IEEE 754" system, and > how many variations there are even for a single platform. Probably not. -- Grant Edwards grante Yow! My face is new, my at license is expired, and I'm visi.com under a doctor's care!!!! From jo at durchholz.org Thu Jun 22 16:01:52 2006 From: jo at durchholz.org (Joachim Durchholz) Date: Thu, 22 Jun 2006 22:01:52 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <0%Wlg.3521$MF6.947@tornado.socal.rr.com> <44992e6c$0$664$bed64819@news.gradwell.net> Message-ID: Andreas Rossberg schrieb: > (Btw, Pascal did not have it either, AFAIK) Indeed. Some Pascal dialects have it. Regards, Jo From steve at holdenweb.com Mon Jun 12 03:07:38 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 12 Jun 2006 08:07:38 +0100 Subject: An error ? In-Reply-To: <448D06AB.3070104@gmail.com> References: <448D06AB.3070104@gmail.com> Message-ID: Bo Yang wrote: > Hi , > I am confronted with an odd question in the python cgi module ! > > Below is my code : > > import cgitb ; cgitb.enable() > import cgi > > print "Hello World !" > > How easy the script is , and the url is 202.113.239.51/vote/cgi/a.py > but apache give me a 'Server internal error !' > and the error log is : > > > [Fri Jun 16 14:06:45 2006] [error] [client 10.10.110.17] malformed > header from script. Bad header=Hello World!: a.py > > I wish somebody could help me , thanks in advance ! > You don't include any HTTP headers. This is easily corrected: try instead: import cgitb ; cgitb.enable() import cgi print "Content-Type: text\plain\n" # note the extra blank line terminate the headers print "Hello World !" regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From nmm1 at cus.cam.ac.uk Fri Jun 30 06:15:45 2006 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 30 Jun 2006 10:15:45 GMT Subject: Interprocess communication on multi-user machine References: <44a41cae$0$29145$9b4e6d93@newsread4.arcor-online.net> Message-ID: In article <44a41cae$0$29145$9b4e6d93 at newsread4.arcor-online.net>, Michael Butscher writes: |> |> this is not really Python-specific but I need it for Python. |> |> I'm wanting a method for interprocess communication which is OS- |> independent (sockets would be the normal way to go), but which works if |> multiple users use the machine at the same time so that one user has no |> access to the communication of programs of another user. You're onto a complete loser if you really mean that. But you are probably meaning Unix-like systems (including Microsoft ones), and excluding the systems that are not based on or largely cloned from Unix. You should look at the POSIX facilities, but don't rely on them without checking. Also think very carefully whether you want to separate by user or job - the latter is trickier under Unix. Regards, Nick Maclaren. From fredrik at pythonware.com Sun Jun 4 12:51:34 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 04 Jun 2006 18:51:34 +0200 Subject: mutable member, bug or ... In-Reply-To: References: Message-ID: Sambo wrote: > By accident I assigned int to a class member 'count' which was > initialized to (empty) string and had no error till I tried to > use it as string, obviously. Why was there no error on assignment > (near the end ). Python uses dynamic typing, which means that objects have types, but variables don't. A variable is just a name. I suggest reading up on variables, namespaces and classes/instances in your favourite tutorial. Python's not C++, and you won't get very far by pretending that it is. From rsutradhar_python at yahoo.com Sat Jun 17 02:20:13 2006 From: rsutradhar_python at yahoo.com (rsutradhar_python) Date: Sat, 17 Jun 2006 06:20:13 -0000 Subject: Date Subtraction Message-ID: How to subtract date which is stored in string variable? Example: date1="2006-01-10" date2="2005-12-15" date = date1 - date2 should give me 25 but problem is that date1 and date2 datatype is string which need to be conerted into date fromat which i am not able to do so please help me. From jbellis at gmail.com Sun Jun 11 18:46:53 2006 From: jbellis at gmail.com (Jonathan Ellis) Date: 11 Jun 2006 15:46:53 -0700 Subject: Get my airlines boarding pass In-Reply-To: <1150056721.796442.130690@m38g2000cwc.googlegroups.com> References: <1hgotbh.1vd74fb1qhzdziN%aleax@mac.com> <1149954923.868806.87270@m38g2000cwc.googlegroups.com> <1149969384.065683.224810@f6g2000cwb.googlegroups.com> <1150056721.796442.130690@m38g2000cwc.googlegroups.com> Message-ID: <1150066013.127303.204880@m38g2000cwc.googlegroups.com> KenAggie wrote: > I posted it on activestate already ... sorry. I would like for the > geniuses here to use it and improve upon it so here is the activestate > post URL: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496790 Whoa. Check out BeautifulSoup -- you will never write HTMLParser-based screen scrapers again. :) -Jonathan From dev at null.com Tue Jun 27 16:38:22 2006 From: dev at null.com (Mike Currie) Date: Tue, 27 Jun 2006 13:38:22 -0700 Subject: Python UTF-8 and codecs References: Message-ID: <5Hgog.627$Gv.173@fed1read09> I did make a mistake, it should have been 'wU'. The starting data is ASCII. What I'm doing is data processing on files with new line and tab characters inside quoted fields. The idea is to convert all the new line and characters to 0x85 and 0x88 respectivly, then process the files. Finally right before importing them into a database convert them back to new line and tab's thus preserving the field values. Will python not handle the control characters correctly? "Serge Orlov" wrote in message news:mailman.7516.1151440194.27775.python-list at python.org... > On 6/27/06, Mike Currie wrote: >> I'm trying to write out files that have utf-8 characters 0x85 and 0x08 in >> them. Every configuration I try I get a UnicodeError: ascii codec can't >> decode byte 0x85 in position 255: oridinal not in range(128) >> >> I've tried using the codecs.open('foo.txt', 'rU', 'utf-8', >> errors='strict') >> and that doesn't work and I've also try wrapping the file in an >> utf8_writer >> using codecs.lookup('utf8') >> >> Any clues? > > Use unicode strings for non-ascii characters. The following program > "works": > > import codecs > > c1 = unichr(0x85) > f = codecs.open('foo.txt', 'wU', 'utf-8') > f.write(c1) > f.close() > > But unichr(0x85) is a control characters, are you sure you want it? > What is the encoding of your data? From deets at nospam.web.de Mon Jun 19 08:56:39 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 19 Jun 2006 14:56:39 +0200 Subject: comparing two arrays References: <1150721380.948808.231760@h76g2000cwa.googlegroups.com> Message-ID: <4fnlbiF1j83q2U1@uni-berlin.de> Sheldon wrote: > Hi, > > I have two arrays that are identical and contain 1s and zeros. Only the Obviously they aren't identical. They may be of same size. > ones are valid and I need to know where both arrays have ones in the > same position. I thought logical_and would work but this example proves > otherwise: >>>> a = [0,1,2,5,6,6] >>>> b = [5,4,1,6,4,6] >>>> Numeric.logical_and(a==6,b==6) > 0 >>>> Numeric.where(a==b,1,0) > 0 >>>> Numeric.where(a==6 and b==6,1,0) > 0 > > The where() statement is also worhtless here. Does anyone have any > suggestion on how to do this? print [i for i, _ in enumerate((None for v in zip(a, b) where v == (1,1)))] should give you the list of indices. Diez From sjmachin at lexicon.net Fri Jun 23 18:59:35 2006 From: sjmachin at lexicon.net (John Machin) Date: Sat, 24 Jun 2006 08:59:35 +1000 Subject: Unicode problem with exec In-Reply-To: References: Message-ID: <449C7257.8020606@lexicon.net> On 23/06/2006 9:06 PM, Thomas Heller wrote: > I'm using code.Interactive console but it doesn't work correctly > with non-ascii characters. I think it boils down to this problem: > > Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)] on > win32 > Type "help", "copyright", "credits" or "license" for more information. >>>> print u"?" This is utterly useless for diagnostic purposes. What you see is NOT what you've got. Use repr(). What you've got, as the error message says, is u'\x84' which is not u"\N{LATIN SMALL LETTER A WITH DIAERESIS}", it is a control character. See below. > ? >>>> exec 'print u"?"' > Traceback (most recent call last): > File "", line 1, in ? > File "", line 1, in ? > File "c:\python24\lib\encodings\cp850.py", line 18, in encode > return codecs.charmap_encode(input,errors,encoding_map) > UnicodeEncodeError: 'charmap' codec can't encode character u'\x84' in > position 0: character maps to >>>> ^Z > > Why does the exec call fail, and is there a workaround? > Executive summary: The exec statement didn't fail, it was the print statement trying to print, to your CP850 console, a unicode char that doesn't exist in CP850. This happened because you copied a character whose repr() is '\x84' from your MS-DOS console and pasted it into 'u""' :-) Details: Windows XP, in a console screen: Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. |>> uc = u"\N{LATIN SMALL LETTER A WITH DIAERESIS}" |>> uc u'\xe4' <<== agrees with Unicode book |>> encoded = uc.encode('cp850') >>> encoded '\x84' <<== agrees with http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/PC/CP850.TXT |>> print uc ? <<== looks like LATIN SMALL LETTER A WITH DIAERESIS, as expected |>> print encoded ? <<== looks like LATIN SMALL LETTER A WITH DIAERESIS, as expected |>> print u"\x84" Traceback (most recent call last): File "", line 1, in ? File "c:\python24\lib\encodings\cp850.py", line 18, in encode return codecs.charmap_encode(input,errors,encoding_map) UnicodeEncodeError: 'charmap' codec can't encode character u'\x84' in position 0: character maps to <<== as expected Looks like Python is working fine to me ... So, what's happening? Look at this: |>> char1 = u"?" <<= corresponds to your "print" |>> char2 = "?" <<= corresponds to your exec -- which was given a STRING constant, like this, not a Unicode constant. Character in char1 was copied from DOS console. Second line was obtained by DOS console editing of copy of first line. |>> char1 u'\xe4' |>> char2 '\x84' <<= Aha! What you have done is effectively: exec 'print u"\x84"' Workaround/kludge/bypass: exec u'print u"?"' .....^ Much better: embed non-ASCII characters in source code *ONLY* when you have a proper coding header: http://www.python.org/dev/peps/pep-0263/ HTH, John From fredrik at pythonware.com Sat Jun 10 03:10:24 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 10 Jun 2006 09:10:24 +0200 Subject: Killing a thread In-Reply-To: <448A0D8A.4000008@mvista.com> References: <7c8a9a970606091338t174fbcb0wc73cdb8b385f8ccd@mail.gmail.com> <7c8a9a970606091354u73308bf8o2758eea5ef690c39@mail.gmail.com> <1149889827.2754.6.camel@kenshin.CASA> <448A0D8A.4000008@mvista.com> Message-ID: Carl J. Van Arsdall wrote: > Are there any plans in the future to add the capability to kill threads > from the outside? it cannot be done in a portable way, so that's not very likely. > I noticed that each python thread spawns a new interpreter are you sure? what Python version and OS is this? From knoerrich at hagen-partner.de Tue Jun 27 06:37:52 2006 From: knoerrich at hagen-partner.de (=?iso-8859-15?Q?Peter_Kn=F6rrich?=) Date: Tue, 27 Jun 2006 12:37:52 +0200 Subject: Inconsistent float behaviour on "inf" - current state? Message-ID: Hello, I've found another inconsistency, and looking through the list archives I can find mentions of funky stuff like print float('inf') giving Infanity with Python 1.5.2 on Solaris 7 in 2001, and a couple closed bug reports on why "float('inf')" isn't supported everywhere, and I understand the underlying problem: libc simply isn't that good - never mind standard - with regard to floats. However, seeing how Python does a great job with long ints by using something better than standard libc, I fail to see how reliance on libc should be a reason not to provide at least consistency: Why does conversion from a long constant not use the same library function that conversion from a long string would use? a = float(1234....298299300) -> OverflowError: long int too large to convert to float a = float('1234....298299300') -> inf, which led to silly errors in SQL (table has no column 'inf') a = inf -> NameError: name 'inf' is not defined a = float('inf') -> inf Now, I could understand how that may need some changes on lexing the source code, so I'm not actually opening more bugs having found workarounds for my own troubles here (quality guys insisting on entering silly numbers, hah, try that with a 50 character input field limit!). Still, I'm interested to hear what the current state of affairs is on using possibly inconsistent libc for floats? Bye, Peter Kn?rrich From yalexfan at gmail.com Sun Jun 18 02:01:10 2006 From: yalexfan at gmail.com (Fan Zhang) Date: Sun, 18 Jun 2006 14:01:10 +0800 Subject: Detecting key presses References: <1150607857.186185.183130@g10g2000cwb.googlegroups.com> Message-ID: <200606181400577625818@gmail.com> On 2006-06-18 13:20:06, tylertacky write: >Ok, I'm pretty new to python, so this might be a stupid question. I'm >trying to write a simple text-based pong clone, and I can't figure out >how to read key presses to move the paddles. I just need something that >does the same thing as getch() and kbhit(). I can't use those because >their windows only, and I'm running Linux. > >Someone suggested using curses, but that does crazy things with my >output, and leaves the terminal unusable after the program closes. > >-- >http://mail.python.org/mailman/listinfo/python-list The python.org site has a faq about getting keystroke. It uses termios and fcntl modules. Here's the link: http://www.python.org/doc/faq/library/#how-do-i-get-a-single-keypress-at-a-time Hope it can help you! ----- Fan Zhang From grante at visi.com Thu Jun 1 15:37:13 2006 From: grante at visi.com (Grant Edwards) Date: Thu, 01 Jun 2006 19:37:13 -0000 Subject: integer to binary... References: <1149189570.376091.319890@j55g2000cwa.googlegroups.com> Message-ID: <127ugf9jgu7av18@corp.supernews.com> On 2006-06-01, nicolasg at gmail.com wrote: > does anyone know a module or something to convert numbers like integer > to binary format ? They _are_ in binary format. > for example I want to convert number 7 to 0111 so I can make some > bitwise operations... Just do it: >>> 7 & 3 3 >>> 7 | 8 15 -- Grant Edwards grante Yow! QUIET!! I'm being at CREATIVE!! Is it GREAT visi.com yet? It's s'posed to SMOKEY THE BEAR... From egodet at equisys.com Tue Jun 20 10:37:06 2006 From: egodet at equisys.com (egodet at equisys.com) Date: 20 Jun 2006 07:37:06 -0700 Subject: Debugging C++ code called from Python 2.2 with Visual Studio.NET In-Reply-To: <1150812006.311261.99140@y41g2000cwy.googlegroups.com> References: <1150799634.503338.302780@b68g2000cwa.googlegroups.com> <1150812006.311261.99140@y41g2000cwy.googlegroups.com> Message-ID: <1150814226.544579.178260@c74g2000cwc.googlegroups.com> I can't seem to be able to download http://www.python.org/ftp/python/2.2/Python-2.2.tgz. Do you know if I can find it elsewhere? Thanks, Emmanuel From dingbat at codesmiths.com Wed Jun 21 12:56:45 2006 From: dingbat at codesmiths.com (Andy Dingley ) Date: 21 Jun 2006 09:56:45 -0700 Subject: [newbie] Iterating a list in reverse ? Message-ID: <1150909005.604896.122290@m73g2000cwd.googlegroups.com> Python newbie: I've got this simple task working (in about ten different ways), but I'm looking for the "favoured" and "most Python like" way. Forwards I can do this for t in listOfThings: print t Now how do I do it in reverse? In particular, how might I do it if I only wanted to iterate part-way through (with a conditional test and a break), or if I had a large list ? reverse( listOfThings ) for t in listOfThings: print t As reverse() operates in-place I often can't do this. I'm also (slightly) concerned about possible inefficiency issues of manipulating a big list just to scan a peek at its tail. Currently I'm doing this: for i in range( len( listOfThings )-1, 0, -1): t = listOfThings [i] print t Is this the optimum ? Would xrange() be a better choice (and when is it a "big" list) ? Thanks for any guidance From rossberg at ps.uni-sb.de Wed Jun 21 05:06:01 2006 From: rossberg at ps.uni-sb.de (Andreas Rossberg) Date: Wed, 21 Jun 2006 11:06:01 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <4fo19aF1jsudeU1@individual.net> Message-ID: David Hopwood wrote: > > Oh, but it *does* make sense to talk about dynamic tagging in a statically > typed language. It even makes perfect sense to talk about dynamic typing in a statically typed language - but keeping the terminology straight, this rather refers to something like described in the well-known paper of the same title (and its numerous follow-ups): Martin Abadi, Luca Cardelli, Benjamin Pierce, Gordon Plotkin Dynamic typing in a statically-typed language. Proc. 16th Symposium on Principles of Programming Languages, 1989 / TOPLAS 13(2), 1991 Note how this is totally different from simple tagging, because it deals with real types at runtime. - Andreas From marshall.spight at gmail.com Mon Jun 19 18:08:38 2006 From: marshall.spight at gmail.com (Marshall) Date: 19 Jun 2006 15:08:38 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150749670.053433.242210@p79g2000cwp.googlegroups.com> Message-ID: <1150754918.338770.89870@i40g2000cwc.googlegroups.com> Chris Smith wrote: > Marshall wrote: > > While I am quite sympathetic to this point, I have to say that > > this horse left the barn quite some time ago. > > I don't think so. Perhaps it's futile to go scouring the world for uses > of the phrase "dynamic type" and eliminating them. It's not useless to > point out when the term is used in a particularly confusing way, though, > as when it's implied that there is some class of "type errors" that is > strictly a subset of the class of "errors". Terminology is often > confused for historical reasons, but incorrect statements eventually get > corrected. That's fair. One thing that is frustrating to me is that I really want to build an understanding of what dynamic typing is and what its advantages are, but it's difficult to have a productive discussion on the static vs. dynamic topic. Late binding of every function invocation: how does that work, what are the implications of that, what does that buy you? I have come to believe that the two actually represent very different ways of thinking about programming. Which goes a long way to explaining why there are such difficulties communicating. Each side tries to describe to the other how the tools and systems they use facilitate doing tasks that don't exist in the other side's mental model. > > PS. Hi Chris! > > Hi! Where are you posting from these days? I'm mostly on comp.databases.theory, but I also lurk on comp.lang.functional, which is an awesome group, and if you're reading Pierce then you might like it too. Marshall From michael.f.ellis at gmail.com Thu Jun 1 12:05:04 2006 From: michael.f.ellis at gmail.com (michael.f.ellis at gmail.com) Date: 1 Jun 2006 09:05:04 -0700 Subject: An oddity in list comparison and element assignment In-Reply-To: <1149177617.985251.74560@c74g2000cwc.googlegroups.com> References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> Message-ID: <1149177904.203543.285010@i39g2000cwa.googlegroups.com> oops! last sentence of 2nd paragraph in previous message should read "If my expectation is NOT met ..." From k.retheesh at gmail.com Fri Jun 9 14:38:51 2006 From: k.retheesh at gmail.com (k.retheesh at gmail.com) Date: 9 Jun 2006 11:38:51 -0700 Subject: TypeError: unsubscriptable object In-Reply-To: References: <1149874726.470436.279200@i40g2000cwc.googlegroups.com> Message-ID: <1149878331.500752.8170@j55g2000cwa.googlegroups.com> So wat should I do ?? K.S.Sreeram wrote: > k.retheesh at gmail.com wrote: > > print template % (ID, IID, Function[:10], Description[:10], > > ErrorNumber, StatusCD) > > TypeError: unsubscriptable object > > It means either 'Function' or 'Description' is not a sequence. > Try inserting print statements to see what values they are. > > e.g: > > a = 2 > a[:10] > > will give me an 'unsubscriptable object' > > Regards > Sreeram > > > --------------enig08E562E3E8ED90BF5BC3C92B > Content-Type: application/pgp-signature > Content-Transfer-Encoding: base64 > Content-Disposition: inline; > filename="signature.asc" > Content-Description: OpenPGP digital signature > X-Google-AttachSize: 253 From istvan.albert at gmail.com Wed Jun 21 22:52:36 2006 From: istvan.albert at gmail.com (Istvan Albert) Date: 21 Jun 2006 19:52:36 -0700 Subject: new python icons for windows References: <1150811271.282850.321510@p79g2000cwp.googlegroups.com> <1150901231.837272.129040@g10g2000cwb.googlegroups.com> Message-ID: <1150944756.720958.78670@u72g2000cwu.googlegroups.com> and-google at doxdesk.com wrote: > > For example it resembles the icon for text files. > > This is intentional: to make it obvious that .py files are the > readable, editable scripts, contrasting with .pyc's binary gunk - I think this is a mistake, it does not seem obious, all it does is just blends in and does not separate the python files from regular text files. As I said before I think your icons are neat, the design is clean and it looks very professional. Unfortunately, in my experience, this design did not allow me to easily pick out the python files from the text files. Also the black icons for pyc files are far more visible and stand out much more than the white ones. If anything I wish the pyc had no icons at all or was invisible, I mean how often do you need to do any work with pyc files... From jjl at pobox.com Thu Jun 1 18:08:25 2006 From: jjl at pobox.com (John J. Lee) Date: 01 Jun 2006 22:08:25 +0000 Subject: urllib2 and HTTP 302 References: <4476C7A6.5040506@designaproduct.biz> Message-ID: <8764jkedgm.fsf@pobox.com> Laszlo Nagy writes: [...] > how can I return the redirection URL? > I tried to get this information from the exception but I could not. Is > it possible to read it from the openerdirector? > Any suggestions? > > > try: > self.post_multipart( > url, > [('uploadType','Inventory')], > [('uploadFileName','inv.txt',fdata)] > ) > except urllib2.HTTPError, e: > if e.code == 302: > return "I would like to get the URL to be redirected > to...." > else: > raise redirected_url = e.geturl() John From diffuser78 at gmail.com Thu Jun 15 10:04:11 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 15 Jun 2006 07:04:11 -0700 Subject: GUI in Python using wxGlade Message-ID: <1150380251.279150.73620@u72g2000cwu.googlegroups.com> I recently tried a hand at wxGlade and was happy to see it designs a GUI for you in minutes. I am a newbie Python coder. I am not completely aware of GUI programming. I can easily make menubars etc but I am not too sure sure how to get more windows poppping to get more information. I mean when you click something, a new windows would open and ask for input like that. Since I am using wxGlade and wxPython....can you suggest me a quick tutorial for GUI programming. Every help is appreciate, Thanks From sreeram at tachyontech.net Sat Jun 3 09:41:57 2006 From: sreeram at tachyontech.net (K.S.Sreeram) Date: Sat, 03 Jun 2006 19:11:57 +0530 Subject: image lib & Qt4 In-Reply-To: References: <1149173540.470829.34940@c74g2000cwc.googlegroups.com> <4e8haiF1dp2heU1@uni-berlin.de> <1149180814.585713.209640@i39g2000cwa.googlegroups.com> <44818202.8060607@tachyontech.net> Message-ID: <448191A5.1050502@tachyontech.net> My bad. I was hacking the code trying to support RGBA mode images, and inadvertently i tried im.tostring("raw","BGRX") on the RGBA mode image. So BGRX does indeed work for RGB mode images. While trying to support RGBA mode images, i realized that a BGRA raw mode is needed for working with QImage. It doesn't seem to be supported by PIL. Any workarounds? Regards Sreeram Fredrik Lundh wrote: > $ python > >>> import Image > >>> im = Image.new("RGB", (100, 100)) > >>> print len(im.tostring("raw", "BGRX")) > 40000 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 260 bytes Desc: OpenPGP digital signature URL: From akameswaran at gmail.com Thu Jun 1 14:16:20 2006 From: akameswaran at gmail.com (akameswaran at gmail.com) Date: 1 Jun 2006 11:16:20 -0700 Subject: ideas for programs? In-Reply-To: References: Message-ID: <1149185780.594711.37530@y43g2000cwc.googlegroups.com> James Stroud wrote: > A digest of the major points summarizing the consensus opinion: > > Thomas Bartkus wrote: > > Python is your tool to put your expertise on a computer. Skill with > Python, > > or any computer language for that matter, counts for little. > > And akameswaran at gmail.com wrote: > > As far as employment. I come from a java background, and that seems > > the only language I can pay the bills with:). Particularly in the US > > paid python jobs are hard to come by. > > James Hmm, I'm not clear what you were trying to say when you put these two quotes together. They seem actually opposed to each other. Despite what I wrote, Thomas is making a more accurate statement. However, Java EXPERIENCE does look good on my resume - and seems to carry a lot more weight than python experience. I don't like that fact - but let's face it, a lot of HR departments look at things just that way. From jim at trainplayer.com Thu Jun 22 08:31:02 2006 From: jim at trainplayer.com (Jim) Date: 22 Jun 2006 05:31:02 -0700 Subject: bug in Makepy In-Reply-To: References: <1150972502.331130.138410@b68g2000cwa.googlegroups.com> Message-ID: <1150979462.521276.261960@y41g2000cwy.googlegroups.com> > This only works if the hexadecimal representation has digits in [A-F]. > What if the stored value is 10, but in hexadecimal? I don't get what you mean. If the value is "10, but in hexadecimal", isn't that A? The problem my fix solves is where the folder under the typelib guid is named something like "a.0." It does what I need. If you see a case it doesn't handle, maybe you could propose a better fix? -- Jim From michele.simionato at gmail.com Fri Jun 16 03:40:51 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 16 Jun 2006 00:40:51 -0700 Subject: a good programming text editor (not IDE) In-Reply-To: References: <_xgkg.2317$No6.48542@news.tufts.edu> <1150402733.116243.9680@y41g2000cwy.googlegroups.com> Message-ID: <1150443651.924324.96750@y41g2000cwy.googlegroups.com> Fredrik Lundh wrote: > BartlebyScrivener wrote: > > > Emacs must be dying if this thread could get all the way to 20 with > > nobody arguing with the vi folks. > > hints: 1) editor wars are so last century. 2) emacs has already won. > > Yep, there is no much point about arguing for Emacs since everything is already explained here: http://www.dina.kvl.dk/~abraham/religion Michele Simionato From Bulkan at gmail.com Sat Jun 24 10:35:00 2006 From: Bulkan at gmail.com (placid) Date: 24 Jun 2006 07:35:00 -0700 Subject: Python and cellular automata (It works this time!) In-Reply-To: <1151158859.422817.239810@y41g2000cwy.googlegroups.com> References: <1151158859.422817.239810@y41g2000cwy.googlegroups.com> Message-ID: <1151159700.344882.304100@g10g2000cwb.googlegroups.com> defcon8 wrote: > I thought people would be interested in this little script I wrote to > reproduce the 256 simple automata that is shown in the first chapters > of "A New Kind of Science". You can see a few results without running > the script, at http://cooper-j.blogspot.com . And here is the code (You > will need PIL (Python Imaging Library)): > > import Image > > # Contract: > # To simulate simple cellular automata. > > class calculations: > def __init__(self,which): > self.against = self.array_maker_2()[which] > self.check = self.array_maker_1() > self.array = self.array_maker_3(311) > self.calculator() > > def binary(self, n, size): ## This is the Int -> str(BINARY) > converter > assert n >= 0 > bits = [] > while n: > bits.append('01'[n&1]) > n >>= 1 > bits.reverse() > result = ''.join(bits) or '0' > for iteration in range(len(result),size): > result = "0" + result > return result > > def array_maker_1(self): # This makes the array that represents the > 8 different permutations of 3 cells. Itself, its left and its right. > return [self.binary(n, 3) for n in range(8)] > > def array_maker_2(self): # This makes the array that represents > every single different rule. If for instance the second element in one > # of these rules is 1, then the corresponding permutation that may > be found in the result array (array_maker_3), will be 1 (black). > return [self.binary(n, 8) for n in range(256)] > > def array_maker_3(self, y): # This is the array for all the > results. The automaton starts from the middle of the first row > x = [["0" for x in range((2*y)+1)] for n in range(y)] > x[0][(2*y+1)/2] = "1" > return x > > def calculator(self): # This cycles over all of the cells, and > scans one row at a time, and changes the next row according to the > current cell. > self.buff_result = ["0","0","0"] # This is the current permutation > buffer to be checked against the corresponding arrays. > for i in range(len(self.array)-1): > for j in range(1, len(self.array[0])-1): > self.step1(j,i) > self.step2(j,i) > self.step3(j,i) > y = self.check.index(''.join(self.buff_result)) > self.array[i+1][j] = self.against[y] > > # The steps update the result buffer. > def step1(self, step, y): > self.buff_result[0] = self.array[y][step-1] > > def step2(self, step, y): > self.buff_result[1] = self.array[y][step] > > def step3(self, step, y): > self.buff_result[2] = self.array[y][step+1] > > for number in range(256): > objo = calculations(number) > x = objo.array > y = [] > for num,zo in enumerate(x): > for com,wo in enumerate(zo): > x[num][com] = int(wo) > > nim = Image.new("1", (623,311)) > > for n in x: #converting the array of arrays into a single array so > putdata can take it. > for p in n: > y.append(p) > nim.putdata(y) > nim.resize((6230/2,3110/2)).save("output" + str(number) + ".png") > print number > > Ah, celular automata! Another of my on-off interest! I shall run this as soon as posible. From steve at holdenweb.com Wed Jun 28 04:24:38 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 28 Jun 2006 09:24:38 +0100 Subject: a class variable question In-Reply-To: <9PKdnb3Sff2Tgj_ZnZ2dnUVZ_uudnZ2d@speakeasy.net> References: <1151474768.546012.254380@p79g2000cwp.googlegroups.com> <9PKdnb3Sff2Tgj_ZnZ2dnUVZ_uudnZ2d@speakeasy.net> Message-ID: <44A23CC6.2000105@holdenweb.com> Erik Max Francis wrote: [...] > All you're doing in your example is setting a local variable inside the > func1 method, which has no effect. > I think EMF was thinking, but failed to write, "outside the function" at the end of that sentence ;-) regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From eval.apply at gmail.com Thu Jun 22 13:43:42 2006 From: eval.apply at gmail.com (Joe Marshall) Date: 22 Jun 2006 10:43:42 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> Message-ID: <1150998222.352746.65520@i40g2000cwc.googlegroups.com> Chris Smith wrote: > Joachim Durchholz wrote: > > Assume a language that > > a) defines that a program is "type-correct" iff HM inference establishes > > that there are no type errors > > b) compiles a type-incorrect program anyway, with an establishes > > rigorous semantics for such programs (e.g. by throwing exceptions as > > appropriate). > > So the compiler now attempts to prove theorems about the program, but > once it has done so it uses the results merely to optimize its runtime > behavior and then throws the results away. I'd call that not a > statically typed language, then. You're assuming that type-correctness is an all-or-nothing property (well, technically it *is*, but bear with me). What if the compiler is unable to prove a theorem about the entire program, but *can* prove a theorem about a subset of the program. The theorems would naturally be conditional, e.g. `Provided the input is an integer, the program is type-safe', or time-bounded, e.g. `Until the program attempts to invoke function FOO, the program is type-safe.' Of course, we could encode that by restricting the type of the input and everything would be copacetic, but suppose there is a requirement that floating point numbers are valid input. For some reason, our program is not type-safe for floats, but as a developer who is working on the integer math routines, I have no intention of running that code. The compiler cannot prove that I won't perversely enter a float, but it can prove that if I enter an integer everything is type-safe. I can therefore run, debug, and use a subset of the program. That's the important point: I want to run broken code. I want to run as much of the working fragments as I can, and I want a `safety net' to prevent me from performing undefined operations, but I want the safety net to catch me at the *last* possible moment. I'm not playing it safe and staying where the compiler can prove I'll be ok. I'm living dangerously and wandering near the edge where the compiler can't quite prove that I'll fail. Once I've done the major amount of exploratory programming, I may very well want to tighten things up. I'd like to have the compiler prove that some mature library is type-safe and that all callers to the library use it in a type-correct manner. I'd like the compiler to say `Hey, did you know that if the user enters a floating point number instead of his name that your program will crash and burn?', but I don't want that sort of information until I'm pretty sure about what I want the program to do in the normal case. From george.sakkis at gmail.com Mon Jun 19 16:43:00 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 19 Jun 2006 13:43:00 -0700 Subject: Calling every method of an object from __init__ References: <1150746953.156851.92820@r2g2000cwb.googlegroups.com> Message-ID: <1150749780.298537.272540@c74g2000cwc.googlegroups.com> Rob Cowie wrote: > Hi all, > > Is there a simple way to call every method of an object from its > __init__()? > > For example, given the following class, what would I replace the > comment line in __init__() with to result in both methods being called? > I understand that I could just call each method by name but I'm looking > for a mechanism to avoid this. > > class Foo(object): > def __init__(self): > #call all methods here > def test(self): > print 'The test method' > def hello(self): > print 'Hello user' > > Thanks, > > Rob C First off, calling *every* method of an object is most likely a bad idea. A class has special methods defined automatically and you probably don't intend calling those. The way to go is have a naming convention for the methods you want to call, e.g. methods starting with "dump_". In this case you could use the inspect module to pick the object's methods and filter out the irrelevant methods: import inspect class Foo(object): def __init__(self): for name,method in inspect.getmembers(self,inspect.ismethod): if name.startswith('dump_'): method() def dump_f(self): print 'The test method' def dump_g(self): print 'Hello user' if __name__ == '__main__': Foo() George From jweida at gmail.com Tue Jun 13 09:15:59 2006 From: jweida at gmail.com (Jerry) Date: 13 Jun 2006 06:15:59 -0700 Subject: What's wrong in this HTML Source file of a Bank In-Reply-To: <1150196896.819711.154640@c74g2000cwc.googlegroups.com> References: <1150196896.819711.154640@c74g2000cwc.googlegroups.com> Message-ID: <1150204559.415713.288600@h76g2000cwa.googlegroups.com> This really isn't the place to ask what is wrong with code that isn't Python, especially of someone else's website. There is absolutely no way for us to tell what is happening on the server side. You should contact the maintainer of the site and let them know you are having problems. -- Jerry From dieter at handshake.de Thu Jun 29 13:25:30 2006 From: dieter at handshake.de (Dieter Maurer) Date: 29 Jun 2006 19:25:30 +0200 Subject: [Pyrex] pyrex functions to replace a method (Re: replace a method in class: how?) References: <44A06A6B.6010200@bryant.edu> <44A11564.9030009@bryant.edu> Message-ID: Greg Ewing writes on Wed, 28 Jun 2006 11:56:55 +1200: >... > I have suggested that builtin functions should be > given the same method-binding behaviour as interpreted > functions. The idea wasn't rejected out of hand, but > I don't think anything has been done about it yet. You can use: def wrapAsMethod(to_be_wrapped) def wrapped(*args, **kw): return to_be_wrapper(*args, **kw) return wrapped and then use in your class: class ...: ... myMethod = wrapAsMethod(builtin_function) Such, this use case probably does not require a language change. Dieter From steven.bethard at gmail.com Wed Jun 7 00:18:49 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 6 Jun 2006 22:18:49 -0600 Subject: python-dev Summary for 2006-03-16 through 2006-03-31 Message-ID: python-dev Summary for 2006-03-16 through 2006-03-31 ++++++++++++++++++++++++++++++++++++++++++++++++++++ .. contents:: [The HTML version of this Summary is available at http://www.python.org/dev/summary/2006-03-16_2006-03-31] ============= Announcements ============= ------------------- Python 2.5 schedule ------------------- Python 2.5 is moving forward along its release schedule. A few issues still remain; check `PEP 356`_ for details. .. _PEP 356: http://www.python.org/dev/peps/pep-0356/ Contributing thread: - `Python 2.5 Schedule `__ ----------------------------- Python 3000 gets its own list ----------------------------- Serious work on Python 3000 has started now, with a new `python-3000 mailing list`_ for general discussion, and a `python-3000-checkins mailing list`_ for checkins to the p3yk branch. Right now, Guido wants patches to focus mainly on ripping out old code (e.g. classic classes) and wants the discussion to focus primarily on formalizing the processes for introducing Python 3000. Note that processes is what's important right now .. _python-3000 mailing list: http://mail.python.org/mailman/listinfo/python-3000 .. _python-3000-checkins mailing list: http://mail.python.org/mailman/listinfo/python-3000-checkins Contributing threads: - `Python 3000 Process `__ - `svn checkins are now split `__ - `Discussing the Great Library Reorganization `__ ----------------------------------------------- Buildbot warnings redirected to python-checkins ----------------------------------------------- The buildbot warnings, which for a short time this month appeared on python-dev, have been redirected to the python-checkins list. Contributing thread: - `[Fwd: buildbot warnings in amd64 gentoo trunk] `__ ---------------------------------------------------------- Checkins that change behavior must be accompanied by tests ---------------------------------------------------------- Though it's always been good practice to check in a test with any behavior-changing patch, Neal Norwitz has requested extra care in this area as we approach the release of Python 2.5. From this point on, *any* checkin that could change behavior should be accompanied by a corresponding test. Contributing thread: - `improving quality `__ -------------------------------------- Email 4.0 merged into Python 2.5 trunk -------------------------------------- Barry Warsaw has merged the Email 4.0 package into the Python 2.5 trunk. There's a minor incompatibility in that email.Parser is now a placeholder object instead of a module, but this should not affect the vast majority of users. Contributing thread: - `Merging email 4.0 to Python 2.5 svn trunk `__ --------------------- Python 2.4.3 released --------------------- `Python 2.4.3`_ was released on March 30th. This fixes over 50 bugs in Python 2.4.2, so now's the time to upgrade. .. _Python 2.4.3: http://www.python.org/2.4.3/ Contributing threads: - `release24-maint FREEZE for 2.4.3c1, this Thursday `__ - `RELEASED Python 2.4.3, release candidate 1 `__ - `release24-maint unfrozen, kinda `__ - `BRANCH release24-maint FREEZE from 00:00 UTC on Wednesday 29th `__ - `RELEASED Python 2.4.3, final. `__ ========= Summaries ========= -------------------------------- Including pysqlite in the stdlib -------------------------------- Anthony Baxter asked if folks were still interested in including pysqlite_ in Python 2.5 and got a pretty positive response. Gerhard H??ring said he could release pysqlite 2.2 and then merge that into Python SVN trunk. In the future, he agreed to synchronize stable changes in the standalone release with the Python core sqlite module. Accompanying these agreements was a long discussion about the pros and cons of including pysqlite, and of course an endless debate about what the new module should be named. In the end, Guido approved the inclusion of pysqlite, and it was given the name sqlite3. .. _pysqlite: http://initd.org/tracker/pysqlite/ Contributing thread: - `pysqlite for 2.5? `__ ----------------------------- Choosing a new tracker system ----------------------------- After Guido noticed that SourceForge had stopped sending him emails when a patch was assigned to him, a number of people took up a discussion about how to replace the SourceForge tracker system. There was already an existing PSF committee in charge of finding such a replacement, and they were considering roundup_, trac_ and jira_, though Bugzilla_ and RT_ had already been vetoed. There was already an instance of roundup running on python.org, and Python-Hosting and Atlassian had existing offers to host Python on Trac and Jira (respectively). There was some discussion about setting up one of these for Python 3000, but Guido thought it was too early for this. Getting the data out of SourceForge seemed to be the current sticking point, and so Fredrik Lundh wrote up `some tools`_ to do this and posted the results to http://effbot.org/tracker-20060403.zip. The discussion was then moved to the `infrastructure list`_. .. _bugzilla: http://www.bugzilla.org/ .. _jira: http://www.atlassian.com/software/jira/ .. _roundup: http://roundup.sourceforge.net/ .. _rt: http://www.bestpractical.com/rt/ .. _trac: http://www.edgewall.com/trac/ .. _python-hosting: http://www.python-hosting.com/freetrac .. _some tools: http://effbot.python-hosting.com/browser/stuff/sandbox/sourceforge/ .. _infrastructure list: http://mail.python.org/mailman/listinfo/infrastructure/ Contributing threads: - `I'm not getting email from SF when assigned a bug/patch `__ ------------------- The C-level set API ------------------- Barry Warsaw wanted to add PySet_Clear(), PySet_Update() and PySet_Next() to the C-level set API. Raymond Hettinger objected, saying that this functionality was already available through PyObject_CallMethod(s, "clear", NULL), PyObject_CallMethod(s, "update", "O", iterable) and PyObject_GetIter(s) respectively (with the last being notably safer too). Barry said that he was hoping to get some static compiler checks and easier debugging that would be lost by using PyObject_CallMethod, and to get some speedups over PyObject_GetIter() in the same way that PyDict_Next() had. Eventually, Raymond agreed to adding PySet_Clear() to the public API and to adding _PySet_Next() and _PySet_Update() to the private API. Contributing threads: - `PySet API `__ - `PySet_Next (Was: PySet API) `__ ---------------- Class decorators ---------------- Greg Ewing suggested a use-case for class decorators that could not be easily addressed with metaclasses: adding a class (but not its subclasses) to a registry. After Phillip J. Eby explained the hack that PyProtocols currently uses to make something like class decorators available, Guido suggested that someone write a PEP to add class decorators to Python 2.6. There was some discussion about moving decorators for classes inside the class for readability reasons, but Guido felt like this was too magical. No PEP had yet been produced at the time of this summary. Contributing thread: - `Class decorators `__ -------------------------------------- Python 3.0: Exception hierarchy issues -------------------------------------- A question from Nick Coghlan about where the new GeneratorExit exception should be placed sparked a new discussion about how the exception hierarchy should look. Barry Warsaw suggested that Exception should be at the top of the hierarchy with KeyboardInterrupt, GeneratorExit, SystemExit, StopIteration, Error and Warning being the next level down. All user defined errors would inherit from Error. People seemed to like this idea, but it would break backwards compatibility as users have been told for a while that their exceptions should derive from Exception, not Error. Guido voted for keeping the `PEP 352`_ semantics (with BaseException at the top of the hierarchy). Barry promised to address the hierarchy issue again on the Python 3000 list. .. _PEP 352: http://www.python.org/dev/peps/pep-0352/ Contributing thread: - `GeneratorExit inheriting from Exception `__ ------------------------------- Python 3.0: Exception statement ------------------------------- Greg Ewing asked if the except clause in Python 3.0 could be changed to:: except as : instead of the current:: except , : which can result in confusing behavior when you accidentally write:: except TypeError, ValueError: and have your TypeError instance bound to the name ValueError. Guido approved the proposal, and then the discussion veered off into the usual syntax debate, this time about whether to use "with" instead, whether to use commas or "or"s between the exception types, and whether or not to require parentheses around multiple types. Guido reiterated his support for the original proposal and shortly afterwards, the thread died. Contributing thread: - `Py3k: Except clause syntax `__ ------------------------------------------------- Adding an N-dimensional array interface to Python ------------------------------------------------- Travis E. Oliphant asked about including Numpy's `N-dimensional array interface`_ in Python core by adding a __array_struct__ member to array.array that looks like:: typedef struct { int version; /* contains the integer 2 as a sanity check */ int nd; /* number of dimensions */ char typekind; /* kind in array --- character code of typestr */ int itemsize; /* size of each element */ int flags; /* flags indicating how the data should be interpreted */ Py_intptr_t *shape; /* A length-nd array of shape information */ Py_intptr_t *strides; /* A length-nd array of stride information */ void *data; /* A pointer to the first element of the array */ } PyArrayInterface; This struct is basically unchanged over Numpy's last 10 years of evolution and Travis was hoping to finally get the interface blessed by official inclusion in Python so that PIL, PyVox, WxPython, PyOpenGL, etc. could all start using the same interface. Guido asked for a PEP, but no one seemed to feel comfortable taking the array interface definition and producing a PEP out of it. .. _N-dimensional array interface: http://numeric.scipy.org/array_interface.html Contributing thread: - `Expose the array interface in Python 2.5? `__ ------------------------------------------------ Inconsistent behavior between += and .__iadd__() ------------------------------------------------ Travis Oliphant noticed that ``a.__iadd__(b)`` and ``a += b`` currently do different things depending on the type of their arguments:: a = range(5) b = numpy.arange(5) a.__iadd__(b) assert a == [0, 1, 2, 3, 4, 0, 1, 2, 3, 4] a = range(5) b = numpy.arange(5) a += b assert a == numpy.array([0, 2, 4, 6, 8]) This apparently occurs because PyNumber_InPlaceAdd coerces ``a`` into a numeric type (a numpy.array object) before trying PySequence_InPlaceConcat. Guido suggested that += (and \*=) should check both the numeric and sequence slots before trying to coerce either arguments. Armin Rigo pointed out that this fix would require that ``listobject.__add__(intobject)`` would have to return NotImplemented instead of immediately raising an exception, but promised to provide the fix when he could. Contributing thread: - `INPLACE_ADD and INPLACE_MULTIPLY oddities in ceval.c `__ ------------------- Supported platforms ------------------- A couple different threads asked about which of the lesser-known platforms Python is supported on. Andrew MacIntyre verified that OS/2 is still being supported, Donn Cave and Francois Revol maintain the BeOS (a.k.a. Zeta OS) port, and Ralf W. Grosse-Kunstleve promised to make Tru64 machines available for testing Python if people needed them. Contributing threads: - `supported platforms OS2? `__ - `r43214 - peps/trunk/pep-3000.txt `__ - `[Fwd: Re: r43214 - peps/trunk/pep-3000.txt] `__ ---------------------------- Definition of sys.executable ---------------------------- Fredrik Lundh pointed out that when Python is embedded, the documentation for sys.executable seems suggest that it should be pointed to the executable used to start the program, not Python itself. Since this executable is no longer Python, you can no longer run sys.executable to start another Python instance. At least py2exe and PyXPCOM both depend on the current behavior, so the implementation can't be changed. Fredrik suggested adding sys.python_executable so that Python code would always be able to start another Python instance, even when embedded, but the discussion concluded without any final decisions. Contributing thread: - `towards a stricter definition of sys.executable `__ ---------------------------------------------------- Location of modules for multi-architecture platforms ---------------------------------------------------- Neal Becker reported that on x86_64, the Twisted package gets split between an architecture independent directory and an architecture dependent one, and so when Python searches for the package, it finds only the first part of the installation. There was then some discussion about how multi-architecture platforms should be properly supported. The conclusion seemed to be that the package should not be split; instead two versions of the package, one for each architecture, should be installed to two different directories. But Martin v. L??wis indicated that if anyone thought they knew better how this should work, he would accept patches. Contributing thread: - `Problem with module loading on multi-arch? `__ ----------------- PEP 299: rejected ----------------- Guido rejected `PEP 299`_, which would have encouraged the definition of a module-level __main__() function instead of the current:: if __name__ == '__main__': ... The rejection came after it was clear that writing code to work both before and after the PEP was going to be difficult, that ``import __main__`` would have started raising TypeErrors, and that the proposal didn't particularly gain much over the status quo. .. _PEP 299: http://www.python.org/dev/peps/pep-0299/ Contributing thread: - `What about PEP 299? `__ -------------------------------------- String exceptions in generator.throw() -------------------------------------- In its implementation at the time, `PEP 342`_'s throw method on generators did not support string exceptions. Phillip J. Eby wanted to add support for them, but suggested that string exceptions only be allowed if accompanied by a traceback so that string exceptions could only be passed on, not created. Guido indicated that he'd rather keep things simple and just allow string exceptions regardless of the presence of a traceback. .. _PEP 342: http://www.python.org/dev/peps/pep-0342/ Contributing thread: - `PEP 342 support for string exceptions in throw() `__ ---------------------- Generator memory leaks ---------------------- With `PEP 342`_, generators need a __del__ method to raise the GeneratorExit exception in active generators. However, the __del__ method also means the generator cannot be cleaned up when it's part of a reference cycle. Tim Peters suggested that the best solution was simply to add a special test for generators, and leave any generalizations of this idea until they're actually needed. Contributing threads: - `[Python-checkins] r43358 - python/trunk/Modules/itertoolsmodule.c `__ - `Fwd: [Python-checkins] r43358 - python/trunk/Modules/itertoolsmodule.c `__ ------------------------------------- PyMem and PyObject freeing mismatches ------------------------------------- When Python's small-object memory allocator was introduced, Python originally supported obtaining an object through PyObject_{New,NEW} and freeing it using any one of PyObject_{Free,FREE}, PyMem_{Del,DEL} or PyMem_{Free,FREE}. The hacks to support the mismatched (PyMem_*) frees were pretty horrible, and since using such mismatched calls has been forbidden for years, Tim Peters started ripping out the support code. Turns out that Python core itself had a number of mismatched calls, but Tim decided to leave the change checked in so that these kinds of issues could get fixed before the 2.5 release. Adam DePrince promised to provide a patch to identify in a debug-build when an object was freed with a mismatched call. Contributing thread: - `Prevalence of low-level memory abuse? `__ ================ Deferred Threads ================ - `reference leaks, __del__, and annotations `__ - `New-style icons, .desktop file `__ ================== Previous Summaries ================== - `Still looking for volunteer to run Windows buildbot `__ - `Making staticmethod objects callable? `__ - `Switch to MS VC++ 2005 ?! `__ - `_bsddb.c ownership `__ =============== Skipped Threads =============== - `[Python-checkins] r43041 - python/trunk/Modules/_ctypes/cfield.c `__ - `open() mode is lax `__ - `bytes thoughts `__ - `Python Library Reference top page too long `__ - `Weekly Python Patch/Bug Summary `__ - `Bug 1184112 still valid `__ - `Making runpy.run_module *not* thread-safe `__ - `Py3K thought: use external library for client-side HTTP `__ - `dealing with decorators hiding metadata of decorated functions `__ - `All green! `__ - `Py_ssize_t backwards compatibility `__ - `PY_SSIZE_T_CLEAN `__ - `Patch or feature? Tix.Grid working for 2.5 `__ - `__dict__ strangeness `__ - `Two buildbot slaves wedged `__ - `pyexpat namespace problem (Was: libbzip2 version?) `__ - `buildbot failure in sparc solaris10 gcc trunk `__ - `Test `__ - `Py3K timescale and stdlib philosophy (was: Re: Py3K thought: use...) `__ - `Py3K timescale and stdlib philosophy `__ - `Long-time shy failure in test_socket_ssl `__ - `Bug Day? `__ - `Bug Day on Friday, 31st of March `__ - `buildbot failure in x86 W2k trunk `__ - `buildbot failure in x86 XP-2 trunk `__ - `buildbot failure in x86 XP 2.4 `__ - `Documenting the ssize_t Python C API changes `__ - `r43041 - python/trunk/Modules/_ctypes/cfield.c `__ - `buildbot warnings in x86 gentoo trunk `__ - `segfaults on Mac (was Re: Long-time shy failure in test_socket_ssl)) `__ - `buildbot warnings in amd64 gentoo trunk `__ - `[Python-checkins] r43126 - in python/trunk: Doc/lib/libsocket.tex Lib/socket.py Lib/test/test_socket.py Misc/NEWS Modules/socketmodule.c `__ - `buildbot warnings in x86 XP-2 trunk `__ - `buildbot warnings in g4 osx.4 trunk `__ - `buildbot warnings in sparc solaris10 gcc trunk `__ - `Building Python for AMD64 (Windows) `__ - `buildbot warnings in x86 W2k trunk `__ - `buildbot warnings in x86 XP trunk `__ - `Patch to add timestamp() method to datetime objects `__ - `test_quopri, test_wait3, and test_popen2 `__ - `[Python-3000] Iterators for dict keys, values, and items == annoying :) `__ - `howto return malloc()ed memory from C -> Python `__ - `PEP 343: A messy contextmanager corner case `__ - `Another PEP 343 contextmanager glitch `__ - `Pickling problems are hard to debug `__ - `daily releases? `__ - `Changing -Q to warn for 2.5? `__ - `TRUNK FREEZE for 2.5a1: 0000 UTC, Thursday 30th `__ - `refleaks in 2.4 `__ - `Inconsistency in 2.4.3 for __repr__() returning unicode `__ - `Next PyPy Sprint: Tokyo 23/4 - 29/4 `__ - `[Python-checkins] TRUNK FREEZE for 2.5a1: 0000 UTC, Thursday 30th `__ - `Libref sections to put new modules under? `__ - `[Python-checkins] Cancelled! TRUNK FREEZE for 2.5a1: 0000 UTC, Thursday 30th `__ - `Error msgs for new-style division `__ - `Reminder: Bug Day this Friday, 31st of March `__ - `warnings in libffi `__ - `Name for python package repository `__ - `alpha problems -- need input `__ - `unicode vs buffer (array) design issue can crash interpreter `__ - `building sql queries in python `__ - `Win64 AMD64 (aka x64) binaries available64 `__ - `_xmlplus fixup for 2.5 `__ - `(finally) getting around to killing __private names from stdlib `__ - `new article - MapPoint and Python `__ - `xmlrpclib.binary missing? `__ - `Fwd: Python 2.5 update `__ - `2.5 trunk built for Windows available? `__ - `Nasty trunk test failures `__ - `x86 trunk MSI preview `__ - `[Python-checkins] Python Regression Test Failures all (1) `__ - `gmane.comp.python.devel.3000 has disappeared `__ ======== Epilogue ======== This is a summary of traffic on the `python-dev mailing list`_ from March 16, 2006 through March 31, 2006. It is intended to inform the wider Python community of on-going developments on the list on a semi-monthly basis. An archive_ of previous summaries is available online. An `RSS feed`_ of the titles of the summaries is available. You can also watch comp.lang.python or comp.lang.python.announce for new summaries (or through their email gateways of python-list or python-announce, respectively, as found at http://mail.python.org). This python-dev summary is the 1st written by the python-dev summary slave, Steve Bethard (Looks like I'm on my own now!). To contact me, please send email: - Steve Bethard (steven.bethard at gmail.com) Do *not* post to comp.lang.python if you wish to reach me. The `Python Software Foundation`_ is the non-profit organization that holds the intellectual property for Python. It also tries to advance the development and use of Python. If you find the python-dev Summary helpful please consider making a donation. You can make a donation at http://python.org/psf/donations.html . Every cent counts so even a small donation with a credit card, check, or by PayPal helps. -------------------- Commenting on Topics -------------------- To comment on anything mentioned here, just post to `comp.lang.python`_ (or email python-list at python.org which is a gateway to the newsgroup) with a subject line mentioning what you are discussing. All python-dev members are interested in seeing ideas discussed by the community, so don't hesitate to take a stance on something. And if all of this really interests you then get involved and join `python-dev`_! ------------------------- How to Read the Summaries ------------------------- That this summary is written using reStructuredText_. Any unfamiliar punctuation is probably markup for reST_ (otherwise it is probably regular expression syntax or a typo :); you can safely ignore it. We do suggest learning reST, though; it's simple and is accepted for `PEP markup`_ and can be turned into many different formats like HTML and LaTeX. Unfortunately, even though reST is standardized, the wonders of programs that like to reformat text do not allow us to guarantee you will be able to run the text version of this summary through Docutils_ as-is unless it is from the `original text file`_. .. _python-dev: http://www.python.org/dev/ .. _SourceForge: http://sourceforge.net/tracker/?group_id=5470 .. _python-dev mailing list: http://mail.python.org/mailman/listinfo/python-dev .. _c.l.py: .. _comp.lang.python: http://groups.google.com/groups?q=comp.lang.python .. _PEP Markup: http://www.python.org/peps/pep-0012.html .. _Docutils: http://docutils.sf.net/ .. _reST: .. _reStructuredText: http://docutils.sf.net/rst.html .. _PSF: .. _Python Software Foundation: http://python.org/psf/ .. _original text file: http://www.python.org/dev/summary/2006-03-16_2006-03-31.rst .. _archive: http://www.python.org/dev/summary/ .. _RSS feed: http://www.python.org/dev/summary/channews.rdf From gneuner2/ at comcast.net Mon Jun 19 13:33:23 2006 From: gneuner2/ at comcast.net (George Neuner) Date: Mon, 19 Jun 2006 13:33:23 -0400 Subject: What is Expressiveness in a Computer Language References: <7zpshbsvjy.fsf@app-1.diku.dk> <2006061410510511272-raffaelcavallaro@pasdespamsilvousplaitmaccom> <2006061501423327544-raffaelcavallaro@pasdespamsilvousplaitmaccom> <2006061611492350073-raffaelcavallaro@pasdespamsilvousplaitmaccom> <2006061618250975249-raffaelcavallaro@pasdespamsilvousplaitmaccom> <7zhd2himme.fsf@app-3.diku.dk> <7z8xnt8iqq.fsf@app-1.diku.dk> Message-ID: On 19 Jun 2006 13:53:01 +0200, torbenm at app-1.diku.dk (Torben ?gidius Mogensen) wrote: >George Neuner writes: > >> On 19 Jun 2006 10:19:05 +0200, torbenm at app-3.diku.dk (Torben ?gidius >> Mogensen) wrote: > >> >I expect a lot of the exploration you do with incomplete programs >> >amount to the feedback you get from type inference. >> >> The ability to write functions and test them immediately without >> writing a lot of supporting code is _far_ more useful to me than type >> inference. > >I can't see what this has to do with static/dynamic typing. You can >test individul functions in isolation is statically typed languages >too. It has nothing to do with static/dynamic typing and that was the point ... that support for exploratory programming is orthogonal to the language's typing scheme. George -- for email reply remove "/" from address From nyamatongwe+thunder at gmail.com Thu Jun 15 19:19:43 2006 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Thu, 15 Jun 2006 23:19:43 GMT Subject: a good programming text editor (not IDE) In-Reply-To: <_xgkg.2317$No6.48542@news.tufts.edu> References: <_xgkg.2317$No6.48542@news.tufts.edu> Message-ID: John Salerno: > Based on another thread, I tried out Scite, but no matter what I do it > doesn't seem to remember the window size and position, or any options I > choose (like showing line numbers). It seems to always reset itself each > time I open it. SciTE is configured by modifying options files rather than by automatically remembering your choices. If you don't like this approach then you probably won't like SciTE. Neil From runlevelten at gmail.com Sun Jun 18 20:00:52 2006 From: runlevelten at gmail.com (Ten) Date: Mon, 19 Jun 2006 01:00:52 +0100 Subject: Getting output from external programs... In-Reply-To: <4495B759.4040002@gmail.com> References: <4495B759.4040002@gmail.com> Message-ID: <200606190100.52765.runlevelten@gmail.com> On Sunday 18 June 2006 21:28, ph0b0s wrote: > Hi, > > i'm making an mp3 conversion program in Python, but am kind of stuck now. > The conversion routines work, using LAME, but now a i'm building a GUI > ?with GLADE around it, and would like to be able to show LAME's output > ?to the user in a status window in my gui.. but don't know where to > start... > > The command i use to invoke LAME is this : > command = ("lame -b " + str(bitrate) + " " + infile + " \"" + > dir_outpath + separator + outfile + "\"") > > ??? ?? ?? You can do this in various ways, ranging from the very simple and not very good from commands import getoutput x=getoutput(command) - to your more common and better popens. ie: import popen2 (stdOut, stdIn) = popen2.popen4(command) x=stdOut.readlines() - asynchronously if appropriate. How are you running the command at the moment? -- There are 10 types of people in this world, those who understand binary, and those who don't. From robert.thorpe at antenova.com Mon Jun 19 11:44:49 2006 From: robert.thorpe at antenova.com (Rob Thorpe) Date: 19 Jun 2006 08:44:49 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> Message-ID: <1150731889.008745.12180@i40g2000cwc.googlegroups.com> Chris Smith wrote: > Torben ?gidius Mogensen wrote: > > That's not really the difference between static and dynamic typing. > > Static typing means that there exist a typing at compile-time that > > guarantess against run-time type violations. Dynamic typing means > > that such violations are detected at run-time. This is orthogonal to > > strong versus weak typing, which is about whether such violations are > > detected at all. The archetypal weakly typed language is machine code > > -- you can happily load a floating point value from memory, add it to > > a string pointer and jump to the resulting value. ML and Scheme are > > both strongly typed, but one is statically typed and the other > > dynamically typed. > > Knowing that it'll cause a lot of strenuous objection, I'll nevertheless > interject my plea not to abuse the word "type" with a phrase like > "dynamically typed". If anyone considers "untyped" to be perjorative, > as some people apparently do, then I'll note that another common term is > "type-free," which is marketing-approved but doesn't carry the > misleading connotations of "dynamically typed." We are quickly losing > any rational meaning whatsoever to the word "type," and that's quite a > shame. I don't think dynamic typing is that nebulous. I remember this being discussed elsewhere some time ago, I'll post the same reply I did then .. A language is statically typed if a variable has a property - called it's type - attached to it, and given it's type it can only represent values defined by a certain class. A language is latently typed if a value has a property - called it's type - attached to it, and given it's type it can only represent values defined by a certain class. Some people use dynamic typing as a word for latent typing, others use it to mean something slightly different. But for most purposes the definition above works for dynamic typing also. Untyped and type-free mean something else: they mean no type checking is done. From dongdonglove8 at hotmail.com Fri Jun 2 03:58:07 2006 From: dongdonglove8 at hotmail.com (python) Date: 2 Jun 2006 00:58:07 -0700 Subject: after del list , when I use it again, prompt 'not defined'.how could i delete its element, but not itself? Message-ID: <1149235087.256704.309360@g10g2000cwb.googlegroups.com> after del list , when I use it again, prompt 'not defined'.how could i delete its element,but not itself? except list.remove(val) ,are there other ways to delete list 's elements? and , I wrote: list1=[] def method1(): global list1 list1=['a','b','c','d'] def method2(): list2=list1 list2.remove['a'] main(): global list1 method1() method2() print list1[0] it prints 'b'. How could I keep the list1 not to change when remove list2's elements? From paddy3118 at netscape.net Sat Jun 17 13:55:24 2006 From: paddy3118 at netscape.net (Paddy) Date: 17 Jun 2006 10:55:24 -0700 Subject: code is data In-Reply-To: References: Message-ID: <1150566924.066371.323110@c74g2000cwc.googlegroups.com> Anton Vredegoor wrote: > With the inclusion of ElementTree (an XML-parser) in Python25 and recent > developments concerning JSON (a very Pythonesque but somewhat limited > XML notation scheme, let's call it statically typed XML) > Your thoughts please. > > Anton Hi Anton. If you mean this JSON: http://www.json.org/example.html then I'd just point out that JSON isn't XML-like at all. In fact the examples look like valid Python nested dictionaries. - Pad. P.S. This is good too: http://en.wikipedia.org/wiki/JSON From cdsmith at twu.net Mon Jun 26 13:49:51 2006 From: cdsmith at twu.net (Chris Smith) Date: Mon, 26 Jun 2006 11:49:51 -0600 Subject: What is a type error? References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <7i3mg.204167$8W1.155367@fe1.news.blueyonder.co.uk> <44992e6c$2$664$bed64819@news.gradwell.net> <%Igmg.464974$xt.353729@fe3.news.blueyonder.co.uk> <4fv0v3F1kipa6U1@individual.net> <4gakhiF1m698cU1@individual.net> Message-ID: Pascal Costanza wrote: > Consider division by zero: appropriate arguments for division are > numbers, including the zero. The dynamic type check will typically not > check whether the second argument is zero, but will count on the fact > that the processor will raise an exception one level deeper. Of course zero is not appropriate as a second argument to the division operator! I can't possibly see how you could claim that it is. The only reasonable statement worth making is that there doesn't exist a type system in widespread use that is capable of checking this. > This is maybe better understandable in user-level code. Consider the > following class definition: > > class Person { > String name; > int age; > > void buyPorn() { > if (< this.age 18) throw new AgeRestrictionException(); > ... > } > } > > The message p.buyPorn() is a perfectly valid message send and will pass > both static and dynamic type tests (given p is of type Person in the > static case). It appears you've written the code above to assume that the type system can't cerify that age >= 18... otherwise, the if statement would not make sense. It also looks like Java, in which the type system is indeed not powerfule enough to do that check statically. However, it sounds as if you're claiming that it wouldn't be possible for the type system to do this? If so, that's not correct. If such a thing were checked at compile-time by a static type check, then failing to actually provide that guarantee would be a type error, and the compiler would tell you so. Whether you'd choose to call an equivalent runtime check a "dynamic type check" is a different matter, and highlights the fact that again there's something fundamentally different about the definition of a "type" in the static and dynamic sense. -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation From micklee74 at hotmail.com Tue Jun 13 10:05:35 2006 From: micklee74 at hotmail.com (micklee74 at hotmail.com) Date: 13 Jun 2006 07:05:35 -0700 Subject: a string problem In-Reply-To: References: <1150206140.912224.113420@p79g2000cwp.googlegroups.com> Message-ID: <1150207535.589909.263990@p79g2000cwp.googlegroups.com> John Salerno wrote: > micklee74 at hotmail.com wrote: > > hi > > > > if i have a some lines like this > > a ) "here is first string" > > b ) "here is string2" > > c ) "here is string3" > > > > When i specify i only want to print the lines that contains "string" ie > > the first line and not the others. If i use re module, how to compile > > the expression to do this? I tried the re module and using simple > > search() and everytime it gives me all the 3 lines that have "string" > > in it, whereas i only need line 1. > > If re module is not needed, how can i use string manipulation to do > > this? thanks > > > > As far as re goes, you can search for the pattern '\bstring\b', which > will find just the word 'string' itself. Not sure if there's a better > way to do it with REs. > > And I'm actually ashamed to admit that I know the RE way, but not the > regular string manipulation way, if there is one! This seems like > something easy enough to do without REs though. if RE has the \b and it works, can we look into the source of re and see how its done for \b ? From esj at harvee.org Wed Jun 14 09:52:01 2006 From: esj at harvee.org (Eric S. Johansson) Date: Wed, 14 Jun 2006 09:52:01 -0400 Subject: [*SPAM*] Python open proxy honeypot In-Reply-To: References: Message-ID: <44901481.3030507@harvee.org> Alex Reinhart wrote: > Eric S. Johansson wrote: >> Alex Reinhart wrote: >>> Yeah, I just realized that. What would I do to act as an open proxy as >>> well? >> emulate the Apache proxy capability, especially the reverse proxy. >> >> more seriously, what you need to do is from common proxy and web server >> ports, accept proxy requests with a destination port number of 25 and >> pretend to relay them. at least, that was the behavior I saw on a >> misconfigured Apache web server proxy. > Is there a library that implements such functionality (that I can > override) or will I have to implement SOCKS and such myself? I've found > one SOCKS library and it's rather old and out of date... I'm not sure. I would seriously look at the Apache code in figure out what it does differently. The other possibilities look at the pound code which is probably more comprehensible and a better example of secure code. It's not out yet but I believe Cherokee will have a proxy soon. I advocated filtering out anything with a port 25 destination. After they heard my experience with Apache, they thought it was a real good idea. :-) From conveycj at npt.nuwc.navy.mil Thu Jun 22 13:37:23 2006 From: conveycj at npt.nuwc.navy.mil (Christian Convey) Date: Thu, 22 Jun 2006 13:37:23 -0400 Subject: better Python IDE? Mimics Maya's script editor? In-Reply-To: <200606221818.20164.runlevelten@gmail.com> References: <1149810048.765664.107820@i40g2000cwc.googlegroups.com> <200606221818.20164.runlevelten@gmail.com> Message-ID: <449AD553.4050403@npt.nuwc.navy.mil> Ten wrote: > If you get into emacs, it's worth the time invested. The learning curve's > alleged to be steep, but it isn't that bad, I use it and I'm as dumb as a > stump. It's a very good IDE for everyday use. :-) Not to get into the classic emacs/vi/etc. argument, but from my experience emacs has never been a good learning investment. For an editor (on Linux) I just use Kate or Gedit, which have syntax highlighting. For debugging, I use the print statement, because I haven't found an interactive debugger that I like. I did try Eclipse's "PyDev" module. It was OK, but I found Eclipse to have so much screen clutter and so-so responsiveness, so I decided to not keep on using it. KDevelop now has support for Python coding, but no Python debugger yet. It also doesn't support tab completions for Python (that I'm aware of). So for now, I've found just a plain old text editor, plus print statements, to be the right choice for me. -- Christian Convey Computer Scientist, Naval Undersea Warfare Centers Newport, RI (401) 832-6824 conveycj at npt.nuwc.navy.mil From nun at example.com Fri Jun 23 15:11:43 2006 From: nun at example.com (Mitja Trampus) Date: Fri, 23 Jun 2006 21:11:43 +0200 Subject: Reuseable iterators - which is better? In-Reply-To: References: Message-ID: zefciu wrote: > In the tutorial there is an example iterator class that revesrses the > string given to the constructor. The problem is that this class works > only once, unlike built-in types like string. How to modify it that it > could work several times? I have tried two approaches. They both work, > but which of them is stylistically better? Of the two posted below, I would much prefer the second one because iterators are not meant to be reused (so they can be used on streams and similar as well). Therefore, "resetting" an iterator by creating a new, similar one, is the natural way. Beware, however, that your code does not actually create a new iterator and breaks if you want to concurrently use more than one iterator of the same Reverse instance. The "normal" way would be to have def __iter__(self): return Reverse(self) as a method of the sequence that is meant to be iterated over in reverse. Plus, of course, everything but the __iter__ method from your second "reusable" iterator (which now isn't reusable any more). > class Reverse: #original one > "Iterator for looping over a sequence backwards" > def __init__(self, data): > self.data = data > self.index = len(data) > def __iter__(self): > return self > def next(self): > if self.index == 0: > raise StopIteration > self.index = self.index - 1 > return self.data[self.index] > > class Reverse: #1st approach > "Reuseable Iterator for looping over a sequence backwards" > def __init__(self, data): > self.data = data > self.index = len(data) > def __iter__(self): > return self > def next(self): > if self.index == 0: > self.index = len(self.data) #Reset when previous # > iterator goes out > raise StopIteration > self.index = self.index - 1 > return self.data[self.index] > > class Reverse: #2nd approach > "Reuseable Iterator for looping over a sequence backwards" > def __init__(self, data): > self.data = data > def __iter__(self): > self.index = len(self.data) #Reset as a part of iterator # creation > return self > def next(self): > if self.index == 0: > raise StopIteration > self.index = self.index - 1 > return self.data[self.index] From fredrik at pythonware.com Tue Jun 27 09:29:58 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 27 Jun 2006 15:29:58 +0200 Subject: Re-loading updated modules References: <1151414294.809032.44850@u72g2000cwu.googlegroups.com> Message-ID: "fileexit" wrote: > Shouldn't python recompile a module if there is a later version of the > code (.py file)? it does, when the module is first loaded. > While i am debuging, i always have to exit python and > delete the pyc before every run deleting the PYC shouldn't be necessary. > then start it again and import the > modules. It seems that this is the only way for it to recompile the > new code. reload(module) however, see the caveats on this page: http://pyref.infogami.com/reload > What is going on? is this normal behaviour? yes. and this is tutorial stuff, too: http://pytut.infogami.com/node8.html From gandalf at designaproduct.biz Sat Jun 10 04:02:48 2006 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Sat, 10 Jun 2006 10:02:48 +0200 Subject: __getattr__ question In-Reply-To: <1149916979.821376.208960@h76g2000cwa.googlegroups.com> References: <1149916979.821376.208960@h76g2000cwa.googlegroups.com> Message-ID: <448A7CA8.5020208@designaproduct.biz> > > Either way is a few more characters to type, but it's far saner than > trying to distinguish between "real" and "fake" attributes. > I think you are right. I'll make up my mind. From andrew.arobert at gmail.com Mon Jun 19 17:18:26 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Mon, 19 Jun 2006 17:18:26 -0400 Subject: Newbie Question In-Reply-To: <1150750938.973049.114780@y41g2000cwy.googlegroups.com> References: <1150750938.973049.114780@y41g2000cwy.googlegroups.com> Message-ID: <129e55eahc35f00@corp.supernews.com> Saint Malo wrote: > I am new to programming, and I've chosen python to start with. I wrote > a simple program that asks several questions and assings each one of > them a variable via raw_input command. I then combined all the > variables into one like this a = b + c + d. After this I wrote these > values to a file. What I want to do now is be able to search through > the file for any data in there. Is this possible? > Most certainly. It depends on how you want to treat the read data. for example # Open a file for read file=open(r'test.txt','r') # Read each line in file for line in file #Search each line if "A" in line: print "I found A" file.close() From mahall at ncsa.uiuc.edu Tue Jun 20 00:23:20 2006 From: mahall at ncsa.uiuc.edu (Matteo) Date: 19 Jun 2006 21:23:20 -0700 Subject: list of polynomial functions In-Reply-To: <1150390140.459461.169900@i40g2000cwc.googlegroups.com> References: <1150390140.459461.169900@i40g2000cwc.googlegroups.com> Message-ID: <1150777400.370686.162340@i40g2000cwc.googlegroups.com> Josiah Manson wrote: > In the following program I am trying to learn how to use functional > programming aspects of python, but the following program will crash, > claiming that the recursion depth is too great. I am attempting to make > a list of polynomial functions such that poly[0](3) = 1, poly[1](3) = > 3, poly[2](3) = 9, etc. Could someone point me in the right direction? > Thanks. > > def make_polys(n): > """Make a list of polynomial functions up to order n. > """ > p = lambda x: 1 > polys = [p] > > for i in range(n): > polys.append(lambda x: polys[i](x)*x) > > return polys > > # construct a vector of polynomials > polys = make_polys(5) > > # print > for p in polys: > print p(3) Many wise things have been said in this thread. I would like to proffer another solution which does not rely on default arguments, just for a more functional flavor. def makepolys(n): if n==0: return [lambda x: 1] else: tailfunc=makepolys(n-1) return tailfunc + [ lambda x: x * tailfunc[-1](x)] Another way, which is properly tail recursive is the following: def makepolys2helper(n,retval): if n==0: return retval else: return makepolys2helper(n-1,retval+[lambda x: x* retval[-1](x)]) def makepolys2(n): return makepolys2helper(n,[lambda x: 1]) (Note: this could be collapsed into a single function either with a default argument, or a nested function, but I thought this was a bit clearer) This last approach could, at least theoretically, create an arbitrarily long list of polys, without overflowing any kind of stack. In practice, python does not seem to perform tail recursion optimizations, and conks out after makepolys(997) on my machine. And yes - I did just sit in on my first functional programming class :) -matt From anton at appsolutions.com Fri Jun 23 03:42:25 2006 From: anton at appsolutions.com (Anton van Straaten) Date: Fri, 23 Jun 2006 07:42:25 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: <1151030140.202720.245140@y41g2000cwy.googlegroups.com> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150904134.520639.71070@b68g2000cwa.googlegroups.com> <1151030140.202720.245140@y41g2000cwy.googlegroups.com> Message-ID: Marshall wrote: >>The short answer is that I'm most directly referring to "the types in >>the programmer's head". > > > In the database theory world, we speak of three levels: conceptual, > logical, physical. In a dbms, these might roughly be compared to > business entities described in a requirements doc, (or in the > business owners' heads), the (logical) schema encoded in the > dbms, and the b-tree indicies the dbms uses for performance. > > So when you say "latent types", I think "conceptual types." That sounds plausible, but of course at some point we need to pick a term and attempt to define it. What I'm attempting to do with "latent types" is to point out and emphasize their relationship to static types, which do have a very clear, formal definition. Despite some people's skepticism, that definition gives us a lot of useful stuff that can be applied to what I'm calling latent types. > The thing about this is, both the Lisp and the Haskell programmers > are using conceptual types (as best I can tell.) Well, a big difference is that the Haskell programmers have language implementations that are clever enough to tell them, statically, a very precise type for every term in their program. Lisp programmers usually don't have that luxury. And in the Haskell case, the conceptual type and the static type match very closely. There can be differences, e.g. a programmer might have knowledge about the input to the program or some programmed constraint that Haskell isn't capable of inferring, that allows them to figure out a more precise type than Haskell can. (Whether that type can be expressed in Haskell's type system is a separate question.) In that case, you could say that the conceptual type is different than the inferred static type. But most of the time, the human is reasoning about pretty much the same types as the static types that Haskell infers. Things would get a bit confusing otherwise. > And also, the > conceptual/latent types are not actually a property of the > program; That's not exactly true in the Haskell case (or other languages with static type inference), assuming you accept the static/conceptual equivalence I've drawn above. Although static types are often not explicitly written in the program in such languages, they are unambiguously defined and automatically inferrable. They are a static property of the program, even if in many cases those properties are only implicit with respect to the source code. You can ask the language to tell you what the type of any given term is. > they are a property of the programmer's mental > model of the program. That's more accurate. In languages with type inference, the programmer still has to figure out what the implicit types are (or ask the language to tell her). You won't get any argument from me that this figuring out of implicit types in a Haskell program is quite similar to what a Lisp, Scheme, or Python programmer does. That's one of the places the connection between static types and what I call latent types is the strongest. (However, I think I just heard a sound as though a million type theorists howled in unison.[*]) [*] most obscure inadvertent pun ever. > It seems we have languages: > with or without static analysis > with or without runtime type information (RTTI or "tags") > with or without (runtime) safety > with or without explicit type annotations > with or without type inference > > Wow. And I don't think that's a complete list, either. Yup. > I would be happy to abandon "strong/weak" as terminology > because I can't pin those terms down. (It's not clear what > they would add anyway.) I wasn't following the discussion earlier, but I agree that strong/weak don't have strong and unambiguous definitions. > Uh, oh, a new term, "manifest." Should I worry about that? Well, people have used the term "manifest type" to refer to a type that's explicitly apparent in the source, but I wouldn't worry about it. I just used the term to imply that at some point, the idea of "latent type" has to be converted to something less latent. Once you explicitly identify a type, it's no longer latent to the entity doing the identifying. >>But if we ask Javascript what it thinks the type of timestwo is, by >>evaluating "typeof timestwo", it returns "function". That's because the >>value bound to timestwo has a tag associated with it which says, in >>effect, "this value is a function". > > > Well, darn. It strikes me that that's just a decision the language > designers > made, *not* to record complete RTTI. No, there's more to it. There's no way for a dynamically-typed language to figure out that something like the timestwo function I gave has the type "number -> number" without doing type inference, by examining the source of the function, at which point it pretty much crosses the line into being statically typed. > (Is it going to be claimed that > there is an *advantage* to having only incomplete RTTI? It is a > serious question.) More than an advantage, it's difficult to do it any other way. Tags are associated with values. Types in the type theory sense are associated with terms in a program. All sorts of values can flow through a given term, which means that types can get complicated (even in a nice clean statically typed language). The only way to reason about types in that sense is statically - associating tags with values at runtime doesn't get you there. This is the sense in which the static type folk object to the term "dynamic type" - because the tags/RTTI are not "types" in the type theory sense. Latent types as I'm describing them are intended to more closely correspond to static types, in terms of the way in which they apply to terms in a program. > Hmmm. Another place where the static type isn't the same thing as > the runtime type occurs in languages with subtyping. Yes. > Question: if a language *does* record complete RTTI, and the > languages does *not* have subtyping, could we then say that > the runtime type information *is* the same as the static type? You'd still have a problem with function types, as I mentioned above, as well as expressions like the conditional one I gave: (flag ? 5 : "foo") The problem is that as the program is running, all it can ever normally do is tag a value with the tags obtained from the path the program followed on that run. So RTTI isn't, by itself, going to determine anything similar to a static type for such a term, such as "string | number". One way to think about "runtime" types is as being equivalent to certain kinds of leaves on a statically-typed program syntax tree. In an expression like "x = 3", an inferring compiler might determine that 3 is of type "integer". The tagged values which RTTI uses operate at this level: the level of individual values. However, as soon as you start dealing with other kinds of nodes in the syntax tree -- nodes that don't represent literal values, or compound nodes (that have children) -- the possibility arises that the type of the overall expression will be more complex than that of a single value. At that point, RTTI can't do what static types do. Even in the simple "x = 3" case, a hypothetical inferring compiler might notice that elsewhere in the same function, x is treated as a floating point number, perhaps via an expression like "x = x / 2.0". According to the rules of its type system, our language might determine that x has type "float", as opposed to "number" or "integer". It might then either treat the original "3" as a float, or supply a conversion when assigning it to "x". (Of course, some languages might just give an error and force you to be more explicit, but bear with me for the example - it's after 3:30am again.) Compare this to the dynamically-typed language: it sees "3" and, depending on the language, might decide it's a "number" or perhaps an "integer", and tag it as such. Either way, x ends up referring to that tagged value. So what type is x? All you can really say, in the RTTI case, is that x is a number or an integer, depending on the tag the value has. There's no way it can figure out that x should be a float at that point. Of course, further down when it runs into the code "x = x / 2.0", x might end up holding a value that's tagged as a float. But that only tells you the value of x at some point in time, it doesn't help you with the static type of x, i.e. a type that either encompasses all possible values x could have during its lifetime, or alternatively determines how values assigned to x should be treated (e.g. cast to float). BTW, it's worth noting at this point, since it's implied by the last paragraph, that a static type is only an approximation to the values that a term can have during the execution of a program. Static types can (often!) be too conservative, describing possible values that a particular term couldn't actually ever have. This gives another hint as to why RTTI can't be equivalent to static types. It's only ever dealing with the concrete values right in front of it, it can't see the bigger static picture. Anton From girodt at gmail.com Thu Jun 22 15:26:05 2006 From: girodt at gmail.com (TG) Date: 22 Jun 2006 12:26:05 -0700 Subject: Numeric N-dimensional array initialization In-Reply-To: References: <1150999204.839644.179940@g10g2000cwb.googlegroups.com> <1151000155.059823.256350@b68g2000cwa.googlegroups.com> Message-ID: <1151004365.327078.222120@c74g2000cwc.googlegroups.com> Thanks for your precious advices. The flat iterator is definitely what i need. From mwilson-to at sympatico.ca Sun Jun 4 11:42:04 2006 From: mwilson-to at sympatico.ca (Mel Wilson) Date: Sun, 04 Jun 2006 11:42:04 -0400 Subject: Proposed new PEP: print to expand generators In-Reply-To: References: <4482390E.7060809@cascade-sys.com> Message-ID: Terry Reedy wrote: > "James J. Besemer" wrote in message > news:4482390E.7060809 at cascade-sys.com... >> I propose that we extend the semantics of "print" such that if the object >> to >> be printed is a generator then print would iterate over the resulting >> sequence of sub-objects and recursively print each of the items in order. > Iterating over an iterator is usually destructive. So you would be > printing what it was but no longer is. This is why iterators are printed > differently from sequences. I guess the motivation is the case of people who would set up an iterator specifically to print from it. print-as-debug-aid would get badly broken by the proposal, and I'd find that painful. Mel. From siona at chiark.greenend.org.uk Fri Jun 2 11:14:56 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 02 Jun 2006 16:14:56 +0100 (BST) Subject: integer to binary... References: <1149189570.376091.319890@j55g2000cwa.googlegroups.com> <127ugf9jgu7av18@corp.supernews.com> <1149190940.548582.27200@h76g2000cwa.googlegroups.com> Message-ID: <0Oh*8vbir@news.chiark.greenend.org.uk> Tim Chase wrote: >bitCount = len([c for c in "01001010101" if c=="1"]) bitCount = "01001010101".count("1") -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From bborcic at gmail.com Fri Jun 9 05:59:43 2006 From: bborcic at gmail.com (Boris Borcic) Date: Fri, 09 Jun 2006 11:59:43 +0200 Subject: How to generate k+1 length strings from a list of k length strings? In-Reply-To: <1149800459.244528.220790@u72g2000cwu.googlegroups.com> References: <44883789$1_4@news.bluewin.ch> <1149785331.109164.208340@i39g2000cwa.googlegroups.com> <4488658e$1_5@news.bluewin.ch> <1149800459.244528.220790@u72g2000cwu.googlegroups.com> Message-ID: <448946a6$1_1@news.bluewin.ch> bearophileHUGS at lycos.com wrote: > It's not that difficult to improve the readability of a quite long > line, you can start splitting it. The point is that it is observer and context dependent whether res = set(''.join(sorted(X|Y)) for X in sets for Y in sets if len(X^Y)==2) is measurably easier to read than res = set(''.join(sorted(X|Y)) for X in sets for Y in sets if len(X^Y)==2) *and* that I acknowledged it by writing "I find most readable" while you denied it by speaking of "the readability" - and similar language. From Dennis.Benzinger at gmx.net Wed Jun 28 12:48:13 2006 From: Dennis.Benzinger at gmx.net (Dennis Benzinger) Date: Wed, 28 Jun 2006 18:48:13 +0200 Subject: Problem with sets and Unicode strings In-Reply-To: References: <44a17d05$1@news.uni-ulm.de> <44a19d55$2@news.uni-ulm.de> Message-ID: <44a2b2cc$2@news.uni-ulm.de> Robert Kern wrote: > Dennis Benzinger wrote: >> Serge Orlov wrote: >>> On 6/27/06, Dennis Benzinger wrote: >>>> Hi! >>>> >>>> The following program in an UTF-8 encoded file: >>>> >>>> >>>> # -*- coding: UTF-8 -*- >>>> >>>> FIELDS = ("F?cher", ) >>>> FROZEN_FIELDS = frozenset(FIELDS) >>>> FIELDS_SET = set(FIELDS) >>>> >>>> print u"F?cher" in FROZEN_FIELDS >>>> print u"F?cher" in FIELDS_SET >>>> print u"F?cher" in FIELDS >>>> >>>> >>>> gives this output >>>> >>>> >>>> False >>>> False >>>> Traceback (most recent call last): >>>> File "test.py", line 9, in ? >>>> print u"F??cher" in FIELDS >>>> UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 1: >>>> ordinal not in range(128) >>>> >>>> >>>> Why do the first two print statements succeed and the third one fails >>>> with an exception? >>> Actually all three statements fail to produce correct result. >> >> So this is a bug in Python? > > No. > [...] But I'd say that it's not intuitive that for sets x in y can be false (without raising an exception!) while the doing the same with a tuple raises an exception. Where is this difference documented? Thanks, Dennis From Kiran.Karra at gmail.com Tue Jun 20 15:22:09 2006 From: Kiran.Karra at gmail.com (Kiran) Date: 20 Jun 2006 12:22:09 -0700 Subject: Segmentation fault only on Iinux Message-ID: <1150831329.649174.60410@g10g2000cwb.googlegroups.com> Hello All, In my program, I have a main thread which is the GUI (wxPython) and then a thread which goes and reads data from a socket. The reason this is in a different thread is because the data might take some time to come back, and I want to have the GUI to be responsive during this wait. When I run my program in Linux, a segmentation fault occurs. When I run it in Windows XP, it works just fine. The main thing that would be of interest is as follows: The segmentation fault does NOT occur if I disable the threads and read the data all in 1 thread (the main thread [gui's]). This leads me to believe it is some sort of threading problem related to linux. However, I personally dont think that it can be something wrong with my code, since my program runs perfectly fine in WindowsXP. I am also carefully protecting data that my threads share with the MainGUI using a Queue and also a semaphore lock. I know this is kind of hard to answer without any code, but would anybody know of some kind of issue such as this where there is some threading problems with Linux and not Windows. I am happy to send the code to anybody who wishes to see it. I havent posted it here because it is kind of lengthy. Also, I should note that I think we are running Linux Kernel 2.4 thanks a lot for your help, Kiran From ketil+news at ii.uib.no Tue Jun 20 11:34:21 2006 From: ketil+news at ii.uib.no (Ketil Malde) Date: Tue, 20 Jun 2006 17:34:21 +0200 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <1150809118.677124.142230@u72g2000cwu.googlegroups.com> <1150815461.210286.53120@r2g2000cwb.googlegroups.com> Message-ID: "Rob Thorpe" writes: > But it only gaurantees this because the variables themselves have a > type, the values themselves do not. I think statements like this are confusing, because there are different interpretations of what a "value" is. I would say that the integer '4' is a value, and that it has type Integer (for instance). This value is different from 4 the Int16, or 4 the double-precision floating point number. From this viewpoint, all values in statically typed languages have types, but I think you use 'value' to denote the representation of a datum in memory, which is a different thing. -k -- If I haven't seen further, it is by standing in the footprints of giants From webraviteja at gmail.com Sat Jun 17 19:19:59 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 17 Jun 2006 16:19:59 -0700 Subject: Standard Yes / No Windows Dialog box creation In-Reply-To: <1150581640.385143.83410@y41g2000cwy.googlegroups.com> References: <1150581640.385143.83410@y41g2000cwy.googlegroups.com> Message-ID: <1150586399.452037.85270@h76g2000cwa.googlegroups.com> flaus.a at wanadoo.fr wrote: > I found a way to create "Open File" or "Open Folder" windows dialog > boxes, but not to create an easier Yes / No dialog box... > Maybe someone has a solution for this? Assuming you are on MS Windows. import win32api, win32con win32api.MessageBox(0, "Question", "Title", win32con.MB_YESNO) From rpdooling at gmail.com Fri Jun 23 12:32:23 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 23 Jun 2006 09:32:23 -0700 Subject: Opening a file with system default application References: <1151077662.598370.214490@c74g2000cwc.googlegroups.com> Message-ID: <1151080343.917275.296520@g10g2000cwb.googlegroups.com> don't know Jython, but in Python, I think you want: import os os.system('mytextfile.txt') Whatever file you reference should open in the application associated with it. At least that's the way it works on Win XP rd From grante at visi.com Wed Jun 14 11:25:08 2006 From: grante at visi.com (Grant Edwards) Date: Wed, 14 Jun 2006 15:25:08 -0000 Subject: Numerics, NaNs, IEEE 754 and C99 References: <12904mjhl493t49@corp.supernews.com> Message-ID: <1290aik50hmk94a@corp.supernews.com> On 2006-06-14, Nick Maclaren wrote: >|>> Now, I should like to improve this, but there are two problems. The >|>> first is political, and is whether it would be acceptable in Python to >|>> restore the semantics that were standard up until about 1980 in the >|>> numerical programming area. I.e. one where anything that is numerically >|>> undefined or at a singularity which can deliver more than one value is >|>> an error state (e.g. raises an an exception or returns a NaN). >|> >|> That's fine as long as the behavior is selectable. I almost >|> always want a quiet NaN. > > That is one of the two modes that I regard as respectable. However, > because integer arithmetic doesn't have a NaN value (which could be > fixed, in Python), anything that returns an integer has to raise an > exception. On that matter, division by zero and several other currently > trapped numeric errors could be modified to return NaN for people like > you (if the option were selected, of course). The division by zero trap is really annoying. In my world the right thing to do is to return Inf. >|> While you're at it, the pickle modules need to be fixed so they >|> support NaN and Inf. ;) > > Yup. On my list :-) -- Grant Edwards grante Yow! Were these parsnips at CORRECTLY MARINATED in visi.com TACO SAUCE? From orome.the.valar at gmail.com Wed Jun 14 11:52:50 2006 From: orome.the.valar at gmail.com (sinan nalkaya) Date: Wed, 14 Jun 2006 15:52:50 -0000 Subject: popen and password entry Message-ID: <200604141852.59515.erchamion.beren@gmail.com> hello, i want to use rsync for remote file transfer via popen, but couldnt pass the Password yet. here`s what i did cmd = 'rsync -av config root at 10.1.1.1:/tmp/.' f = os.popen(cmd,'w') f.write('1234') #not worked f.write('1234\n') #not worked every time i see "Password:" line, then i tried popen2 st_out, st_in = popen2.popen2(cmd) st_in.write('1234') #not worked st_in.write('1234\n') #not worked again i got bored to see "Password:" line every time and did st_out.close() to not to see stdout messages from rsync, but even this did not work. also i tried popen3() function same way. what should i do? Thanks. From bencvt at gmail.com Mon Jun 26 20:49:14 2006 From: bencvt at gmail.com (Ben Cartwright) Date: 26 Jun 2006 17:49:14 -0700 Subject: nested dictionary assignment goes too far References: <1151366182.359999.312270@m73g2000cwd.googlegroups.com> Message-ID: <1151369354.492540.84470@y41g2000cwy.googlegroups.com> Jake Emerson wrote: > However, when > the process goes to insert the unique 'char_freq' into a nested > dictionary the value gets put into ALL of the sub-keys The way you're currently defining your dict: rain_raw_dict = dict.fromkeys(distinctID,{'N':-6999,'char_freq':-6999,...}) Is shorthand for: tmp = {'N':-6999,'char_freq':-6999,...} rain_raw_dict = {} for key in distinctID: rain_raw_dict[key] = tmp Note that tmp is a *reference*. Python does not magically create copies for you; you have to be explicit. Unless you want a shared value, dict.fromkeys should only be used with an immutable value (e.g., int or str). What you'll need to do is either: tmp = {'N':-6999,'char_freq':-6999,...} rain_raw_dict = {} for key in distinctID: # explicitly make a (shallow) copy of tmp rain_raw_dict[key] = dict(tmp) Or more simply: rain_raw_dict = {} for key in distinctID: rain_raw_dict[key] = {'N':-6999,'char_freq':-6999,...} Or if you're a one-liner kinda guy, rain_raw_dict = dict((key, {'N':-6999,'char_freq':-6999,...}) for key in distinctID) --Ben From sjmachin at lexicon.net Thu Jun 1 19:58:59 2006 From: sjmachin at lexicon.net (John Machin) Date: Fri, 02 Jun 2006 09:58:59 +1000 Subject: Can Python format long integer 123456789 to 12,3456,789 ? In-Reply-To: <8oKfg.1621$Su3.139425@news20.bellglobal.com> References: <8oKfg.1621$Su3.139425@news20.bellglobal.com> Message-ID: <447f7f43$1@news.eftel.com> On 2/06/2006 9:08 AM, A.M wrote: > Hi, > > Is there any built in feature in Python that can format long integer > 123456789 to 12,3456,789 ? > > Thank you, > Alan Not that I know of, but this little kludge may help: 8<--- import re subber = re.compile(r'^(-?\d+)(\d{3})').sub def fmt_thousands(amt, sep): if amt in ('', '-'): return '' repl = r'\1' + sep + r'\2' while True: new_amt = subber(repl, amt) if new_amt == amt: return amt amt = new_amt if __name__ == "__main__": for prefix in ['', '-']: for k in range(11): arg = prefix + "1234567890.1234"[k:] print "<%s> <%s>" % (arg, fmt_thousands(arg, ",")) 8<--- HTH, John From ray_usenet at yahoo.com Thu Jun 1 04:38:17 2006 From: ray_usenet at yahoo.com (Ray) Date: 1 Jun 2006 01:38:17 -0700 Subject: How do you practice programming? Message-ID: <1149151097.741307.79440@f6g2000cwb.googlegroups.com> OK, maybe I shoot a more general question to the group since there are so many great programmers here: how do you practice your craft? I do it in the following way: 1. Set aside 30 minutes to 1 hour a day to read up on the latest development, be it about the tool I'm using, the language, or the platform, or the framework, etc. 2. Once every 1-2 months, go to Amazon, and look for the book with the best reviews in a particular technology (e.g.: SQL Cookbook, etc.) 3. Practice something that I may not be using currently at work, but always good to know, e.g.: I try to be reasonably competent in at least 2 major current languages--right now it's Java and C#, and 1 dynamic language, which has been Python for quite some time. SQL is always useful, so I try to practice that, especially the more complex queries involving group bys and window function, etc. How do you do your practice? From rbutler at mtsu.edu Sat Jun 17 22:32:11 2006 From: rbutler at mtsu.edu (Ralph Butler) Date: Sat, 17 Jun 2006 21:32:11 -0500 Subject: statically linked python In-Reply-To: <1150588687.938894.86830@r2g2000cwb.googlegroups.com> References: <1150588687.938894.86830@r2g2000cwb.googlegroups.com> Message-ID: <6JOdnf4KX7yxJgnZnZ2dnUVZ_rqdnZ2d@comcast.com> Serge Orlov wrote: > Ralph Butler wrote: >> Hi: >> >> I have searched the docs and google but have not totally figured >> out how to accomplish my task: On a linux box, I want to compile >> and link python so that it uses no shared libraries, but does support >> import of some "extra" modules. I have made a few attempts but >> with limited success. In particular, I have tried things like >> adding -static to the compiler options in the Makefile. >> >> At one point I managed to build a python that was close to what I >> wanted, e.g. when I ran "ldd python", it said: >> not a dynamic executable >> In that version, when I do some imports, e.g. sys, os, etc. they >> load fine. But, when I try to import some other modules, e.g. time, >> they are not found. I have tried similar procedures while also >> altering Modules/Setup.local (produced by configure) to contain: >> time timemodule.c # -lm # time operations and variables >> >> There has to be a simple, "elegant" way to accomplish this which I am >> simply overlooking. Any help would be appreciated. > > This has nothing to do with python. glibc doesn't support loading > shared libraries into statically linked executables. At least it didn't > support in 2002: > http://www.cygwin.com/ml/libc-alpha/2002-06/msg00079.html > Since it still doesn't work most likely it is still not supported, but > you may ask glibc developers what is the problem. > I do not want to load them. I want to statically link the code for a module (e.g. time) directly into the statically linked executable. Sorry if that was not clear. From joh12005 at yahoo.fr Sat Jun 3 07:50:16 2006 From: joh12005 at yahoo.fr (joh12005 at yahoo.fr) Date: 3 Jun 2006 04:50:16 -0700 Subject: grouping a flat list of number by range In-Reply-To: References: <1149196642.001466.53990@c74g2000cwc.googlegroups.com> Message-ID: <1149335416.359226.228600@i39g2000cwa.googlegroups.com> thanks to all ! my version was far less clever/long thant the one you posted, i'm going to examine all these with much interest, and learn... best regards. From johnjsal at NOSPAMgmail.com Thu Jun 15 11:32:12 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 15 Jun 2006 15:32:12 GMT Subject: Python is fun (useless social thread) ;-) In-Reply-To: <1150381872.958342.180420@p79g2000cwp.googlegroups.com> References: <1150381872.958342.180420@p79g2000cwp.googlegroups.com> Message-ID: <04fkg.2311$No6.48470@news.tufts.edu> BartlebyScrivener wrote: > I am not touching OO, classes, or GUIs until I understand EVERYTHING > else. Could take a few years. ;) LOL. That's exactly why I love Python, because you don't have to mess with any of that (explicitly) if you don't want to! Of course, here I am probably going way overboard by messing with classes and GUIs. I'd like to reinforce all the Python basics first though, so I don't want to get too far ahead of myself. I just need to find a project to work on that will limit me to the Python basics (although I'm sure that will still involve classes, at least). From fredrik at pythonware.com Fri Jun 30 02:44:48 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 30 Jun 2006 08:44:48 +0200 Subject: Reddit broke - should have remained on Lisp? References: <1151626961.232761.255550@d56g2000cwd.googlegroups.com> Message-ID: "Alok" wrote: > While posting a comment on http://www.reddit.com I got an error page > with the following curious statement on it. > > "reddit broke (sorry)" > "looks like we shouldn't have stopped using lisp..." > > See screenshot at > http://photos1.blogger.com/blogger/1773/1980/1600/reddit-broke.jpg > > Whether they truly repent not using lisp or otherwise, their site > appears to be 3 times slower ... since when? don't you think that the massive growth in usage that they've been seeing lately might have something to do with that ? From dnew at san.rr.com Fri Jun 23 16:00:13 2006 From: dnew at san.rr.com (Darren New) Date: Fri, 23 Jun 2006 20:00:13 GMT Subject: What is a type error? In-Reply-To: <0tXmg.28329$VE1.19407@newssvr14.news.prodigy.com> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <7i3mg.204167$8W1.155367@fe1.news.blueyonder.co.uk> <44992e6c$2$664$bed64819@news.gradwell.net> <%Igmg.464974$xt.353729@fe3.news.blueyonder.co.uk> <449aaea0$2$656$bed64819@news.gradwell.net> <0tXmg.28329$VE1.19407@newssvr14.news.prodigy.com> Message-ID: Eliot Miranda wrote: > classes do _not_ have to inherit from Object, I was unaware of this subtlety. Thanks! -- Darren New / San Diego, CA, USA (PST) Native Americans used every part of the buffalo, including the wings. From diffuser78 at gmail.com Wed Jun 28 11:35:09 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 28 Jun 2006 08:35:09 -0700 Subject: String Question Message-ID: <1151508909.273667.270910@x69g2000cwx.googlegroups.com> mac_string = '001485e55503' (This is the mac address of a computer.) I am using wake on LAN python script to start computer remote.It uses format like this .... s.sendto('\xff'*6 + '\x00\x014\x85\xe5\x55\x03'*16, ('192.168.1.255', 80)) where '\x00\x14\x85\xe5\x55\x03' is the MAC address to be used. What I do is break the string into 6 parts like this, str01=mac_string[0:2] str02=mac_string[2:4] str03=mac_string[4:6] str04=mac_string[6:8] str05=mac_string[8:10] str06=mac_string[10:12] and if I use it like this s.sendto('\xff'*6 + '\xstr01\xstr02\xstr03\xstr04\xstr05\xstr06'*16, ('192.168.1.255', 80)) I get an error I also tried like this s.sendto('\xff'*6 + 'mac_string'*16, ('192.168.1.255', 80)) Thiis also didnt work. Since the MAC adddress are hexadecimal, how should I go about it here. Please help, every help is appreciated. Thanks From aljosa.mohorovic at gmail.com Tue Jun 6 10:18:08 2006 From: aljosa.mohorovic at gmail.com (aljosa) Date: 6 Jun 2006 07:18:08 -0700 Subject: capture video from camera In-Reply-To: References: <1149598946.182874.121650@c74g2000cwc.googlegroups.com> Message-ID: <1149603488.012417.269760@j55g2000cwa.googlegroups.com> i searched on google and found http://videocapture.sourceforge.net/ before i posted here. videocapture has no docs and doesn't provide additional options like motion detection nor any info on possibility of motion detection or howto implement (use of minimal system resources). i posted here to find out if anybody knows a better way to capture video. Fredrik Lundh wrote: > aljosa wrote: > > > i'm trying to capture video from camera/webcam using python. > > so far i haven't found any library that would allow me to do that. > > > > cross-platform solution related to SDL/pygame would be nice but a > > simple solution to capture video under windows is ok. > > first google hit for "python video capture": > > http://videocapture.sourceforge.net/ > > for linux, see: > > http://www.antonym.org/libfg > > From faulkner612 at comcast.net Tue Jun 20 19:25:56 2006 From: faulkner612 at comcast.net (faulkner) Date: 20 Jun 2006 16:25:56 -0700 Subject: Segmentation fault only on Iinux In-Reply-To: <1150831329.649174.60410@g10g2000cwb.googlegroups.com> References: <1150831329.649174.60410@g10g2000cwb.googlegroups.com> Message-ID: <1150845956.620708.298460@b68g2000cwa.googlegroups.com> if you don't know exactly which line of code causes the segfault, use print statements to determine that. then try to either redesign/refactor so that line isn't necessary, or protect its operation somehow. if you do know, tell us what it is and we might not need to see all your code. Kiran wrote: > Hello All, > In my program, I have a main thread which is the GUI (wxPython) and > then a thread which goes and reads data from a socket. The reason this > is in a different thread is because the data might take some time to > come back, and I want to have the GUI to be responsive during this > wait. > > When I run my program in Linux, a segmentation fault occurs. When I > run it in Windows XP, it works just fine. > > The main thing that would be of interest is as follows: > The segmentation fault does NOT occur if I disable the threads and > read the data all in 1 thread (the main thread [gui's]). This leads me > to believe it is some sort of threading problem related to linux. > However, I personally dont think that it can be something wrong with my > code, since my program runs perfectly fine in WindowsXP. I am also > carefully protecting data that my threads share with the MainGUI using > a Queue and also a semaphore lock. > > I know this is kind of hard to answer without any code, but would > anybody know of some kind of issue such as this where there is some > threading problems with Linux and not Windows. I am happy to send the > code to anybody who wishes to see it. I havent posted it here because > it is kind of lengthy. > > Also, I should note that I think we are running Linux Kernel 2.4 > > thanks a lot for your help, > Kiran From sonja.coussell at gmail.com Wed Jun 14 18:27:39 2006 From: sonja.coussell at gmail.com (sonjaa) Date: 14 Jun 2006 15:27:39 -0700 Subject: memory leak problem with arrays In-Reply-To: <1150322504.136131.139350@i40g2000cwc.googlegroups.com> References: <1150317325.614389.14770@i40g2000cwc.googlegroups.com> <1150322504.136131.139350@i40g2000cwc.googlegroups.com> Message-ID: <1150324059.063981.70450@u72g2000cwu.googlegroups.com> Serge Orlov wrote: > sonjaa wrote: > > Hi > > > > I'm new to programming in python and I hope that this is the problem. > > > > I've created a cellular automata program in python with the numpy array > > extensions. After each cycle/iteration the memory used to examine and > > change the array as determined by the transition rules is never freed. > > I've tried using "del" on every variable possible, but that hasn't > > worked. > > Python keeps track of number of references to every object if the > object has more that one reference by the time you use "del" the object > is not freed, only number of references is decremented. > > Print the number of references for all the objects you think should be > freed after each cycle/iteration, if is not equal 2 that means you are > holding extra references to those objects. You can get the number of > references to any object by calling sys.getrefcount(obj) thanks for the info. I used this several variables/objects and discovered that little counters i.e. k = k +1 have many references to them, up tp 10000+. Is there a way to free them? regards Sonja From skip at pobox.com Thu Jun 1 13:28:43 2006 From: skip at pobox.com (skip at pobox.com) Date: Thu, 1 Jun 2006 12:28:43 -0500 Subject: New to Python: Do we have the concept of Hash in Python? In-Reply-To: References: Message-ID: <17535.9163.63334.44669@montanaro.dyndns.org> Alan> but please consider the fact that I am in time pressure and I Alan> cannot go through a 400 book today. The tutorial is online and not 400 pages long: http://www.python.org/doc/current/tut/tut.html It's got a pretty comprehensive table of contents, looking at which you might jump quickly to Chapter 5, "Data Structures", and quickly eliminate lists, sets and maybe tuples as possible synonyms for "hash" and investigate Section 5.5, "Dictionaries" more closely. The first sentence of that section should ring bells: Another useful data type built into Python is the dictionary. Dictionaries are sometimes found in other languages as ``associative memories'' or ``associative arrays''. I suspect that was what Fredrik was thinking you might reasonably have done before asking on the list. In addition, you could have probably answered your own question faster by using the online documentation instead of waiting for the Q&A round-trip to comp.lang.python. Skip From skip at pobox.com Thu Jun 1 12:22:05 2006 From: skip at pobox.com (skip at pobox.com) Date: Thu, 1 Jun 2006 11:22:05 -0500 Subject: DB-API: how can I find the column names in a cursor? In-Reply-To: References: Message-ID: <17535.5165.592323.404609@montanaro.dyndns.org> Alan> The other problem is accessing data in each row by column name. In Alan> Ruby I can say: Alan> Print row["ColName"] Alan> In Python; however, I must access to row contents by integer Alan> index, like PRINT ROW[0], which reduces my program's readability. Alan> Can I access to row's contents by column name? There are a couple things you can try. First, see if the adaptor for your database has a way to specify that query results should be returned as a list of dicts instead of a list of tuples. MySQLdb allows you to select the style of cursor class to instantiate when you create the connection. I think Psycopg provides a dictcursor() method on the connection (though I may be misremembering - it's been awhile). Other adaptors may provide similar functionality. Failing that, you can whip something up yourself using the description attribute to which Fredrik referred: for row in curs.fetchall(): row = dict(zip([d[0] for d in curs.description], row)) ... Skip From steve at holdenweb.com Tue Jun 6 13:26:27 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 06 Jun 2006 18:26:27 +0100 Subject: Newbie: returning dynamicly built lists (using win32com) In-Reply-To: <1149613586.862299.125070@u72g2000cwu.googlegroups.com> References: <1149613586.862299.125070@u72g2000cwu.googlegroups.com> Message-ID: Ransom wrote: > Very newb here, but my question will hopefully be obvious to someone. > > Code: > > import string > from win32com.client import Dispatch > docdir = 'E:\\scripts\\Python\\RSAutomation\\' > > def getOldData(testcases): > > excel = Dispatch("Excel.Application") > excel.Workbooks.Open(docdir + 'FILE.xls') > > # load and create list from file (testcases.csv) > for rsinput in testcases.xreadlines(): > > inputlist = string.split(rsinput, ',') > > > # iterate through and update spreadsheet input > cellx = range(3,51) > values = range(0,48) > for i,r in zip(cellx, values): > > excel.ActiveSheet.Cells(i,2).Value = inputlist[r] > > # TODO: read output from cell 32,6 into a tuple or list and > then return list to __main__ > > [THIS IS WHERE I AM HAVING A PROBLEM] > print excel.ActiveSheet.Cells(32,6) <--This prints properly > as loop executes > > excel.ActiveWorkbook.Close(SaveChanges=0) > excel.Quit() > > if __name__ == "__main__": > csv_testcases = open('arse_testcases.csv','r') > getOldData(csv_testcases) > > OK, so what is happening is that I am sending a list of data to an > overly complicated spreadsheet that produces it's own output (in cell > 32,6). As I loop through multiple test cases, the print statement > calling into COM for the cell data seems to be printing out results > just fine. But when I try and put the output from the spreadsheet into > a dynamic list after the TODO section thusly: > > outputlist = [] > outputlist.extend(excel.ActiveSheet.Cells(32,6) > return outputlist > > I get an error like: > [ 0x15450880>] > That's not an error, that's a list containing a single Python COM object. > I need to be able to return the dynamically generated built up by the > responses from the spreadsheet lookup call (the exce.Activesheet > thingy). Is there a better way to get this dynamically built list out > of the funtion? > > Thanks!!! > I suspect that you need to apply judicious conversions to string or numeric to grab the values of the cells you are interested in, unencumbered by the COM wrappings. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From steve at holdenweb.com Mon Jun 12 02:51:21 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 12 Jun 2006 07:51:21 +0100 Subject: How to link foreign keys & primary keys using python? In-Reply-To: <1150092695.050971.33880@u72g2000cwu.googlegroups.com> References: <1149856668.055162.209650@u72g2000cwu.googlegroups.com> <1150092695.050971.33880@u72g2000cwu.googlegroups.com> Message-ID: sonal.patankar at 3i-infotech.com wrote: > Hi Mr. George, > > Let me try it again... > > I am not using any relational database to store the required tables > with primary keys & foreign keys.... > None the less, you are using relational database terminology. If you want people to understand you then you should use it correctly or explain yourself in other ways ... > When I say PRIMARY KEY => > 1. It means an index is created on the specified fields > (Out of various fields given in the comma separated txt file) > FileFormat: CODE, FIRST_NAME, last_name, area_of_expertise, country > Eg: A1,Harry,George, python, XYZCOUNTRY--------(1st record) > > 2. The index can be formed on a single field or on multiple fields > Eg: a. 'CODE' (single field ) {pk_code} > b. 'CODE' & 'NAME' (multiple fields ) {pk_code_fname} > > Now when I say FOREIGN KEY => > 1. If the foreign Key is formed on the field 'CODE' in another text > file > Format: subsriber_code,CODE,first_name, no_of_posts,active(Y/N) > Eg: SUB_001, A1, Harry, 50, Y > > This means the CODE (A1) given here is checked in the index formed > above > with primary key: pk_code... > > 2. If the foreign Key is formed on the fields 'CODE' & 'FIRST_NAME' > Format: subsriber_code,CODE,FIRST_NAME, no_of_posts,active(Y/N) > Eg: SUB_001, A1, Harry, 50, Y > > This means the CODE (A1) & FIRST_NAME (Harry) given here > are checked in the index formed above with primary key: > pk_code_fname... > > I am done till here..... > > The problem starts if I have defined an index on multiple fields > (composite PK) > say: CODE & FIRST_NAME (pk_code_fname) > and if I need to define a FK on a single field out of these > say: CODE > > I am unable to do that... > Mr. George, I thought i must explain the code i am dealin with, > for better understanding.., but i am sorry i confused you all the more > (incase, u want to view the code please refer to the code snippets in > my first query posted) > > I hope you atleast get an idea of what i am hunting for.... :( > You say you have to use existing code, which is a pity because it seems that code is organised in such a way as to make your problem difficult. The only ways to locate information by a *portion* of the primary key, given that you appear to be using tuples as primary key values, is either to maintain a separate index on the partial key (in other words have a lookup table that holds the partial key values). Note, also, that you run a risk here: there is no guarantee that only one record will have any given partial key value. The whole point of foreign keys in databases is that they are *complete* primary key values, and can therefore refer at at most one occurrence of the referenced entity. It is not correct to refer to a reference to a partial primary key as a "foreign key", precisely because all guarantees of uniqueness are lost. It seems that you are not a native English speaker, so I am sorry if this is leading to further problems. The more simply you can explain yourself the easier it will be to help! regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From fredrik at pythonware.com Wed Jun 7 16:41:30 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 07 Jun 2006 22:41:30 +0200 Subject: Regular expression - dot problem! In-Reply-To: <20060607202924.60898.qmail@web15809.mail.cnb.yahoo.com> References: <20060607202924.60898.qmail@web15809.mail.cnb.yahoo.com> Message-ID: ?? wrote: > I've a problem with regular express(dot problem). I checked Python > Library Reference, but i can't find any infomation that is useful. like what a dot means in a regular expression? you really need to work on your google fu ;-) in the meantime, look under "The special characters are" on this page: http://docs.python.org/lib/re-syntax.html > * if re.compile(pattern).match(urldomain) is not None:* > return INTERNAL_LINK # match. url is internal link if you want to check if the url starts with a given prefix, use if url.startswith(prefix): ... From jo at durchholz.org Wed Jun 14 15:09:08 2006 From: jo at durchholz.org (Joachim Durchholz) Date: Wed, 14 Jun 2006 21:09:08 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: <1150297932.458202.227360@c74g2000cwc.googlegroups.com> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <1150297932.458202.227360@c74g2000cwc.googlegroups.com> Message-ID: Rob Thorpe schrieb: > > If a language can express constraints of one kind that is an increase > in expressiveness. Agreed. > If a language requires constraint to be in one particular way thats a > decrease in expressiveness. Unless alternatives would be redundant. Having redundant ways to express the same thing doesn't make a language more or less expressive (but programs written in it become more difficult to maintain). > So I would say languages that can be statically typed and can be > dynamically typed are the most expressive. Languages that require > static typing or are dynamic but cannot express static typing are less > expressive. Note that this is a different definition of expressiveness. (The term is very diffuse...) I think Felleisen's paper defines something that should be termed "conciseness". Whether there's a way to express constraints or other static properties of the software is something different. I don't have a good word for it, but "expressiveness" covers too much for my taste to really fit. Regards, Jo From jstroud at ucla.edu Fri Jun 9 18:11:36 2006 From: jstroud at ucla.edu (James Stroud) Date: Fri, 09 Jun 2006 15:11:36 -0700 Subject: Most elegant way to generate 3-char sequence In-Reply-To: <1149889784.391965.271570@h76g2000cwa.googlegroups.com> References: <1149889784.391965.271570@h76g2000cwa.googlegroups.com> Message-ID: Rob Cowie wrote: > Hi all, > > I wish to generate a sequence of the form 'aaa', 'aab', aac'.... 'aba', > 'abb', 'abc' etc. all the way to 'zzz'. > > How would you construct a generator to acheive this? > > A simple, working but somewhat inelegant solution is... > > alpha = ['a','b','c','d'] #shortened for brevity > alpha2 = ['a','b','c','d'] > alpha3 = ['a','b','c','d'] > > def generator(): > for char in alpha: > for char2 in alpha2: > for char3 in alpha3: > yield char + char2 + char3 > > x = generate() > x.next() # etc, etc, etc, > import string alpha = string.lowercase def generator(choices, length): for a in choices: if length > 1: for g in generator(choices, length-1): yield a + g else: yield a for a in generator(alpha, 3): print a -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From tero.vantanen at poista.wlanmail.com.invalid Sat Jun 10 23:03:01 2006 From: tero.vantanen at poista.wlanmail.com.invalid (=?UTF-8?B?VCBWw6RudMOkbmVu?=) Date: Sun, 11 Jun 2006 06:03:01 +0300 Subject: Algorithm for Labels like in Gmail In-Reply-To: <1149991446.047249.92020@m38g2000cwc.googlegroups.com> References: <1149985001.668803.121260@c74g2000cwc.googlegroups.com> <1149988373.769406.305720@i40g2000cwc.googlegroups.com> <1149991446.047249.92020@m38g2000cwc.googlegroups.com> Message-ID: <448b87ef$0$24851$39db0f71@news.song.fi> Rodolfo wrote: [...] > Ok, but how can I keep my Relationship Table out of bugs, bad data?! > I wonder how i'll control the following: > 1st) Given an generic email, in which group(s) is it contained? > 2nd) Given a group, which Emails/contacts does it contain? To none perhaps? > I don't have much expererience with databases (yet). > Will the pysqlite work with ease? Because I don't mean to make a big > big program, just something very simple for my personal use. If database sounds like too big beast, there are easy ways to save your objects in the standard library. Take a look at shelve, pickle and cPickle. [...] From brochu121 at gmail.com Fri Jun 2 09:29:19 2006 From: brochu121 at gmail.com (david brochu jr) Date: Fri, 2 Jun 2006 09:29:19 -0400 Subject: Tkinter Message-ID: <9583ed900606020629n6b54b522j117b521ca7ac616e@mail.gmail.com> Does anyone know how to get the value of the file selected when using tk_getOpenFile in Tkinter? -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Tue Jun 6 09:28:45 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 06 Jun 2006 15:28:45 +0200 Subject: capture video from camera In-Reply-To: <1149598946.182874.121650@c74g2000cwc.googlegroups.com> References: <1149598946.182874.121650@c74g2000cwc.googlegroups.com> Message-ID: aljosa wrote: > i'm trying to capture video from camera/webcam using python. > so far i haven't found any library that would allow me to do that. > > cross-platform solution related to SDL/pygame would be nice but a > simple solution to capture video under windows is ok. first google hit for "python video capture": http://videocapture.sourceforge.net/ for linux, see: http://www.antonym.org/libfg From fredrik at pythonware.com Thu Jun 15 15:20:39 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 15 Jun 2006 21:20:39 +0200 Subject: billionlaughs, on me :-(( - on winXP help! In-Reply-To: <1150397596.520219.125780@c74g2000cwc.googlegroups.com> References: <1150397596.520219.125780@c74g2000cwc.googlegroups.com> Message-ID: jmdeschamps at gmail.com wrote: > Looking up different blogs etc on xml parsers I wind up on the site of > Computer stuff, www.razorvine.net. > And in the browser torture section, the billionlaughs.xml link (that > you shouldn't use if you don't know what your doing, as was my case > (mea culpa)) > Thinking I was about to crash the browser, I look up the web for > assorted advice and find nothing except a post about the *killer xml > file*... > So hereb goes nothing... click, hang, reboot, hangs, (mouse pointer > moves, that's it folks) the disk spins occasionally, the vents go up > mad, I guess the CPU is working - have know idea on what. the billion laughs attack is a carefully constructed XML file that takes requires an immense number of CPU cycles to parse... > I'm able to boot in safe mode but don't know what to do next? reboot as usual, and the next time you see a link that says "do NOT click if you don't know what you're doing", don't click on it. From hancock at anansispaceworks.com Wed Jun 28 13:19:24 2006 From: hancock at anansispaceworks.com (Terry Hancock) Date: Wed, 28 Jun 2006 12:19:24 -0500 Subject: Questions about OSS projects. In-Reply-To: References: <1151431692.418333.123060@y41g2000cwy.googlegroups.com> Message-ID: <44A2BA1C.7070208@anansispaceworks.com> Paul McGuire wrote: > "Daniel Dittmar" wrote in message > news:e7tf7j$kio$1 at news.sap-ag.de... > > > If you've written a few small scripts that might be of use to > > others and that you assume that there are others who do the same, > > you might start with a wiki or something like the Python Cookbook > > (http://aspn.activestate.com/ASPN/Python/Cookbook/), but geared > > toward labs and biology. > > I would suggest going the wiki route - wikispaces.com makes this very > easy, and free if you don't mind ads on your wikipages. Could be a > low-cost/low-effort way to get started. Specifically, I would recommend that you build up a links list and/or repository of scripts that you find relevant. Eventually, if there's enough accumulation, somebody might express interest in creating a more integrated tool based on them. Maybe there's somebody who'd be willing to do that, but doesn't know where the material is. Cheers, Terry -- Terry Hancock (hancock at AnansiSpaceworks.com) Anansi Spaceworks http://www.AnansiSpaceworks.com From marshall.spight at gmail.com Wed Jun 21 11:04:35 2006 From: marshall.spight at gmail.com (Marshall) Date: 21 Jun 2006 08:04:35 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> Message-ID: <1150902275.129780.50260@p79g2000cwp.googlegroups.com> Joachim Durchholz wrote: > > Hmm... I think this distinction doesn't cover all cases. > > Assume a language that > a) defines that a program is "type-correct" iff HM inference establishes > that there are no type errors > b) compiles a type-incorrect program anyway, with an establishes > rigorous semantics for such programs (e.g. by throwing exceptions as > appropriate). > The compiler might actually refuse to compile type-incorrect programs, > depending on compiler flags and/or declarations in the code. > > Typed ("strongly typed") it is, but is it statically typed or > dynamically typed? I think what this highlights is the fact that our existing terminology is not up to the task of representing all the possible design choices we could make. Some parts of dynamic vs. static a mutually exclusive; some parts are orthogonal. Maybe we have reached the point where trying to cram everything in two one of two possible ways of doing things isn't going to cut it any more. Could it be that the US two-party system has influenced our thinking? Marshall From bj_666 at gmx.net Sun Jun 18 12:54:32 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sun, 18 Jun 2006 18:54:32 +0200 Subject: Extracting values from text file References: <20060617232543.9a0338fb.randhol+valid_for_reply_from_news@pvv.org> <20060618133459.2a56f781.randhol+valid_for_reply_from_news@pvv.org> Message-ID: In , Mirco Wahab wrote: > You see the picture? Pythons designer made the > same mistake as the Java/Javascript designer - > they use the _same_ operator (+) for number _addition_ > and string _concatenation_, which is, imho, cumbersome. And ``+`` means also list/tuple concatenation and really anything for user defined types. > If you have an operator with meaning "add numbers" (+) > and one for "add strings" (.), the language could then > do the obvious for you. The dot also has already a meaning, it's the attribute lookup operator. > Why would one go from C/C++ to "dynamical typed" > things, if he has to be so explicit on easy > things? Strings that act sometimes as strings and sometimes as numbers when used with ``+`` are quite confusing. Two relevant lines from the Zen of Python: Explicit is better than implicit. In the face of ambiguity, refuse the temptation to guess. And don't mix up weakly and dynamically typed. Python is dynamically and strictly typed. Ciao, Marc 'BlackJack' Rintsch From davecook at nowhere.net Thu Jun 15 18:41:43 2006 From: davecook at nowhere.net (Dave Cook) Date: Thu, 15 Jun 2006 22:41:43 GMT Subject: a good programming text editor (not IDE) References: <_xgkg.2317$No6.48542@news.tufts.edu> Message-ID: On 2006-06-15, John Salerno wrote: > I know there's a request for a good IDE at least once a week on the ng, > but hopefully this question is a little different. I'm looking for > suggestions for a good cross-platform text editor (which the features > for coding, such as syntax highlighting, etc.) but not a full IDE with > all the fancy jazz (GUI developer, UML diagrams, etc.). For something very light, jed has a pretty good python mode that is based on the emacs python-mode. I still swear by XEmacs with python-mode, though I do wish for intelligent code completion sometimes (pycomplete just gives me errors). The XEmacs features that keep me from switching to Gnu Emacs are buffer tabs and hyperlinked error messages. Most IDEs are rather weak as text editors compared to emacsen. On the Mac, you might try Aquamacs; though I don't like the default behavior, a new user would probably have less of a problem with it. Dave Cook From gherron at islandtraining.com Mon Jun 26 21:30:43 2006 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 26 Jun 2006 18:30:43 -0700 Subject: Beginner question: use function to read text file In-Reply-To: References: Message-ID: <44A08A43.9010707@islandtraining.com> Luke wrote: > I'm pretty stuck at the moment and wondering if anyone can spot the problem. > Trying to create a function that will read a text file into a list and > return that list. > > I wrote the following function and saved it as 'fileloader.py' > > def fileload(fname): > infile=open(fname) > dates =[] > times=[] > open=[] > Here's the problem. You are using the name "open" it two contexts. The variable named "open" is a local variable, and as such it hides the builtin function of the same name used to open files. (It does not matter that the use of "open" as a function precedes the use of "open" as a variable name. Python is rather strict about this. If you use a variable in a def, then ANYWHERE in that def, that name refers to the local variable and hides any uses of the name from enclosing scopes.) If that last makes sense, good. If not, then just follow this rule: Choose your variable names to be different than any builtin names -- or at least different than any of the builtin names you intend to use. Gary Herron > high=[] > low=[] > close=[] > vol=[] > count=0 > for line in infile: > item=line.split() > dates.append(item[0]) > times.append(item[1]) > open.append(item[2]) > high.append(item[3]) > low.append(item[4]) > close.append(item[5]) > vol.append(item[6]) > #print > dates[count],times[count],open[count],high[count],low[count],vol[count] > count=count+1 > > > return dates,times,open,high,low,close > > > Then I executed the following script (merge contract v1.py): > > import fileloader > filename='c:/Python24/test/testdata2.txt' > fileloader.fileload(filename) > > > I then get the following error messages: > > Traceback (most recent call last) > File "C:\Python24\test\merge contract v1.py", in line3, in? > fileloader.fileload(filename) > File ("C:\Python24\text\fileloader.py", in line2, in fileload > infile=open(fname) > UnboundLocalError: local variable 'open' referenced before assignment > Script terminated > > Thanks for any help, > Luke > > > From rune.strand at gmail.com Mon Jun 26 13:40:41 2006 From: rune.strand at gmail.com (Rune Strand) Date: 26 Jun 2006 10:40:41 -0700 Subject: Beginner Programmer Question In-Reply-To: <1151343383.139891.219270@u72g2000cwu.googlegroups.com> References: <1151342733.742416.180370@r2g2000cwb.googlegroups.com> <1151343383.139891.219270@u72g2000cwu.googlegroups.com> Message-ID: <1151343641.509435.245210@u72g2000cwu.googlegroups.com> > > I am doing alot of reading, and the problem didnt come with an answer. > I dont understand how to get it to continually input numbers and add > all those together Use while, raw_input, sys.argv[1] and int() and break the loop when the sum is above 100. ;-) From diffuser78 at gmail.com Sun Jun 25 13:12:29 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 25 Jun 2006 10:12:29 -0700 Subject: Python taught in schools? In-Reply-To: <1151220913.406987.162420@u72g2000cwu.googlegroups.com> References: <1151220913.406987.162420@u72g2000cwu.googlegroups.com> Message-ID: <1151255549.642173.25300@u72g2000cwu.googlegroups.com> I think there is a Python club at UCF, Orlando....might help you indirectly. MilkmanDan wrote: > I'll be a college freshman this fall, attending Florida Institute of > Tech studying electrical engineering. > > I was considering taking some classes in programming and computer > science, and I happened to notice that everything taught is using C++. > After further research, it seems to me that C++ seems to be the > dominating language in universities. > > By comparison, our local community college teaches a few classes in VB, > Java, Javascript, C++, and for some reason, PASCAL. > > I'm certianly not against any of this, but out of curiousity does > anyone know of a school that teaches Python? From overly.crazy.steve at gmail.com Fri Jun 2 14:12:38 2006 From: overly.crazy.steve at gmail.com (overly.crazy.steve at gmail.com) Date: 2 Jun 2006 11:12:38 -0700 Subject: execfile then import back In-Reply-To: References: <1149208230.216141.5400@f6g2000cwb.googlegroups.com> <1149208503.207296.204200@i39g2000cwa.googlegroups.com> Message-ID: <1149271958.509934.141110@j55g2000cwa.googlegroups.com> Dennis Lee Bieber wrote: > And the problem you are seeing is that the initial "v" in the t.py > that you "run", is considered "__main__.v", NOT "t.v" Yes, the 2 different copies of v apparently imply that __main__ and t are 2 different modules. But I had expected __main__ to be an alias of t. Can you point out the passage in Python doc that explains this? From faulkner612 at comcast.net Tue Jun 13 10:29:30 2006 From: faulkner612 at comcast.net (faulkner) Date: 13 Jun 2006 07:29:30 -0700 Subject: Linux info In-Reply-To: <448ec675_1@news.tm.net.my> References: <448ec675_1@news.tm.net.my> Message-ID: <1150208970.621031.249840@i40g2000cwc.googlegroups.com> os.path.realpath TheSaint wrote: > Hello there, > > I still learning, but I couldn't find anything which tells me where a > symlink is pointing to. > A part of os.system('ls -l ' + path) and cutting down to the need, I haven't > got any specialized function. > > F From Dennis.Benzinger at gmx.net Fri Jun 2 16:55:25 2006 From: Dennis.Benzinger at gmx.net (Dennis Benzinger) Date: Fri, 02 Jun 2006 22:55:25 +0200 Subject: Using pysqlite2 In-Reply-To: <1149276702.992801.247640@j55g2000cwa.googlegroups.com> References: <1149276702.992801.247640@j55g2000cwa.googlegroups.com> Message-ID: <4480a5c8$1@news.uni-ulm.de> lolmcbride at googlemail.com wrote: > Is it possible to use this for sending triggers to a sqlite db?Could > someone provide me with an example of how to do this please? > Thanks Do you want to implement a trigger for a SQLite database in Python? That won't work. Triggers in SQLite can only contain UPDATE, INSERT, DELETE and SELECT statements http://sqlite.org/lang_createtrigger.html>. Bye, Dennis From cdsmith at twu.net Sun Jun 25 20:16:08 2006 From: cdsmith at twu.net (Chris Smith) Date: Sun, 25 Jun 2006 18:16:08 -0600 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> Message-ID: Chris F Clark wrote: > These informal systems, which may not prove what they claim to prove > are my concept of a "type system". Okay, that works. I'm not sure where it gets us, though, except for gaining you the right to use "type system" in a completely uninteresting sense to describe your mental processes. You still need to be careful, since most statements from type theory about type systems tend to implicitly assume the property of being sound. I'm not exactly convinced that it's possible to separate that set of reasoning people do about programs into types and not-types, though. If you want to stretch the definition like this, then I'm afraid that you end up with the entire realm of human thought counting as a type system. I seem to recall that there are epistemologists who would be happy with that conclusion (I don't recall who, and I'm not actually interested enough to seek them out), but it doesn't lead to a very helpful sort of characterization. > It is to the people who are reasoning informally about > the program we wish to communicate that there is a type error. That > is, we want someone who is dealing with the program informally to > realize that there is an error, and that this error is somehow related > to some input not being kept within proper bounds (inside the domain > set) and that as a result the program will compute an unexpected and > incorrect result. I've lost the context for this part of the thread. We want this for what purpose and in what situation? I don't think we necessarily want this as the goal of a dynamic type system, if that's what you mean. There is always a large (infinite? I think so...) list of potential type systems under which the error would not have been a type error. How does the dynamic type system know which informally defined, potentially unsound, mental type system to check against? If it doesn't know, then it can't possibly know that something is a type error. If it does know, then the mental type system must be formally defined (if nothing else, operationally by the type checker.) > I also stress the informality, because beyond a certain nearly trivial > level of complexity, people are not capable of dealing with truly > formal systems. I think (hope, anyway) that you overstate the case here. We can deal with formal systems. We simply make errors. When those errors are found, they are corrected. Nevertheless, I don't suspect that a large part of the established base of theorems of modern mathematics are false, simply because they are sometimes rather involved reasoning in a complex system. Specifications are another thing, because they are often developed under time pressure and then extremely difficult to change. I agree that we should write better specs, but I think the main challenges are political and pragmatic, rather than fundamental to human understanding. > Therefore, I do not want to exlcude from type systems, things wich are > informal and unsound. They are simply artifacts of human creation. Certainly, though, when it is realized that a type system is unsound, it should be fixed as soon as possible. Otherwise, the type system doesn't do much good. It's also true, I suppose, that as soon as a person realizes that their mental thought process of types is unsound, they would want to fix it. The difference, though, is that there is then no formal definition to fix. -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation From chris.uppal at metagnostic.REMOVE-THIS.org Tue Jun 20 13:51:41 2006 From: chris.uppal at metagnostic.REMOVE-THIS.org (Chris Uppal) Date: Tue, 20 Jun 2006 18:51:41 +0100 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> Message-ID: <4498356b$0$659$bed64819@news.gradwell.net> Chris Smith wrote: > > Easy, any statically typed language is not latently typed. > > I'm actually not sure I agree with this at all. I believe that > reference values in Java may be said to be latently typed. Practically > all class-based OO > languages are subject to similar consideration, as it turns out. Quite probably true of GC-ed statically typed languages in general, at least up to a point (and provided you are not using something like a tagless ML implementation). I think Rob is assuming a rather too specific implementation of statically typed languages. > I'm unsure whether to consider explicitly stored array lengths, which > are present in most statically typed languages, to be part of a "type" > in this sense or not. If I understand your position correctly, wouldn't you be pretty much forced to reject the idea of the length of a Java array being part of its type ? If you want to keep the word "type" bound to the idea of static analysis, then -- since Java doesn't perform any size-related static analysis -- the size of a Java array cannot be part of its type. That's assuming that you would want to keep the "type" connected to the actual type analysis performed by the language in question. Perhaps you would prefer to loosen that and consider a different (hypothetical) language (perhaps producing identical bytecode) which does do compile time size analysis. But then you get into an area where you cannot talk of the type of a value (or variable) without relating it to the specific type system under discussion. Personally, I would be quite happy to go there -- I dislike the idea that a value has a specific inherent type. It would be interesting to see what a language designed specifically to support user-defined, pluggable, and perhaps composable, type systems would look like. Presumably the syntax and "base" semantics would be very simple, clean, and unrestricted (like Lisp, Smalltalk, or Forth -- not that I'm convinced that any of those would be ideal for this), with a defined result for any possible sequence of operations. The type-system(s) used for a particular run of the interpreter (or compiler) would effectively reduce the space of possible sequences. For instance, one could have a type system which /only/ forbade dereferencing null, or another with the job of ensuring that mutability restrictions were respected, or a third which implemented access control... But then, I don't see a semantically critically distinction between such space reduction being done at compile time vs. runtime. Doing it at compile time could be seen as an optimisation of sorts (with downsides to do with early binding etc). That's particularly clear if the static analysis is /almost/ able to prove that is legal (by its own rules) but has to make certain assumptions in order to construct the proof. In such a case the compiler might insert a few runtime checks to ensure that it's assumptions were valid, but do most of its checking statically. There would /be/ a distinction between static and dynamic checks in such a system, and it would be an important distinction, but not nearly as important as the distinctions between the different type systems. Indeed I can imagine categorising type systems by /whether/ (or to what extent) a tractable static implementation exists. -- chris P.S Apologies Chris, btw, for dropping out of a conversation we were having on this subject a little while ago -- I've now said everything that I /would/ have said in reply to your last post if I'd got around to it in time... From frank at chagford.com Tue Jun 13 05:08:01 2006 From: frank at chagford.com (Frank Millman) Date: 13 Jun 2006 02:08:01 -0700 Subject: "groupby" is brilliant! In-Reply-To: References: <1150180151.643245.148210@y43g2000cwc.googlegroups.com> Message-ID: <1150189681.614913.218500@f6g2000cwb.googlegroups.com> Paul McGuire wrote: > > > > reader = csv.reader(open('trans.csv', 'rb')) > > rows = [] > > for row in reader: > > rows.append(row) > > > > This is untested, but you might think about converting your explicit "for... > append" loop into either a list comp, > > rows = [row for row in reader] > > or just a plain list constructor: > > rows = list(reader) > > Neh? > > -- Paul > Yup, they both work fine. There may be times when you want to massage the data before appending it, in which case you obviously have to do it the long way. Otherwise these are definitely neater, the last one especially. You could even do it as a one-liner - rows = list(csv.reader(open('trans.csv', 'rb'))) It still looks perfectly readable to me. Thanks Frank From eric_brunel at despammed.com Thu Jun 1 11:56:03 2006 From: eric_brunel at despammed.com (Eric Brunel) Date: Thu, 01 Jun 2006 17:56:03 +0200 Subject: Function mistaken for a method References: <447ee701$0$22029$626a54ce@news.free.fr> Message-ID: On Thu, 01 Jun 2006 15:07:26 +0200, bruno at modulix wrote: > Do yourself a favour : use new-style classes. > class C(object) I would if I could: I'm stuck with Python 2.1 for the moment (I should have mentionned it; sorry for that). [snip] >> Basically, I want an optional variant function across sub-classes of >> the same class. >> >> I did it like in C1 for a start, then I needed >> something like C2. The result is... surprising: >> >> 0 >> Traceback (most recent call last): >> File "func-vs-meth.py", line 18, in ? >> o2 = C2() >> File "func-vs-meth.py", line 5, in __init__ >> self.x = self.f(0) >> TypeError: () takes exactly 1 argument (2 given) > > Not surprising at all. > > Functions implement the descriptor protocol[1]. When bound to a class > and looked up via an instance, it's the __get__ method of the function > object that get called - with the instance as param, as defined by the > descriptor protocol. This method then return the function wrapped - with > the instance - in an Method object - which itself, when called, returns > the result of calling the function *with the instance as first > parameter*. Which is how methods can work on the instance, and why one > has to explicitly declare the instance parameter in "functions to be > used as methods", but not explicitly pass it at call time. > > (please some guru correct me if I missed something here, but AFAIK it > must be a correct enough description of method invocation mechanism in > Python). > > [1] about descriptors, see: > http://docs.python.org/ref/descriptors.html > http://www.geocities.com/foetsch/python/new_style_classes.htm#descriptors > >> So the first works and o1.x is actually 0. > > int is not a function. >>>> type(int) > > > int is a type. Python 2.1 again: >>> type(int) But as someone mentionned, the problem is the same with other built-in functions, such as chr, even in the latest Python version. I still find that a little counter-intuitive to have different behaviours for a built-in function and a Python function. I really would expect them to work (or not to work) the same in all situations, even if I now understand better how all works behind the scenes. But I'll live with it... [snip] > If you understood all my explanations, you now know how to solve the > problem. > > Else, here the solution: > > class C3(C): > f = lambda self, x: return x This is actually the first thing I did, but it seemed a bit weird to me to have a - let's say - callable with one parameter in one case and another with two parameters in the other one. So I finally turned my callable attribute into a real instance method, just for consistency. Anyway, thanks a lot for your explanations. -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From timr at probo.com Thu Jun 8 01:57:55 2006 From: timr at probo.com (Tim Roberts) Date: Thu, 08 Jun 2006 05:57:55 GMT Subject: follow-up to FieldStorage References: <4484b428$0$29635$636a55ce@news.free.fr> Message-ID: John Salerno wrote: >Bruno Desthuilliers wrote: >> John Salerno a ?crit : >>> If I want to get all the values that are entered into an HTML form and >>> write them to a file, is there some way to handle them all at the same >>> time, or must FieldStorage be indexed by each specific field name? >> >> AFAIK, FieldStorage is a somewhat dict-like object, but I'm not sure it >> supports the whole dict interface. At least, it does support keys(), so >> you should get by with: >> >> for k in fs.keys(): >> print >> myfile, k, ":", fs[k] >> >> But reading the doc may help... > >Thanks. The cgi docs don't seem to get into too much detail, unless I >wasn't thorough enough. But your method seems like it might work well if >I can't find something after another read through. On the other hand, 45 seconds with the source code shows that "class FieldStorage" has member functions called "keys()" and "has_key()". Use the source, Luke. To me, that's one of the big beauties of Python. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From mayyash at gmail.com Tue Jun 27 09:18:14 2006 From: mayyash at gmail.com (fileexit) Date: 27 Jun 2006 06:18:14 -0700 Subject: Re-loading updated modules Message-ID: <1151414294.809032.44850@u72g2000cwu.googlegroups.com> Hi, Shouldn't python recompile a module if there is a later version of the code (.py file)? While i am debuging, i always have to exit python and delete the pyc before every run, then start it again and import the modules. It seems that this is the only way for it to recompile the new code. What is going on? is this normal behaviour? I noticed that on both Windows and linux (Fedora Core 4, and 5 and RHEL 4) From digitalorganics at gmail.com Sun Jun 11 23:02:21 2006 From: digitalorganics at gmail.com (digitalorganics at gmail.com) Date: 11 Jun 2006 20:02:21 -0700 Subject: direct initialization of class attributes vs. declarations w/in __init__ In-Reply-To: References: <1150041510.139609.171120@f6g2000cwb.googlegroups.com> <4f2thrF1fd4r4U1@uni-berlin.de> <1150043792.136250.99770@u72g2000cwu.googlegroups.com> <1150047314.025241.260750@c74g2000cwc.googlegroups.com> <1150062413.303012.177330@f6g2000cwb.googlegroups.com> Message-ID: <1150081341.740383.144910@u72g2000cwu.googlegroups.com> Oh wow, I wasn't expecting so much help. I really appreciate it. My problem, however, has been solved. I uninstalled my ActiveState Python distro on my laptop and installed the distro from python.org along with Stan's Python Editor. I ran the same code I'd run before and guess what? The behavior now matches that of my desktop! Why? *shrug* As for the code being identical, it certainly was as I emailed the .py file to myself (from the laptop) and downloaded it to my desktop where I then ran it just as I had done on the laptop, with PythonWin. Unless Google programmed Gmail to muck w/ people's python code.... Additionally, the bytes on the files match. Thus, I feel I can guarantee that the code is indeed identical. Here's my wild guess: for some reason a bug in PythonWin was causing my changes to the class attribute (i.e. jerk variable) not to be reflected in the actual code. This explanation, if you can call it one, still doesn't make sense to me however because I could make other changes to the code and it would indeed be reflected in execution. Add to the fact that PythonWin is essentially just a text editor, I don't see how/why it would selectively save code changes. It is true that I never restarted the PythonWin IDE after a change of the class attribute to something other than 0, and perhaps reinstalling python etc. was unnecessary. I'm only coming to this realization now. In any event, I am now problem free and quite pleased to be able to exchange .py files between computers and know they'll behave the same (rather, I'm assuming this henceforth). Furthermore, I'd like to thank everyone who tried to help, and that certainly includes Fredrik. Cheers, DigiO From artur_spruce at yahoo.com Wed Jun 21 11:55:39 2006 From: artur_spruce at yahoo.com (AdSR) Date: 21 Jun 2006 08:55:39 -0700 Subject: Python is fun (useless social thread) ;-) References: Message-ID: <1150905339.551741.115980@m73g2000cwd.googlegroups.com> John Salerno wrote: > Did you have to learn it for a job? No, although it became useful once I learnt it. > Or did you just like what you saw and decided to learn it for fun? I saw Bruce Eckel mention it in "Thinking in Java, 2nd ed." as "something that was slowly becoming his favorite programming language". How would *you* react to that? :) > Also, how did you go about learning it? (i.e., like I described above, I > started with the main stuff then moved on to the different available > frameworks) I started with the tutorial, although I didn't read it end-to-end. Then I toyed a little with DB API (MySQLdb). It came useful some two weeks after installing Python, when I was doing some DB refactoring in the (Java) app I was working on at the time. Compared to JDBC, Python DB API is very lightweight, which also taught me how not to overdesign. Later I learnt Tkinter when I wrote a tool for some admin tasks on that DB. I was to lazy to do it in Java. > Was there any necessity in the specifics you learned, or did you just > dabble in something (e.g. wxPython) for fun? See above. > Are there still some things you feel you need to learn or improve? Metaclasses and other magic, if I ever need that stuff. Otherwise, design and algorithms - these are not Python-specific, but Python can be a useful learning tool here. > Additional comments/complains here: :) Every XML API for Python that I tried sucks in one way or another. Try manipulating a document with multiple namespaces, you'll know. Not that I ever saw any XML API in any language that would do everything I expected from it correctly. Ergo, XML sucks. :) Cheers, AdSR From rvtol+news at isolution.nl Fri Jun 23 12:30:16 2006 From: rvtol+news at isolution.nl (Dr.Ruud) Date: Fri, 23 Jun 2006 18:30:16 +0200 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150892256.591282.43880@u72g2000cwu.googlegroups.com> Message-ID: Rob Thorpe schreef: > I would suggest that at least assembly should be referred to as > "untyped". There are many different languages under the umbrella of "assembly", so your suggestion is bound to be false. -- Affijn, Ruud "Gewoon is een tijger." From python.list at tim.thechases.com Fri Jun 9 13:30:38 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 09 Jun 2006 12:30:38 -0500 Subject: Getting start/end dates given week-number In-Reply-To: <1149872045.876974.200050@h76g2000cwa.googlegroups.com> References: <1149872045.876974.200050@h76g2000cwa.googlegroups.com> Message-ID: <4489B03E.6090909@tim.thechases.com> > I think you missed %U format, since later you write: correct. I remember seeing something (a long while back) that had a Sunday-first format, but I must have missed it in my reading of "man strftime". > If you want to match %U: > > def weekBoundaries(year, week): > startOfYear = date(year, 1, 1) > week0 = startOfYear - timedelta(days=startOfYear.isoweekday()) > sun = week0 + timedelta(weeks=week) > sat = sun + timedelta(days=6) > return sun, sat Works wonderfully...Thanks! -tkc From jstroud at mbi.ucla.edu Fri Jun 30 23:39:19 2006 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 01 Jul 2006 03:39:19 GMT Subject: Maximize main window with code In-Reply-To: <44a5e356$0$14238$892e7fe2@authen.yellow.readfreenews.net> References: <44a5e356$0$14238$892e7fe2@authen.yellow.readfreenews.net> Message-ID: JohnJohnUSA wrote: > I am new to Python. How do I get the following program to appear > initially with the window maximized? Thanks for your help! > > from Tkinter import * > # set up the window itself > top = Tk() > F = Frame(top) > F.pack() > # add the widgets > lHello = Label(F, text="Hello") > lHello.pack() > bQuit = Button(F, text="Quit", command=F.quit) > bQuit.pack() > # set the loop running > top.mainloop() > This gets pretty close: top.geometry('%sx%s+0+0' % top.maxsize()) James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From andrewm at object-craft.com.au Mon Jun 26 21:00:36 2006 From: andrewm at object-craft.com.au (Andrew McNamara) Date: Tue, 27 Jun 2006 11:00:36 +1000 Subject: 'r' vs 'rb' in csv (was Re: Python SHA-1 as a method for unique file identification ? [help!]) In-Reply-To: <44a07ddc@news.eftel.com> References: <1150873779.832601.154920@b68g2000cwa.googlegroups.com> <1151354361.950035.274210@u72g2000cwu.googlegroups.com> <44a07ddc@news.eftel.com> Message-ID: <20060627010037.28A646F4AD4@longblack.object-craft.com.au> >> On a semi-related note, I have a database on Linux that imports from a >> Macintosh CSV file. The 'csv' module says to always open files in >> binary mode, but this didn't work in my case: I had to open it as 'rU' >> (text with universal newlines) or 'csv' misparsed it. I'd like the >> program to be portable to Windows and Mac. Is there a way around this? >> Will I really burn in hell for using 'rU'? > >Yes, you will burn in hell for using any old kludge that gets results >(by accident) instead of reading the manual to find a principled solution: > >""" >lineterminator >The string used to terminate lines in the CSV file. It defaults to '\r\n'. >""" > >In the case of a Mac CSV file, '\r' is probably required. Unfortunately, the documentation is misleading in this case: "lineterminator" is only used for output. The documentation specifies that the file should be opened in binary mode, because the CSV parser has it's own idea of "universal newlines". The complicating factor is that newlines can appear quoted inside a field: using universal newlines, these "quoted newlines" would be damaged (because it's unaware of the quoting conventions). If your data file contains no quoted newlines (they're rare, but if you need them, you need them), then opening the file in "universal newline" mode should be harmless (and in this case, is the right thing to do). -- Andrew McNamara, Senior Developer, Object Craft http://www.object-craft.com.au/ From fzhenglee23 at yahoo.com.cn Wed Jun 7 16:29:23 2006 From: fzhenglee23 at yahoo.com.cn (=?gb2312?q?=C0=EE=D5=FE?=) Date: Thu, 8 Jun 2006 04:29:23 +0800 (CST) Subject: Regular expression - dot problem! Message-ID: <20060607202924.60898.qmail@web15809.mail.cnb.yahoo.com> Hi, I've a problem with regular express(dot problem). I checked Python Library Reference, but i can't find any infomation that is useful . Nor did Google. They have the same way: re.compile(''www").match(string). It always works better. But my pattern string must be an argument of re.compile(). In this case, I can not use Here is my code. Bold text is where the problem is. Is there anyone know the right way to do this. ---------------------------------------------------------------------------------------------------------- def getLinkType(url, sitedomain): # get the domain which 'url' belongs to urldomain = urlparse4esa(url)[1] tmpsd = '' if re.compile('^www').match(sitedomain) is not None: tmpsd = sitedomain[4:] tmpsd.replace('.', '\.') # it seems that it doesn't work pattern = tmpsd + '$' # this is my pattern string. # Example: pattern 'ibm.com' if re.compile(pattern).match(urldomain) is not None: return INTERNAL_LINK # match. url is internal link else: return EXTERNAL_LINK # doesn't match. url is external link ---------------------------------------------------------------------------------------------------------- Alex, China __________________________________________________ ??????????????? http://cn.mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Wed Jun 7 18:27:02 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 08 Jun 2006 00:27:02 +0200 Subject: How do I get the process id when starting a process using os.popen2 or os.popen3 on linux? In-Reply-To: <1149717934.308699.166930@i39g2000cwa.googlegroups.com> References: <1149717934.308699.166930@i39g2000cwa.googlegroups.com> Message-ID: mikem76 at gmail.com wrote: > Is there a way to get the process id when starting a process using > os.popen2 or os.popen3 on linux? on Unix, os.popen2/popen3 uses functions and classes from the popen2 module. they return file objects attached to the process, but there's no (non-hacky) way to get at the process itself. if you need more control over the subprocess, you can use the classes in the popen2 module, or, better, the subprocess module. From ray_usenet at yahoo.com Fri Jun 2 02:02:17 2006 From: ray_usenet at yahoo.com (Ray) Date: 1 Jun 2006 23:02:17 -0700 Subject: Are there something like "Effective Python"? In-Reply-To: <1149224468.481470.74580@i39g2000cwa.googlegroups.com> References: <1149224468.481470.74580@i39g2000cwa.googlegroups.com> Message-ID: <1149228137.540238.161060@f6g2000cwb.googlegroups.com> I think Aahz stated somewhere that he was workign on Effective Python. I'm not sure if it's an ongoing plan or it's been canned though? Mike Meng wrote: > Hi all, > I just finished reading Learning Python 3rd ed, and am doing my > first Python application, which retrieves and process text and XML > documents from Web. Python helped me to write the application in a few > hours, I'm very happy with its productivity. But the performance is not > satisfactory. I decide to optimized it in Python before trying C/C++ > extensions. But I don't know Python much and have no clu to tune my > program. Also, I don't know what Pythonist's preferred styles. Are > there any books/documents which play the similar role for Python as > 'Effective C++' does for C++? > > For example, one of my friends read my program and suggest me to > move the re.compile() out of a for-loop, since the regular pattern is > fixed, and re.compile() is slow. I want to find more such advice, where > can I find them? > > Thank you. > > Mike From duncan.booth at invalid.invalid Fri Jun 23 10:24:03 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 23 Jun 2006 14:24:03 GMT Subject: what exceptions may file() and read() throw? References: Message-ID: Daniel Sch?le wrote: > Hello, > > currently I am using this instance method > > def getFilecontent(self, filename): > try: > return file(filename).read() > except IOError, err_msg: > print err_msg > sys.exit(1) > except: > print "unknown exception in PackageParser" > sys.exit(1) > > I tried to open a file for which I don't have the permissions to read > (etc/shadow) > and I tried to open a file which doesn't exist > in both cases I got IOError exception, so my question is > does it make sence to have > > except: > print "unknown exception in PackageParser" > sys.exit(1) > > or is it a dead code? It is dead code in the sense that it simply converts every exception into a SystemExit exception thereby losing information from the message and the traceback which might have helped you track down the problem. If you aren't able to do anything useful with an exception then the best thing is almost always to let it propogate upwards to somewhere it can be handled usefully. That generally means that exceptions you haven't thought of need to be communicated to a human who can lodge a bug report or fix the code. You can't easily list the exceptions that your code could throw. There are some obvious ones apart from IOError: say filename was an int (or even certain strings) you would get TypeError, or you might get MemoryError or KeyboardInterrupt. More obscurely, if you reused file as a global variable you could generate any exception at all. From nmm1 at cus.cam.ac.uk Wed Jun 14 13:21:23 2006 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 14 Jun 2006 17:21:23 GMT Subject: Numerics, NaNs, IEEE 754 and C99 References: <12904mjhl493t49@corp.supernews.com> <1290aik50hmk94a@corp.supernews.com> <4490329e$0$12356$636a55ce@news.free.fr> Message-ID: In article , Gary Herron writes: |> Christophe wrote: |> > Grant Edwards a =E9crit : |> > |> >> The division by zero trap is really annoying. In my world the |> >> right thing to do is to return Inf. |> > |> > Your world is flawed then, this is a big mistake. NaN is the only=20 |> > aceptable return value for a division by zero. |> > |> Sorry, but this is not true. |> |> The IEEE standard specifies (plus or minus) infinity as the result of |> division by zero. This makes sense since such is the limit of division |> by a quantity that goes to zero. The IEEE standard then goes on to |> define reasonable results for arithmetic between infinities and real |> values. The production of, and arithmetic on, infinities is a choice |> that any application may want allow or not. That is true, and it is numerical nonsense. Christophe is right. Despite Kahan's eminence as a numerical analyst, he is no software engineer. And I am amazed at ANY engineer that can believe that inverting zero should give infinity - while there ARE circumstances where it is correct, it is NEVER a safe thing to do by default. The reason is that it is correct only when you know for certain that the sign of zero is meaningful. IEEE 754 gets this wrong by conflating true zero, sign-unknown zero and positive zero. Inter alia, it means that you get situations like: A = 0.0; B = -A; C = B+0.0; A == B == C; 1/A != 1/B != 1/C; Regards, Nick Maclaren. From claird at lairds.us Fri Jun 23 15:54:54 2006 From: claird at lairds.us (Cameron Laird) Date: Fri, 23 Jun 2006 19:54:54 +0000 Subject: Opening a file with system default application References: <1151077662.598370.214490@c74g2000cwc.googlegroups.com> <1151080644.805513.257140@r2g2000cwb.googlegroups.com> <1151081172.418493.190730@i40g2000cwc.googlegroups.com> Message-ID: In article , Marc 'BlackJack' Rintsch wrote: >In <1151081172.418493.190730 at i40g2000cwc.googlegroups.com>, >BartlebyScrivener wrote: > >>>> It would probably break like mad under *nix >> >> I bet it would work the same way on linux or os x; it's the equivalent >> of double-clicking on the file. > >No it doesn't work. Double clicking is not an OS thing but a a GUI thing. . . . HOWEVER this is just the question Portland is designed to answer. If you can wait a few weeks, I'll publish an article focused almost exactly on the topic at hand. From g.brandl-nospam at gmx.net Wed Jun 28 04:39:01 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Wed, 28 Jun 2006 10:39:01 +0200 Subject: Immutability In-Reply-To: References: Message-ID: Nick Maclaren wrote: > In article , > Robert Kern writes: > |> Nick Maclaren wrote: > |> > The way that I read it, Python allows only values (and hence types) > |> > to be immutable, and not class members. The nearest approach to the > |> > latter is to use the name hiding conventions. > |> > > |> > Is that correct? > |> > |> You can also make properties that don't allow writing. > |> > |> class Foo(object): > |> > |> def __init__(self, bar): > |> self._bar = bar > |> > |> @property > |> def bar(self): > |> return self._bar > > Thanks very much. And, what's more, I have even found its documentation! > Whatsnew2.2. The 2.4.2 reference is, er, unhelpful. Is it? http://docs.python.org/lib/built-in-funcs.html documents "property" quite well. Georg From struggleyb at gmail.com Mon Jun 12 02:16:11 2006 From: struggleyb at gmail.com (Bo Yang) Date: Mon, 12 Jun 2006 14:16:11 +0800 Subject: An error ? Message-ID: <448D06AB.3070104@gmail.com> Hi , I am confronted with an odd question in the python cgi module ! Below is my code : import cgitb ; cgitb.enable() import cgi print "Hello World !" How easy the script is , and the url is 202.113.239.51/vote/cgi/a.py but apache give me a 'Server internal error !' and the error log is : [Fri Jun 16 14:06:45 2006] [error] [client 10.10.110.17] malformed header from script. Bad header=Hello World!: a.py I wish somebody could help me , thanks in advance ! Best Regard ! From rbann11 at hotmail.com Fri Jun 9 17:43:59 2006 From: rbann11 at hotmail.com (rbann11 at hotmail.com) Date: 9 Jun 2006 14:43:59 -0700 Subject: wxpython wxgrid question In-Reply-To: <44872b73$0$7769$7a628cd7@news.club-internet.fr> References: <1149366330.999234.299880@u72g2000cwu.googlegroups.com> <1149393484.553463.286220@i39g2000cwa.googlegroups.com> <44872b73$0$7769$7a628cd7@news.club-internet.fr> Message-ID: <1149889439.662650.154260@f6g2000cwb.googlegroups.com> jean-michel bain-cornu wrote: > rbann11 at hotmail.com a ?crit : > > Tim Roberts wrote: > >> rbann11 at hotmail.com wrote: > >>> I am looking for example code that consists of just a frame and a > >>> grid(10x2). The grid must fill the its parent even if the frame is > >>> resized. > >> Have you gone through the wxPython demo application? It contains examples > >> of every standard control and almost every behavior you might want. > >> -- > >> - Tim Roberts, timr at probo.com > >> Providenza & Boekelheide, Inc. > > > > Yes, and i have even checked out "wxpython in action". All of the > > examples tend to leave white space on the right of the frame. I tried > > basic a example with sizers and it didnt work. That why I was > > wondering if someone had got it to work. > > > > > > Roger > > > Hi Roger, > A key point is that the Grid manages itself its available space > according to the size it can have. > If you just tried to create a simple grid within a simple frame, you > probably got a grid filling all the frame space, and it's what you want. > Why that ? > If you do it (for instance with the script below), and you try to > manually reduce/increase the size of the window, you should see > scrollbars at the edge of the window ; these scrollbars come from the > grid, because they take in account the labels row and col (wxGrid comes > from wxScrolledWindow). You can see that no more space is available > beyond the scrollbar, so the grid takes the whole space. > And why the white space on the right ? This space is not on the right of > the grid, but on the right of the last col. We could think it's like > that because it's not possible to compute an appropriate col size for > the grid cols, but it's not displayed exactly the same in linux and in > windows. In one case it's over the last col (not enough space) and in > the other case it's beyond (too much space). I think that as the program > must work on all the environments, the interface must stay enough > global, and sometimes the display is not perfectly done. > The advantage is that if we let wx decide, we won't have to think how to > set the widgets. > Regards, > jm > > #---------------------------------------------------------------------- > import wx,wx.grid > #---------------------------------------------------------------------- > class MainWindow(wx.Frame): > def __init__(self,parent,id,title): > wx.Frame.__init__(self,parent,wx.ID_ANY,title) > #-- > self.grid= wx.grid.Grid(id=wx.ID_ANY,parent=self) > self.grid.CreateGrid(numRows=10,numCols=2) > self.grid.Fit() > self.Fit() > #-- > self.Show(1) > #---------------------------------------------------------------------- > app = wx.PySimpleApp() > frame=MainWindow(None,-1,'Grid sizer') > app.MainLoop() > del app > #---------------------------------------------------------------------- Thanks Tim, I knew it was something like that, but I had to ask the question. I was hoping that there was a way around the problem. Roger From greg at cosc.canterbury.ac.nz Tue Jun 13 00:59:32 2006 From: greg at cosc.canterbury.ac.nz (greg) Date: Tue, 13 Jun 2006 16:59:32 +1200 Subject: ANN: PyGUI 1.7.2-1 In-Reply-To: <1150165048.582537.53640@h76g2000cwa.googlegroups.com> References: <1150165048.582537.53640@h76g2000cwa.googlegroups.com> Message-ID: <448E4634.90506@cosc.canterbury.ac.nz> hale at tulane.edu wrote: > if I try to run blobedit.py in the IDLE ide ... > the path is equal to "8833" for some > reason. I believe that IDLE sets up some kind of debugging connection to its child process. That number might be a processs ID or port number or something related to that. > I tried to hunt down where the problem occurs, but I was led > to the method "application_openFile_(self, ns_app, path)" in the > class _PyGui_NSApplication. I couldn't find out how this method > ever got called though. It's called by the Cocoa framework to handle files passed to the application from the Finder. It also seems to get called when there are command-line arguments. But it works on the C-level argv, which means it can pick up stuff that doesn't normally end up in sys.argv. The check for sys.argv[0] is there to work around one of the side effects of that. It appears that you've encountered another one. I'm using a different method of dealing with this now, which will probably fix your problem as well. I've attached a replacement for GUI/Cocoa/Applications.py. Let me know if it works for you. -- Greg -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: Applications.py URL: From frank at chagford.com Sat Jun 3 02:58:53 2006 From: frank at chagford.com (Frank Millman) Date: 2 Jun 2006 23:58:53 -0700 Subject: wxPython problems with Fedora Core 5 In-Reply-To: <1149271626.481398.34440@h76g2000cwa.googlegroups.com> References: <1149271626.481398.34440@h76g2000cwa.googlegroups.com> Message-ID: <1149317933.786386.304070@c74g2000cwc.googlegroups.com> writeson wrote: > Hi all, > > I'm trying to use wxPython from a fairly new installation of Fedora > Core 5. I installed wxPython using yum -y install wxPython and that all > seemed to work fine. However, when I run Python and do this: > > import wx > > I get this: > > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/lib/python2.4/site-packages/wx/__init__.py", line 45, in ? > from wxPython import wx > File "/usr/lib/python2.4/site-packages/wxPython/__init__.py", line > 20, in ? > import wxc > ImportError: /usr/lib/libwx_gtk2-2.4.so.0: undefined symbol: > pango_x_get_context > > Anyone have any ideas what's going on and what I can do to fix this? > > Thanks in advance, > Doug Here is a link to a message in the wxpython-users mailing list archive, which apparently gives the solution to your problem. http://tinyurl.com/gf276 I cannot vouch for it. I installed wxPython on FC5 without any problems, using the FC4 binary rpm's from wxPython.org. Hope it works for you. Frank Millman From shejo284 at gmail.com Mon Jun 12 04:31:38 2006 From: shejo284 at gmail.com (Sheldon) Date: 12 Jun 2006 01:31:38 -0700 Subject: printing all variables In-Reply-To: References: <1150098291.647296.86340@f6g2000cwb.googlegroups.com> Message-ID: <1150101098.078633.81270@u72g2000cwu.googlegroups.com> Duncan Booth skrev: > Sheldon wrote: > > > Good day, > > > > I would like to know if there is a way to print all the variables set > > in a python program with having to write > > "print variable" on all? > > > Not all the variables in a program (that would be rather more than you > want), but you can print all the variables in a specific namespace easily > enough: > > >>> from pprint import pprint > >>> def f(x): > pprint(locals()) > > > >>> f(2) > {'x': 2} > >>> pprint(globals()) > {'__builtins__': , > '__doc__': None, > '__name__': '__main__', > 'f': , > 'pprint': } > >>> class C: > classvar = [] > def __init__(self, n): > self.n = n > > > >>> c = C(3) > >>> pprint(vars(c)) > {'n': 3} > >>> pprint(vars(C)) > {'__doc__': None, > '__init__': , > '__module__': '__main__', > 'classvar': []} > >>> Thanks Duncan! This really helps! /Sheldon From agr at fq.uniovi.es Wed Jun 28 04:19:54 2006 From: agr at fq.uniovi.es (=?UTF-8?B?w4FuZ2VsIEd1dGnDqXJyZXogUm9kcsOtZ3Vleg==?=) Date: Wed, 28 Jun 2006 10:19:54 +0200 Subject: Beginner question? Classes, variables, ... Message-ID: The problem: I have two classes: class X: def __init__(self): pass class Y: def __init__(self): self.a=1 self.b=X() and I would like to make 'a' visible inside 'x'. Is there a way to refer to the Y class from the X? To make things easier :), each class is in a different file, so class X is imported. Or the only way I have is to pass 'a' as a variable in each method call of 'b' ('a' can take different values that affect to the behaviour of 'b'). Thanks in advance. -- ?ngel Guti?rrez Rodr?guez - agr at fq.uniovi.es Instituto de Ciencia de los Materiales de Madrid - CSIC SpLine - European Syncrothorn Radiation Facility - Grenoble - France Postal adress: Departamento de Qu?mica F?sica y Anal?tica Universidad de Oviedo - c/Juli?n Claver?a 8 33006 - Oviedo Asturias - Spain E-mail: agr at fq.uniovi.es Telf.: +34-985103687 From kay.schluehr at gmx.net Tue Jun 6 11:27:29 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 6 Jun 2006 08:27:29 -0700 Subject: Namespace problems References: <1149603634.391551.229700@c74g2000cwc.googlegroups.com> Message-ID: <1149607648.951461.322910@j55g2000cwa.googlegroups.com> Kiran wrote: > Hello All, > I am kind of a beginner to python, but here is the deal. > > I am writing a wxpython Application, in which I have a GUI. This GUI > imports some other modules that I have written, using the format > import mymodule as _MyModule > > Now, this GUI in addition to having all it's bells and whistles has a > console (from pyshell), so that the user can run their own scripts > inside this GUI. > What I am trying to do is to get these scripts that the user runs to > be able to see all the other objects created and modules imported by > the GUI. > > To make this clear, what I want to be able to do for example is in my > script, do , > dir(mymodule), > already having imported mymodule in the GUI. > Any ideas on how to make this happen? I don't want to import > mymodule in this script, i want this script to see the mymodule that I > imported in the main GUI. > > thanks a lot for your help, > Kiran Well, it depends on the context. If the __main__ context is that of PyShell it will likely contain no GUI object and you shall pass the GUI to PyShell before a PyShell window is created ( e.g. PyShell.__dict__["GUI"] = GUI ). Descendent objects like mymodule that live in the GUI context will be accessible in the usual way i.e. by GUI.mymodule. You can experiment a little bit with contexts. Simply open a Python session and import PyShell: >>> import PyShell >>> PyShell.main() # causes creation of main window for PyShell Now you can inspect locals of PyShell using dir(). In this case the __main__ context is that of the top level session in which PyShell runs as an own session. You just have to import GUI to make it accessible to PyShell. If PyShell is the __main__ context you might assign GUI as described above. Regards, Kay From nmm1 at cus.cam.ac.uk Fri Jun 30 06:11:10 2006 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 30 Jun 2006 10:11:10 GMT Subject: Interprocess communication on multi-user machine References: <44a41cae$0$29145$9b4e6d93@newsread4.arcor-online.net> Message-ID: In article , Lawrence D'Oliveiro writes: |> In article <44a41cae$0$29145$9b4e6d93 at newsread4.arcor-online.net>, |> Michael Butscher wrote: |> |> >Normally any user could connect to an open socket on a machine |> >regardless which user established the socket (the user's program, to be |> >precise). |> |> That's not true. On *nix systems, a socket is a file, and is subject to |> the usual file ownership and protection mechanisms. I am afraid that BOTH answers are badly wrong! Sockets are often accessed via special files, but are not files. They may also be accessed by port numbers, for example. Secondly, even when they are accessed via files, FIFOs generally do NOT use the usual file ownership and protection mechanisms to control access. Blame Berkeley for that :-( It is normal for the actual file ownership and permissions to be ignored, and a similar set (hidden internally) to be used. You are right that there is almost always such control. While any user can attempt to open any socket accessed by port number, the rules for when it is permitted are complicated to a degree, and depend on the system, configuration and program that is listening on that port. Regards, Nick Maclaren. From rhymes at myself.com Thu Jun 29 08:01:07 2006 From: rhymes at myself.com (Lawrence Oluyede) Date: Thu, 29 Jun 2006 14:01:07 +0200 Subject: mmap as a sequence behavior References: <1hho1x1.1ntwxi3z2hdzhN%rhymes@myself.com> Message-ID: <1hhp5em.1hfcek51snnwmpN%rhymes@myself.com> Lawrence Oluyede wrote: > What am I missing from the C API? Found. I edit abstract.c placing some printf here and there and discovered PyObject_GetItem is always called and in turn it call PySequence_GetItem so is there my index is translated. -- Lawrence - http://www.oluyede.org/blog "Nothing is more dangerous than an idea if it's the only one you have" - E. A. Chartier From rupole at hotmail.com Wed Jun 14 21:09:38 2006 From: rupole at hotmail.com (Roger Upole) Date: Wed, 14 Jun 2006 21:09:38 -0400 Subject: How to select a folder with native windows dialog box? References: <1150237380.370088.29270@p79g2000cwp.googlegroups.com> <1150252926_60371@sp6iad.superfeed.net> <1150317678.028483.49080@i40g2000cwc.googlegroups.com> Message-ID: <1150333450_5593@sp6iad.superfeed.net> wrote in message news:1150317678.028483.49080 at i40g2000cwc.googlegroups.com... > Thanks for your answer, it's working fine! > > For information, the function to use to get the pathName is > shell.SHGetPathFromIDList > It returns an error if you select a special folder (!?!?) but otherwise > it's working fine... And I was unable to fix this issue. SHGetPathFromIDList only works for real filesystem folders. Pseudo-folders like Control Panel or Network Connections throw an error. You can use PyIShellFolder.BindToObject to get an interface to perform operations on these. Roger From steve at holdenweb.com Fri Jun 9 08:36:09 2006 From: steve at holdenweb.com (Steve Holden) Date: Fri, 09 Jun 2006 13:36:09 +0100 Subject: Win XP: Problem with shell scripting in Python In-Reply-To: References: Message-ID: A.M wrote: > "Fredrik Lundh" wrote in message > news:mailman.6785.1149837599.27775.python-list at python.org... > >>A.M wrote: >> >> >>in python, "MD" is spelled os.mkdir. >> >> >>>Am I missing anything? >> >>the difference between STDOUT and STDERR, and the difference between >>buffered output and non-buffered output, and perhaps a few other things >>related to how STDIO behaves on modern computers... however, if you want >>to pretend that STDOUT and STDERR are the same thing, you can use >>os.popen4: >> >> >>>>>o, i = os.popen4("md :") >>>>>i.read() >> >>'The filename, directory name, or volume label syntax is incorrect.\n' >> >>or the subprocess module. >> >> >>>Considering the fact that Ruby doesn't have any problem with redirecting >>>STDOUT into files or string variables, is Python the right tool for >>>this kinds of shell scripting? >> >>rewriting BAT files as a series of os.system or os.popen calls isn't >>exactly optimal (neither for the computer nor the programmer nor the >>future user); better take an hour to skim the "generic operating system >>services" section in the library reference, and use built-in functions >>wherever you can: >> >> http://docs.python.org/lib/allos.html >> >>the following modules are especially useful: >> >> http://docs.python.org/lib/module-os.html >> http://docs.python.org/lib/module-os.path.html >> http://docs.python.org/lib/module-glob.html >> http://docs.python.org/lib/module-shutil.html >> >>by using the built-in tools, you get better performance in many cases, >>better error handling, and code that's a lot easier to reuse (also on >>non-Windows platforms). >> >> >> > > > Thanks Fredrik for help. > > > > The "MD :" is just a sample. The actual script contains different commands. > > > > The actual script that I am "translating" consolidates huge table data from > multiple SQL Server database into Oracle. I have to use BCP command line at > the SQL server side and SQL*Loader at the Oracle side. > > > > I must capture the stdout/stderr output of command lines into log files for > future inspection/troubleshooting. Beside the issue with stdout/stderror, > the main stressful problem that I have is the fact that Python captures > command line's output somehow differently. For example, popen captures BCP's > command output completely wrong. Some part of summary is at the top and the > progress percentages are at the bottom and more.! This is just stdout > output. > > > > I am going to investigate other popen4 and other popen forms per your > suggestion and try to fix the stdout sequence problem. > I dare hardly suggest this, but might it not be better to use Python's database functionality to perform the task? The language can access both databases, and you might find it quicker. Then again, if your database experience is limited, you may not ... regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From jparlar at cogeco.ca Sun Jun 11 00:00:50 2006 From: jparlar at cogeco.ca (Jay Parlar) Date: Sun, 11 Jun 2006 00:00:50 -0400 Subject: Can I set timeout for the sys.stdin.readline() ? In-Reply-To: <1149930880.741381.230270@i40g2000cwc.googlegroups.com> References: <1149930880.741381.230270@i40g2000cwc.googlegroups.com> Message-ID: On Jun 10, 2006, at 5:14 AM, ywzhan wrote: > Hi, I am new here. > When I use sys.stdin.readline() to get input string from user, > how can I set a timeout value for this operation? > thank you. > > You can do a select() on sys.stdin, and put a timeout on the select, ie: rfds, wfds, efds = select.select( [sys.stdin], [], [], 5) would give you a five second timeout. If the timeout expired, then rfds would be an empty list. If the user entered something within five seconds, then rfds will be a list containing sys.stdin. Note that by "user entered something", I mean they pressed Enter/Return. The select will not exit if they just enter other text. Jay P. From crazymykl at gmail.com Sun Jun 11 16:43:04 2006 From: crazymykl at gmail.com (MacDonald) Date: 11 Jun 2006 13:43:04 -0700 Subject: Killing a thread In-Reply-To: References: <7c8a9a970606091338t174fbcb0wc73cdb8b385f8ccd@mail.gmail.com> <7c8a9a970606091354u73308bf8o2758eea5ef690c39@mail.gmail.com> <1149889827.2754.6.camel@kenshin.CASA> <448A0D8A.4000008@mvista.com> <1149965895.702667.3970@u72g2000cwu.googlegroups.com> Message-ID: <1150058584.276456.278840@u72g2000cwu.googlegroups.com> Fredrik Lundh wrote: > crazymykl at gmail.com wrote: > > >> it cannot be done in a portable way, so that's not very likely. > > > def __run(self): > > """Hacked run function, which installs the trace.""" > > sys.settrace(self.globaltrace) > > self.__run_backup() > > self.run = self.__run_backup > > I'm not sure using a non-portable API to run the code under a "custom > debugger" qualifies as a "portable implementation", though... Everything used is a part of the standard library, which is portable, AFAICT. Could you say specifically what is non-portable? > have you benchmarked this, btw? It has some overhead, but it should only be used in situations where one line will either return before the timeout or take far too long. E. g. an eval() statement with code generated from user input should return quickly for reasonable entries, but something like "9**9**9" will trigger the timeout. > From marc.t.davies at gmail.com Thu Jun 8 11:26:56 2006 From: marc.t.davies at gmail.com (MTD) Date: 8 Jun 2006 08:26:56 -0700 Subject: How to generate k+1 length strings from a list of k length strings? In-Reply-To: <1149773165.890230.228960@g10g2000cwb.googlegroups.com> References: <1149773165.890230.228960@g10g2000cwb.googlegroups.com> Message-ID: <1149780416.430558.251860@h76g2000cwa.googlegroups.com> Jon Clements wrote: > Are you asking the question, "Which pairs of strings have one character > different in each?", or "Which pairs of strings have a substring of > len(string) - 1 in common?". > > Jon. I imagine it's the former because the latter is trivially easy, I mean _really_ trivially easy. From cito at online.de Sat Jun 3 22:06:30 2006 From: cito at online.de (Christoph Zwerschke) Date: Sun, 04 Jun 2006 04:06:30 +0200 Subject: reordering elements of a list In-Reply-To: <1149382009.640607.217470@y43g2000cwc.googlegroups.com> References: <1149382009.640607.217470@y43g2000cwc.googlegroups.com> Message-ID: greenflame wrote: > Suppose the main list is: mainlist = list('qwertyuiop') > Suppose the ordering list is: orderinglist = [3, 4, 2, 1] > > Then I am looking for a function that will take mainlist and > orderinglist as arguments and return the following list: > > ['e', 'r', 'w', 'q', 't', 'y', 'u', 'i', 'o', 'p'] > > Also by the way the main list is always going to be a list of strings > and the ordering list will be a list of numbers. Also the largest > number in orderinglist will always be equal to the length of > orderinglist. I hope this makes any sense. Thanks for your help. The following will do: map(lambda c, i: i and mainlist[i-1] or c, mainlist, orderinglist) -- Christoph From python.list at tim.thechases.com Wed Jun 21 13:09:18 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 21 Jun 2006 12:09:18 -0500 Subject: [newbie] Iterating a list in reverse ? In-Reply-To: <1150909005.604896.122290@m73g2000cwd.googlegroups.com> References: <1150909005.604896.122290@m73g2000cwd.googlegroups.com> Message-ID: <44997D3E.1090301@tim.thechases.com> > Python newbie: I've got this simple task working (in about ten > different ways), but I'm looking for the "favoured" and "most Python > like" way. > > Forwards I can do this > for t in listOfThings: > print t > > Now how do I do it in reverse? Then general process would be to use the reversed() iterator: for t in reversed(listOfThings): print t Python provides a sorted() wrapper of the same non-in-place form. -tkc From digitalorganics at gmail.com Sun Jun 11 12:36:32 2006 From: digitalorganics at gmail.com (digitalorganics at gmail.com) Date: 11 Jun 2006 09:36:32 -0700 Subject: direct initialization of class attributes vs. declarations w/in __init__ In-Reply-To: <4f2thrF1fd4r4U1@uni-berlin.de> References: <1150041510.139609.171120@f6g2000cwb.googlegroups.com> <4f2thrF1fd4r4U1@uni-berlin.de> Message-ID: <1150043792.136250.99770@u72g2000cwu.googlegroups.com> Ah, you've brought me much clarity Diez, thank you. That would explain some "bugs" I've been having... Diez B. Roggisch wrote: > digitalorganics at gmail.com schrieb: > > What's the difference between initializing class variables within the > > class definition directly versus initializing them within the class's > > __init__ method? Is there a reason, perhaps in certain situations, to > > choose one over the other? > > You are confusing class variables with instance variables. The former > are what you can initialize inside the class-statement. However, they > are shared amongst _all_ instances. Consider this little example: > > class Foo(object): > FOO = 1 > BAR = [] > > def __init__(self, FOO): > self.FOO = FOO > self.BAR.append(FOO) > > def __repr__(self): > return "FOO: %r\nBAR: %r\n" % (self.FOO, self.BAR) > > > f1 = Foo(1) > print f1 > f2 = Foo(2) > print f2 > print f1 > > > ------ > meskal:~/Projects/CameraCalibrator deets$ python2.4 /tmp/test.py > FOO: 1 > BAR: [1] > > FOO: 2 > BAR: [1, 2] > > FOO: 1 > BAR: [1, 2] > > > ----- > > As you can see, the list BAR is shared. And you can also see that > _assigning_ to something like this: > > self.FOO > > will create an instance-variable. Even if a variable of the same name > existed on the class before! > > Which is precisely the difference between using variable initialization > in __init__ and inside the class-statement. > > BTW, > > self.__class__.FOO = value > > will set class-variables inside a method. Just if you wondered. > > Diez From mhellwig at xs4all.nl Wed Jun 7 08:30:35 2006 From: mhellwig at xs4all.nl (Martin P. Hellwig) Date: Wed, 07 Jun 2006 14:30:35 +0200 Subject: secure xmlrpc server? In-Reply-To: References: Message-ID: <4486c6ee$0$31647$e4fe514c@news.xs4all.nl> Laszlo Nagy wrote: Have a look at: http://trevp.net/tlslite/ -- mph From jo at durchholz.org Fri Jun 16 17:59:07 2006 From: jo at durchholz.org (Joachim Durchholz) Date: Fri, 16 Jun 2006 23:59:07 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: <2006061611492350073-raffaelcavallaro@pasdespamsilvousplaitmaccom> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <2006061410510511272-raffaelcavallaro@pasdespamsilvousplaitmaccom> <2006061501423327544-raffaelcavallaro@pasdespamsilvousplaitmaccom> <2006061611492350073-raffaelcavallaro@pasdespamsilvousplaitmaccom> Message-ID: Raffael Cavallaro schrieb: > There is a very large class of software where user inputs are > unpredictable and/or where input data comes from an untrusted source. In > these cases run-time checks are going to be needed anyway so the > advantages of static type checking are greatly reduced - you end up > doing run-time checks anyway, precisely the thing you were trying to > avoid by doing static analysis. There's still a large class of errors that *can* be excluded via type checking. > Ideally one wants a language with switchable typing - static where > possible and necessary, dynamic elsewhere. That has been my position for a long time now. > To a certain extent this is > what common lisp does but it requires programmer declarations. Some > implementations try to move beyond this by doing type inference and > alerting the programmer to potential static guarantees that the > programmer could make that would allow the compiler to do a better job. I think it's easier to start with a good (!) statically-typed language and relax the checking, than to start with a dynamically-typed one and add static checks. With the right restrictions, a language can make all kinds of strong guarantees, and it can make it easy to construct software where static guarantees abound. If the mechanisms are cleverly chosen, they interfere just minimally with the programming process. (A classical example it Hindley-Milner type inference systems. Typical reports from languages with HM systems say that you can have it verify thousand-line programs without a single type annotation in the code. That's actually far better than you'd need - you'd *want* to document the types at least on the major internal interfaces after all *grin*.) With a dynamically-typed language, programming style tends to evolve in directions that make it harder to give static guarantees. > It seems to > me that if we set aside that class of software where safety is paramount > - mostly embedded software such as aircraft and medical devices - we are > left mostly with efficiency concerns. Nope. Efficiency has taken a back seat. Software is getting slower (barely offset by increasing machine speed), and newer languages even don't statically typecheck everything (C++, Java). (Note that the impossibility to statically typecheck everything in OO languages doesn't mean that it's impossible to do rigorous static checking in general. FPLs have been quite rigorous about static checks; the only cases when an FPL needs to dynamically typecheck its data structures is after unmarshalling one from an untyped data source such as a network stream, a file, or an IPC interface.) The prime factor nowadays seems to be maintainability. And the difference here is this: With dynamic typing, I have to rely on the discipline of the programmers to document interfaces. With static typing, the compiler will infer (and possibly document) at least part of their semantics (namely the types). > So static typing should be invoked for that small portion of a program > where efficiency is really needed and that dynamic typing should be the > default elswhere. This is how common lisp works - dynamic typing by > default with static guarantees available where one needs them. Actually static typing seems to become more powerful at finding errors as the program size increases. (Yes, that's a maintainability argument. Efficiency isn't *that* important; since maintenance is usually the most important single factor, squelching bugs even before testing is definitely helpful.) Regards, Jo From wanja at merlinux.de Thu Jun 29 06:02:07 2006 From: wanja at merlinux.de (Wanja Saatkamp) Date: Thu, 29 Jun 2006 12:02:07 +0200 Subject: Release of PyPy videos Message-ID: <44A3A51F.30203@merlinux.de> The PyPy team is happy to announce that the first bunch of PyPy videos can now be downloaded from: http://codespeak.net/pypy/dist/pypy/doc/video-index.html The videos introduce involved people and contain different talks, tutorials and interviews such as: 1. Technical talk on the PyPy architecture, standard interpreter, translation toolchain and Just-in-time compiler at the University of Palma de Mallorca (72 min) 2. Coding discussion between Armin Rigo and Samuele Pedroni during the PyPy sprint at the University of Palma de Mallorca (40 min) 3. Core developer Holger Krekel and project manager Beatrice During explain the agile open source methods used in the PyPy project at Pycon, Dallas (26 min) 4. Core developers Michael Hudson and Christian Tismer are giving an introductory talk at Pycon, Dallas (28 min) 5. A PyPy architecture session given by core developers Holger Krekel and Armin Rigo at Pycon, Dallas (48 min) 6. A Sprint tutorial by core developer Michael Hudson who provides a detailed and hands-on overview about the architecture of PyPy, especially the translation toolchain (44 min) 7. What do you think about PyPy? Interview with American software developer Bob Ippolito at this year's PyCon, Dallas (8 min) 8. Interview with CPython core developer Tim Peters at this year's PyCon, Dallas (23 min) Some technical details: All films are in European PAL system, encoded with DivX and packed in .avi file format. The files can be downloaded using a bittorrent client. Further details regarding downloading and viewing can be found at the URL above. Have fun and don't hesitate to contact us at pypy-dev at codespeak.net if you encounter any problems or have any other comments, Best regards, Wanja Saatkamp & the PyPy team From fredrik at pythonware.com Thu Jun 15 14:02:15 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 15 Jun 2006 20:02:15 +0200 Subject: a good programming text editor (not IDE) In-Reply-To: References: <_xgkg.2317$No6.48542@news.tufts.edu> <1150393919.514359.55580@h76g2000cwa.googlegroups.com> Message-ID: John Salerno wrote: >> jEdit is for me still the best text editor available. Very extensible >> with macros (which can be written in Jython with the appropriate plugin >> installed). > > I like the idea of being extensible, but of course I can only write in > Python. Are there any editors that support that? Jython is a Python implementation for Java. From fredrik at pythonware.com Tue Jun 6 10:12:51 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 06 Jun 2006 16:12:51 +0200 Subject: Expanding Search to Subfolders In-Reply-To: References: <1149526866.681348.273590@c74g2000cwc.googlegroups.com> Message-ID: Lou Losee wrote: > How about something like: > import os, stat > > class DirectoryWalker: > # a forward iterator that traverses a directory tree, and > # returns the filename > ... > not tested speak for yourself ;-) (the code is taken from http://effbot.org/librarybook/os-path.htm ) From michael.f.ellis at gmail.com Thu Jun 1 14:32:15 2006 From: michael.f.ellis at gmail.com (michael.f.ellis at gmail.com) Date: 1 Jun 2006 11:32:15 -0700 Subject: An oddity in list comparison and element assignment In-Reply-To: <127u81kdf70ch8d@corp.supernews.com> References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> <127u81kdf70ch8d@corp.supernews.com> Message-ID: <1149186735.650036.62670@i39g2000cwa.googlegroups.com> Yes. You stated it quite precisely. I believe l1==l2 should always return True and l1==l3 should always be False. (unless l3 is reassigned as l3=l1). Your idea of a separate operator for 'all elements have numerically equal values at the moment of comparision' is a good one. For want of a better name, it could be called DeepCopyEquality(a,b) and would be equivalent to a byte-by-byte comparison of two distinct regions in memory created by a deep copies of a and b. Cheers, Mike Jim Segrave wrote: > In article <1149177617.985251.74560 at c74g2000cwc.googlegroups.com>, > wrote: > >Hi Alex, > >With all due respect to your well-deserved standing in the Python > >community, I'm not convinced that equality shouldn't imply invariance > >under identical operations. > > > >Perhaps the most fundamental notion is mathematics is that the left and > >right sides of an equation remain identical after any operation applied > >to both sides. Our experience of the physical world is similar. If I > >make identical modifications to the engines of two identical > >automobiles, I expect the difference in performance to be identical. > >If my expectation is met, I would assert that either the two vehicles > >were not identical to begin with or that my modifications were not > >performed identically. > > > >As to containers, would you say that envelope containing five $100 > >bills is the same as an envelope containing a single $100 bill and 4 > >xerox copies of it? If so, I'd like to engage in some envelope > >exchanges with you :-) > > > >As I see it, reference copying is a very useful performance and memory > >optimization. But I don't think it should undermine the validity of > >assert(a==b) as a predictor of invariance under identical operations. > > I think you end up with a totally unwieldy definition of '==' for > containers, since you have to check for _identical_ aliasing to > whatever depth it might occur, and, if you insist on equality > modeling the physical world, two lists can only be equal if: > > for each corresponding element in the two lists, either the element is > a reference to the same underlying object or the corresponding > elements are references to objects which do not have and never will > have other references bound to them. > > For example: > > ra = ['a', 'a'] > rb = ['b', 'b'] > > l1 = [ra, rb] > l2 = [ra, rb] > > This will be equal by your definition and will preserve equality over > identical operations on l1 and l2 > > l3 = [ ['a', 'b'], ['a', 'b']] > > This list will be identical, under your definition, so long as we > don't have anyone doing anything to the references ra or rb. Your > equality test has to claim that l1 and l3 are not equal, since ra > could be changed and that's not an operation on l1 or l3 > > This also leaves out the complexity of analysiing nested structures - > if you have a tuple, containing tuples which contain lists, then are > those top level tuples 'equal' if there are aliases in the lists? How > many levels deep should an equality test go? > > Does the more common test, to see if the elements of a sequence are > identical at the time of comparision need a new operator or hand > coding, since most of the time programmers aren't interested in future > equality or not of the structures. > > -- > Jim Segrave (jes at jes-2.demon.nl) From tdelaney at avaya.com Sun Jun 4 18:29:58 2006 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Mon, 5 Jun 2006 08:29:58 +1000 Subject: C# equivalent to range() Message-ID: <2773CAC687FD5F4689F526998C7E4E5F074380@au3010avexu1.global.avaya.com> Luis M. Gonz?lez wrote: > There are thousands of threads to choose from in this forum. > If they didn't like this question, they could have picked any other > one to discuss. > There's no need to be disagreeable :-) Well, there are reasons to reply to a message stating that it's not on-topic for the group. The most common reaction to receiving no replies is to start a new thread petulantly asking why there were no answers to the original thread. If that one gets no replies the most common reaction is start another new thread stating that Python sucks, the newsgroup sucks, etc. Not saying that this is what would have happened in this case, but it is the most common sequence of events. Better to head it off before it happens. At least any upset replies tend to be restricted to the one thread ;) Unfortunately, posting a good response, whilst apparently helpful, tends to encourage further off-topic postings :( Tim Delaney From arvind.mulay at gmail.com Thu Jun 29 05:29:07 2006 From: arvind.mulay at gmail.com (arvind) Date: 29 Jun 2006 02:29:07 -0700 Subject: Widget access Message-ID: <1151573347.600081.221380@x69g2000cwx.googlegroups.com> how to make the widgets defined inside the function available outside it without using OOPs concept? From me at privacy.net Thu Jun 8 22:50:42 2006 From: me at privacy.net (Dan Sommers) Date: Thu, 08 Jun 2006 22:50:42 -0400 Subject: dynamic inheritance References: <_IidnWMwvOnfRBXZnZ2dneKdnZydnZ2d@comcast.com> Message-ID: On Thu, 08 Jun 2006 21:14:48 -0400, alf wrote: > is there any way to tell the class the base class during runtime? >>> class A(object): >>> pass >>> class B(object): >>> pass >>> o = A() >>> o.__class__ >>> o.__class__ = B >>> o.__class__ I don't know if that's a good idea. Maybe this one: class A(object): pass class B(object): pass if some_function(): C = A else: C = B class D(C): pass Why do you want to change a class' base class during runtime? HTH, Dan -- Dan Sommers "I wish people would die in alphabetical order." -- My wife, the genealogist From grante at visi.com Wed Jun 7 09:56:32 2006 From: grante at visi.com (Grant Edwards) Date: Wed, 07 Jun 2006 13:56:32 -0000 Subject: what are you (not) using python language for? References: Message-ID: <128dmogrr1uts08@corp.supernews.com> On 2006-06-07, robert wrote: > I am curious for what kind of (new) serious programs and projects the > Python language and its offsprings like Pyrex would not be the optimal > programming language currently? The stuff I work on for which I don't use Python: * Device drivers (Linux and BSD). * Embedded systems. Even at the high end of things, my projects have only a few MB of memory -- not nearly enough to run Python. There's really not much point in discussing Python for the smaller projects with 16KB of ROM and 256 bytes of RAM. ;) -- Grant Edwards grante Yow! I'm gliding over a at NUCLEAR WASTE DUMP near visi.com ATLANTA, Georgia!! From deets at nospam.web.de Tue Jun 20 06:09:28 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 20 Jun 2006 12:09:28 +0200 Subject: comparing two arrays References: <1150721380.948808.231760@h76g2000cwa.googlegroups.com> <4fnlbiF1j83q2U1@uni-berlin.de> <4fnqoqF1k8n10U1@uni-berlin.de> <1150795424.752973.303420@g10g2000cwb.googlegroups.com> Message-ID: <4fpvr0F1k8dauU1@uni-berlin.de> >> print [i for i, _ in enumerate((None for x, y in zip(a, b) where x == >> y))] >> >> instead. >> >> Diez > > Hi Diez, > > I wish I say that I understood what you wrote here but I can't. > Do you mind explaining a little more? I actually made a typo, instead of "where" in the above use "if". and the whole thing won't compute what you are after. This will: [i for i, equals in enumerate((x == y for x, y in zip(a, b))) if equals] Sorry for that. Its a nested list-comprehension. Actually, the outer thingy is a list-comprehension while the inner is a generator expression. There is of course a difference, but for now this doesn't matter too much. a list comprehension of form [ for in if ] is a more compact form for result = [] for in : if : result.append() A generator expression works the same with () instead of []. Now let's decompose the above statment: (x == y for x, y in zip(a, b) )) = x, y = zip(a, b) = x == y So: the iterable is returned by the function zip. That is a built-in which will take 2 or more lists and return a list of tuples, where the first element is from the first list, then the second and so on. So your example lists become: a = [0,1,2,5,6,6] b = [5,4,1,6,4,6] zip(a, b) = [(0,5), (1,4), (2,1), (5,6), (6,4), (6,6)] So iterating over this yields the pairs of (0,5) and so forth. Next thing is that with x, y = p python unpacks a tuple and refers to its contents by name x for the first one and y for the second. So overall, we loop in sync over both lists, and getting x and y to point to the corresponding elements. Now the expression x == y will result True if x == y - False otherwise. So the result of the inner listcomp/genexp looks like this: res = [False, False, False, False, False, True] As you can see: for each pair x,y in the original lists we come up with the result of comparing them. Now the outer listcomp using "res" instead of the genexps for clarity reads like this: [i for i, equals in enumerate(res) if equals] = i, equals = enumerate(res) = i = equals enumerate is another built-in that takes an iterable and returns a tuple of (pos, element) for each element in the iterable. So for our list, it will return: [(0, False), (1, False), (2, False), (3, False), (4, False), (5, True)] These tupkes values are assigened to i and equals for each element of the above list. The condtion equals will then guarantee that only those expressions are evaluated where equals is True - the last pair, so to speak. The expression then only stores the index i. Which will give us the desired result. Diez From marshall.spight at gmail.com Wed Jun 21 11:00:19 2006 From: marshall.spight at gmail.com (Marshall) Date: 21 Jun 2006 08:00:19 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> Message-ID: <1150902019.850531.204740@g10g2000cwb.googlegroups.com> Chris Smith wrote: > > When I used the word "type" above, I was adopting the > working definition of a type from the dynamic sense. That is, I'm > considering whether statically typed languages may be considered to also > have dynamic types, and it's pretty clear to me that they do. I suppose this statement has to be evaluated on the basis of a definition of "dynamic types." I don't have a firm definition for that term, but my working model is runtime type tags. In which case, I would say that among statically typed languages, Java does have dynamic types, but C does not. C++ is somewhere in the middle. Marshall From tim.peters at gmail.com Wed Jun 21 04:34:45 2006 From: tim.peters at gmail.com (Tim Peters) Date: Wed, 21 Jun 2006 04:34:45 -0400 Subject: Python SHA-1 as a method for unique file identification ? [help!] In-Reply-To: <1150873779.832601.154920@b68g2000cwa.googlegroups.com> References: <1150873779.832601.154920@b68g2000cwa.googlegroups.com> Message-ID: <1f7befae0606210134w1dabf47ak6e583925def5acb7@mail.gmail.com> [EP ] > This inquiry may either turn out to be about the suitability of the > SHA-1 (160 bit digest) for file identification, the sha function in > Python ... or about some error in my script It's your script. Always open binary files in binary mode. It's a disaster on Windows if you don't (if you open a file in text mode on Windows, the OS pretends that EOF occurs at the first instance of byte chr(26) -- this is an ancient Windows behavior that made an odd kind of sense in the mists of history, and has persisted in worship of Backward Compatibility despite that the original reason for it went away _long_ ago). ... > I am trying to reduce duplicate files in storage at home - I have a > large number files (e.g. MP3s) which have been stored on disk multiple > times under different names or on different paths. ... > All seemed to be working until I examined my log files and found files > with the same SHA digest had different sizes according to > os.stat(fpath).st_size . This is on Windows XP. > > - Am I expecting too much of SHA-1? No. SHA-1 should work well for this. > - Is it that the os.stat data on Windows cannot be trusted? It can be trusted to the extent that anything on Windows can be trusted ;-) ... > def hashit(pth): > """Takes a file path and returns a SHA hash of its string""" > fs=open(pth,'r').read() Make that 'rb' instead of 'r', and your problem will go away. Do note that there are faster ways to go about this. For example, if a particular file has a unique size among the files you're looking at, there's no reason to even open that file (let alone compute its hash). Group the files by size, and within a size group you can find duplicates by, e.g., first comparing their initial 16 bytes, then the next 32, then the next 64 ... etc. If duplicates are uncommon, this can be a huge savings. For example, here's output from an old dup-finding Python program of mine run over a directory tree which happens to contain no duplicates: Files ----- Total 10,718 Unique 10,718 Duplicate 0 # w/ unique size 10,053 # w/ unique prefix 665 Bytes ----- Total 1,401,668,015 Unique 1,401,668,015 Duplicate 0 Read 76,688 Excess 76,688 That last two lines mean it actually read a total of only about 77,000 file bytes on its way to proving there were no duplicates among about 11,000 files spanning about 1.4 gigabytes. No hashes are computed by that program. I'd use a hash if instead I were going to save a persistent (across runs) set of known hashes, so that answering "here's a new file -- same as one I already have?" could be done by computing its hash. While the program above generally reads "amazingly" few file bytes, it hammers the OS file directory services, and it would go faster to compute a hash of a new file than to run the whole analysis again. From Bulkan at gmail.com Sat Jun 24 09:01:21 2006 From: Bulkan at gmail.com (placid) Date: 24 Jun 2006 06:01:21 -0700 Subject: search engine In-Reply-To: <1151151361.359777.269130@y41g2000cwy.googlegroups.com> References: <1151151361.359777.269130@y41g2000cwy.googlegroups.com> Message-ID: <1151154081.787601.121110@i40g2000cwc.googlegroups.com> George Sakkis wrote: > vinodh kumar wrote: > > hai all, > > i am student of computer science dept. i have planned to > > design a search engine in python. i am seeking info about how to > > proceed further. > > i need to know what r the modules that can be used. > > There is not a "search engine module" around AFAIK. You should do your > homework first and learn about search engines in a language-independent > way from some good textbook such as "Mining the Web" > (http://http.cs.berkeley.edu/~soumen/mining-the-web/), break the > problem into subparts and decide which ones you will implement. By then > you should have a much better idea of what modules to look for. > Anyway, if you are going to design a new search engine and implement it then you will probably need to use modules only as a helper to your algorithm. From johnjsal at NOSPAMgmail.com Tue Jun 13 09:50:01 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 13 Jun 2006 13:50:01 GMT Subject: wxpython: how do i write this without the id parameter? In-Reply-To: <448e430d$1@nntp0.pdx.net> References: <448e430d$1@nntp0.pdx.net> Message-ID: Scott David Daniels wrote: > class InputForm(wx.Frame): > def __init__(self, parent=None, id=-1, title=__file__): > # or, if you prefer: ..., id=wx.ID_ANY, ... > wx.Frame.__init__(self, parent=parent, id=id, > title='%s v%s' % (title, __version__)) > class MyApp(wx.App): > def OnInit(self): > frame = InputForm(title='Data Entry Form') > self.SetTopWindow(frame) > frame.Show() > return True Thanks, but there was an example (which I can't find now) somewhere in the wxPython wiki that showed a call to wx.Frame without the id parameter at all, like wx.Frame(parent, title). How is that possible? Is the issue with my code just that I'm passing the parameters around and so I can't be as concise as that? From rossberg at ps.uni-sb.de Thu Jun 22 11:30:04 2006 From: rossberg at ps.uni-sb.de (Andreas Rossberg) Date: Thu, 22 Jun 2006 17:30:04 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: <449aaea0$0$656$bed64819@news.gradwell.net> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <0%Wlg.3521$MF6.947@tornado.socal.rr.com> <44992e6c$0$664$bed64819@news.gradwell.net> <449aaea0$0$656$bed64819@news.gradwell.net> Message-ID: Chris Uppal wrote: > >>>It's worth noting, too, that (in some sense) the type of an object can >>>change over time[*]. >> >>No. Since a type expresses invariants, this is precisely what may *not* >>happen. If certain properties of an object may change then the type of >>the object has to reflect that possibility. Otherwise you cannot >>legitimately call it a type. > > Well, it seems to me that you are /assuming/ a notion of what kinds of logic > can be called type (theories), and I don't share your assumptions. No offence > intended. OK, but can you point me to any literature on type theory that makes a different assumption? > I see no reason, > even in practise, why a static analysis should not be able to see that the set > of acceptable operations (for some definition of acceptable) for some > object/value/variable can be different at different times in the execution. Neither do I. But what is wrong with a mutable reference-to-union type, as I suggested? It expresses this perfectly well. - Andreas From grante at visi.com Wed Jun 28 16:21:37 2006 From: grante at visi.com (Grant Edwards) Date: Wed, 28 Jun 2006 20:21:37 -0000 Subject: Passing a Cookie with httplib References: Message-ID: <12a5p6h9ug19818@corp.supernews.com> On 2006-06-28, scott at bogusaddress.com wrote: > From a shell script, I have used /usr/bin/curl to access a web site > and pass a cookie I use ClientCookie for that. http://wwwsearch.sourceforge.net/ClientCookie/ -- Grant Edwards grante Yow! I'm into SOFTWARE! at visi.com From jstroud at ucla.edu Thu Jun 1 00:51:25 2006 From: jstroud at ucla.edu (James Stroud) Date: Wed, 31 May 2006 21:51:25 -0700 Subject: ideas for programs? In-Reply-To: References: Message-ID: A digest of the major points summarizing the consensus opinion: Thomas Bartkus wrote: > Python is your tool to put your expertise on a computer. Skill with Python, > or any computer language for that matter, counts for little. And akameswaran at gmail.com wrote: > As far as employment. I come from a java background, and that seems > the only language I can pay the bills with:). Particularly in the US > paid python jobs are hard to come by. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From daniel.dittmar at sap.corp Wed Jun 28 04:39:14 2006 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Wed, 28 Jun 2006 10:39:14 +0200 Subject: Questions about OSS projects. In-Reply-To: <1151431692.418333.123060@y41g2000cwy.googlegroups.com> References: <1151431692.418333.123060@y41g2000cwy.googlegroups.com> Message-ID: bio_enthusiast wrote: > I was wondering how to go about starting an open source project for > doing routine biological problems? There is a plethora of scripts and > a fairly large biopython project to back up anyone who tried, these > however cater to the bioinformatics community and it loses the vast > majority of the wet-lab scientists. How can someone who is used to > writing small scripts and doing wet-lab work contribute to the open > source community? Starting software projects seems to be the domain of > people with much more experience and skill but there are some serious > needs by people who do not have the skills to upkeep any software > based project. > If you've written a few small scripts that might be of use to others and that you assume that there are others who do the same, you might start with a wiki or something like the Python Cookbook (http://aspn.activestate.com/ASPN/Python/Cookbook/), but geared toward labs and biology. If this gains any traction (that is if you get additional code snippets, people are commenting etc.), after a while, it might be useful to look at the material and see if there is enough code that warrants a library. This does not mean to simply package all the scripts into one package, but to see if there are any common tasks among the scripts to 'refactor' them into a library. Daniel From deets at nospam.web.de Tue Jun 6 09:33:25 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 06 Jun 2006 15:33:25 +0200 Subject: 10GB XML Blows out Memory, Suggestions? In-Reply-To: References: <1149594519.098115.8980@u72g2000cwu.googlegroups.com> Message-ID: <4eleh3F1eguosU1@uni-berlin.de> K.S.Sreeram schrieb: > axwack at gmail.com wrote: >> I wrote a program that takes an XML file into memory using Minidom. I >> found out that the XML document is 10gb. > > With a 10gb file, you're best bet might be to juse use Expat and C!! No what exactly makes C grok a 10Gb file where python will fail to do so? What the OP needs is a different approach to XML-documents that won't parse the whole file into one giant tree - but I'm pretty sure that (c)ElementTree will do the job as well as expat. And I don't recall the OP musing about performances woes, btw. Diez From micklee74 at hotmail.com Wed Jun 7 13:00:10 2006 From: micklee74 at hotmail.com (micklee74 at hotmail.com) Date: 7 Jun 2006 10:00:10 -0700 Subject: printing backslash Message-ID: <1149699610.014336.98540@g10g2000cwb.googlegroups.com> hi how can i sucessfully print |\| in the output of a print command a = "|\|" print a but it gives me "|\\|" i tried raw strings too, but it doesn't print |\| . It prints |\\| instead eventually, i also want |\| to be inside a list: alist = ["|\|", 'blah', 'blah'] . How can i put |\| inside a list? can someone show me how it can be done? thanks From dale_huffman at steris.com Wed Jun 7 09:54:19 2006 From: dale_huffman at steris.com (Dale Huffman) Date: 7 Jun 2006 06:54:19 -0700 Subject: what are you using python language for? In-Reply-To: References: Message-ID: <1149688459.498335.249090@i39g2000cwa.googlegroups.com> hacker1017 wrote: > im just asking out of curiosity. Embedded control system From jmdeschamps at gmail.com Wed Jun 7 13:44:27 2006 From: jmdeschamps at gmail.com (jmdeschamps at gmail.com) Date: 7 Jun 2006 10:44:27 -0700 Subject: GUI Program Error In-Reply-To: <1149700099.634036.88090@f6g2000cwb.googlegroups.com> References: <1149536396.375285.319390@y43g2000cwc.googlegroups.com> <920hg.2238$No6.47697@news.tufts.edu> <1149700099.634036.88090@f6g2000cwb.googlegroups.com> Message-ID: <1149702267.402484.266070@f6g2000cwb.googlegroups.com> Byte wrote: > Thanks, this works. Now, since the tutorial I was using is clearly > rubbish, any better ones? For a (relative) newbie please. Also, how do > I code a GUI Hello World program? > > -- /usr/bin/byte How does John Salerno previous code NOT fit the bill? >> John Salerno wrote: >> ... >> import Tkinter as tk >> >> root = tk.Tk() >> label = tk.Label(root, text='Hello world!') >> label.pack() >> root.mainloop() >> ... I think you should get a copy of "an-introduction-to-tkinter" from Fredrik Lundh and try out the different usage examples and experiment, then post more specific questions (after searching this newsgroup since many questions lie here already answered). From rbonvall at gmail.com Mon Jun 5 18:45:53 2006 From: rbonvall at gmail.com (Roberto Bonvallet) Date: Mon, 5 Jun 2006 18:45:53 -0400 Subject: Storing nothing in a dictionary and passing it to a function In-Reply-To: <1149527899.364138.312150@j55g2000cwa.googlegroups.com> References: <1149527899.364138.312150@j55g2000cwa.googlegroups.com> Message-ID: <1908cb6b0606051545t7d24e83fteaec07c3e47e8e4b@mail.gmail.com> 63q2o4i02 at sneakemail.com: > I'd like to have a dictionary (actually a nested dictionary) to call > these functions so I can avoid if-then-elsing everything. Eath > dictionary item has three things in it: the function to be called, a > string to pass to the function (which is also the key to the dict), and > a tuple to pass to the function. In the case of the function with no > arguments, obviously I'd like not to pass anything. [...] > something like this: > alldict = \ > {'pulse': {'func': self.arbtrandef, 'args':(2,5)},\ > 'sin' : {'func': self.arbtrandef, 'args':(2,3)},\ > 'exp' : {'func': self.arbtrandef, 'args':(2,4)},\ > 'pwl' : {'func': self.pwldef , 'args': (None,)},\ <------- how > do I store "no" arguments? > 'sffm' : {'func': self.arbtrandef, 'args':(5,0)}} > > for it in alldict.items(): > name = it[0] > args = (name,) + it[1]['args'] > it[1]['func'](*args) I would do it like this: alldict = { 'pulse': (self.arbtrandef, (2, 5)), # function and args packed in a tuple 'sin' : (self.arbtrandef, (2, 3)), 'exp' : (self.arbtrandef, (2, 4)), 'pwl' : (self.pwldef, ()), # empty tuple represented by () 'sffm' : (self.arbtrandef, (5, 0)), } for (fname, (func, args)) in alldict.items(): # items unpacked directly func(fname, *args) Best regards. -- Roberto Bonvallet From gherron at islandtraining.com Sun Jun 25 02:26:39 2006 From: gherron at islandtraining.com (Gary Herron) Date: Sat, 24 Jun 2006 23:26:39 -0700 Subject: MSoffice metadata In-Reply-To: <1151209771.276872.299240@b68g2000cwa.googlegroups.com> References: <1151209771.276872.299240@b68g2000cwa.googlegroups.com> Message-ID: <449E2C9F.3060109@islandtraining.com> micklee74 at hotmail.com wrote: > hi > is there a module in Python to extract metadata in MS office documents > thanks > > Perhaps. OpenOffice can read and write MS office files, and OpenOffice has an API (called UNO for Universal Network Objects) which has a Python binding (called the Python-UNO bridge). This might (eventually) get you what you want. Here's a URL for it: http://udk.openoffice.org/python/python-bridge.html Good luck, Gary Herron From bignose+hates-spam at benfinney.id.au Fri Jun 16 01:20:48 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 16 Jun 2006 15:20:48 +1000 Subject: BeautifulSoup error References: <871wtpdbas.fsf@www.williamxu.com> Message-ID: <874pylllqn.fsf@benfinney.id.au> William Xu writes: > >>> import urllib > >>> from BeautifulSoup import BeautifulSoup > >>> url = 'http://www.google.com' > >>> port = urllib.urlopen(url).read() Gets the data from the HTTP response. (I'm not sure why you call this "port".) The data is HTML text encoded to a string of bytes according to the character encoding specified in the response header fields. > >>> soup = BeautifulSoup() > >>> soup.feed(port) > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/lib/python2.3/sgmllib.py", line 94, in feed > self.rawdata = self.rawdata + data > UnicodeDecodeError: 'ascii' codec can't decode byte 0xb8 in position 565: ordinal not in range(128) > >>> Uses the default Python text encoding, 'ascii', when it needs to decode the data in 'port' to Unicode. Some of the data in that object makes no sense in the 'ascii' encoding, so it barfs. > Any ideas to solve this? Get the character encoding specified in the HTTP response, and decode the data to Unicode from that encoding. -- \ "Man cannot be uplifted; he must be seduced into virtue." -- | `\ Donald Robert Perry Marquis | _o__) | Ben Finney From onurb at xiludom.gro Fri Jun 16 09:11:32 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 16 Jun 2006 15:11:32 +0200 Subject: a good programming text editor (not IDE) In-Reply-To: References: <_xgkg.2317$No6.48542@news.tufts.edu> <1150393919.514359.55580@h76g2000cwa.googlegroups.com> Message-ID: <4492ae05$0$19179$626a54ce@news.free.fr> John Salerno wrote: > Ant wrote: > >> jEdit is for me still the best text editor available. Very extensible >> with macros (which can be written in Jython with the appropriate plugin >> installed). > > > I like the idea of being extensible, but of course I can only write in > Python. Jython is Python on Java. > Are there any editors that support that? Emacs. Which BTW is just great for python programming - not only do you have an embedded interactive python shell - the default one or IPython - but much more, you can with a simple keystroke eval either the whole buffer or a selected block in this embedded shell. Could'nt live without it no more !-) (and you have ecb if you want a file/class browser) But learning other languages might be a good idea too (even if once spoiled by Python, if can be quite frustrating). -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From iainking at gmail.com Fri Jun 30 09:45:58 2006 From: iainking at gmail.com (Iain King) Date: 30 Jun 2006 06:45:58 -0700 Subject: conecting with a MsAcces DB by dao In-Reply-To: <1151671163.810358.215630@d56g2000cwd.googlegroups.com> References: <1151650208.783778.186690@d56g2000cwd.googlegroups.com> <1151655436.083906.143380@75g2000cwc.googlegroups.com> <1151663549.731904.259030@d56g2000cwd.googlegroups.com> <1151665145.582514.262970@75g2000cwc.googlegroups.com> <1151671163.810358.215630@d56g2000cwd.googlegroups.com> Message-ID: <1151675158.630796.151270@m73g2000cwd.googlegroups.com> luis wrote: > Iain King ha escrito: > > > luis wrote: > > > Iain King ha escrito: > > > > > > > luis wrote: > > > > > while not rs.EOF: > > > > > id=rs.Fields(colName.Value) #colName, valid column name > > > > > ... > > > > > rs.MoveNext() > > > > > rs.Close() > > > > > conn.Close() > > > > > > > > I don't know if it's the problem your asking about, but your > > > > rs.MoveNext() should be inside the while loop, no? > > > Yes, is inside > > > > > > > > You mean, it is inside the while loop in your code, but you made a > > mistake copying it into your post? In the code you posted it is not > > inside the while loop - it would have to be indented one more level for > > that. > > > > Iain > > this is te correct identation > > def append_from_Access(self): > try: > import ... > conn = win32com.client.Dispatch(r'ADODB.Connection') > DSN = "PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA > SOURCE=C:/Afile.mdb;" > conn.Open(DSN) > except Exception, inst: > ... > try: > sql_statement='SELECT * FROM Mytable' > rs = win32com.client.Dispatch(r'ADODB.Recordset') > rs.Open(sql_statement, conn, 1, 3) > while not rs.EOF: > id=rs.Fields(colName.Value) #colName, valid column name > ... > rs.MoveNext() > rs.Close() > conn.Close() > > except Exception, inst: > ... > > I think my problem must be with ado and dao. > Now I have run makepy utility and select Microsoft ActiveX Data Objects > 2.5 Library, perhaps I must also select Microsoft DAO3.5 Object Library > and write > win32com.client.Dispatch("DAO.DBEngine.35") for Access 97 or > win32com.client.Dispatch(r'ADODB.Connection') for Acess 2000 > Do you know is it possible ? > luis Well, without being able to test on your system I don't think I can give you any real advice. This is the module I use to interface with Access: Access.py --------------- import win32com.client from win32com.client import constants def isWriteable(field): """Is given Field writeable?""" return field.Attributes & 4 class Access(object): def __init__(self, filename, password=""): self._filename = filename self._connection = win32com.client.Dispatch(r'ADODB.Connection') if password: self._DSN = 'PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=%s;Jet OLEDB:Database Password=%s;' % (filename, password) else: self._DSN = 'PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=%s;' % (filename) def Query(self, query): self._connection.Open(self._DSN) rs = win32com.client.Dispatch(r'ADODB.Recordset') rs.Open(query, self._connection, 1, 3) fields = [] for x in xrange(rs.Fields.Count): fields.append(rs.Fields(x).Name) if rs.EOF: data = [] else: data = rs.GetRows() rs.Close() self._connection.Close() return fields, data def Add(self, table, records): """Adds records to table.""" self._connection.Open(self._DSN) rs = win32com.client.Dispatch(r'ADODB.Recordset') rs.Open(table, self._connection, 1, 3) unwriteables = [] for record in records: rs.AddNew() unwriteable = [] for i in xrange(len(record)): if isWriteable(rs.Fields(i)): rs.Fields(i).Value = record[i] else: unwriteable.append(rs.Fields(i).Value) unwriteables.append(unwriteable) rs.Update() rs.Close() self._connection.Close() return unwriteables def Update(self, query, function): """Updates all records found in query with function(record)""" self._connection.Open(self._DSN) rs = win32com.client.Dispatch(r'ADODB.Recordset') rs.Open(query, self._connection, 1, 3) columns = rs.Fields.Count while not rs.EOF: record = [] for i in xrange(columns): record.append(rs.Fields(i).Value) newRecord = function(record[:]) for i in xrange(columns): if isWriteable(rs.Fields(i)): rs.Fields(i).Value = newRecord[i] rs.MoveNext() rs.Close() self._connection.Close() def Delete(self, query): """Deletes all records found in query""" self._connection.Open(self._DSN) rs = win32com.client.Dispatch(r'ADODB.Recordset') rs.Open(query, self._connection, 1, 3) while not rs.EOF: rs.Delete() rs.MoveNext() rs.Close() self._connection.Close() We only have Access 2000+, so I don't know if it'll work with prior versions. Iain From harry.g.george at boeing.com Thu Jun 1 01:00:28 2006 From: harry.g.george at boeing.com (Harry George) Date: Thu, 1 Jun 2006 05:00:28 GMT Subject: How do you practice Python? References: <1149150517.034409.292530@g10g2000cwb.googlegroups.com> <447eaae0$0$20867$636a55ce@news.free.fr> <1149152214.215907.31800@i39g2000cwa.googlegroups.com> Message-ID: "Ray" writes: > bruno at modulix wrote: > > > In our field, we don't always get to program in the language we'd like > > > to program. So... how do you practice Python in this case? Say you're > > > doing J2EE right now. > > > > Hopefully not ! > > I am :-( > > > > How do you practice Python to keep your skills > > > sharp? > > > > How *would* I do ? Well, perhaps I'd use Jython ? > > Um, I mean, what if you have to use something other than > Python/Jython/IronPython? :) How do you keep your Python skill sharp? > > > -- > > bruno desthuilliers > > python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for > > p in 'onurb at xiludom.gro'.split('@')])" > Do projects at home. Either find an existing OSS project, or roll your own. Once you have the basics of the language, the skills are domain-specific: XML, GUIs, CAD, gaming, multithreading, numerical analysis, natural language progromming, etc. If you do an existing project, then you benefit from peer reviews and other informal learning opportunities. -- Harry George PLM Engineering Architecture From jstroud at ucla.edu Sat Jun 10 19:41:20 2006 From: jstroud at ucla.edu (James Stroud) Date: Sat, 10 Jun 2006 16:41:20 -0700 Subject: Most elegant way to generate 3-char sequence In-Reply-To: References: <1149889784.391965.271570@h76g2000cwa.googlegroups.com> Message-ID: Steve Holden wrote: > James Stroud wrote: > >> SuperHik wrote: >> >>> and the winner is... :D >>> David Isaac wrote: >>> >>> >>>> alpha = string.lowercase >>>> x=(a+b+c for a in alpha for b in alpha for c in alpha) >>> >>> >>> >>> >> >> Not necessarily vying for winner, but David's solution is highly >> specific as it doesn't do so well for something like >> >> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab >> . >> . >> . >> zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzy >> zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz >> >> > You can't justify your solution by requirements gold-plating ... see the > subject line :-) > > regards > Steve See the actual question: >How would you construct a generator to acheive this? -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From steve at holdenweb.com Fri Jun 9 03:25:13 2006 From: steve at holdenweb.com (Steve Holden) Date: Fri, 09 Jun 2006 08:25:13 +0100 Subject: Select hangs after some reads In-Reply-To: References: <1149737234.816833.177710@j55g2000cwa.googlegroups.com> <1149764138.868847.326250@i39g2000cwa.googlegroups.com> <128g8uvi6aj4240@corp.supernews.com> <1149779056.498540.46620@f6g2000cwb.googlegroups.com> Message-ID: Donn Cave wrote: > In article , > Steve Holden wrote: > > >>The PSH flag indicates that the data stream must be flushed right >>through to the other end. This is essential for interactive protocols >>such as FTP: without it the server has no way to know that the client >>has sent a complete command, and vice versa. > > > So you would expect to see this done explicitly in the source > for an FTP client or server implementation -- something that > sets this PSH flag or else the protocol won't work? Or am > I misunderstanding what you mean? > > I don't see that specific string anywhere in a the particular > FTP implementation whose source happened to be handy, basically > a Berkeley 4.4 variant as I think most are on UNIX. Somewhere > around here I have a pass-through FTP client/server application > that adds GSSAPI-Kerberos5 authentication to the protocol traffic, > and I don't remember needing to do any such thing there. > > I'd have to look harder at the details, but as I recall it, > like any sane application the protocol is defined in terms of > data, so you know if you have a complete command by looking at > what you have. > Nope, I wouldn't look any harder. You and I both know you won't find them. "The client" in this case was the client's transport layer, not the client application - I should have said "sender", since I referred to the system at the other end as the "receiver". regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From steve at holdenweb.com Mon Jun 12 18:44:04 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 12 Jun 2006 23:44:04 +0100 Subject: [newbie]apache authentication questions In-Reply-To: <1150132535.766644.99870@g10g2000cwb.googlegroups.com> References: <1150132535.766644.99870@g10g2000cwb.googlegroups.com> Message-ID: nuffnough at gmail.com wrote: > I have an apache 1.3.29 server that is running my website. I have > written a bunch of scripts to generate the pages from csv files which > work great. > > My next thing to learn is how to get user authentication functioning > the way I need it. > > I understand the steps required to make .htpaccess files work, but that's ".htaccess", but you probably knew that. > this won't be enough for my purposes. I want the site to remember that > a visitor has logged in or not, and also to read a bunch of personal > info from a csv file dedicated to the userbase. (A later project will > be to convert my csv files into databases, but I am into baby steps at > the moment, so just focussing on python webiste authentication) > > Ideally I would like this authentication to not be in the form of a > popup, but rather via a username/password pair of fields at some place > on the page. After authentication, this should be reaplced by some > generic "have a nice day" kinda message, or perhaps simply removed > altogether. Additionally, they will be able to alter their personal > information and doing stuff like filling in the feedback form should > mean that they don't have to enter any personal info, just fill in the > details and click the send buttopn. My experience with .htaccess files > is that they make an authentication popup, which is not what I am > aiming at. > > How can I incorporate this sort of user info in the apache > authentication stuff using python? > In other words you want the application to authenticate the user rather than use any of the HTTP authentication schemes. This entails maintaining "session state", usually referenced by a cookie, and having each page that requires authentication check that the user's session state indicates login has already been achieved (and hasn't been timed out). Alternatively they can verify by program that the browser has presented correct authorization credentials, but there seem little advantage to doing this since the server can do it for you, and it still involved the browser pop-up you want to get rid of. It also means that your authenticated pages must all be programmed pages (no static content like HTML or plain text). Since HTTP authentication is managed by the browser it's difficult to integrate it with web application authentication: basically you have to choose between the two. There's no way for the server to tell the browser to start presenting the required authentication credentials except by raising a 401 (not authorised) error response, which is what makes the browser bring up its little popup. I could write a book about this stuff ... regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From dnew at san.rr.com Fri Jun 23 18:23:19 2006 From: dnew at san.rr.com (Darren New) Date: Fri, 23 Jun 2006 22:23:19 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: <1151099579.205144.145130@r2g2000cwb.googlegroups.com> References: <7zpshbsvjy.fsf@app-1.diku.dk><4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150902275.129780.50260@p79g2000cwp.googlegroups.com> <1150918629.818145.143220@y41g2000cwy.googlegroups.com> <4fv081F1jh4ifU1@individual.net> <1150967543.947096.72840@g10g2000cwb.googlegroups.com> <4fv84rF1kp06kU1@individual.net> <1150988625.527780.148710@c74g2000cwc.googlegroups.com> <4g22l7F1j8p4mU1@individual.net> <1151081129.290382.297530@r2g2000cwb.googlegroups.com> <1151099579.205144.145130@r2g2000cwb.googlegroups.com> Message-ID: Marshall wrote: > point. My point was, I don't see why you'd be writing code using > operators that you thought might not be applicable to the operands. I see. I thought your point was that you might write code for which you didn't know the type of arguments. Unless you equate "type" with what smalltalk calls "protocol" (i.e., the type is the collection of operators applicable to values in the type), these are two different statements. -- Darren New / San Diego, CA, USA (PST) Native Americans used every part of the buffalo, including the wings. From kewashi at gmail.com Sun Jun 11 16:12:01 2006 From: kewashi at gmail.com (KenAggie) Date: 11 Jun 2006 13:12:01 -0700 Subject: Get my airlines boarding pass In-Reply-To: <1149969384.065683.224810@f6g2000cwb.googlegroups.com> References: <1hgotbh.1vd74fb1qhzdziN%aleax@mac.com> <1149954923.868806.87270@m38g2000cwc.googlegroups.com> <1149969384.065683.224810@f6g2000cwb.googlegroups.com> Message-ID: <1150056721.796442.130690@m38g2000cwc.googlegroups.com> I posted it on activestate already ... sorry. I would like for the geniuses here to use it and improve upon it so here is the activestate post URL: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496790 Enjoy. Ken BartlebyScrivener wrote: > >> SW air script > > Post it here, first, and these geniuses will improve it; then post it > on ActiveState. Besides, if you post it here first, I can use it. That > would be handy! > > Thanks, > > rpd From aisaac0 at verizon.net Thu Jun 8 14:48:53 2006 From: aisaac0 at verizon.net (David Isaac) Date: Thu, 08 Jun 2006 18:48:53 GMT Subject: Request new feature suggestions for my PDF conversion toolkit - xtopdf References: <1149789349.974338.242080@i39g2000cwa.googlegroups.com> Message-ID: "vasudevram" wrote in message news:1149789349.974338.242080 at i39g2000cwa.googlegroups.com... > http://sourceforge.net/projects/xtopdf Serendipity: I was just looking for this functionality. Thanks! So here is an idea for a great enhancement: rst -> PDF The good news: the project is all Python, so you will only have to write a writer! (But to make this great: support stylesheets!) Alan Isaac From steve at holdenweb.com Wed Jun 14 16:31:39 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 14 Jun 2006 21:31:39 +0100 Subject: prog1 | prog2 . How not to make prog2 block if not piped? In-Reply-To: References: <1150297984.798904.229730@h76g2000cwa.googlegroups.com> <1150306815.394154.130250@h76g2000cwa.googlegroups.com> Message-ID: imcs ee wrote: > yeah, forget my post ,it;s useless. > sorry for my thoughtless > On 14 Jun 2006 10:40:15 -0700, riquito at gmail.com wrote: > >>imcs ee ha scritto: >> >> >>>do u really need read something even when you run the scripts2.py directly? >>>why not just change script2.py to >>> #script2.py >>>if __name__ == "__main__": >>> x=sys.stdin.read() >>> print 'passed' >>>else: >>> print 'passed from else branch' >>> >>>is it what you want? or anything i misunderstand. >> >>it won't do. clever btw. >>Script2 is not a module, it's a program that _could_ receive input via >>pipe. >> It really doesn't matter *how* it receives input, whether from a pipe, or a terminal or a redirected file. When you run it "standalone" you should give it some input - type some text then enter ^D (on Unix-like systems) or ^Z (on Windows). How else do you expect read() to return anything? It *has* to read to the end fo the file before it returns a value. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From martin at v.loewis.de Fri Jun 16 19:30:31 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 17 Jun 2006 01:30:31 +0200 Subject: Which compiler will Python 2.5 / Windows (Intel) be built with? In-Reply-To: <1150444191.618761.22810@c74g2000cwc.googlegroups.com> References: <1150367139.495114.148550@g10g2000cwb.googlegroups.com> <44917535$1@nntp0.pdx.net> <1150391891.130185.4640@f6g2000cwb.googlegroups.com> <4492414C.10505@v.loewis.de> <1150444191.618761.22810@c74g2000cwc.googlegroups.com> Message-ID: <44933F17.7050500@v.loewis.de> meyer at mesw.de wrote: > thanks for the tip, I wasn't fully aware of that. OTOH, though GCC > might be a theoretical alternative, it isn't a practical one for many > situations: > > * In a professional environment, it opens up another can of potential > problems, where one would rather like to stay with one single > compiler/build system. That's a theoretic argument to me: Can you name four or five problems out of that can? > * I suppose Python's distutils have to be tweaked to work with GCC No, it should work out of the box. If it doesn't: contributions are welcome. > * The Makefiles/build system will need to be changed to work with the > GCC toolchain If you are using distutils, you don't need a Makefile, and the setup.py won't have to be tweaked. If you are not using distutils, but, say, nmake already, then you will already have an earlier version of the compiler - how else did you create the nmake files in the first place? > * The different semantics of GCC and Microsoft C often need rewriting > some of the code For C code, the semantic differences are really minor. You almost never need any rewriting when moving from MS compilable code to gcc; if you do, it is fairly straight forward to formulate the code so that it compiles with both compilers > * There is no support for MFC/ATL in GCC That's true. > * The code created by the Windows GCC is not as good as the one created > by the Microsoft compiler I never found that relevant for practical purposes. While it is possible to create hand-crafted programs that show a difference, real-world programs are often more limited by the performance of the OS (disk IO, database IO, GUI) than raw processor speed. Still, if you really cannot use gcc, then go ahead and compile with VS 2005. Just make sure you link with mscvr71.dll. If you absolutely need that to work, you will find a way to make it work. Regards, Martin From apardon at forel.vub.ac.be Fri Jun 9 09:51:07 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 9 Jun 2006 13:51:07 GMT Subject: Allowing zero-dimensional subscripts References: <1149801040.936452.26270@i40g2000cwc.googlegroups.com> <1149807149.516004.48590@f6g2000cwb.googlegroups.com> Message-ID: Op 2006-06-08, spam.noam at gmail.com schreef : > Hello, > > Terry Reedy wrote: >> > In a few more words: Currently, an object can be subscripted by a few >> > elements, separated by commas. It is evaluated as if the object was >> > subscripted by a tuple containing those elements. >> >> It is not 'as if'. 'a,b' *is* a tuple and the object *is* subcripted by a >> tuple. >> Adding () around the non-empty tuple adds nothing except a bit of noise. >> > > It doesn't necessarily matter, but technically, it is not "a tuple". Yes it is. > The "1, 2" in "x[1, 2]" isn't evaluated according to the same rules as > in "x = 1, 2" I was pretty sure it was. > - for example, you can have "x[1, 2:3:4, ..., 5]", which > isn't a legal tuple outside of square braces Yes it is, it just is illegal notation outside square brackets. You could have approximate the same effect by I = 1, slice(2,3,4), Ellipsis, 5 x[I] > - in fact, it even isn't > legal inside parens: "x[(1, 2:3:4, ..., 5)]" isn't legal syntax. But what is illegal is the notation, not the value. -- Antoon Pardon From bignose+hates-spam at benfinney.id.au Wed Jun 14 06:51:06 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 14 Jun 2006 20:51:06 +1000 Subject: Test functions and test discovery References: <1150218398.443615.304880@p79g2000cwp.googlegroups.com> <448fd035$0$1806$636a55ce@news.free.fr> Message-ID: <874pyonh7p.fsf@benfinney.id.au> bruno at modulix writes: > Ben Finney wrote: > (snip) > > if __name__ == "__main__": > > test_funcs = [x for name, x in globals() > > if name.startswith("test") and hasattr(x, "__call__") > > ] > > Any reason not to use callable(x) here ? (instead of hasattr(x, "__call__")) Other than my ignorance until now of 'callable', no :-) -- \ "About four years ago, I was -- no, it was yesterday." -- | `\ Steven Wright | _o__) | Ben Finney From fredrik at pythonware.com Tue Jun 6 17:58:10 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 06 Jun 2006 23:58:10 +0200 Subject: Writing to a certain line? In-Reply-To: <1149630414.246008.270720@f6g2000cwb.googlegroups.com> References: <1149576072.168354.14470@f6g2000cwb.googlegroups.com> <44854184$0$29904$636a55ce@news.free.fr> <1149630414.246008.270720@f6g2000cwb.googlegroups.com> Message-ID: Tommy B wrote: >> import os >> old = open("/path/to/file.txt", "r") >> new = open("/path/to/new.txt", "w") >> for line in old: >> if line.strip() == "Bob 62" >> line = line.replace("62", "66") >> new.write(line) >> old.close() >> new.close() >> os.rename("/path/to/new.txt", "/path/to/file.txt") > Umm... I tried using this method and it froze. Infiinite loop, I'm > guessing. you have an infinitely large disk with an infinitely large file on it? From george.sakkis at gmail.com Tue Jun 20 07:33:16 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 20 Jun 2006 04:33:16 -0700 Subject: crawlers in python with graphing? References: Message-ID: <1150803196.031930.290370@r2g2000cwb.googlegroups.com> bryan rasmussen wrote: > Hi, > > Sorry, was imprecise, I meant not save the downloaded page locally. > There probably isn't one though, so I should build one myself. > Probably just need a good crawler that can be set to dump all links > into dataset that I can analyse with R. > > Cheers, > Bryan Rasmussen Harvestman (http://harvestman.freezope.org/) is your best bet. George From fredrik at pythonware.com Thu Jun 15 07:11:59 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 15 Jun 2006 13:11:59 +0200 Subject: memory leak problem with arrays References: <1150317325.614389.14770@i40g2000cwc.googlegroups.com><1150322504.136131.139350@i40g2000cwc.googlegroups.com><1150324059.063981.70450@u72g2000cwu.googlegroups.com><1150327127.904461.84740@h76g2000cwa.googlegroups.com> <1150349112.780025.289480@i40g2000cwc.googlegroups.com> Message-ID: wrote: > After doing this I see that iterative counters used to collect occurrences > and nested loop counters (ii & jj) as seen in the code example below > are the culprits with the worst ones over 1M: > > for ii in xrange(0,40): > for jj in xrange(0,20): > try: > nc = y[a+ii,b+jj] > except IndexError: nc = 0 > > if nc == "1" or nc == "5": > news = news +1 > if news == 100: > break > else: > pass > y[a+ii,b+jj] = 4 > else: > pass what's "y" in this example ? From oliphant.travis at ieee.org Sat Jun 3 21:03:52 2006 From: oliphant.travis at ieee.org (Travis E. Oliphant) Date: Sat, 03 Jun 2006 19:03:52 -0600 Subject: reordering elements of a list In-Reply-To: <1149382009.640607.217470@y43g2000cwc.googlegroups.com> References: <1149382009.640607.217470@y43g2000cwc.googlegroups.com> Message-ID: greenflame wrote: > I am trying to reorder elements of a list and I am stuck as to what > might be the best way to approach this. I have a (main) list of > elements and another (ordering) list (which is may shorter, but not > longer than the main list) which contains the order in which I want the > elements of the main list but only as far along as the length of the > ordering list. This may be confusing so I will try to give an example. > > Suppose the main list is: mainlist = list('qwertyuiop') > > Suppose the ordering list is: orderinglist = [3, 4, 2, 1] > > Then I am looking for a function that will take mainlist and > orderinglist as arguments and return the following list: > > ['e', 'r', 'w', 'q', 't', 'y', 'u', 'i', 'o', 'p'] > > Also by the way the main list is always going to be a list of strings > and the ordering list will be a list of numbers. Also the largest > number in orderinglist will always be equal to the length of > orderinglist. I hope this makes any sense. Thanks for your help. > NumPy ( http://numeric.scipy.org ) can do this using element-based indexing on an array of strings. Your example: import numpy a = numpy.array('qwertyuiop','c') newlist = a[[2,3,1,0]+range(4,10)].tolist() print newlist Returns: ['e', 'r', 'w', 'q', 't', 'y', 'u', 'i', 'o', 'p'] But you can also do it with list comprehension pretty easily, so this is probably just a shameless plug for NumPy :-) -Travis From marcelo.gosling at gmail.com Fri Jun 23 18:58:49 2006 From: marcelo.gosling at gmail.com (Marcelo Gosling) Date: 23 Jun 2006 15:58:49 -0700 Subject: Trouble including Python.h References: <1151099498.381282.64590@b68g2000cwa.googlegroups.com> <1151102580.317497.60390@p79g2000cwp.googlegroups.com> Message-ID: <1151103529.616128.129550@p79g2000cwp.googlegroups.com> No, that didn't do the trick. The main reason I'm posting this here is that I get all tese error messages just from including Python.h, the code itself does absolutely nothing. Cheers vduber6er wrote: > Try > > #undef _DEBUG > #include "C:\Python24\include\python.h" > > or which ever path your python.h is located at > > works for me > > Marcelo Gosling wrote: > > Hi, everyone. > > > > This is on WinXP SP2, with Python 2.4.3 and DJGPP gcc 4.1.0. > > > > I'm having trouble including Python.h in a C file. The following C > > code: > > > > #include "Python.h" > > > > int main() > > { > > return 0; > > } > > > > when compiled with "gcc -I..\Python2.4\include\", gives more than 1000 > > lines of errors, beginning with: > > > > c:/documents and settings/marcelo.gosling/my > > documents/djgpp/bin/as.exe: BFD 2.16.1 assertion fail > > ../../bfd/coff-i386.c:576 > > c:/documents and settings/marcelo.gosling/my > > documents/djgpp/tmp/ccACtxBR.s: Assembler messages: > > c:/documents and settings/marcelo.gosling/my > > documents/djgpp/tmp/ccACtxBR.s:28: Error: cannot represent relocation > > type BFD_RELOC_386_PLT32 > > In file included from ../../Python2.4/include/Python.h:74, > > from example_wrap.c:112: > > ../../Python2.4/include/pymem.h: In function '__declspec': > > ../../Python2.4/include/pymem.h:51: error: expected declaration > > specifiers before '__declspec' > > ../../Python2.4/include/pymem.h:52: error: expected declaration > > specifiers before '__declspec' > > In file included from ../../Python2.4/include/Python.h:76, > > from example_wrap.c:112: > > ../../Python2.4/include/object.h:104: error: storage class specified > > for parameter 'PyObject' > > ../../Python2.4/include/object.h:108: error: storage class specified > > for parameter 'PyVarObject' > > ../../Python2.4/include/object.h:126: error: expected '=', ',', ';', > > 'asm' or '__attribute__' before '*' token > > ../../Python2.4/include/object.h:127: error: expected '=', ',', ';', > > 'asm' or '__attribute__' before '*' token > > ../../Python2.4/include/object.h:128: error: expected '=', ',', ';', > > 'asm' or '__attribute__' before '*' token > > ../../Python2.4/include/object.h:129: error: expected ')' before '*' > > token > > ../../Python2.4/include/object.h:130: error: expected ')' before '*' > > token > > > > Am I missing something important here? > > > > Thanks in advance, > > > > Marcelo From bogus@does.not.exist.com Fri Jun 9 14:20:29 2006 From: bogus@does.not.exist.com (Morpheus) Date: Fri, 9 Jun 2006 20:20:29 +0200 Subject: wxpython: another missing attribute References: Message-ID: <4489bbed$0$11610$3b214f66@aconews.univie.ac.at> "John Salerno" wrote in message news:mLiig.2280$No6.48033 at news.tufts.edu... > Ah, the object-oriented stuff is just so FUN! :) Here's my code, > followed by the error. I thought I was referring to the 'text' attribute > correctly, but it seems not. > > import wx > > > class InputForm(wx.Frame): > > def __init__(self, parent, id, title, pos=wx.DefaultPosition, > size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE, > name='frame'): > wx.Frame.__init__(self, parent, id, title, pos, size, style, name) > panel = wx.Panel(self) > text = wx.StaticText(panel, -1, 'Click results') This becomes a local var, i.e. local to __init__. To make it an instance var write self.text = wx.StaticText(panel, -1, 'Click results') HTH Morpheus > btnOK = wx.Button(panel, -1, 'OK') > self.Bind(wx.EVT_BUTTON, self.clickOK, btnOK) > btnCancel = wx.Button(panel, -1, 'Cancel') > self.Bind(wx.EVT_BUTTON, self.clickCancel, btnCancel) > sizer = wx.BoxSizer(wx.HORIZONTAL) > sizer.Add(btnOK, 0, wx.ALL, 10) > sizer.Add(btnCancel, 0, wx.ALL, 10) > sizer.Add(text, 0, wx.ALL, 10) > panel.SetSizer(sizer) > > def clickOK(self, event): > self.text.SetLabel('You clicked OK') > > def clickCancel(self, event): > self.text.SetLabel('You clicked Cancel') > > > class MyApp(wx.App): > > def OnInit(self): > frame = InputForm(None, -1, 'Data Entry Form') > self.SetTopWindow(frame) > frame.Show() > return True > > > app = MyApp() > app.MainLoop() > > ------------------- > > Traceback (most recent call last): > File "C:\Python24\myscripts\wx_tests\wxtest.py", line 23, in clickOK > self.text.SetLabel('You clicked OK') > AttributeError: 'InputForm' object has no attribute 'text' From fredrik at pythonware.com Tue Jun 6 02:36:59 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 06 Jun 2006 08:36:59 +0200 Subject: OT: unix newbie questions In-Reply-To: <20060606035507.XHEA21801.mta9.adelphia.net@AT119L38513> References: <20060606035507.XHEA21801.mta9.adelphia.net@AT119L38513> Message-ID: Carlos Lopez wrote: > Please help i am losing my mind ... UNIX Newbee > > *23. How do you add a line to the end of an existing file "myfile" with > date stamp. (1) * >>> f = open("myfile", "a+") >>> f.write(datestamp) >>> f.close() > *24. Display recent 10 java files, (with *.java extension) , in > descending order by time, latest to oldest time. (1) * >>> files = sorted(glob.glob("*.py"), key=os.path.getmtime)[-10:] >>> files.reverse() > *25. How do you set only read permissions to user, group and others in > octal mode for a file "myfile.txt" ? (2) >>> os.chmod("myfile.txt", 0444) # note the leading zero > *26. You observed that some of your group members are fiddling with your > file "myfile" and you wanted to remove the read permission to your > group. How do you do? (1) >>> os.chmod("myfile.txt", 0404) > *28. Here is another long listing of a file. (1)* > -rw-r----- 1 Y435678 odms 20 Sep 02 17:03 file.txt. *** > > *What are the owner permissions? * >>> s = os.stat("urllib.py").st_mode >>> if s & stat.S_IREAD: print "READ" >>> if s & stat.S_IWRITE: print "WRITE" >>> if s & stat.S_IEXEC: print "EXEC" > *29. The file ?users_data? has the following contents : (1) > Tom Smith 7.00 15 105.00 > Rob Sheryl 8.00 20 160.00 > Ken Bradman 7.00 13 91.00 > Peter Smith 6.00 15 90.00 > Dennis Smith 8.00 13 104.00 > Tom Dave 9.00 12 108.00 * > > *How do you sort the above file and redirect the output to another file > called ?sortedusers? * >>> out = open("sortedusers", "w") >>> out.writelines(sorted(open("users_data"))) > *20. What is the command to list files in a directory : (2) >>> os.listdir(directory) or, if you want full path names and glob-style filtering: >>> glob.glob(os.path.join(directory, "*")) From steve at holdenweb.com Wed Jun 7 12:33:39 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 07 Jun 2006 17:33:39 +0100 Subject: creating and naming objects In-Reply-To: <1149696358.065614.76150@h76g2000cwa.googlegroups.com> References: <1149696358.065614.76150@h76g2000cwa.googlegroups.com> Message-ID: Brian wrote: > I have a question that some may consider silly, but it has me a bit > stuck and I would appreciate some help in understanding what is going > on. > > For example, lets say that I have a class that creates a student > object. > > Class Student: > def setName(self, name) > self.name = name > def setId(self, id) > self.id = id > > Then I instantiate that object in a method: > > def createStudent(): > foo = Student() Of course here you'd need an argument to correspond to the student name, but we'll overlook that. > /add stuff > This actually looks like a Student "factory function", though I have reservations about it (see below). > Now, suppose that I want to create another Student. Do I need to name > that Student something other than foo? What happens to the original > object? If I do not supplant the original data of Student (maybe no id > for this student) does it retain the data of the previous Student > object that was not altered? I guess I am asking how do I > differentiate between objects when I do not know how many I need to > create and do not want to hard code names like Student1, Student2 etc. > > I hope that I am clear about what I am asking. > > Thanks, > Brian > Presumably your definition of createStudent() ends with something like return foo otherwise the created Student object has no references once the function complete, and will therefore become non-referenced garbage immediately. Assuming that createStudent() does indeed return the created Student instance then you would use it like this: s1 = createStudent() ... s2 = createStudent() and so on. Of course there's nothing to stop you creating lists of students or dicts of students either. Objects don't really "have names" in Python, it's better to think of names being references to objects. Each object can be referenced by zero, one or more names, but references can also be stored in the items of container objects. A point you don't appear to have thought of, though, is that all the functionality implemented in your createStudent() function could just as easily become part of the Student.__init__() method. Then there's no need to create a factory function at all - the __init__() method just initialises each newly-created instance before you get your hands on it. Then your code would be more like s1 = Student() ... s2 = Student() and so on. Plus, of course, the __init__() method can take arguments if they are needed to initialize the object successfully. So I'm not really sure quite what createStudent() is for. Hope this rambling helps at least a bit. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From vesa.karvonen at cs.helsinki.fi Wed Jun 21 12:36:10 2006 From: vesa.karvonen at cs.helsinki.fi (Vesa Karvonen) Date: 21 Jun 2006 16:36:10 GMT Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <0%Wlg.3521$MF6.947@tornado.socal.rr.com> <44992e6c$0$664$bed64819@news.gradwell.net> Message-ID: In comp.lang.functional Andreas Rossberg wrote: > Darren New wrote: [...] > > Indeed, the ability to declare a new type that has the exact same > > underlying representation and isomorphically identical operations but > > not be the same type is something I find myself often missing in > > languages. It's nice to be able to say "this integer represents vertical > > pixel count, and that represents horizontal pixel count, and you don't > > get to add them together." > Not counting C/C++, I don't know when I last worked with a typed > language that does *not* have this ability... (which is slightly > different from ADTs, btw) Would Java count? -Vesa Karvonen From fredrik at pythonware.com Mon Jun 5 05:47:09 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 05 Jun 2006 11:47:09 +0200 Subject: re beginner In-Reply-To: <4483665A.206@lexicon.net> References: <44834d62$0$6192$626a54ce@news.free.fr> <4483665A.206@lexicon.net> Message-ID: John Machin wrote: > Fantastic -- at least for the OP's carefully copied-and-pasted input. > Meanwhile back in the real world, there might be problems with multiple > tabs used for 'prettiness' instead of 1 tab, non-integer values, etc etc. yeah, that's probably why the OP stated "which always has the same format". and the "trying to understand regex for the first time, and it would be very helpful to get an example" part was obviously mostly irrelevant to the "smarter than thou" crowd; only one thread contributor was silly enough to actually provide an RE-based example. From david at boddie.org.uk Wed Jun 7 09:27:01 2006 From: david at boddie.org.uk (David Boddie) Date: 7 Jun 2006 06:27:01 -0700 Subject: pyqt show wizard In-Reply-To: <1149686724.992518.104290@i39g2000cwa.googlegroups.com> References: <1149686724.992518.104290@i39g2000cwa.googlegroups.com> Message-ID: <1149686821.537392.154130@h76g2000cwa.googlegroups.com> Summary of the usual mess made by the Google Groups web interface: I suspect that you really want to call w.exec_loop() instead, since this will only return control to the method after the user has finished interacting with the wizard. Take a look at the QWizard documentation for more information: http://doc.trolltech.com/3.3/qwizard.html David From d__ at mac.com Tue Jun 20 10:02:21 2006 From: d__ at mac.com (David Vincent) Date: Wed, 21 Jun 2006 00:02:21 +1000 Subject: unittest behaving oddly In-Reply-To: <1150809306.287758.48870@h76g2000cwa.googlegroups.com> References: <1150809306.287758.48870@h76g2000cwa.googlegroups.com> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- On 20/06/2006, at 23:15, Mike Kent wrote: > David Vincent wrote: > >>> import unittest >>> >>> class IntegerArithmenticTestCase(unittest.TestCase): >>> def testAdd(self): ## test method names begin 'test*' >>> assertEquals((1 + 2), 3) >>> assertEquals(0 + 1, 1) > > assertEquals is a member function, inherited from unittest.TestCase, so > you must call it as self.assertEquals. ForEx: (Details deleted) Thank you Mike. That fixes most of my problems. The code quoted above was from my verbatim copy of the example from the doc strings of unittest.py, from my computer's Python library. I wonder how the example code could have been so badly wrong? regards David - -- David A Vincent dvincent at toshiba-tap.com Software Engineer telephone +61 2 9850-2593 RESEARCH AND DEVELOPMENT TOSHIBA (AUSTRALIA) PTY. LIMITED "The situation is hopeless, we must take the next step." P.Casals -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (Darwin) iQCVAwUBRJf/7pjExRNGDpoZAQEaKgQAgCVSdE/WJCunEdPfEIgCHk+dKMJHc2B6 XWfc3WPvUcH5RL4dQ18bbKNHEoHSZbMrN4CLKD55LueeaPbIgFgOpSkwoRRoakDi LWNbn7OWz2G1mbNgEVvqkOBhfK5l582kjzndtdsPBPD+Pv/KiEC77/6dN27Fnl6e d0oKoDD3aac= =/dqt -----END PGP SIGNATURE----- From tdelaney at avaya.com Sun Jun 4 18:35:39 2006 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Mon, 5 Jun 2006 08:35:39 +1000 Subject: Which exceptions are recommended to me handled? Message-ID: <2773CAC687FD5F4689F526998C7E4E5FF1E74B@au3010avexu1.global.avaya.com> Florencio Cano wrote: > Hello, > Is it recommended as a good programming practice to catch all > exceptions and raise our own exceptions or let Python itself raise > these kinds of exceptions? > For example imagine a function that needs an integer and '34' is > passed, this is ok because inside the function it uses int(variable) > but if a 'hello' is passed it will raise a ValueError exception. Is > it better to handle this exception or let Python raise directly > ValueError and stop execution or what is recommended? If you can validly handle the exception, do so. Otherwise, let it propagate. Valid handling could be (for example) logging the error and using a default value. Note that it's a particularly bad idea to just replace one exception with another exception (not suggesting that that is what you intended - just something I've seen a lot ;) try: int(val) except ValueError: raise MyValueError('Bad value: ' + val) The most important problem here is that you've lost the stack trace from the original exception. The next most important is that anything else that believes it can handle a ValueError now won't be able to. Tim Delaney From robert.kern at gmail.com Tue Jun 6 20:29:12 2006 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 06 Jun 2006 19:29:12 -0500 Subject: fsolve() from scipy crashes python on windows In-Reply-To: References: Message-ID: Vedran Fura? wrote: > When I call optimize.fsolve(...) python interpreter crashes immediately, > no error messages, nothing, just brings me back to c:\ > On linux the same code works fine. I tried it on different computers. I > seems that it doesn't crash on pentium4, only on athlon and pentium2. > > python 2.4.3 (activestate), scipy 0.4.8/0.4.9, windows xp Please ask on scipy-user. http://www.scipy.net/mailman/listinfo/scipy-user We will need some more information, like how you build scipy (or exactly which binary you are using), what version of numpy you are using with scipy, and the exact code that causes the crash. -- 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 From flupke at nonexistingdomain.com Fri Jun 30 09:11:10 2006 From: flupke at nonexistingdomain.com (flupke) Date: Fri, 30 Jun 2006 13:11:10 GMT Subject: logging error with RotatingFileHandler In-Reply-To: <4v8pg.511318$Hm7.12716147@phobos.telenet-ops.be> References: <_asng.501715$x64.12701762@phobos.telenet-ops.be> <1151391562.198586.249130@m73g2000cwd.googlegroups.com> <1151604839.290366.90950@m73g2000cwd.googlegroups.com> <4v8pg.511318$Hm7.12716147@phobos.telenet-ops.be> Message-ID: <44A522E9.3050008@nonexistingdomain.com> flupke schreef: > Hi Vinay, > > thanks for the info. > > I tried to change the handlers.py file. > First, i changed some code in doRollover. > > if os.path.exists(dfn): > os.remove(dfn) > try: > #os.rename(self.baseFilename, dfn) > > -> The rename fails for some reason. > > I tried with the move function of shutil > shutil.move(self.baseFilename, dfn) > > This partially works: the file is now rotated but i still get an error: > The error that i get is this: > Error [Errno 13] Permission denied: 'E:\\python\\proj1\\src\\proj1.log' > Traceback (most recent call last): > File "C:\Python24\lib\logging\handlers.py", line 72, in emit > self.doRollover() > File "C:\Python24\lib\logging\handlers.py", line 141, in doRollover > self.handleError(record) > NameError: global name 'record' is not defined > > The last part of the error shows that the part where the exception is > caugth is also not working correctly as the "record" isn't know. > > When i close my program, i get this error as well: > > Error in atexit._run_exitfuncs: > Traceback (most recent call last): > File "C:\Python24\lib\atexit.py", line 24, in _run_exitfuncs > func(*targs, **kargs) > File "C:\Python24\lib\logging\__init__.py", line 1333, in shutdown > h.close() > File "C:\Python24\lib\logging\__init__.py", line 772, in close > StreamHandler.close(self) > File "C:\Python24\lib\logging\__init__.py", line 674, in close > del _handlers[self] > KeyError: > Error in sys.exitfunc: > Traceback (most recent call last): > File "C:\Python24\lib\atexit.py", line 24, in _run_exitfuncs > func(*targs, **kargs) > File "C:\Python24\lib\logging\__init__.py", line 1333, in shutdown > h.close() > File "C:\Python24\lib\logging\__init__.py", line 772, in close > StreamHandler.close(self) > File "C:\Python24\lib\logging\__init__.py", line 674, in close > del _handlers[self] > KeyError: > > Regards > Benedict I was able to solve the errors (i think): 1. in the function doRollover of the class RotatingFileHandler if os.path.exists(dfn): os.remove(dfn) try: os.rename(self.baseFilename, dfn) I added this instead of the rename function: import shutil shutil.copy(self.baseFilename, dfn) If this code works ok, then the "import shutil" should be placed at the top of the file for performance reasons. The logic of the copy is that a few statements later, the self.stream var is set to a new file again so it doesn't need to be deleted. At least it seems to work here. I will need to test further. Weird thing is, the stream is closed and yet you get this error when you use rename: [Errno 13] Permission denied 2. in the same function, when an error occurred, the record var wasn't found. This can be solved by changing the code of emit in BaseRotatingHandler. Change this: if self.shouldRollover(record): self.doRollover() by: if self.shouldRollover(record): self.doRollover(record) 3. The last error (error when closing the program) can be solved by editing the __init__.py, close(self) function. Change this: _acquireLock() try: #unlikely to raise an exception, but you never know... del _handlers[self] _handlerList.remove(self) finally: _releaseLock() by: _acquireLock() try: #unlikely to raise an exception, but you never know... #del _handlers[self] if ( _handlers.has_key(self) ): del _handlers[self] #if ( self in _handlerList ): _handlerList.remove(self) _handlerList.remove(self) finally: _releaseLock() It might even be better to change the _handlerList.remove(self) statement by this statement: if ( self in _handlerList ): _handlerList.remove(self) Regards, Benedict Verheyen From davecook at nowhere.net Sat Jun 17 04:36:39 2006 From: davecook at nowhere.net (Dave Cook) Date: Sat, 17 Jun 2006 08:36:39 GMT Subject: python texts? References: Message-ID: On 2006-06-17, nate wrote: > reading Learning Python 2nd edition by O'Reilly. I am enjoying it at the I'd get the Python Cookbook, next. Dave Cook From dieter at handshake.de Fri Jun 16 14:40:18 2006 From: dieter at handshake.de (Dieter Maurer) Date: 16 Jun 2006 20:40:18 +0200 Subject: Possible inaccuracy in Python 2.4 when using profiler calibration References: Message-ID: Brian Quinlan writes on Thu, 15 Jun 2006 10:36:26 +0200: > I have a misinformed theory that I'd like to share with the list. > > I believe that profiler calibration no longer makes sense in Python > 2.4 because C functions are tracked and they have a different call > overhead than Python functions (and calibration is done only using > Python functions). Here is my reasoning (in code form): I fear it never made sense -- even with pure Python functions: I tried to calibrate under Linux and failed miserably: apparently, the "clock" resolution is very coarse introducing a very high variance which is very bad for calibration. From bdesth.quelquechose at free.quelquepart.fr Fri Jun 2 19:53:43 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 03 Jun 2006 01:53:43 +0200 Subject: integer to binary... In-Reply-To: <1149189570.376091.319890@j55g2000cwa.googlegroups.com> References: <1149189570.376091.319890@j55g2000cwa.googlegroups.com> Message-ID: <44809ff9$0$6172$626a54ce@news.free.fr> nicolasg at gmail.com a ?crit : > does anyone know a module or something to convert numbers like integer > to binary format ? > > for example I want to convert number 7 to 0111 so I can make some > bitwise operations... You don't need to convert anything. The bitwise ops are &, |, <<, >> 0 | 2 | 4 -> 6 6 & 2 -> 2 2 << 4 -> 32 8 >> 1 -> 4 From grante at visi.com Wed Jun 28 18:20:13 2006 From: grante at visi.com (Grant Edwards) Date: Wed, 28 Jun 2006 22:20:13 -0000 Subject: curiosity about the nature of identity (in python) References: <44a2ff3e$0$5668$636a55ce@news.free.fr> Message-ID: <12a604t2jlu2de7@corp.supernews.com> On 2006-06-29, Bruno Desthuilliers wrote: > Now what about this: > >>>> id(600) > 134745616 >>>> id(601) > 134745616 > > id of an object is unique *for the lifetime of this object*. Nothing > prevents it from being reused later. Indeed. Since in CPython, it's the address of a C language data structure, if IDs didn't get re-used, then the virtual memory size of any long-running Python program would grow without bound. The working set would grow more slowly that the total virtual size, but it would still be problematic. -- Grant Edwards grante Yow! I'm GLAD I at remembered to XEROX all visi.com my UNDERSHIRTS!! From codecraig at gmail.com Thu Jun 8 16:02:00 2006 From: codecraig at gmail.com (abcd) Date: 8 Jun 2006 13:02:00 -0700 Subject: Importing again and again Message-ID: <1149796920.757115.290840@h76g2000cwa.googlegroups.com> If I have code which imports a module over and over again...say each time a function is called, does that cause Python to actually re-import it...or will it skip it once the module has been imported?? for example: def foo(): import bar bar.printStuff() foo() foo() foo() foo() ...will that re-import bar 4 times...or just import it once? is this a big performance hit? thanks From Serge.Orlov at gmail.com Tue Jun 13 19:22:12 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 13 Jun 2006 16:22:12 -0700 Subject: [OT] Re: Python open proxy honeypot References: <1150236597.152868.250740@y43g2000cwc.googlegroups.com> Message-ID: <1150240932.039735.200750@f14g2000cwb.googlegroups.com> Alex Reinhart wrote: > Serge Orlov wrote: > > IMHO it's pretty useless, spammers are starting to use botnets, and the > > more you make inconvenient to them use open proxies, the more of them > > will move to closed botnets. > As long as I inconvenience them, or at least catch one or two, I'll be > satisfied. What makes you think that spammers won't discover you're blackholing their spam as soon as you start to make some impact on their business? They will just skip your proxypots and move to real open proxies. I think you'll make bigger impact if you implement proxy checking software in Python, so it can run on windows too. From martin.wiechert at gmx.de Sun Jun 4 10:17:08 2006 From: martin.wiechert at gmx.de (Martin Wiechert) Date: Sun, 04 Jun 2006 16:17:08 +0200 Subject: linking errors with debug build of Python2.4.3 In-Reply-To: <1148781211.487215.260090@j73g2000cwa.googlegroups.com> References: <1148781211.487215.260090@j73g2000cwa.googlegroups.com> Message-ID: <200606041617.09198.martin.wiechert@gmx.de> You were right, leaving out --with-pydebug did the trick. Thanks, Martin On Sunday 28 May 2006 03:53, nnorwitz at gmail.com wrote: > Martin Wiechert wrote: > > Hi list, > > > > I've created a fresh build of Python 2.4.3 using the following > > configuration > > > > $ ./configure --with-pydebug --prefix=/usr/local/debug --enable-shared > > --with-fpectl --with-signal-module > > > > What did I do wrong? > > Try with just: ./configure --with-pydebug --prefix=/usr/local/debug > > I think the problem is --enable-shared. I'm not sure what you are > doing, but you probably don't need the other options. The signal > module should always be built, I've never even seen the > --with-signal-module option. :-) > > n From colincolehour at gmail.com Fri Jun 16 19:55:02 2006 From: colincolehour at gmail.com (colincolehour at gmail.com) Date: 16 Jun 2006 16:55:02 -0700 Subject: Need Help comparing dates In-Reply-To: <1150419503.224684.320550@c74g2000cwc.googlegroups.com> References: <1150419503.224684.320550@c74g2000cwc.googlegroups.com> Message-ID: <1150502102.377475.38140@u72g2000cwu.googlegroups.com> So when I grab the date of the website, that date is actually a string? How would I got about converting that to a date? From writetoalok at googlemail.com Fri Jun 30 11:02:22 2006 From: writetoalok at googlemail.com (Alok) Date: 30 Jun 2006 08:02:22 -0700 Subject: Reddit broke - should have remained on Lisp? In-Reply-To: <1151675353.665556.97520@x69g2000cwx.googlegroups.com> References: <1151626961.232761.255550@d56g2000cwd.googlegroups.com> <1151627462.297352.205150@i40g2000cwc.googlegroups.com> <1151627924.322764.6040@y41g2000cwy.googlegroups.com> <1151628347.551890.48050@y41g2000cwy.googlegroups.com> <1151662765.178529.82670@75g2000cwc.googlegroups.com> <1151675353.665556.97520@x69g2000cwx.googlegroups.com> Message-ID: <1151679741.965412.6700@y41g2000cwy.googlegroups.com> Luis M. Gonz?lez wrote: Luis, Thank you very much for you detailed and careful response. I very much appreciate your comments. > Alok wrote: > > Luis M. Gonz?lez wrote: > > > Alok wrote: > > > > I was merely describing my experience and inviting others' response > > > > about theirs. > > > > > > That's exactly what I'm doing. > > > > You misinterpret, I was talking about my experience with the site and > > inviting response from other people about their experience with the > > site. Now, I don't know much about python or lisp, but I have read > > about this web-site's history with the two programming languages. And > > hence I chose to post in comp.lang.lisp and comp.lang.python. > > > > Now if there were a reddit.technology.lisp or > > reddit.technology.python, and if they had the same traction as these > > usenet groups, then I could have posted there. But that was not an > > option was it. > > > > > > > > > Please don't misconstrue that as a blame on any language. > > > > > > I think it can be interpreted in many ways. > > > > Can you please explain what your interpretation is? > > > > > Now if you're not ready to read other people's oppinions, don't ask. > > > > > > > Now, I think you are unfairly prejudiced about my not wanting to read > > other people's opinion. I would rather have a 1000 acrid responses to > > something I write and learn from it, than post into a responseless > > vacuum. > > > > > > And of course, I disagree with your comments about ridicule etc. > > > > > > Ok. > > Dear Alok, > > I think is you who are misinterpreting me (or I didn't make myself > clear). > You posted a link to a joke from reddit, which is perfectly fine, is > very funny. > But below, you added a comment wondering whether the change from Lisp > to Python may be a reason for a huge performance loss. I did not intend to comment on Python or Lisp but yes, I have aired my subjective observations about the site and in the context of the technologies used. And I hoped that other users may respond with comments if they have experienced any similar issues using the site. If I have implied an indication that the change from Lisp to Python was the reason that the site became 3 times slower, then I have slipped in unintended innuendos. And I must accept that I have to be more careful about it. > > I'm not a python bigot, but I just said that blamming a language choice > for such a deficieny was ridiculous. There are hundreds of very complex > web sites developed in python that doesn't suffer these problems, and, > even if they are developed in python, you must take into account which > other technologies they are using for deployment (web server, > framework, mod_python, cgi, fastcgi, hardware, etc, etc...). > Also, the fact that someone could be more versed or knowledgeable of > one language compared to another one, doesn't make it better or worse. > This is s subjective fact, and has nothing to do with the language. It > has to do with who's using the language. > > Also, as someone pointed out above, don't you think that the huge > incresement of traffic since they switched to python may have had > something to do with this problem? > Perhaps, their lack of experise in a new language didn't prepare them > for facing such a challenge. Who knows? Yeah, perhaps if they sticked > to Lisp, they could have handled the problem better. They are lispers, > aren't they? > > Anyway, you posted a comment, you asked for opinons, you got mine. > Sorry if I ofended you. It wasn't my intention. There is no offense taken or hurt feelings. But yes, detailed responses (and smileys) do make conversations more rewarding. > I'll make sure I place more smileys in my posts to avoid hurting > feelings from now on :-) > > Luis From chris at kateandchris.net Sat Jun 10 10:26:38 2006 From: chris at kateandchris.net (Chris Lambacher) Date: Sat, 10 Jun 2006 10:26:38 -0400 Subject: TKinter In-Reply-To: References: Message-ID: <20060610142638.GB9046@kateandchris.net> GTK+ + Glade http://pygtk.org/ WxPython has several GUI editors http://wxpython.org PyQt has the ability to generate code from the Qt GUI designer http://www.riverbankcomputing.co.uk/pyqt/ I personally have used GTK+ and Glade with great success. I found WxPython to be lacking in polish. I have not worked with PyQt. Pretty much all of the above work models are not embedded into an IDE. There is a GUI editor, and then you use your regular editor to write code. This is actually a pretty good model because from my experience, as your application becomes bigger and more complicated, you want less GUI generated UI and more had written UI code. -Chris On Thu, Jun 08, 2006 at 10:29:44PM -0000, V Sivakumar wrote: > Dear Group!, > I am new to Python. I have Eclipse with Python support , is there > better IDE for free and with good support for GUI development. I need > to develop a nice looking desktop application. Like we could do in VB, > C# and Java Swing. Is there a drag drop support GUI toolkit for > Python like the above languages do? > > Thanks > Siva > > > > > -- > http://mail.python.org/mailman/listinfo/python-list From riquito at gmail.com Wed Jun 14 13:40:15 2006 From: riquito at gmail.com (riquito at gmail.com) Date: 14 Jun 2006 10:40:15 -0700 Subject: prog1 | prog2 . How not to make prog2 block if not piped? In-Reply-To: References: <1150297984.798904.229730@h76g2000cwa.googlegroups.com> Message-ID: <1150306815.394154.130250@h76g2000cwa.googlegroups.com> imcs ee ha scritto: > do u really need read something even when you run the scripts2.py directly? > why not just change script2.py to > #script2.py > if __name__ == "__main__": > x=sys.stdin.read() > print 'passed' > else: > print 'passed from else branch' > > is it what you want? or anything i misunderstand. it won't do. clever btw. Script2 is not a module, it's a program that _could_ receive input via pipe. From cdsmith at twu.net Sun Jun 25 14:39:52 2006 From: cdsmith at twu.net (Chris Smith) Date: Sun, 25 Jun 2006 12:39:52 -0600 Subject: What is Expressiveness in a Computer Language References: <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <0%Wlg.3521$MF6.947@tornado.socal.rr.com> <44992e6c$0$664$bed64819@news.gradwell.net> <1151010139.960608.122470@b68g2000cwa.googlegroups.com> Message-ID: Andrew McDonagh wrote: > I haven't read all of this thread, I wonder, is the problem to do with > Class being mistaken for Type? (which is usually the issue) Hi Andrew! Not much of this thread has to do with object oriented languages... so the word "class" would be a little out of place. However, it is true that the word "type" is being used in the dynamically typed sense to include classes from class-based OO languages (at least those that include run-time type features), as well as similar concepts in other languages. Some of us are asking for, and attempting to find, a formal definition to justify this concept, and are so far not finding it. Others are saying that the definition is somehow implicitly psychological in nature, and therefore not amenable to formal definition... which others (including myself) find rather unacceptable. I started out insisting that "type" be used with its correct formal definition, but I'm convinced that was a mistake. Asking someone to change their entire terminology is unlikely to succeed. I'm now focusing on just trying to represent the correct formal definition of types in the first place, and make it clear when one or the other meaning is being used. Hopefully, that's a fair summary of the thread to date. -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation From userprogoogle-139 at yahoo.co.uk Tue Jun 13 14:08:59 2006 From: userprogoogle-139 at yahoo.co.uk (rodmc) Date: 13 Jun 2006 11:08:59 -0700 Subject: USB support Message-ID: <1150222139.721785.268830@f14g2000cwb.googlegroups.com> Hi, I need to write a program which can access the USB ports on Mac and Linux, is there a library available for Python? Thanks in advance. Best, rod From alanmk at hotmail.com Thu Jun 8 06:40:47 2006 From: alanmk at hotmail.com (Alan Kennedy) Date: 8 Jun 2006 03:40:47 -0700 Subject: language-x-isms References: <1149753206.451066.120960@h76g2000cwa.googlegroups.com> <1149759486.695563.110640@g10g2000cwb.googlegroups.com> <1149760633.796809.166430@h76g2000cwa.googlegroups.com> Message-ID: <1149763247.026736.57020@f6g2000cwb.googlegroups.com> [Steve Holden] > You are assuming a relatively recent release of CPython. If you look at > the stuff that the effbot distributes you will see that most of it > supports CPython all the way back to 1.5.2. Oh for cripes sake. The code I posted 1. works on all versions of cpython 2. works on all versions of jython 3. works on all versions of ironpython 4. never replaces the builtin enumerate > I don't think many of us > have the right to be telling Fredrik what's pythonic and what's not ... Who ever said anything like that? I never said anything about pythonicity. Read the thread again: All I said was "Here's what I use on jython 2.1". Fred picked a non-existent hole in my code by saying "using a user-defined enumerate is slower than using the builtin", implying that the code I posted replaced the builtin, which it never does. While the comment "using a user-defined enumerate is slower than using the builtin" may be true, it has no bearing on the code I posted, which is all I'm trying to say ... -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From gajownik at gmail.com Tue Jun 13 15:26:48 2006 From: gajownik at gmail.com (Dawid Gajownik) Date: Tue, 13 Jun 2006 21:26:48 +0200 Subject: [pysqlite] [ANN] pysqlite 2.3.0 In-Reply-To: <448F0982.70906@ghaering.de> References: <448F0982.70906@ghaering.de> Message-ID: <448F1178.7060407@gmail.com> Dnia 06/13/2006 08:52 PM, U?ytkownik Gerhard H?ring napisa?: > pysqlite 2.3.0 released Great :) I have one more problem, though. It does not compile: gcc -pthread -fno-strict-aliasing -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m32 -march=i386 -mtune=generic -fasynchronous-unwind-tables -D_GNU_SOURCE -fPIC -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m32 -march=i386 -mtune=generic -fasynchronous-unwind-tables -fPIC -DMODULE_NAME="pysqlite2.dbapi2" -I/usr/include -I/usr/include/python2.4 -c src/connection.c -o build/temp.linux-i686-2.4/src/connection.o src/connection.c:31:26: error: sqlitecompat.h: No such file or directory src/connection.c: In function '_set_result': src/connection.c:404: error: 'Py_ssize_t' undeclared (first use in this function) src/connection.c:404: error: (Each undeclared identifier is reported only once src/connection.c:404: error: for each function it appears in.) src/connection.c:404: error: expected ';' before 'buflen' src/connection.c:417: error: 'buflen' undeclared (first use in this function) src/connection.c: In function '_build_py_params': src/connection.c:443: error: 'Py_ssize_t' undeclared (first use in this function) src/connection.c:443: error: expected ';' before 'buflen' src/connection.c:472: error: 'buflen' undeclared (first use in this function) error: command 'gcc' failed with exit status 1 I had to manually download this file ? http://www.initd.org/tracker/pysqlite/browser/pysqlite/tags/2.3.0/src/sqlitecompat.h Why it's not included in the tarball? Regards, Dawid -- ^_* From cito at online.de Sat Jun 3 17:23:32 2006 From: cito at online.de (Christoph Zwerschke) Date: Sat, 03 Jun 2006 23:23:32 +0200 Subject: Python less error-prone than Java Message-ID: You will often hear that for reasons of fault minimization, you should use a programming language with strict typing: http://turing.une.edu.au/~comp284/Lectures/Lecture_18/lecture/node1.html I just came across a funny example in which the opposite is the case. The following is a binary search algorithm in Java. It searches a value in an ordered array a of ints: public static int binarySearch(int[] a, int key) { int low = 0; int high = a.length - 1; while (low <= high) { int mid = (low + high) / 2; int midVal = a[mid]; if (midVal < key) low = mid + 1; else if (midVal > key) high = mid - 1; else return mid; // key found } return -(low + 1); // key not found. } Now the same thing, directly converted to Python: def binarySearch(a, key): low = 0 high = len(a) - 1 while low <= high: mid = (low + high) / 2 midVal = a[mid] if midVal < key: low = mid + 1 elif midVal > key: high = mid - 1; else: return mid # key found return -(low + 1) # key not found. What's better about the Python version? First, it will operate on *any* sorted array, no matter which type the values have. But second, there is a hidden error in the Java version that the Python version does not have. See the following web page if you dont find it ;-) http://googleresearch.blogspot.com/2006/06/extra-extra-read-all-about-it-nearly.html -- Christoph From claird at lairds.us Sat Jun 24 21:15:42 2006 From: claird at lairds.us (Cameron Laird) Date: Sun, 25 Jun 2006 01:15:42 +0000 Subject: 2Qs References: Message-ID: In article , SuperHik wrote: >1st question: > >If a make an exe with i.e. py2exe, can I get any kind of error/bug >report from the exe file saved into a file error.log and how? . . . Yes. It's hard to know what more to say, in the absence of knowledge about your background. I *think* what you're after is this: define a import sys def main(): # All the real work starts here. do_first_important_thing() do_more() still_more() finish_it_all() try: main() except: problem = sys.exc_info() fp = open("error.log", "w") fp.write("The problem was '%s'.\n", str(problem[1])) fp.close() From tim.golden at viacom-outdoor.co.uk Fri Jun 2 03:41:52 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Fri, 2 Jun 2006 08:41:52 +0100 Subject: win32com: how to connect to a specific instance of a running object? Message-ID: [ago] | Is it possible to use win32com.client to connect to a | specific instance | of a running application? In particular I am interested in finding the | instance of excel which has a particular spreadsheet opened | considering | that there might be more instances of excel running at the | same time. I | need to take a "snapshot" of the spreadsheet which contains | live feeds. Not something I've tried myself, but perhaps this post/thread might help: http://groups.google.com/group/comp.lang.python/msg/d985ada28948dcd8 (I cheated slightly when I Googled because I knew that GetActiveObject was something to do with the business) 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 ________________________________________________________________________ From fredrik at pythonware.com Wed Jun 21 06:27:06 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 21 Jun 2006 12:27:06 +0200 Subject: help() on stdout.closed References: Message-ID: Pekka Karjalainen wrote: >>>> from sys import stdout >>>> help (stdout.closed) > > If I do this, it gives me help on the bool object. that's probably because "sys.stdout.closed" *is* a bool object: >>> sys.stdout.closed False >>> type(sys.stdout.closed) there's no way the reflection system can figure out how a given boolean was created; all it knows is that it gets an object of a given type. > Other docstrings in sys.stdout work fine. have you tried things like >>> help(sys.stdout.name) and >>> help(sys.stdout.write("hello")) ? From zefirek at Speacock.Pau.Apoznan.Mpl Fri Jun 9 11:09:03 2006 From: zefirek at Speacock.Pau.Apoznan.Mpl (zefciu) Date: Fri, 09 Jun 2006 17:09:03 +0200 Subject: [noob question] References and copying Message-ID: Hello! Where can I find a good explanation when does an interpreter copy the value, and when does it create the reference. I thought I understand it, but I have just typed in following commands: >>> a=[[1,2],[3,4]] >>> b=a[1] >>> b=[5,6] >>> a [[1, 2], [3, 4]] >>> b [5, 6] And I don't understand it. I thought, that b will be a reference to a, so changing b should change a as well. What do I do wrong. And a second question - can I create a reference to element of a list of floating points and use this reference to change that element? Greets to all PyFans zefciu From mrmakent at cox.net Mon Jun 12 09:15:10 2006 From: mrmakent at cox.net (Mike Kent) Date: 12 Jun 2006 06:15:10 -0700 Subject: Searching and manipulating lists of tuples In-Reply-To: <1150117632.693617.45310@c74g2000cwc.googlegroups.com> References: <1150117632.693617.45310@c74g2000cwc.googlegroups.com> Message-ID: <1150118110.412882.159240@f14g2000cwb.googlegroups.com> MTD wrote: > Hello, > > I'm wondering if there's a quick way of resolving this problem. > > In a program, I have a list of tuples of form (str,int), where int is a > count of how often str occurs ... > So clearly that doesn't work... any ideas? Yes, use the proper tool for the job. Tuples are immutable (they are read-only once created). Instead use a dictionary. They key would be your string, the value would be the count. Also, don't use 'str' as the name for a string, as it shadows the built-in 'str' function. From alanalan at newsgroup.nospam Thu Jun 8 15:32:29 2006 From: alanalan at newsgroup.nospam (A.M) Date: Thu, 8 Jun 2006 15:32:29 -0400 Subject: Win XP Error: There is not enough space on the disk Message-ID: Hi, I am using ActivePython 2.4.on windows XP I created test.py that contains the following simple script: import os os.system("dir *.py") When I run the script, it works fine. But, when I run the following command on windows XP: Test.py > file.txt I receive this error: "There is not enough space on the disk." Which is not correct. I am translating dos batch files to python scripts and I redirect the stdout output of all scripts to a LOG file. With this error, I cannot have a log file for my Python scripts. Is there any way that I can fix this problem? Thanks, Alan From david.nospam.hopwood at blueyonder.co.uk Wed Jun 21 11:29:30 2006 From: david.nospam.hopwood at blueyonder.co.uk (David Hopwood) Date: Wed, 21 Jun 2006 15:29:30 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: <44992e6c$0$664$bed64819@news.gradwell.net> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <0%Wlg.3521$MF6.947@tornado.socal.rr.com> <44992e6c$0$664$bed64819@news.gradwell.net> Message-ID: Chris Uppal wrote: > It's worth noting, too, that (in some sense) the type of an object can change > over time[*]. That can be handled readily (if not perfectly) in the informal > internal type system(s) which programmers run in their heads (pace the very > sensible post by Anton van Straaten today in this thread -- several branches > away), but cannot be handled by a type system based on sets-of-values (and is > also a counter-example to the idea that "the" dynamic type of an object/value > can be identified with its tag). > > ([*] if the set of operations in which it can legitimately partake changes. > That can happen explicitly in Smalltalk (using DNU proxies for instance if the > proxied object changes, or even using #becomeA:), but can happen anyway in less > "free" languages -- the State Pattern for instance, or even (arguably) in the > difference between an empty list and a non-empty list). Dynamic changes in object behaviour are not incompatible with type systems based on sets of values (e.g. semantic subtyping). There are some tricky issues in making such a system work, and I'm not aware of any implemented language that does it currently, but in principle it's quite feasible. For a type system that can handle dynamic proxying, see . -- David Hopwood From riquito at gmail.com Wed Jun 14 11:13:04 2006 From: riquito at gmail.com (riquito at gmail.com) Date: 14 Jun 2006 08:13:04 -0700 Subject: prog1 | prog2 . How not to make prog2 block if not piped? Message-ID: <1150297984.798904.229730@h76g2000cwa.googlegroups.com> I googled around, but couldn't understand how to solve this problem. I have 2 scripts # script1.py # print 'something' #script2.py x=sys.stdin.read() print 'passed' if I run script1.py | script2.py all goes well. But if I run just script2.py the program blocks waiting forever for input. On *nix I used select.select to solve this problem, but on windows? I read that maybe I should use, from win32api, GetStdHandle and WaitForMultipleObjects, but how to do it it's far from my knowledge. Any help? Thank you, Riccardo From fredrik at pythonware.com Wed Jun 14 03:56:44 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 14 Jun 2006 09:56:44 +0200 Subject: Decimals References: <1150188516.739925.102810@h76g2000cwa.googlegroups.com><1150190908.231517.314040@h76g2000cwa.googlegroups.com><1150191995.559582.140270@p79g2000cwp.googlegroups.com> Message-ID: Tim Roberts wrote: > DECIMAL is an SQL thing. Unless the language has a native decimal type, it > cannot possibly know how to display it in the same format as your SQL. unless your database adapter returns everything as strings... From bborcic at gmail.com Fri Jun 9 05:32:05 2006 From: bborcic at gmail.com (Boris Borcic) Date: Fri, 09 Jun 2006 11:32:05 +0200 Subject: How to generate k+1 length strings from a list of k length strings? In-Reply-To: <1149841951.219910.206100@g10g2000cwb.googlegroups.com> References: <44883789$1_4@news.bluewin.ch> <1149785331.109164.208340@i39g2000cwa.googlegroups.com> <4488658e$1_5@news.bluewin.ch> <1149800459.244528.220790@u72g2000cwu.googlegroups.com> <44892d49$1_2@news.bluewin.ch> <1149841951.219910.206100@g10g2000cwb.googlegroups.com> Message-ID: <44894027$1_2@news.bluewin.ch> bearophileHUGS at lycos.com wrote: > Boris Borcic: >>> I don't do challenges. >> Pfff... and you don't do real debates either. > > Different nations have different values and different cultures, in mine > challenges are often seen as things for children, and a waste of time > for adults (probably in USA challenges are appreciated more). (1) This is becoming very ridiculous. What do the USA have to do with it ? (2) Different nations have different languages, and a good rule of thumb when debating with someone of unknown linguistic origins is not to focus on the connotations you percieve to a single word you abstract from its context. (3) Different intellectual communities have different values, in mine it is the rule not to make abstract claims if not ready to put them to experimental test - and it's less a matter of (passing or failing) tests than a matter of making clear the rule of translation between one's own abstract language and objective facts. And by these means, ultimately, to measure the divergence in languages. (4) As concerns the matter of the case, you made broad and abstract claims while implicitely referring to some doctrine(s), and I concisely formulated the demand that you back them up with (according to you) observable facts. I note that instead you chose to articulate your doctrine while avoiding an occasion to probe its adequacy. (5) I find your systematic enrollment of children to your cause quite inappropriate. > > Bye, > bearophile > From fredrik at pythonware.com Tue Jun 6 14:47:16 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 06 Jun 2006 20:47:16 +0200 Subject: RSS feeds In-Reply-To: <9583ed900606061141h72939138jdbdcfd7073da7c22@mail.gmail.com> References: <9583ed900606061141h72939138jdbdcfd7073da7c22@mail.gmail.com> Message-ID: david brochu jr wrote: > I am looking to take RSS feeds a process them with a python program..any > idea where I can get RSS feeds for sports stats, and how I would use the > script to connect automatically to the feed? for the python-related part of your question, start here: http://www.feedparser.org/ From jzgoda at o2.usun.pl Thu Jun 15 12:06:27 2006 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Thu, 15 Jun 2006 18:06:27 +0200 Subject: Which compiler will Python 2.5 / Windows (Intel) be built with? In-Reply-To: <44917535$1@nntp0.pdx.net> References: <1150367139.495114.148550@g10g2000cwb.googlegroups.com> <44917535$1@nntp0.pdx.net> Message-ID: Scott David Daniels napisa?(a): >> which compiler will Python 2.5 on Windows (Intel) be built with? > > Same as for Python 2.4 (the decision was taken a while ago). > Intel sells a compatible compiler, I believe. Sounds rather bad. Anyway, there should be some kits available from second-hand at auction websites. Besides no free (as in "free beer") toolkit will be available, as noone except Microsoft can distribute it. -- Jarek Zgoda http://jpa.berlios.de/ From andreizilla at gmail.com Mon Jun 5 21:26:28 2006 From: andreizilla at gmail.com (Andrei B) Date: 5 Jun 2006 18:26:28 -0700 Subject: Get EXE (made with py2exe) path directory name Message-ID: <1149557188.392915.287220@i39g2000cwa.googlegroups.com> I need to get absolute path name of a file that's in the same dir as the exe, however the Current Working Directory is changed to somthing else. I turn my script into an executable with py2exe, then I create a shortcut to the EXE on the desktop. I change the "Start In" variable of the shortcut "C:\somthing_else", so now the currect working directory of the executable is not the same as the directory where the EXE is located. I need to load a file that's in the same directory as the EXE, so I do the following: dir = os.path.dirname(sys.argv[0]) filepath = os.path.join(dir, 'server.pkey') however it doesn't seem to work. Any idea? thanks! From deets at nospam.web.de Wed Jun 28 05:08:35 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 28 Jun 2006 11:08:35 +0200 Subject: Beginner question? Classes, variables, ... References: <4getagF1mpqksU1@uni-berlin.de> Message-ID: <4gev94F1mo2p2U1@uni-berlin.de> Dennis Lee Bieber wrote: > On Wed, 28 Jun 2006 10:35:10 +0200, "Diez B. Roggisch" > declaimed the following in comp.lang.python: > >> class X: >> def __init__(self, my_y): >> self.my_y > self.my_y = my_y *argl* Thanks :) No tea so far... Diez From a.flow at tiscali.it Thu Jun 8 20:34:49 2006 From: a.flow at tiscali.it (And80) Date: 8 Jun 2006 17:34:49 -0700 Subject: Python Class for Apache log analysis Message-ID: <1149813289.467298.6110@j55g2000cwa.googlegroups.com> Hi all, I am looking for a python package that I could employ to analyze Apache's log files in real time. Of course I already have found some scripts, but most of them are outdated (python1.5), while others are simply impossible to use for a custom application. I was looking for something reliable, flexible and not to much outdated... Thank you in advance, Andrea From raffaelcavallaro at pas-d'espam-s'il-vous-plait-mac.com Fri Jun 16 18:25:09 2006 From: raffaelcavallaro at pas-d'espam-s'il-vous-plait-mac.com (Raffael Cavallaro) Date: Fri, 16 Jun 2006 18:25:09 -0400 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <2006061410510511272-raffaelcavallaro@pasdespamsilvousplaitmaccom> <2006061501423327544-raffaelcavallaro@pasdespamsilvousplaitmaccom> <2006061611492350073-raffaelcavallaro@pasdespamsilvousplaitmaccom> Message-ID: <2006061618250975249-raffaelcavallaro@pasdespamsilvousplaitmaccom> On 2006-06-16 17:59:07 -0400, Joachim Durchholz said: > I think it's easier to start with a good (!) statically-typed language > and relax the checking, than to start with a dynamically-typed one and > add static checks. > With the right restrictions, a language can make all kinds of strong > guarantees, and it can make it easy to construct software where static > guarantees abound. If the mechanisms are cleverly chosen, they > interfere just minimally with the programming process. (A classical > example it Hindley-Milner type inference systems. Typical reports from > languages with HM systems say that you can have it verify thousand-line > programs without a single type annotation in the code. That's actually > far better than you'd need - you'd *want* to document the types at > least on the major internal interfaces after all *grin*.) > With a dynamically-typed language, programming style tends to evolve in > directions that make it harder to give static guarantees. This is purely a matter of programming style. For explorative programming it is easier to start with dynamic typing and add static guarantees later rather than having to make decisions about representation and have stubs for everything right from the start. The lisp programming style is arguably all about using heterogenous lists and forward references in the repl for everything until you know what it is that you are doing, then choosing a more appropriate representation and filling in forward references once the program gels. Having to choose representation right from the start and needing working versions (even if only stubs) of *every* function you call may ensure type correctness, but many programmers find that it also ensures that you never find the right program to code in the first place. This is because you don't have the freedom to explore possible solutions without having to break your concentration to satisfy the nagging of a static type checker. From danmcleran at yahoo.com Tue Jun 20 17:42:30 2006 From: danmcleran at yahoo.com (danmcleran at yahoo.com) Date: 20 Jun 2006 14:42:30 -0700 Subject: Psyco performance In-Reply-To: <44981e4c$0$29812$626a54ce@news.free.fr> References: <1150819763.818687.114360@y41g2000cwy.googlegroups.com> <44981e4c$0$29812$626a54ce@news.free.fr> Message-ID: <1150839749.939196.142440@r2g2000cwb.googlegroups.com> > Place all the code in a function. Even without psyco you might get > somewhat better performances then. And I doubt psyco can optimise code > that isn't in a function anyway. > > And lastly, most of the code is probably spend computing x**2 which is > already optimised C code. I've changed the code to include a class, method call, and function. Now the Psyco code is quite a bit slower. Is this a valid way to test Psyco's effects? When I run the following code I get this result: without psyco = 0.96840101186 with psyco = 1.82430169197 with psyco = 0.855900680114 slower The code: import time import psyco class Test(object): def __init__(self, value): self.value = value def foo(self): return reduce(lambda x,y : x + y, list(range(0,self.value))) def test(n): l = [Test(i) for i in range(1, n)] return [x.foo() for x in l] n = 1000 t1 = time.clock() l2 = test(n) t2 = time.clock() no_psyco = t2 - t1 psyco.full() t1 = time.clock() l2 = test(n) t2 = time.clock() with_psyco = t2 - t1 print 'without psyco = ',no_psyco print 'with psyco = ',with_psyco delta = (no_psyco - with_psyco) if(delta > 0): result = 'faster' else: result = 'slower' print 'with psyco = ',abs(delta),result From scott.daniels at acm.org Fri Jun 23 15:48:07 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Fri, 23 Jun 2006 12:48:07 -0700 Subject: Clearing pythonwin environment In-Reply-To: <1151012168.838694.235610@c74g2000cwc.googlegroups.com> References: <1151012168.838694.235610@c74g2000cwc.googlegroups.com> Message-ID: <449c4071$1@nntp0.pdx.net> Network Ninja wrote: > I want to restart the environment occasionally to default (like I > restarted pythonwin). I wrote this script. I know why it doesn't work, > cause it deletes my variable (item) on each iteration. My question is: > is it possible to do this? What other things might I try? > > keep = ['__builtins__', '__doc__', '__name__', 'pywin', 'keep', 'item'] > for item in dir(): > if item not in keep: > del item keep = set(['__builtins__', '__doc__', '__name__', 'pywin', 'keep', 'item', 'globs']) # Faster to test globs = globals() for item in dir(): if item not in keep: del globs[item] del globs, item Note that this leaves all imported modules imported. --Scott David Daniels scott.daniels at acm.org From david.nospam.hopwood at blueyonder.co.uk Wed Jun 28 09:56:18 2006 From: david.nospam.hopwood at blueyonder.co.uk (David Hopwood) Date: Wed, 28 Jun 2006 13:56:18 GMT Subject: Java identifiers (was: languages with full unicode support) In-Reply-To: <44a26911$1$660$bed64819@news.gradwell.net> References: <1151251736.590910.36050@u72g2000cwu.googlegroups.com> <44a26911$1$660$bed64819@news.gradwell.net> Message-ID: <6Uvog.490321$tc.256914@fe2.news.blueyonder.co.uk> Note Followup-To: comp.lang.java.programmer Chris Uppal wrote: > Since the interpretation of characters which are yet to be added to > Unicode is undefined (will they be digits, "letters", operators, symbol, > punctuation.... ?), there doesn't seem to be any sane way that a language could > allow an unrestricted choice of Unicode in identifiers. Hence, it must define > a specific allowed sub-set. C certainly defines an allowed subset of Unicode > characters -- so I don't think you could call its Unicode support "half-baked" > (not in that respect, anyway). A case -- not entirely convincing, IMO -- could > be made that it would be better to allow a wider range of characters. > > And no, I don't think Java's approach -- where there /is no defined set of > allowed identifier characters/ -- makes any sense at all :-( Java does have a defined set of allowed identifier characters. However, you certainly have to go around the houses a bit to work out what that set is: # An identifier is an unlimited-length sequence of Java letters and Java digits, # the first of which must be a Java letter. An identifier cannot have the same # spelling (Unicode character sequence) as a keyword (?3.9), boolean literal # (?3.10.3), or the null literal (?3.10.7). [...] # A "Java letter" is a character for which the method # Character.isJavaIdentifierStart(int) returns true. A "Java letter-or-digit" # is a character for which the method Character.isJavaIdentifierPart(int) # returns true. [...] # Two identifiers are the same only if they are identical, that is, have the # same Unicode character for each letter or digit. For Java 1.5.0: # Character information is based on the Unicode Standard, version 4.0. # A character may start a Java identifier if and only if one of the following # conditions is true: # # * isLetter(codePoint) returns true # * getType(codePoint) returns LETTER_NUMBER # * the referenced character is a currency symbol (such as "$") [This means that getType(codePoint) returns CURRENCY_SYMBOL, i.e. Unicode General Category Sc.] # * the referenced character is a connecting punctuation character (such as "_"). [This means that getType(codePoint) returns CONNECTOR_PUNCTUATION, i.e. Unicode General Category Pc.] # A character may be part of a Java identifier if any of the following are true: # # * it is a letter # * it is a currency symbol (such as '$') # * it is a connecting punctuation character (such as '_') # * it is a digit # * it is a numeric letter (such as a Roman numeral character) [General Category Nl.] # * it is a combining mark [General Category Mc (see ).] # * it is a non-spacing mark [General Category Mn (ditto).] # * isIdentifierIgnorable(codePoint) returns true for the character # A character is a digit if its general category type, provided by # getType(codePoint), is DECIMAL_DIGIT_NUMBER. [General Category Nd.] # The following Unicode characters are ignorable in a Java identifier or a Unicode # identifier: # # * ISO control characters that are not whitespace # o '\u0000' through '\u0008' # o '\u000E' through '\u001B' # o '\u007F' through '\u009F' # * all characters that have the FORMAT general category value [FORMAT is General Category Cf.] # A character is considered to be a letter if its general category type, provided # by getType(codePoint), is any of the following: # # * UPPERCASE_LETTER # * LOWERCASE_LETTER # * TITLECASE_LETTER # * MODIFIER_LETTER # * OTHER_LETTER ==== To cut a long story short, the syntax of identifiers in Java 1.5 is therefore: Keyword ::= one of abstract continue for new switch assert default if package synchronized boolean do goto private this break double implements protected throw byte else import public throws case enum instanceof return transient catch extends int short try char final interface static void class finally long strictfp volatile const float native super while Identifier ::= IdentifierChars butnot (Keyword | "true" | "false" | "null") IdentifierChars ::= JavaLetter | IdentifierChars JavaLetterOrDigit JavaLetter ::= Lu | Ll | Lt | Lm | Lo | Nl | Sc | Pc JavaLetterOrDigit ::= JavaLetter | Nd | Mn | Mc | U+0000..0008 | U+000E..001B | U+007F..009F | Cf where the two-letter terminals refer to General Categories in Unicode 4.0.0 (exactly). Note that the so-called "ignorable" characters (for which isIdentifierIgnorable(codePoint) returns true) are not ignorable; they are treated like any other identifier character. This quote from the API spec: # The following Unicode characters are ignorable in a Java identifier [...] should be ignored (no pun intended). It is contradicted by: # Two identifiers are the same only if they are identical, that is, have the # same Unicode character for each letter or digit. in the language spec. Unicode does have a concept of ignorable characters in identifiers, which is probably where this documentation bug crept in. The inclusion of U+0000 and various control characters in the set of valid identifier characters is also a dubious decision, IMHO. Note that I am not defending in any way the complexity of this definition; there's clearly no excuse for it (or for the "ignorable" documentation bug). The language spec should have been defined directly in terms of the Unicode General Categories, and then the API in terms of the language spec. They way it is done now is completely backwards. -- David Hopwood From python-url at phaseit.net Mon Jun 26 10:39:06 2006 From: python-url at phaseit.net (Cameron Laird) Date: Mon, 26 Jun 2006 14:39:06 +0000 (UTC) Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jun 26) Message-ID: QOTW: "In short, it's never what you think it is ;-)" - timbot, probably on the subject of performance "Real efficiency comes from elegant solutions, not optimized programs. Optimization is always just a few correctness-preserving transformations away." - Jonathan Sobel http://www.cs.indiana.edu/~jsobel/c455-c511.updated.txt Microsoft is (again) structuring its current marketing around "platforms", and apparently Python is starting to show up in the campaigns: http://www.microsoft.com/presspass/press/2006/jun06/06-20MSRoboticsStudioPR.mspx Intel puts Python to good use in commercial "program slicing": http://groups.google.com/group/comp.lang.python/browse_thread/thread/98cd59f90b169896/ Transcoding PVRs? Constructing collaborative whiteboards? Streaming multimedia in all directions? Apparently you can construct very impressive network-aware audiovisual applications *visually* with Kamaelia: http://groups.google.com/group/comp.lang.python/browse_thread/thread/36c89411fba299b6/ If you only care about advanced concurrency methods, pipeline- based methods, and componentry, well, that's in there, too, wrapped as Axon: http://groups.google.com/group/comp.lang.python/msg/7a5f189e886d9fc0 Discussion about the new Python icons might inspire a reader to try them: http://groups.google.com/group/comp.lang.python/browse_thread/thread/204f2792a882648d/ Wow: PyPy is up to 0.9.0: http://groups.google.com/group/comp.lang.python.announce/msg/6fa325e6c0cdd526 Life becomes more sophisticated than ever before: http://golly.sourceforge.net/ Timbot illustrates how an experienced file-comparer thinks about performance hacks (and Windows): http://groups.google.com/group/comp.lang.python/msg/15d45c2b268fa410 ... and how much deeper one can analyze recursion and numerics than merely the "tastes great! less filling!" level: http://groups.google.com/group/comp.lang.python/msg/e67403fcaa06c022 http://groups.google.com/group/comp.lang.python/msg/4451e63833a0c1c1 ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. For far, FAR more Python reading than any one mind should absorb, much of it quite interesting, several pages index much of the universe of Pybloggers. http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog http://www.planetpython.org/ http://mechanicalcat.net/pyblagg.html comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html Steve Bethard, Tim Lesher, and Tony Meyer continue the marvelous tradition early borne by Andrew Kuchling, Michael Hudson and Brett Cannon 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/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 http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topic/python/ (requires subscription) http://groups-beta.google.com/groups?q=python-url+group:comp.lang.python*&start=0&scoring=d& http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". Write to the same address to unsubscribe. -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From steven.bethard at gmail.com Sat Jun 3 22:42:25 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 03 Jun 2006 20:42:25 -0600 Subject: Proposed new PEP: print to expand generators In-Reply-To: References: Message-ID: James J. Besemer wrote: > I propose that we extend the semantics of "print" such that if the > object to be printed is a generator then print would iterate over the > resulting sequence of sub-objects and recursively print each of the > items in order. I don't feel like searching for the specific python-dev threads right now, but something like this has been suggested before (I think with a "%i" formatting code), and Guido felt strongly that the addition or removal of a simple print statement shouldn't change the behavior of the surrounding code. Consider code like:: items = get_generator_or_None() for item in items: do_something(item) Now let's say I insert a debugging line like:: items = get_generator_or_None() print "make sure this isn't None:", items for item in items: do_something(item) My debugging line now just broke the rest of my code. That's not good. The other reason I don't think this PEP should go forward (at least as it is) is that Python 3000 is already going to turn the print statement into a function (though the exact details of that function have not been hashed out yet). So adding extra cruft to the print statement is kind of wasted effort. STeVe From elekis at gmail.com Thu Jun 1 11:03:16 2006 From: elekis at gmail.com (elekis) Date: 1 Jun 2006 08:03:16 -0700 Subject: how to create a cgi folder??? Message-ID: <1149174196.582085.5150@y43g2000cwc.googlegroups.com> hi there I have a host who suport python cgi script (www.frihost.com that's cool) and discovert python (and mysql) I would like to make my own site on python . But I woulud like to try before on my own machine (localhost.) So I would like to know how to create a CGI folder ??? I installed apache (I m under Ubuntu-linux) php and mysql cause in a first time it was that I used. but... is ther a package or a binary who do all ??? thanks a++++ From Peter.Silva at ec.gc.ca Tue Jun 20 09:47:48 2006 From: Peter.Silva at ec.gc.ca (Peter Silva) Date: 20 Jun 2006 06:47:48 -0700 Subject: transfer rate limiting in socket.py In-Reply-To: <1hh736m.18af1ef1j8hg3vN%aleax@mac.com> References: <1150491228.229045.163110@h76g2000cwa.googlegroups.com> <1150734565.753038.240580@c74g2000cwc.googlegroups.com> <1hh736m.18af1ef1j8hg3vN%aleax@mac.com> Message-ID: <1150811268.710535.266710@i40g2000cwc.googlegroups.com> Cool! Will check it out... Alex Martelli wrote: > Peter Silva wrote: > > > I looked at twisted briefly. It looks like it is server oriented. > > Does it work in for clients initiating connections? > > Twisted supports clients, servers, and "middleware" (proxies etc) in > equally wonderful and powerful ways. > > > Alex From fredrik at pythonware.com Thu Jun 15 14:45:23 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 15 Jun 2006 20:45:23 +0200 Subject: list of polynomial functions In-Reply-To: <4491AA55.7030200@tim.thechases.com> References: <1150390140.459461.169900@i40g2000cwc.googlegroups.com> <4491AA55.7030200@tim.thechases.com> Message-ID: Tim Chase wrote: >> The `i` is the problem. It's not evaluated when the lambda >> *definition* is executed but when the lambda function is >> called. And then `i` is always == `n`. You have to >> explicitly bind it as default value in the lambda definition: >> >> polys.append(lambda x, i=i: polys[i](x)*x) >> >> Then it works. > > Just to sate my curiosity, why can the lambda find "polys", but > not find "i"? If what you're describing is the case, then it > seems to me that the following code should work too: it's not that it cannot find it, it's that if you use a closure, i will have the same value for all lambdas. > There's some subtle behavior here that I'm missing. lexical closures bind to names, default arguments bind to values. From rpdooling at gmail.com Thu Jun 15 10:31:13 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 15 Jun 2006 07:31:13 -0700 Subject: Python is fun (useless social thread) ;-) References: Message-ID: <1150381872.958342.180420@p79g2000cwp.googlegroups.com> >> Did you have to learn it for a job? No. >> Or did you just like what you saw and decided to learn it for fun? Tried Perl first, but since I don't use it every day (sometimes don't do anything but RUN scripts for weeks on end if I'm in a big project), I would forget all of the Perl between learning sessions. Python seems to be made of words, not symbols. Also, it seems to be a minimalist language. I like that. >> Also, how did you go about learning it? I had no computer science background, just a long time Windows user. The Guido tutorial moved way too fast. Alan Gauld's "Learning To Program" was just right. From there, lurking on this group, and books. Especially the Python Cookbook, as I don't normally 'get it' when someone just describes theory or an abstraction, I also must see an example. The examples in the Cookbook are useful and also come with explanations about how they work. Same goes for this group. Nine times out of ten, when people answer a question here, they toss off an example or two, which is just what I need. >> Was there any necessity in the specifics you learned, or did you just >> dabble in something (e.g. wxPython) for fun? I almost always have a task I want to do, e.g. search a database or manipulate files. From there, I branch out and learn, even if it's not part of the original task. >> Are there still some things you feel you need to learn or improve? I am not touching OO, classes, or GUIs until I understand EVERYTHING else. Could take a few years. ;) rd From suma.37 at gmail.com Mon Jun 5 08:32:18 2006 From: suma.37 at gmail.com (su) Date: 5 Jun 2006 05:32:18 -0700 Subject: finding file Message-ID: <1149510738.569437.242050@f6g2000cwb.googlegroups.com> Hi , I am trying to understand myself with some basic programs in python, I have written a small script to search for core files in the current dir. but when i tried to execute, it is searching the core files in the subdir also. could someone help me on how can i restrict my code to search the file in the current dir only import os, os.path import re def core_finder(arg, dir, files): for file in files: path = os.path.join (dir, file) if re.search("core.*", path): print "found" print path os.path.walk('.', core_finder, 0) From rpdooling at gmail.com Mon Jun 5 19:29:29 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 5 Jun 2006 16:29:29 -0700 Subject: Expanding Search to Subfolders In-Reply-To: <1288t2dn5i7bm61@corp.supernews.com> References: <1149526866.681348.273590@c74g2000cwc.googlegroups.com> <1288t2dn5i7bm61@corp.supernews.com> Message-ID: <1149550169.852661.263570@g10g2000cwb.googlegroups.com> >> there are far easier ways >> #!/bin/bash >> cat *.txt >outputfile Well, yes, but if he's kicking things off with: >> os.chdir("C:\\Python23\\programs\\filetree") I'm guessing he's not on Linux. Maybe you're trying to convert him? rd From jerome.decasteau at ksz-bcss.fgov.be Tue Jun 20 04:20:42 2006 From: jerome.decasteau at ksz-bcss.fgov.be (jdec) Date: 20 Jun 2006 01:20:42 -0700 Subject: Missing fpconst? In-Reply-To: References: Message-ID: <1150791642.587143.256490@c74g2000cwc.googlegroups.com> Hi, I was just looking for fpconst too. I found it on : http://www.warnes.net/rwndown/projects/RStatServer/fpconst Jerome From maric at aristote.info Thu Jun 1 08:44:37 2006 From: maric at aristote.info (Maric Michaud) Date: Thu, 1 Jun 2006 14:44:37 +0200 Subject: Function mistaken for a method In-Reply-To: References: Message-ID: <200606011444.38612.maric@aristote.info> Le Jeudi 01 Juin 2006 13:12, Eric Brunel a ?crit?: > Thanks for your explanations, Peter. I'll have to find another way to do ? > what I want... maybe : class C: ? ?f = None ? ?def __init__(self): ? ? ?if self.f is not None: ? ? ? ?self.x = self.f(0) ? ? ?else: ? ? ? ?self.x = 0 class C2(C): ? ?def __init__(self) : self.f = lambda x: x != 0 -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From junkytownMAKNI at gmail.com Sat Jun 17 19:05:08 2006 From: junkytownMAKNI at gmail.com (SuperHik) Date: Sun, 18 Jun 2006 01:05:08 +0200 Subject: Standard Yes / No Windows Dialog box creation In-Reply-To: References: <1150581640.385143.83410@y41g2000cwy.googlegroups.com> Message-ID: Claudio Grondi wrote: > flaus.a at wanadoo.fr wrote: >> I found a way to create "Open File" or "Open Folder" windows dialog >> boxes, but not to create an easier Yes / No dialog box... >> Maybe someone has a solution for this? I've never seen "easier" way to do it, but my solution for you if you want to create a GUI application without learning any GUI programming would be to consider Glade, wxGlade and such... >> > Do it just the same way as you did it with the "Open File" or "Open > Folder" windows dialog. What is your problem with it? > I think what he means by "create" is somethink like win32ui.CreateFileDialog() because of the "easier" part. > Claudio From utabintarbo at gmail.com Thu Jun 29 14:00:58 2006 From: utabintarbo at gmail.com (utabintarbo) Date: 29 Jun 2006 11:00:58 -0700 Subject: list comprehension In-Reply-To: <1151602493.629010.269360@i40g2000cwc.googlegroups.com> References: <1151600332.552024.119990@y41g2000cwy.googlegroups.com> <1151602493.629010.269360@i40g2000cwc.googlegroups.com> Message-ID: <1151604058.221194.122560@b68g2000cwa.googlegroups.com> Simon Forman wrote: > results = [] > for var in some_iterable: > if some condition: > results.append(some expression) > > > The list comprehension version: > > results = [some expression for var in some_iterable if some condition] > > > There's more to it, but that's the basic idea. Even if 'a' doesn't like it, I do! :-) From maric at aristote.info Mon Jun 26 20:54:32 2006 From: maric at aristote.info (Maric Michaud) Date: Tue, 27 Jun 2006 02:54:32 +0200 Subject: TypeError: Cannot create a consistent method resolution order (MRO) for bases object In-Reply-To: <1151345197.691600.200060@y41g2000cwy.googlegroups.com> References: <1151345197.691600.200060@y41g2000cwy.googlegroups.com> Message-ID: <200606270254.33998.maric@aristote.info> Le lundi 26 juin 2006 20:06, digitalorganics at gmail.com a ?crit?: > What are the reason one would get this error: TypeError: Cannot create > a consistent method resolution order (MRO) for bases object ?? > > I can provide the code if needed.... This is the python solution to the diamond problem (cf. wikipedia). In [61]: class a(object) : pass ....: In [62]: class b(a) : pass ....: In [63]: class c(object, a) : pass ....: --------------------------------------------------------------------------- exceptions.TypeError Traceback (most recent call last) /home/maric/ TypeError: Error when calling the metaclass bases Cannot create a consistent method resolution order (MRO) for bases object, a In [64]: b.mro() Out[64]: [, , ] In [65]: class c(a, object) : pass ....: In [66]: c.mro() Out[66]: [, , ] In [67]: class d(b, c) : pass ....: In [69]: d.mro() Out[69]: [, , , , ] mro means "method resolution order", this is the path the interpreter will look for attributes for a given class. You cannot introduce inconsistency in this path, for example duplicate the type object before another type (or any type wich appear to be the ancestor of another). -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From mail at guildgame.com Wed Jun 14 00:44:07 2006 From: mail at guildgame.com (Antoine) Date: 13 Jun 2006 21:44:07 -0700 Subject: os.spawn* on Windows Message-ID: <1150260247.626174.221250@p79g2000cwp.googlegroups.com> Hello list I am using Python 2.4 to invoke other programs on Windows XP, using syntax like this: os.spawnv(P_WAIT, "C:\\my.exe", ("C:\\my.exe",)) where my.exe is a console-mode program. When the above statement is executed, the my.exe program creates a window, what used to be called a Dos prompt but is no doubt called something else now, and steals the keyboard input focus. This proves to be highly annoying (because the window pops up unexpectedly in front of my other windows and often steals several characters of what I am typing). I would rather the 'Dos prompt' was created minimised and did not steal the input focus. Is there any way to achieve this end by using a different Python command to invoke my.exe? Or would I have to change my.exe itself? Cheers A. From percivall at gmail.com Fri Jun 30 06:01:57 2006 From: percivall at gmail.com (Simon Percivall) Date: 30 Jun 2006 03:01:57 -0700 Subject: FIXED: Re: optparse multiple arguments References: <1151657119.837675.213700@p79g2000cwp.googlegroups.com> <1151657634.348133.291340@x69g2000cwx.googlegroups.com> <1151658092.273456.32260@75g2000cwc.googlegroups.com> Message-ID: <1151661717.240109.47650@h44g2000cwa.googlegroups.com> Ritesh Raj Sarraf wrote: > Ritesh Raj Sarraf wrote: > > I just noticed that the args variable is holding values b and c. > > the args variables comes from: > > (options, args) = parser.parse_args() > > > > I guess I only need to figure out now is why args isn't storing > > argument "a" also... > > > > Ritesh > > I fixed it, I guess. > > parser.add_option("", "--my-option", dest="my_option", > action="store_true") > > sets my_option to True and the arguments are all stored in the list > "args". :-) > > Ritesh It might do you good to read the documentation instead of blindly experimenting. Anyway, parser.add_option("", "--my-option", nargs=3) http://docs.python.org/lib/optparse-standard-option-actions.html From tiarno at sas.com Fri Jun 9 08:53:45 2006 From: tiarno at sas.com (Tim Arnold) Date: Fri, 9 Jun 2006 08:53:45 -0400 Subject: wddx problem with entities References: Message-ID: "Tim Arnold" wrote in message news:e66k6n$bc5$1 at foggy.unx.sas.com... > I'm confused about why I get this error: > UnicodeError: ASCII encoding error: ordinal not in range(128) > > when I try to load a wddx file containing this string: > The image file, gif/aperçu.png, does > not exist. > > When I loop through the file as if it's text and check the ord() value of > each character, of course it's clean. Do I have to replace numbered > entities in the wddx file before I can wddx.load() it? > thanks! > --tim > > example program: > ------------------- > from xml.marshal import wddx > > datastring = ''' > > >
> > The image file, gif/aperçu.png,does not exist. > ''' > > data = wddx.loads(datastring) Replying to my own post. I got around this problem, which *looks* like a bug to me, (although I'm sure I don't understand the internals of xml.marshal) with this: self.data = wddx.loads(''.join(codecs.open(self.filename, errors='ignore',encoding='ascii').readlines())) where self.filename contains the numbered entity. just in case anyone else out there is using wddx to communicate between python and php. --Tim Arnold From astyonax at libero.it Thu Jun 8 03:53:26 2006 From: astyonax at libero.it (astyonax) Date: 8 Jun 2006 00:53:26 -0700 Subject: language-x-isms In-Reply-To: References: Message-ID: <1149753206.451066.120960@h76g2000cwa.googlegroups.com> Fredrik Lundh wrote: > Bryan wrote: > > > for example, i've noticed several java developers i know write python code like > > this: > > > > foo_list = [...] > > for i in range(len(foo_list)): > > print '%d %s' % (i, foo_list[i]) > > which is a perfectly valid way of doing things if you're targeting older > Python platforms as well (including Jython). > > But it's not the pythonic way. From maxm at mxm.dk Tue Jun 27 04:06:29 2006 From: maxm at mxm.dk (Max M) Date: Tue, 27 Jun 2006 10:06:29 +0200 Subject: A game idea. In-Reply-To: <1151331265.902998.75620@r2g2000cwb.googlegroups.com> References: <1151331265.902998.75620@r2g2000cwb.googlegroups.com> Message-ID: <44a0e6da$0$149$edfadb0f@dread11.news.tele.dk> defcon8 wrote: > I have had what I think is quite a nice game idea, but I don't really > have the experience or knowledge to go about it. Would anyone be > willing to start a game project? Ideas are a dime a dozen. Implementation is the hard part. If you want something done, you will have to do it yourself. I am not trying to be negative, but I will bet you that every competent programmer on the list has 1+ project that she would love to do, if she just had the time. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science Phone: +45 66 11 84 94 Mobile: +45 29 93 42 96 From salvatore.didio at wanadoo.fr Tue Jun 13 09:44:40 2006 From: salvatore.didio at wanadoo.fr (Salvatore) Date: 13 Jun 2006 06:44:40 -0700 Subject: "Adding" dictionnaries In-Reply-To: <4ezjg.24272$0v4.17029@tornado.texas.rr.com> References: <1150203354.861658.181110@h76g2000cwa.googlegroups.com> <1150203783.897858.221300@h76g2000cwa.googlegroups.com> <4ezjg.24272$0v4.17029@tornado.texas.rr.com> Message-ID: <1150206280.286610.125980@p79g2000cwp.googlegroups.com> Paul McGuire a ?crit : > Also, you will find a wealth of help by using (from the interactive Python > prompt) "help(dict)" or "help(str)" or "import unfamiliarModule; > help(unfamiliarModule)". > Thanks Paul From flippa at flippac.org Sun Jun 11 00:14:42 2006 From: flippa at flippac.org (Philippa Cowderoy) Date: Sun, 11 Jun 2006 05:14:42 +0100 Subject: Xah Lee network abuse In-Reply-To: References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148495974.975395.12920@i40g2000cwc.googlegroups.com> <1149998343.493200.144990@h76g2000cwa.googlegroups.com> Message-ID: On Sat, 10 Jun 2006, Erik Max Francis wrote: > Mallor wrote: > > > I know I'm coming late to the barbeque. In passing, I ask: do you have > > an objective, impartial perspective on the subject of committing > > crimes? Because libel is a crime. > > No, it is a tort. > Rather a lot depends on which legal system you're in, for a start. Including the standards of proof and who the onus is on. -- flippa at flippac.org Sometimes you gotta fight fire with fire. Most of the time you just get burnt worse though. From fredrik at pythonware.com Tue Jun 13 12:43:05 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 13 Jun 2006 18:43:05 +0200 Subject: Making a Label that looks the same as a button. In-Reply-To: References: <1150204443.568118.185030@c74g2000cwc.googlegroups.com> Message-ID: Andrew Gwozdziewycz wrote: > It's imperative that you explain which toolkit you are using since > they all have differences. however, if you knew the answer, you would have recognized what toolkit he was using. From fredrik at pythonware.com Fri Jun 30 07:10:44 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 30 Jun 2006 13:10:44 +0200 Subject: Way for see if dict has a key References: <6V6pg.21624$_J1.271925@twister2.libero.it> Message-ID: Michele Petrazzo wrote: > >> key in dict > > > > new syntax (2.3 and later). > > So, following it, it can be used for the operations like len? what's "it" in this sentence? > len(dict) -> len(dict.keys()) ? len(dict.keys()) is a lousy way to spell len(dict). From sjmachin at lexicon.net Thu Jun 8 21:10:10 2006 From: sjmachin at lexicon.net (John Machin) Date: Fri, 09 Jun 2006 11:10:10 +1000 Subject: Win XP: Problem with shell scripting in Python In-Reply-To: <4488c529$1@news.eftel.com> References: <4488c529$1@news.eftel.com> Message-ID: <4488ca72@news.eftel.com> On 9/06/2006 10:47 AM, John Machin wrote: > Now it's *your* turn to do something for the cause. It appears to me > that popen4 has exactly the same documentation as popen3, as recently as > 2.5a2. I see no fourth gizmoid here. > > Whoooaaah! "4" is not a gizmoid count: > > |>>> handles = os.popen4('MD :') > |>>> handles > (, at 0x00 > AAF4E8>) > > You might like to suss this out, and raise a request to have the docs > fixed. OK, OK, alright already. I didn't read the docs closely enough. Forget the doc-fix request. It looks like it will pay you to investigate popen4 a bit further :-) Cheers, From robert.thorpe at antenova.com Tue Jun 20 13:20:33 2006 From: robert.thorpe at antenova.com (Rob Thorpe) Date: 20 Jun 2006 10:20:33 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <7zpshbsvjy.fsf@app-1.diku.dk><4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <1150809118.677124.142230@u72g2000cwu.googlegroups.com> <1150815461.210286.53120@r2g2000cwb.googlegroups.com> <1150822150.701434.296460@u72g2000cwu.googlegroups.com> Message-ID: <1150824033.452278.45310@c74g2000cwc.googlegroups.com> Darren New wrote: > Rob Thorpe wrote: > > The compiler > > relys entirely on the types of the variables to know how to correctly > > operate on the values. The values themselves have no type information > > associated with them. > > int x = (int) (20.5 / 3); > > What machine code operations does the "/" there invoke? Integer > division, or floating point division? How did the variables involved in > the expression affect that? In that case it knew because it could see at compile time. In general though it doesn't. If I divide x / y it only knows which to use because of types declared for x and y. > >>Casting in C takes values of one type to values of another type. > > > No it doesn't. Casting reinterprets a value of one type as a value of > > another type. > > No it doesn't. > int x = (int) 20.5; > There's no point at which bits from the floating point representation > appear in the variable x. > > int * x = (int *) 0; > There's nothing that indicates all the bits of "x" are zero, and indeed > in some hardware configurations they aren't. I suppose some are conversions and some reinterpretations. What I should have said it that there are cases where cast reinterprets. From george.sakkis at gmail.com Thu Jun 1 11:40:23 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 1 Jun 2006 08:40:23 -0700 Subject: argmax References: Message-ID: <1149176423.854154.152240@i39g2000cwa.googlegroups.com> David Isaac wrote: > 1. Why is there no argmax built-in? > (This would return the index of the largest element in a sequence.) I guess because it's not used frequently enough. I've needed argmax/argmin more than once though, so I would welcome them as builtins. > 2. Is this a good argmax (as long as I know the iterable is finite)? > def argmax(iterable): return max(izip( iterable, count() ))[1] Yes, it's ok. Here's another one that doesn't require importing itertools: def argmax(iterable): return max((x,i) for i,x in enumerate(iterable))[1] > 3. If this is the only place in a module where I need count and izip, > should I import them at the module level or at the level of the function? > What are the considerations here? Both have their merits. I like having the imports close to the point they're used, at least if used only once; OTOH having all imports at the top of the module makes easier to see the module's dependencies without grep'ing for import (that's especially useful for non-standard imported modules or new additions ot the std lib if backwards compatibility is an issue). George From ericcngan at gmail.com Fri Jun 23 18:43:00 2006 From: ericcngan at gmail.com (vduber6er) Date: 23 Jun 2006 15:43:00 -0700 Subject: Trouble including Python.h In-Reply-To: <1151099498.381282.64590@b68g2000cwa.googlegroups.com> References: <1151099498.381282.64590@b68g2000cwa.googlegroups.com> Message-ID: <1151102580.317497.60390@p79g2000cwp.googlegroups.com> Try #undef _DEBUG #include "C:\Python24\include\python.h" or which ever path your python.h is located at works for me Marcelo Gosling wrote: > Hi, everyone. > > This is on WinXP SP2, with Python 2.4.3 and DJGPP gcc 4.1.0. > > I'm having trouble including Python.h in a C file. The following C > code: > > #include "Python.h" > > int main() > { > return 0; > } > > when compiled with "gcc -I..\Python2.4\include\", gives more than 1000 > lines of errors, beginning with: > > c:/documents and settings/marcelo.gosling/my > documents/djgpp/bin/as.exe: BFD 2.16.1 assertion fail > ../../bfd/coff-i386.c:576 > c:/documents and settings/marcelo.gosling/my > documents/djgpp/tmp/ccACtxBR.s: Assembler messages: > c:/documents and settings/marcelo.gosling/my > documents/djgpp/tmp/ccACtxBR.s:28: Error: cannot represent relocation > type BFD_RELOC_386_PLT32 > In file included from ../../Python2.4/include/Python.h:74, > from example_wrap.c:112: > ../../Python2.4/include/pymem.h: In function '__declspec': > ../../Python2.4/include/pymem.h:51: error: expected declaration > specifiers before '__declspec' > ../../Python2.4/include/pymem.h:52: error: expected declaration > specifiers before '__declspec' > In file included from ../../Python2.4/include/Python.h:76, > from example_wrap.c:112: > ../../Python2.4/include/object.h:104: error: storage class specified > for parameter 'PyObject' > ../../Python2.4/include/object.h:108: error: storage class specified > for parameter 'PyVarObject' > ../../Python2.4/include/object.h:126: error: expected '=', ',', ';', > 'asm' or '__attribute__' before '*' token > ../../Python2.4/include/object.h:127: error: expected '=', ',', ';', > 'asm' or '__attribute__' before '*' token > ../../Python2.4/include/object.h:128: error: expected '=', ',', ';', > 'asm' or '__attribute__' before '*' token > ../../Python2.4/include/object.h:129: error: expected ')' before '*' > token > ../../Python2.4/include/object.h:130: error: expected ')' before '*' > token > > Am I missing something important here? > > Thanks in advance, > > Marcelo From shekhar.kaushik at gmail.com Tue Jun 27 04:16:53 2006 From: shekhar.kaushik at gmail.com (Chandrashekhar kaushik) Date: Tue, 27 Jun 2006 13:46:53 +0530 Subject: to py or not to py ? Message-ID: HI all I have the following prob. I am to write a parallel vis application . I wud have by default used C++ for the same but somehow thought if py cud help me .. It does as in many things that i would otherwise have written down already exists ... ( like built in classes for sockets , threading etc ) I would be doin the following type of tasks .. 1. sending data across the network the data is going to be huge 2. once data has been sent i will run some vis algos parallely on them and get the results now one thing that i wud req. is serializing my data structures so that they can be sent across the net. pyton does allow this using cPickle , but it bloats the data like anythin !!! for example a class containing 2 integers which i expect will be 8 bytes long .. cPickle.dumps returns a string thats 86 bytes wide !!!! ( this is the binary version protocol 1 ) anyway to improve serialization ?? also is it actually a good idea to write high perf applications in python ? thanks in advance - -------------- next part -------------- An HTML attachment was scrubbed... URL: From onurb at xiludom.gro Thu Jun 1 08:01:04 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 01 Jun 2006 14:01:04 +0200 Subject: How do you practice programming? In-Reply-To: <1149152428.348192.106970@h76g2000cwa.googlegroups.com> References: <1149151097.741307.79440@f6g2000cwb.googlegroups.com> <447eabee$0$19567$636a55ce@news.free.fr> <1149152428.348192.106970@h76g2000cwa.googlegroups.com> Message-ID: <447ed774$0$12371$626a54ce@news.free.fr> Ray wrote: > bruno at modulix wrote: > >>1/ programming >>2/ programming >>3/ lurking here, reading posts and sometimes trying to answer, reading >>source code of the oss apps/frameworks I'm working with, searching >>practical solutions in the cookbook etc >>4/ programming > > > Yeah, but that's what most of us are doing too, we are programmers > after all. But you know, it's like a boxer cannot get better just by > going into a lot of fights, he needs good instruction from a good > coach. I learned the guitar mostly by watching other guitarists (good and bad ones), trying to teach whoever asked me what I already knew, and practicing many hours a day (until my fingers hurt too much in fact). In programming, like in any other form of art - and like in spirituality for that matters - *everyone* can be your master - sometimes without even being aware of it - if you let him teach you. > So what would you do? (I guess it's your number #3 above). The #3 only would not be of any use without at least the #1, the #2 and the #4. But I admit that #1, #2 and #4 would be equally useless without the #3 !-) How, and yes, also : using one's head - not only to wear a hat - may be of some help too. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From aleax at mac.com Mon Jun 19 22:52:39 2006 From: aleax at mac.com (Alex Martelli) Date: Mon, 19 Jun 2006 19:52:39 -0700 Subject: transfer rate limiting in socket.py References: <1150491228.229045.163110@h76g2000cwa.googlegroups.com> <1150734565.753038.240580@c74g2000cwc.googlegroups.com> Message-ID: <1hh736m.18af1ef1j8hg3vN%aleax@mac.com> Peter Silva wrote: > I looked at twisted briefly. It looks like it is server oriented. > Does it work in for clients initiating connections? Twisted supports clients, servers, and "middleware" (proxies etc) in equally wonderful and powerful ways. Alex From skip at pobox.com Tue Jun 6 12:33:58 2006 From: skip at pobox.com (skip at pobox.com) Date: Tue, 6 Jun 2006 11:33:58 -0500 Subject: Need pixie dust for building Python 2.4 curses module on Solaris 8 Message-ID: <17541.44662.241104.914047@montanaro.dyndns.org> I'm having no success building the curses module on Solaris 8 (yes, I know it's ancient - advancing the state-of-the-art is not yet an option) for Python 2.4. Sun provides an apparently ancient version of curses in /usr/lib, so I downloaded and installed ncurses 5.5, both using default settings and using --with-shared. When the curses module is linked against libcurses.so I get some strange error about acs32map being undefined (which appears to live in a couple termcap-ish files in /usr/lib). When the curses module is linked against libncurses.a I get bazillions of linker errors like this: Text relocation remains referenced against symbol offset in file table.0 0x41 /opt/app/nonc++/ncurses-5.5/lib/libncurses.a(lib_color.o) hls_palette 0x2dc /opt/app/nonc++/ncurses-5.5/lib/libncurses.a(lib_color.o) cga_palette 0x2e3 /opt/app/nonc++/ncurses-5.5/lib/libncurses.a(lib_color.o) hls_palette 0x5e0 /opt/app/nonc++/ncurses-5.5/lib/libncurses.a(lib_color.o) cga_palette 0x5e7 /opt/app/nonc++/ncurses-5.5/lib/libncurses.a(lib_color.o) 0xc9e /opt/app/nonc++/ncurses-5.5/lib/libncurses.a(lib_color.o) 0xcb7 /opt/app/nonc++/ncurses-5.5/lib/libncurses.a(lib_color.o) 0x18 /opt/app/nonc++/ncurses-5.5/lib/libncurses.a(lib_mouse.o) The build step and output from distutils are: $ python ../setup.py build_ext --include-dirs=/opt/app/nonc++/ncurses-5.5/include --rpath=/opt/app/nonc++/ncurses-5.5/lib --library-dirs=/opt/app/nonc++/ncurses-5.5/lib running build_ext INFO: Can't locate readline library INFO: Can't locate Tcl/Tk libs and/or headers building '_curses' extension gcc -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC -I. -I/home/ink/skipm/src/python-svn/release24-maint/./Include -I/opt/app/g++lib6/python-2.4/include -I/usr/local/include -I/opt/app/nonc++/ncurses-5.5/include -I/opt/app/g++lib6/python-2.4/include/python2.4 -c /home/ink/skipm/src/python-svn/release24-maint/Modules/_cursesmodule.c -o build/temp.solaris-2.8-i86pc-2.4/home/ink/skipm/src/python-svn/release24-maint/Modules/_cursesmodule.o /home/ink/skipm/src/python-svn/release24-maint/Modules/_cursesmodule.c: In function `PyCursesWindow_GetStr': /home/ink/skipm/src/python-svn/release24-maint/Modules/_cursesmodule.c:822: warning: implicit declaration of function `mvwgetnstr' gcc -shared build/temp.solaris-2.8-i86pc-2.4/home/ink/skipm/src/python-svn/release24-maint/Modules/_cursesmodule.o -L/opt/app/g++lib6/python-2.4/lib -L/usr/local/lib -L/opt/app/nonc++/ncurses-5.5/lib -Wl,-R/opt/app/nonc++/ncurses-5.5/lib -lncurses -o build/lib.solaris-2.8-i86pc-2.4/_curses.so Any ideas what's wrong and what I need to do to correct the problem? Thx, Skip From claird at lairds.us Sun Jun 18 22:44:46 2006 From: claird at lairds.us (Cameron Laird) Date: Mon, 19 Jun 2006 02:44:46 +0000 Subject: Getting output from external programs... References: <4495B759.4040002@gmail.com> Message-ID: In article , Ten wrote: . . . >You can do this in various ways, ranging from the very simple and not very good > >from commands import getoutput > >x=getoutput(command) > > >- to your more common and better popens. > >ie: > >import popen2 > >(stdOut, stdIn) = popen2.popen4(command) > >x=stdOut.readlines() > >- asynchronously if appropriate. > >How are you running the command at the moment? . . . Why deprecate commands.getoutput()? Are you merely observing that it's applicable in fewer circumstances? From duncan.booth at invalid.invalid Thu Jun 1 06:44:29 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 1 Jun 2006 10:44:29 GMT Subject: what is the reasonable (best?) Exception handling strategy? References: <1149156321.440828.95150@g10g2000cwb.googlegroups.com> Message-ID: Petr Jakes wrote: > I am a little bit confused by all possibilities for exceptions handling > in Python (probably because I am not skilled enough??) I did try to > search trough this list and reading Python tutorial about Errors and > Exceptions but didn't find some "general" answer about exception > handling policy (strategy). It depends on what you are actually able to do about the exception. If you can recover from it meaningfully then you may want to handle it near the place it is thrown. If all you can do is abort the entire program then you handle that at the outermost level of the program. > > In the following example each row can IMHO raise an exception (if the > Firebird service is not running for example, if the database is > corrupted etc.). If a service isn't running that sounds pretty fatal. Handle it at the outer levels of your code. If the database is corrupted that might also be terminal unless you include bad data (e.g. invalid email address) in that definition, in that case it may be something you can fix, ignore, or live with: it should be obvious in this case where in your code you need to do the fixup or ignoring. > > Do I have to write "try/except" clause on each row? The processing you perform on a row might raise an exception for which the correct action would be to simply continue with the next row. In that case handle the exception inside the 'processRow' function so the code which iterates over the rows never sees it. If it is a more serious problem which is going to stop you processing any further rows then you let it propogate. > > Or to write try/except block (function) where to handle (on one place) > all exceptions expected in the program code is a good idea? > > Or do I have to write own "exception hook"? > > What about unexpected exceptions? :( Big errors, or unexpected errors you handle in one place usually by making sure a human is alerted to the problem. From diffuser78 at gmail.com Wed Jun 28 11:56:56 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 28 Jun 2006 08:56:56 -0700 Subject: String Question In-Reply-To: References: <1151508909.273667.270910@x69g2000cwx.googlegroups.com> Message-ID: <1151510216.187445.111010@m73g2000cwd.googlegroups.com> Many Thanks!! It worked like a charm. Fredrik Lundh wrote: > diffuser78 at gmail.com wrote: > > > mac_string = '001485e55503' (This is the mac address of a computer.) > > > > I am using wake on LAN python script to start computer remote.It uses > > format like this .... > > > > s.sendto('\xff'*6 + '\x00\x014\x85\xe5\x55\x03'*16, ('192.168.1.255', > > 80)) > > > > where '\x00\x14\x85\xe5\x55\x03' is the MAC address to be used. > > s.sendto('\xff'*6 + binascii.unhexlify(mac_string) *16, ('192.168.1.255', 80)) > > From rpdooling at gmail.com Thu Jun 15 12:50:13 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 15 Jun 2006 09:50:13 -0700 Subject: code folding, a unique problem to python? In-Reply-To: References: <4fdgh7F1hbtteU1@uni-berlin.de> Message-ID: <1150390213.599580.183090@f6g2000cwb.googlegroups.com> Komodo code folds Python, Perl, PHP . . . From bdesth.quelquechose at free.quelquepart.fr Fri Jun 2 22:03:21 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 03 Jun 2006 04:03:21 +0200 Subject: Initializing an attribute that needs the object In-Reply-To: References: Message-ID: <4480be5b$0$27367$626a54ce@news.free.fr> David Pratt a ?crit : > Hi. I want to have different handlers to do perform logic. The problem > is the Handler requires an instance of the factory since it will use its > own methods in conjunction with methods of the factory. > > Once I have got a Factory instance I can give it a new handler (see > below). It would be more flexible if I could provide a handle in > constructor - but how to do this when it requires the object itself. Hint : Python classes are objects too. > class Factory: Do yourself a favour : use new-style classes. class Factory(object): def __init__(self, handler_class): self.handler = handler_class(self) class SomeHandler(object): def __init__(self, factory): self.factory = factory f = Factory(SomeHandler) From dev at null.com Tue Jun 27 19:44:28 2006 From: dev at null.com (Mike Currie) Date: Tue, 27 Jun 2006 16:44:28 -0700 Subject: Ascii Encoding Error with UTF-8 encoder References: <44a1bbcb$1@news.eftel.com> Message-ID: Thanks for the thorough explanation. What I am doing is converting data for processing that will be tab (for columns) and newline (for row) delimited. Some of the data contains tabs and newlines so, I have to convert them to something else so the file integrity is good. Not my idea, I've been left with the implementation however. "John Machin" wrote in message news:44a1bbcb$1 at news.eftel.com... > On 28/06/2006 7:46 AM, Mike Currie wrote: >> Can anyone explain why I'm getting an ascii encoding error when I'm >> trying to write out using a UTF-8 encoder? >> > >>>>> f = codecs.open('foo.txt', 'wU', 'utf-8') >>>>> print filteredLine >> this?has??tabs?and?line?breaks >>>>> f.write(filteredLine) >> Traceback (most recent call last): >> File "", line 1, in ? >> File "C:\Python24\lib\codecs.py", line 501, in write >> return self.writer.write(data) >> File "C:\Python24\lib\codecs.py", line 178, in write >> data, consumed = self.encode(object, self.errors) >> UnicodeDecodeError: 'ascii' codec can't decode byte 0x88 in position 4: >> ordinal >> not in range(128) >> > > Your fundamental problem is that you are trying to decode an 8-bit string > to UTF-8. The codec tries to convert your string to Unicode first, using > the default encoding (ascii), which fails. > > Get this into your head: > You encode Unicode as ascii, latin1, cp1252, utf8, gagolitic, whatever > into an 8-bit string. > You decode whatever from an 8-bit string into Unicode. > > Here is a run-down on your problem, using just the encode/decode methods > instead of codecs for illustration purposes: > > (1) Equivalent to what you did. > |>> '\x88'.encode('utf-8') > Traceback (most recent call last): > File "", line 1, in ? > UnicodeDecodeError: 'ascii' codec can't decode byte 0x88 in position 0: > ordinal not in range(128) > > (2) Same thing, explicitly trying to decode your 8-bit string as ASCII. > |>> '\x88'.decode('ascii').encode('utf-8') > Traceback (most recent call last): > File "", line 1, in ? > UnicodeDecodeError: 'ascii' codec can't decode byte 0x88 in position 0: > ordinal not in range(128) > > (3) Encoding Unicode as UTF-8 works, as expected. > |>> u'\x88'.encode('utf-8') > '\xc2\x88' > > (4) But you need to know what your 8-bit data is supposed to be encoded > in, before you start. > |>> '\x88'.decode('cp1252').encode('utf-8') > '\xcb\x86' > |>> '\x88'.decode('latin1').encode('utf-8') > '\xc2\x88' > > I am rather puzzled as to what you are trying to achieve. You appear to > believe that you possess one or more 8-bit strings, encoded in latin1, > which contain the C0 controls \x09 (HT) and \x0a (LF) AND the > corresponding C1 controls \x88 (HTS) and \x85 (NEL). You want to change LF > to NEL, and NEL to LF and similarly with the other pair. Then you want to > write the result, encoded in UTF-8, to a file. The purpose behind that > baroque/byzantine capering would be .... what? > From digitalorganics at gmail.com Sun Jun 25 17:26:10 2006 From: digitalorganics at gmail.com (digitalorganics at gmail.com) Date: 25 Jun 2006 14:26:10 -0700 Subject: Mix-In Class Methods At Run-Time In-Reply-To: <1151269186.710343.41210@c74g2000cwc.googlegroups.com> References: <1151191406.755252.210300@i40g2000cwc.googlegroups.com> <1151193767.589325.158820@m73g2000cwd.googlegroups.com> <1151269186.710343.41210@c74g2000cwc.googlegroups.com> Message-ID: <1151270770.030282.237050@u72g2000cwu.googlegroups.com> Okay, while I'd still like to know the answer(s) to my earlier question(s), I've mostly solved my problem thanks to bearophile and my own learning. An example: class Cat(object): def __init__(self): self.love = 0 def meow(self): print "meow" class Dog(object): def bark(self): print "bark" class Bat(object): def scream(self): print "scream" def Mixin(object, *classes): NewClass = type('Mixin', (object.__class__,) + classes, {}) newobj = NewClass() newobj.__dict__.update(object.__dict__) return newobj mycat = Cat() mycat.love = 4 mycat = Mixin(mycat, Dog, Bat) print mycat.__dict__, mycat.__class__, mycat.__class__.__bases__ print dir(mycat) Two additional questions though: 1) is there a way for a function to get a reference to its caller automatically (as in, without the caller having to pass it in)? and 2) what's the reason to use newstyle classes versus the old? In order to create the dynamic class "NewClass" in the code above I called type() but that requires at least one new style class as a base. Thus, I had to have at least one of my animals inherit from "object" and this seemed a nuisance since I don't at this point know what the benefit of "newstyle" classes is. I was going to just use the new module and classobj() but I read somewhere that that was unadvisable and newstyle classes should be used in new code. ... Thank you. Cheers, DigiO digitalorganics at gmail.com wrote: > This looks excellent bearophile, but I'm having trouble understanding > some things. Perhaps you can help wipe clean my ignorance. Firstly, I > thought __classes__ was a read-only attribute? Secondly, what is a > "dictproxy object" and why won't the following code work: > > class Cat: > def meow(self): > print "meow" > def MixIn(object, *classes): > temp = type('ClassPie', (object.__class__,) + classes, {}) > temp.__dict__.update([object.__dict__]) > NewClass = MixIn(Cat(), C, D) > test = NewClass() > > __dict__, to my understanding, is suppose to be a dictionary, but > Python keeps telling me it's a 'dictproxy' object and that it has no > attribute 'update'. Why is this? > > Thanks. > > > bearophileHUGS at lycos.com wrote: > > I think it's possible, most of such kind of things are possible with > > Python. > > I'm not an expert yet in such kind of things, so this can be a starting > > point for you (note the shadowing of m2, the class docstrings, etc). > > Other people can give you something better or more correct. > > > > class A: > > def m1(self): return "m1" > > def m2(self): return "m2" > > > > class B: > > def m3(self): return "m3" > > > > class P: > > def m2(self): return "m2b" > > def m4(self): return"m4" > > > > def mixin(object, *classes): > > class NewClass(object.__class__): > > pass > > for C in classes: > > NewClass.__dict__.update(C.__dict__) > > object.__class__ = NewClass > > > > foo = P() > > print "Before:" > > print "foo.__class__.__dict__.keys():", foo.__class__.__dict__.keys() > > print "P.__dict__.keys():", P.__dict__.keys() > > print "foo.m2():", foo.m2() > > print "foo.m4():", foo.m4(), "\n" > > > > mixin(foo, A, B) > > > > print "After:" > > print "foo.__class__.__dict__.keys():", foo.__class__.__dict__.keys() > > print "P.__dict__.keys():", P.__dict__.keys() > > print "foo.m1():", foo.m1() > > print "foo.m2():", foo.m2() > > print "foo.m3():", foo.m3() > > print "foo.m4():", foo.m4() > > > > Bye, > > bearophile From uche.ogbuji at gmail.com Sun Jun 4 11:49:35 2006 From: uche.ogbuji at gmail.com (uche.ogbuji at gmail.com) Date: 4 Jun 2006 08:49:35 -0700 Subject: how to print newline in xml? In-Reply-To: <1149194353.343074.15140@h76g2000cwa.googlegroups.com> References: <1149023930.292203.152540@u72g2000cwu.googlegroups.com> <1149145466.190011.146250@i39g2000cwa.googlegroups.com> <1149186989.073062.230220@f6g2000cwb.googlegroups.com> <1149194353.343074.15140@h76g2000cwa.googlegroups.com> Message-ID: <1149436175.651269.177270@h76g2000cwa.googlegroups.com> anatoli.barski at googlemail.com wrote: > I use Python/XML packages are xml.dom.minidom and xml.dom.ext (second > just for PrettyPrint) You don't need xml.dom.ext for prettyprint. You can use doc.toprettyxml() I gather you want to tweak the prettyprinter to not add the newline before the comment. The only way to do this is to write your own printing logic, which is really not that hard, if you just start by copying the code from .writexml (used by .toprettyxml). But there's an even easier (if slower) way: pretty print the document, then parse it in again, remove the text node between the element in question and the following comment, and then use .writexml() to serialize it it again. A few general notes: * You cannot set the order of attributes in most XML tools, whether Python or not. This is unfortunate for people who would like to preserve such details for usability reasons, but that's just the way XML is. The closest you can get is by using canonicalization [1], which is available in PyXML as xml.dom.ext.c14n. It just so happens that canonical XML leaves the attributes in the order you want. You won't always be so lucky. * You can always create text nodes by using doc.createTextNode. * You can always remove text nodes (or any other kind) by using .removeChild * It's much easier to navigate if you use XPath. PyXML has an xml.xpath module you can use. Good luck. [1] http://www-128.ibm.com/developerworks/xml/library/x-c14n/ -- Uche Ogbuji Fourthought, Inc. http://uche.ogbuji.net http://fourthought.com http://copia.ogbuji.net http://4Suite.org Articles: http://uche.ogbuji.net/tech/publications/ From bdesth.quelquechose at free.quelquepart.fr Thu Jun 22 20:04:15 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 23 Jun 2006 02:04:15 +0200 Subject: Network Programming in Python In-Reply-To: <1151006542.682915.83500@c74g2000cwc.googlegroups.com> References: <1151002934.586359.174540@m73g2000cwd.googlegroups.com> <1151006542.682915.83500@c74g2000cwc.googlegroups.com> Message-ID: <449affdd$0$32633$626a54ce@news.free.fr> diffuser78 at gmail.com a ?crit : > I have Python 2.4.2 on windows and Linux both. I got an import error. > how can we obtain the twisted libraries ? Is google down ? From aisaac0 at verizon.net Sat Jun 3 19:45:31 2006 From: aisaac0 at verizon.net (David Isaac) Date: Sat, 03 Jun 2006 23:45:31 GMT Subject: numpy bug References: <447f3338$1_7@news.bluewin.ch> Message-ID: "Boris Borcic" wrote in message news:447f3338$1_7 at news.bluewin.ch... > after a while trying to find the legal manner to file numpy bug reports, > since it's a simple one, I thought maybe a first step is to describe the bug > here. Then maybe someone will direct me to the right channel. > > So, numpy appears not to correctly compute bitwise_and.reduce and > bitwise_or.reduce : instead of reducing over the complete axis, these methods > only take the extremities into account. Illustration : > > >>> from numpy import * > >>> bitwise_or.reduce(array([8,256,32,8])) > 8 > >>> import numpy > >>> numpy.__version__ > '0.9.8' > >>> > > Platform : Win XP SP2, Python 2.4.2 Most bug reports start on the numpy list, I believe. (See above.) Cheers, Alan Isaac From maric at aristote.info Mon Jun 12 04:18:44 2006 From: maric at aristote.info (Maric Michaud) Date: Mon, 12 Jun 2006 10:18:44 +0200 Subject: An error ? In-Reply-To: References: <448D06AB.3070104@gmail.com> Message-ID: <200606121018.44943.maric@aristote.info> Le Lundi 12 Juin 2006 09:07, Steve Holden a ?crit?: > print "Content-Type: text\plain\n" a typo I guess, print "Content-Type: text/plain\n" -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From sjmachin at lexicon.net Sun Jun 4 22:40:47 2006 From: sjmachin at lexicon.net (John Machin) Date: Mon, 05 Jun 2006 12:40:47 +1000 Subject: re beginner In-Reply-To: References: <44834d62$0$6192$626a54ce@news.free.fr> <4483665A.206@lexicon.net> Message-ID: <448399AF.9030001@lexicon.net> On 5/06/2006 10:07 AM, Paul McGuire wrote: > "John Machin" wrote in message > news:4483665A.206 at lexicon.net... >> Fantastic -- at least for the OP's carefully copied-and-pasted input. >> Meanwhile back in the real world, there might be problems with multiple >> tabs used for 'prettiness' instead of 1 tab, non-integer values, etc etc. >> In that case a loop approach that validated as it went and was able to >> report the position and contents of any invalid input might be better. > > Yeah, for that you'd need more like a real parser... hey, wait a minute! > What about pyparsing?! > > Here's a pyparsing version. The definition of the parsing patterns takes > little more than the re definition does - the bulk of the rest of the code > is parsing/scanning the input and reporting the results. > [big snip] I didn't see any evidence of error handling in there anywhere. From maxerickson at gmail.com Wed Jun 21 09:29:40 2006 From: maxerickson at gmail.com (Max Erickson) Date: Wed, 21 Jun 2006 13:29:40 +0000 (UTC) Subject: very strange bug coercing to Unicode: need string or buffer, int found References: <8a8f62c80606210604r7746f64dkf82fb97d347e02e0@mail.gmail.com> Message-ID: "bussiere maillist" wrote: > ------=_Part_118629_1441854.1150895040355 > i truly didn't understand this error : > Traceback (most recent call last): > File "D:\Programmation\FrancePaquet\FrancePaquet.py", line 77, > in ? > cabtri = "zz" + chiffrescabtri + clefc > TypeError: coercing to Unicode: need string or buffer, int found > > def calculclef(nombre): > if clef == 10: > clef = 0 > return clef > > clefb = calculclef(debutplage) > clefb = str(clefb) > print clefb > clefc = calculclef(chiffrescabtri) > cabtri = "zz" + chiffrescabtri + clefc Your calculclef function returns an integer. You explitly convert clefb into a string, but you never convert clefc into a string, hence the TypeError. max From kewashi at gmail.com Sun Jun 11 23:42:03 2006 From: kewashi at gmail.com (KenAggie) Date: 11 Jun 2006 20:42:03 -0700 Subject: Get my airlines boarding pass In-Reply-To: <1150066013.127303.204880@m38g2000cwc.googlegroups.com> References: <1hgotbh.1vd74fb1qhzdziN%aleax@mac.com> <1149954923.868806.87270@m38g2000cwc.googlegroups.com> <1149969384.065683.224810@f6g2000cwb.googlegroups.com> <1150056721.796442.130690@m38g2000cwc.googlegroups.com> <1150066013.127303.204880@m38g2000cwc.googlegroups.com> Message-ID: <1150083723.567199.308770@j55g2000cwa.googlegroups.com> Okay, so too bad I didn't know about this before I wrote the 75 lines of code based on HTMLParser. That said, it still wasn't that hard and most of all it is done and it works so I won't be rewriting it. I did check it out and it seems quite powerful. I'll add it to my library of tools to use for the next python project. Thanks for the tip. - Ken Jonathan Ellis wrote: > KenAggie wrote: > > I posted it on activestate already ... sorry. I would like for the > > geniuses here to use it and improve upon it so here is the activestate > > post URL: > > > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496790 > > Whoa. Check out BeautifulSoup -- you will never write HTMLParser-based > screen scrapers again. :) > > -Jonathan From robert.kern at gmail.com Wed Jun 28 04:11:54 2006 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 28 Jun 2006 03:11:54 -0500 Subject: to py or not to py ? In-Reply-To: References: Message-ID: Chandrashekhar kaushik wrote: > okay > so much for a few spelling errors and abbreviations used by me !! > we are losing the main point ! > i had a look at mercurial . It deals with SCM . I am typically > looking at an application thats to deal with geometry data ( tetras ) , > process millions of them and may be process them repeatedly ( iterative ). > It would basically involve client-server operations to first distribute data > over a computing network and then send requests to process the data > at the various nodes that contain the data. I do essentially the same thing (only with pickles of constructive solid geometry definitions). > it is going to be multi-threaded. ... because? > Carl , what are the problems that could arise with threading ?? An old, but still relevant overview is here: http://www.softpanorama.org/People/Ousterhout/Threads/index.shtml A good event-driven framework for Python is Twisted. It's what I use for the program I mention above. http://twistedmatrix.com/trac/ -- 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 From ldo at geek-central.gen.new_zealand Tue Jun 27 01:06:30 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 27 Jun 2006 17:06:30 +1200 Subject: Python taught in schools? References: <1151220913.406987.162420@u72g2000cwu.googlegroups.com> Message-ID: In article , Mirco Wahab wrote: >Thus spoke Lawrence D'Oliveiro (on 2006-06-26 09:21): > >> In article , >> Mirco Wahab wrote: >> >>>C++ programming requires you to massively invest your thinking >>>first into the setup of your build environment ... >> >> I don't understand why. It's easy enough to build small programs with a >> single g++ command. > >Think about beeing a young guy with a >windows pc at home. > >To make sense of your 45 min C++ >class, you need to practice the >stuff at home for sure, I'd guess. > >Now go ahead! What would you do? Download a Linux distro with a complete GCC, Emacs, GDB etc. Then go wild. From webraviteja at gmail.com Thu Jun 29 03:42:45 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 29 Jun 2006 00:42:45 -0700 Subject: Import Issue In-Reply-To: <1151566468.352032.24560@j72g2000cwa.googlegroups.com> References: <1151566468.352032.24560@j72g2000cwa.googlegroups.com> Message-ID: <1151566965.126760.268960@p79g2000cwp.googlegroups.com> praveenkumar.117 at gmail.com wrote: > What is the difference between > import string > and > from string import * Here is an explanation. http://effbot.org/zone/import-confusion.htm From fredrik at pythonware.com Fri Jun 2 00:51:40 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 02 Jun 2006 06:51:40 +0200 Subject: image lib & Qt4 In-Reply-To: <1149180814.585713.209640@i39g2000cwa.googlegroups.com> References: <1149173540.470829.34940@c74g2000cwc.googlegroups.com> <4e8haiF1dp2heU1@uni-berlin.de> <1149180814.585713.209640@i39g2000cwa.googlegroups.com> Message-ID: aljosa wrote: > does anybody know how to load (in-memory > representation of PNG image) from Qt (v.4.1.3) as QImage? If you want the data from a StringIO object, you can either *read* the data from the object (it's a file-like object, after all), or use the getvalue() method. Something like qim = QImage() qim.loadFromData(f.getvalue()) should work (unless they've changed things around lately). To get better performance, you should be able to use PIL's tostring() method together with the QImage(buffer, width, height, depth, colortable, numColors, bitOrder) form of the QImage constructor. From junkytownMAKNI at gmail.com Sat Jun 24 15:24:33 2006 From: junkytownMAKNI at gmail.com (SuperHik) Date: Sat, 24 Jun 2006 21:24:33 +0200 Subject: 2Qs Message-ID: 1st question: If a make an exe with i.e. py2exe, can I get any kind of error/bug report from the exe file saved into a file error.log and how? 2nd question: is there a better way to do this: def tritup(x,y,z): #here is a while loop giving 3 results, i.e. r1,r2,r3 return r1,r2,r3 #I want to put sum of r1,r2,r3 as a condition in if statement #so I created a function to do this, but I can't escape a feeling #there is a more elegant solution, especially in python ;=) def summm(a,b,c): return a+b+c if x>10 and y>10 and z>10 and summ(tritup(x,y,z)): print "OK" From sturnfie at gmail.com Mon Jun 5 15:36:14 2006 From: sturnfie at gmail.com (sturnfie at gmail.com) Date: 5 Jun 2006 12:36:14 -0700 Subject: xml.sax problem: getting parse() to read a string References: <1149525288.546237.78700@u72g2000cwu.googlegroups.com> Message-ID: <1149536174.891894.13760@h76g2000cwa.googlegroups.com> Fredrik Lundh wrote: > if you want to parse a string, use xml.sax.parseString instead of > xml.sax.parse. > > My function has changed to the following (parseString call instead of parse): def parseMessage(self, message): #create a XML parser parser = make_parser() #create an instance of our handler class #generic, prints out to screen on all events dh = docHandler() #tell parser to use our handler parser.setContentHandler(dh) parser.parseString(message) return I am getting the following error. File "acmtest.py", line 205, in parseMessage parser.parseString(message) AttributeError: ExpatParser instance has no attribute 'parseString' Am I simply missing that library here? Or am I calling it incorrectly? My import line reads as follows (but I am not sure how to explictly make sure I have this library) import socket, select, os, sys, traceback, re from xml.sax import make_parser, parseString from xml.sax.handler import ContentHandler -- lucas From durumdara at gmail.com Tue Jun 20 07:59:54 2006 From: durumdara at gmail.com (Dara Durum) Date: Tue, 20 Jun 2006 13:59:54 +0200 Subject: Duplex communication with pipes - is possible ? In-Reply-To: <1150476096.873581.96560@g10g2000cwb.googlegroups.com> References: <1150476096.873581.96560@g10g2000cwb.googlegroups.com> Message-ID: <9e384ef60606200459w5787e4f5v@mail.gmail.com> Hi ! Ahhh ! It's working ! This is the simple client code: if 'C' in sys.argv: #sys.stdout=open(r'c:\tpp2client.log','w') print "clt start" while 1: head=sys.stdin.read(4) print "clt head",[head] if head.lower()=='quit': break dsize=int(head) if dsize: data=sys.stdin.read(dsize) print "clt get data"#,[data] print "clt end\n" And the master: else: print "MS" p=subprocess.Popen([r'c:\python24\python.exe','tpp2.py','C'], \ stdin=subprocess.PIPE,stdout=subprocess.PIPE) print "MSS" (child_stdout, child_stdin) = (p.stdout, p.stdin) data=range(1000) import cPickle bdata=cPickle.dumps(data,1) print len(bdata) import binascii hdata=binascii.hexlify(bdata) print len(hdata) import base64 hdata=base64.encodestring(bdata) print len(hdata) child_stdin.write('%04d'%len(hdata)) child_stdin.write(hdata) child_stdin.write('quit') #child_stdin.write('quit') #child_stdin.write('quit\n') output=child_stdout.readlines() print [output] print "MEE" Now I trying with packet size decreasing. Are PIPE-s can handle the binary data packets, or I need to convert them with base64 ? Thanks for your help: dd From nospam at nospam.com Thu Jun 8 12:03:18 2006 From: nospam at nospam.com (3c273) Date: Thu, 8 Jun 2006 09:03:18 -0700 Subject: Instead of saving text files i need as html References: <1149777499.506986.292830@j55g2000cwa.googlegroups.com> Message-ID: "Shani" wrote in message news:1149777499.506986.292830 at j55g2000cwa.googlegroups.com... > I have the following code which takes a list of urls > "http://google.com", without the quotes ofcourse, and then saves there > source code as a text file. I wan to alter the code so that for the > list of URLs an html file is saved. > > -----begin----- > import urllib > urlfile = open(r'c:\temp\url.txt', 'r') > for lines in urlfile: > try: > outfilename = lines.replace('/', '-') > urllib.urlretrieve(lines.strip('/n'), 'c:\\temp\\' \ > + outfilename.strip('\n')[7:] + '.txt') > except: > pass > -----end----- > Is this what you mean? -----begin----- import urllib urlfile = open(r'c:\temp\url.txt', 'r') for lines in urlfile: try: outfilename = lines.replace('/', '-') urllib.urlretrieve(lines.strip('/n'), 'c:\\temp\\' \ + outfilename.strip('\n')[7:] + '.html') except: pass -----end----- Louis From scott.daniels at acm.org Wed Jun 28 20:14:02 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Wed, 28 Jun 2006 17:14:02 -0700 Subject: mmap as a sequence behavior In-Reply-To: <1hho1x1.1ntwxi3z2hdzhN%rhymes@myself.com> References: <1hho1x1.1ntwxi3z2hdzhN%rhymes@myself.com> Message-ID: <44a31620$1@nntp0.pdx.net> Lawrence Oluyede wrote: > While wrapping mmap indexing/sequence emulation I noticed something > "strange". What's got my attention was the fact that passing -1 from > Python does not trigger the exception but is changed to the last > positive and valid index.... > I expect this raise IndexError as reading the C source code but it > behaves exactly like sequence types in Python. That's fair to me but I > don't get *where* my index is translated. That is sequence behavior. The convention of -1 for last, -2 for second-to-last, ... is done before it gets to your C code. I suspect if you don't define a __len__ method, you'd suppress this. --Scott David Daniels scott.daniels at acm.org From sjmachin at lexicon.net Thu Jun 1 17:48:29 2006 From: sjmachin at lexicon.net (John Machin) Date: Fri, 02 Jun 2006 07:48:29 +1000 Subject: struct: type registration? In-Reply-To: References: <447e4b98$1@news.eftel.com> <447EDF7C.3080104@lexicon.net> Message-ID: <447F60AD.9020506@lexicon.net> On 2/06/2006 3:44 AM, Giovanni Bajo wrote: > John Machin wrote: > >>> Looks like you totally misread my message. >> Not at all. >> >> Your function: >> >> def mystring_pack(s): >> if len(s) > 20: >> raise ValueError, "a mystring can be at max 20 chars" >> s = (s + "\0"*20)[:20] >> s = struct.pack("20s", s) >> return s >> >> can be even better replaced by (after reading the manual "For packing, >> the string is truncated or padded with null bytes as appropriate to >> make it fit.") by: >> >> def mystring_pack(s): >> if len(s) > 20: >> raise ValueError, "a mystring can be at max 20 chars" >> return s >> # return s = (s + "\0"*20)[:20] # not needed, according to the >> manual # s = struct.pack("20s", s) >> # As I said, this particular instance of using struct.pack is a >> big fat no-op. > > John, the point of the example was to show that one could write custom > packer/unpacker which calls struct.pack/unpack and, after that, > post-processes the results to obtain some custom data type. What you appear to be doing is proposing an API for extending struct by registering custom type-codes (ASCII alphabetic?) each requiring three call-back functions (mypacker, myunpacker, mylength). Example registration for an "S" string (fixed storage length, true length determined on unpacking by first occurrence of '\0' (if any)). struct.register("S", packerS, unpackerS, lengthS) You give no prescription for what those functions should do. You provide "examples" which require reverse engineering to deduce of what they are intended to be exemplars. Simple-minded folk like myself might expect that the functions would work something like this: Packing: when struct.pack reaches the custom code in the format, it does this (pseudocode): obj = _get_next_arg() itemstrg = mypacker(obj) _append_to_output_string(itemstrg) Unpacking: when struct.unpack reaches a custom code in the format, it does this (pseudocode): n = mylength() # exception if < n bytes remain obj = myunpacker(remaining_bytes[:n]) _append_to_output_tuple(obj) Thus, in a simple case like the NUL-terminated string: def lengthS(): return 20 def packerS(s): assert len(s) <= 20 return s.ljust(20, '\0') # alternatively, return struct.pack("20s", s) def unpackerS(bytes): assert len(bytes) == 20 i = bytes.find('\0') if i >= 0: return bytes[:i] return bytes In more complicated cases, it may be useful for either/both the packer/unpacker custom functions to call struct.pack/unpack to assist in the assembly/disassembly exercise. This should be (1) possible without perturbing the state of the outer struct.pack/unpack invocation (2) sufficiently obvious to warrant little more than a passing mention. > Now, I apologize > if my example wasn't exactly the shortest, most compact, most pythonic piece > of code. It was not meant to be. It was meant to be very easy to read and > very clear in what it is being done. You are nitpicking that part of my code > is a no-op. Fine. Scarcely a nitpick. It was very clear that parts of it were doing absolutely nothing in a rather byzantine & baroque fashion. What was unclear was whether this was by accident or design. You say (*after* the examples) that "As shown, the custom packer/unpacker can call the original pack/unpack as a basis for their work. ... when called recursively ...". What basis for what work? As for recursion, I see no "19s", "18s", etc here :-) > Sorry if this confused you. It didn't. As a self-confessed idiot, I am resolutely and irredeemably unconfused. > I was just trying to show a > simple pattern: > > custom packer: adjust data, call struct.pack(), return > custom unpacker: call struct.unpack(), adjust data, return > > I should have chosen a most complex example probably, but I did not want to > confuse readers. It seems I have confused them by choosing too simple an > example. The problem was that you chose an example that had minimal justification (i.e. only the length check) for a custom packer at all (struct.pack pads the "s" format with NUL bytes) and no use at all for a call to struct.unpack inside the custom unpacker. Cheers, John From faisjobs at yahoo.co.in Sun Jun 25 13:54:59 2006 From: faisjobs at yahoo.co.in (faisjobs) Date: 25 Jun 2006 10:54:59 -0700 Subject: USA UK CANADA AUSTRALIA Jobs With VISA Sponsorship, USA VISA, UK VISA, CANADA VISA, AUSTRALIA VISA , immigration, VISA Sponsorship Message-ID: <1151258099.055844.299370@y41g2000cwy.googlegroups.com> USA UK CANADA AUSTRALIA Jobs With VISA Sponsorship, USA VISA,UK VISA, CANADA VISA, AUSTRALIA VISA , immigration, VISA Sponsorship click here http://visajobs2u.50webs.com/ =============================================================================================================================================================================================================================================================================================================================================== JOBS, VISA, AUTOS, CRICKET, FOOTBALL, CREDIT CARD, LOAN, LAPTOP, DATING. click here www.freewebs.com/winfais From emanuele.aina at gmail.com Wed Jun 14 16:57:10 2006 From: emanuele.aina at gmail.com (Emanuele Aina) Date: 14 Jun 2006 13:57:10 -0700 Subject: __lt__ slowing the "in" operator even if not called Message-ID: <1150318630.203249.191250@r2g2000cwb.googlegroups.com> I have some code which does a lot of "in" on lists containing objects with no __eq__ defined. It all goes fast until I add the __lt__() method: then I have a slowdown comparable to the one I get using the overridden __eq__, while the __lt__ method is never called. Someone can explain me why? I have here a simple program which shows the behaviour: *-------------------------------------------------------------------* #!/usr/bin/env python import timing class State(object): def __init__(self, value): self.v = value def generate(self): return [self.__class__(self.v+1)] class StateLT(State): def __lt__ (self, other): print 'Foo' return self.v < other.v class StateEQ(State): def __eq__ (self, other): return self.v == other.v def test(state_cls): print state_cls timing.start() initial = state_cls(0) l = [initial] for i in xrange(3000): successors = l[i].generate() successors = [s for s in successors if s not in l] l += successors timing.finish() print timing.milli() if __name__ == '__main__': test(State) print ' ' test(StateLT) print ' ' test(StateEQ) *-------------------------------------------------------------------* On my machine the output is: 406 4982 5395 Here you can see that even with only the __lt__ method it goes 10x slower, but __lt__ is never called as "Foo" is not printed. I use the python 2.3.5-8 package on a debian unstable, but even the python 2.4.3-5 package shows the same behaviour. From antroy at gmail.com Tue Jun 13 09:08:38 2006 From: antroy at gmail.com (Ant) Date: 13 Jun 2006 06:08:38 -0700 Subject: Python Video processing. In-Reply-To: References: <1150201746.657059.228570@i40g2000cwc.googlegroups.com> Message-ID: <1150204118.216976.249580@h76g2000cwa.googlegroups.com> > im = Image.fromstring("RGB", dd.size, dd.data) > > instead of doing that pygame.image call (not that the argument order is different). > > for details, see the pygame tostring/fromstring docs, and the corresponding PIL > methods: That's starting to look promising, yes - thanks! I'll give it a shot this evening and see what happens... From chris at kateandchris.net Thu Jun 8 11:17:31 2006 From: chris at kateandchris.net (Chris Lambacher) Date: Thu, 8 Jun 2006 11:17:31 -0400 Subject: how to switch from os.tmpnam to os.tmpfile In-Reply-To: <1149777877.945829.25390@h76g2000cwa.googlegroups.com> References: <1149773439.534989.54450@i40g2000cwc.googlegroups.com> <1149777877.945829.25390@h76g2000cwa.googlegroups.com> Message-ID: <20060608151730.GA17150@kateandchris.net> You should be able to find exactly what you need in the tempfile module. http://docs.python.org/lib/module-tempfile.html os.tmpfile() is no good whether you want the filename or not since on Windows it is likely to break if you are not a privileged user. Its a windows problem, not an actual bug in Python, the call depends on a broken windows command that creates its files in C:\ -Chris On Thu, Jun 08, 2006 at 07:44:38AM -0700, Harold Fellermann wrote: > > Maric Michaud wrote: > > Le Jeudi 08 Juin 2006 15:30, Harold Fellermann a ?crit : > > > to os.tmpfile() which is supposed to be safer, but I do not know how to > > > get > > > the path information from the file object returned by tmpfile(). any > > > clues? > > There is no path for tmpfile, once it's closed, the file and its content are > > lost. from the doc : > > " The file has no directory entries associated with it and will be > > automatically deleted once there are no file descriptors for the file." > > > > You must maintain a reference to it in your program untill you don't need it > > anymore. > > I am doing so. But still, I need its path. To give you some context: > I have an app built on Tk that uses gnuplot behind the scenes. > My application creates a temporary file where which gnuplot writes its > results to (using the tkcanvas terminal). Later, I load the contents of > that file into the a tk canvas. I don't care about the temporary file > after my app is closed, so I have its reference all the time. But I > need > its path to tell both gnuplot and tk where to read/write data to/from. > > class PlotWindow(Tk.Canvas) : > def plot(self,commands) : > tmp = os.tmpnam() > gnuplot = subprocess.Popen( > "gnuplot", shell=True, > stdin=subprocess.PIPE, stdout=file(tmp,"w") > ) > stdout,stderr = gnuplot.communicate(""" > set terminal tkcanvas interact > set output "%s" > """ % tmp + commands) > assert not stderr > self.tk.call("source",tmp) > self.tk.call("gnuplot",self._w) > > Of course, I could just use matplotlib or Gnuplot.py but the problem > is not necessary enough to make any refacturing. If there is no way > to use os.tmpfile(), I just go ahead with the security warning. Its > only > a small personal app, anyway. > > - harold - > > -- > http://mail.python.org/mailman/listinfo/python-list From g.brandl-nospam at gmx.net Wed Jun 28 09:51:14 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Wed, 28 Jun 2006 15:51:14 +0200 Subject: Immutability In-Reply-To: References: Message-ID: Steve Holden wrote: >>>Thanks very much. And, what's more, I have even found its documentation! >>>Whatsnew2.2. The 2.4.2 reference is, er, unhelpful. >> >> >> Is it? >> >> http://docs.python.org/lib/built-in-funcs.html >> >> documents "property" quite well. >> > I can't really agree that "quite good" documentation doesn't refer to > the use of property as a decorator. It's obvious that a ncessary upgrade > to the docs didn't happen (and we can all understand why, I am sure). In my opinion property isn't really meant to be used as a decorator since it's impossible to create a read-write property. The decorator pattern doesn't really fit here. What I agree is that it's not really defined what a "property" object is and what its properties are. For that, documentation patches are welcome. Georg From peter.mosley at talk21.com Wed Jun 21 16:39:22 2006 From: peter.mosley at talk21.com (peter) Date: 21 Jun 2006 13:39:22 -0700 Subject: tkMessagebox.askyesno always returns False Message-ID: <1150922362.746933.276430@i40g2000cwc.googlegroups.com> I have a weird problem in some code I am writing. The user selects a number of files from a list and then can select an option which will rename the selected files. Before the process starts, a yes/no dialog box pops up just to confirm. Most of the time this works fine, but occasionally it seem the dialog box gets into a state where it always returns False, irrespective of the button clicked. I must be doing something wrong, but I just can't see it! Any suggestions? import tkMessageBox as mb : : if action=='Rename': yn=mb.askyesno(file_list[0],'Ok to rename %d selected file(s)' % file_count) print 'Response: ',yn # Debug only if not yn: exit_flag=1 From deets at nospam.web.de Fri Jun 16 13:44:49 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 16 Jun 2006 19:44:49 +0200 Subject: add elements to indexed list locations In-Reply-To: <1150478265.122559.283000@f6g2000cwb.googlegroups.com> References: <1150478265.122559.283000@f6g2000cwb.googlegroups.com> Message-ID: <4fg90eF1i0huaU1@uni-berlin.de> leventyilmaz at gmail.com schrieb: > Hi, > > I have a very simple problem, but do not know an elegant way to > accomplish this. > ### > # I have a list of names: > names = ['clark', 'super', 'peter', 'spider', 'bruce', 'bat'] > > # and another set of names that I want to insert into > # the names list at some indexed locations: > surnames = { 1: 'kent', 3:'parker', 5:'wayne' } > > # The thing I couldn't figure out is, after I insert a > # surname the rest of the indices are not valid. > # That is, the following won't work: > for i, x in surnames.iteritems(): > names.insert(i,surnames[i]) > ### > > I am searching a nice way to do this. For instance, is there a more > robust way to store indices (as some sort of pointers maybe?) Use a dictionary for both of them? The concept of indices is that they IMPLY a position. So either you work in a way that you e.g. add the surnames in a defined order and adjust the subsequent indices, or you discard the approach entirely and e.g use a map of first to surnames. Diez From reply.in.the.newsgroup at my.address.is.invalid Thu Jun 1 08:49:33 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Thu, 01 Jun 2006 14:49:33 +0200 Subject: what is the reasonable (best?) Exception handling strategy? References: <1149156321.440828.95150@g10g2000cwb.googlegroups.com> Message-ID: Petr Jakes: >What about unexpected exceptions? :( I asked a similar question some time ago: http://groups.google.nl/group/comp.lang.python/browse_thread/thread/25963b99da4b2653 -- Ren? Pijlman From david.nospam.hopwood at blueyonder.co.uk Sat Jun 24 17:53:04 2006 From: david.nospam.hopwood at blueyonder.co.uk (David Hopwood) Date: Sat, 24 Jun 2006 21:53:04 GMT Subject: Termination and type systems In-Reply-To: <1151171209.684163.143410@c74g2000cwc.googlegroups.com> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <86Qmg.10725$o4.1907@newsread2.news.pas.earthlink.net> <0neng.213767$8W1.1948@fe1.news.blueyonder.co.uk> <1151171209.684163.143410@c74g2000cwc.googlegroups.com> Message-ID: <4ving.213803$8W1.62401@fe1.news.blueyonder.co.uk> Marshall wrote: > David Hopwood wrote: > >>A type system that required an annotation on all subprograms that do not >>provably terminate, OTOH, would not impact expressiveness at all, and would >>be very useful. > > Interesting. I have always imagined doing this by allowing an > annotation on all subprograms that *do* provably terminate. If > you go the other way, you have to annotate every function that > uses general recursion (or iteration if you swing that way) and that > seems like it might be burdensome. Not at all. Almost all subprograms provably terminate (with a fairly easy proof), even if they use general recursion or iteration. If it were not the case that almost all functions provably terminate, then the whole idea would be hopeless. If a subprogram F calls G, then in order to prove that F terminates, we probably have to prove that G terminates. Consider a program where only half of all subprograms are annotated as provably terminating. In that case, we would be faced with very many cases where the proof cannot be discharged, because an annotated subprogram calls an unannotated one. If, on the other hand, more than, say, 95% of subprograms provably terminate, then it is much more likely that we (or the inference mechanism) can easily discharge any particular proof involving more than one subprogram. So provably terminating should be the default, and other cases should be annotated. In some languages, annotations may never or almost never be needed, because they are implied by other characteristics. For example, the concurrency model used in the language E (www.erights.org) is such that there are implicit top-level event loops which do not terminate as long as the associated "vat" exists, but handling a message is always required to terminate. > Further, it imposes the > annotation requirement even where the programer might not > care about it, which the reverse does not do. If the annotation marks not-provably-terminating subprograms, then it calls attention to those subprograms. This is what we want, since it is less safe/correct to use a nonterminating subprogram than a terminating one (in some contexts). There could perhaps be a case for distinguishing annotations for "intended not to terminate", and "intended to terminate, but we couldn't prove it". I do not know how well such a type system would work in practice; it may be that typical programs would involve too many non-trivial proofs. This is something that would have to be tried out in a research language. -- David Hopwood From fcorreia at gmail.com Fri Jun 30 12:15:55 2006 From: fcorreia at gmail.com (Filipe) Date: 30 Jun 2006 09:15:55 -0700 Subject: handling unicode data In-Reply-To: References: Message-ID: <1151684155.717753.183680@p79g2000cwp.googlegroups.com> > In summary > > + Depends on what your requirements are, but... > > + Go for ADODBAPI for the widest spread of versions and licenses, but > the least cross-platformability > + Go for Object Craft MSSQL for <= 2.3 and best overall behaviour > + Go for pymssql for >= 2.4 with some small limitations > + Go for mxODBC for general purpose databasing, cross-platform, but > without .nextset and possibly Commercial licensing > + If all else fails, and you've got the SQL Server command line tools, > use the ASPN Recipe > Very nice review! Not having a commercial license ir really a "must" right now, and I'd really prefer it being cross-platform, so I think pymssql might not be a bad choice after all. If I can't make unicode data work in a reasonable way I'll probably switch to ADODBAPI, or maybe the odbc module that comes with PyWin32 mentioned by Frank. thanks, Filipe From python.list at tim.thechases.com Mon Jun 19 16:22:10 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 19 Jun 2006 15:22:10 -0500 Subject: Calling every method of an object from __init__ In-Reply-To: <1150746953.156851.92820@r2g2000cwb.googlegroups.com> References: <1150746953.156851.92820@r2g2000cwb.googlegroups.com> Message-ID: <44970772.8070107@tim.thechases.com> > Is there a simple way to call every method of an object from its > __init__()? > > For example, given the following class, what would I replace the > comment line in __init__() with to result in both methods being called? > I understand that I could just call each method by name but I'm looking > for a mechanism to avoid this. > > class Foo(object): > def __init__(self): > #call all methods here > def test(self): > print 'The test method' > def hello(self): > print 'Hello user' >>> class Foo(object): ... def __init__(self): ... for method in dir(self): ... if method == method.strip("_"): ... f = getattr(self, method) ... if callable(f): f() ... def test(self): ... print "in test..." ... def hello(self): ... print "in hello..." ... >>> x = Foo() in hello... in test... This does assume that the method's signature takes no parameters and that you don't want to try and call "special" methods such as __add__ or "private" methods (usually indicated by leading underscores too) while you're going through the available methods. -tkc From pmartin at snakecard.com Sun Jun 4 05:47:36 2006 From: pmartin at snakecard.com (pcm) Date: Sun, 04 Jun 2006 04:47:36 -0500 Subject: Python + WinCE + serial port References: <4481d342$0$21359$636a55ce@news.free.fr> <1149360567.824911.245750@c74g2000cwc.googlegroups.com> Message-ID: <4482ac3c$0$12347$626a54ce@news.free.fr> Fuzzyman wrote: > > pcm wrote: >> Hi, >> >> Has anyone ever worked on a Python-WinCE-based program that involved >> serial port management ? >> > > Because of the size of the runtime and the fragility of the GUI > toolkits, there has been little serious development with PythonCE. > (Little not none - and it's great to have Python available.) > > There is no built in support for the serial port in PythonCE (AFAIK). > Your best bet is using ctypes (for which a PythonCE port has been done) > and the microsoft API. > > Fuzzyman > http://www.voidspace.org.uk/python/index.shtml > >> Regards, >> >> Philippe Thanks, does that mean that I need to write an extension to the WinCE API or is that built-into the Python package ? Regards, Philippe From bdesth.quelquechose at free.quelquepart.fr Thu Jun 22 20:47:50 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 23 Jun 2006 02:47:50 +0200 Subject: Status of optional static typing in Python? In-Reply-To: References: <449af81d$0$31818$626a54ce@news.free.fr> Message-ID: <449b0a14$0$2140$636a55ce@news.free.fr> Christian Convey a ?crit : > Perhaps I'm deluded but I don't think so. . You are. > I'll tell you my situation > and I'd appreciate your take on it... > > I'm looking into the design a network simulator. The simulator has a > few requirements: > > (1) I need to be able to swap in a variety of replacement components > during different simulations. I.e., RadioFrequencyChannelModel, > WiredNetworkChannelModel, etc. This drives me to want the notion of > inherited interfaces, partly as a form of documentation. Ok. > (2) I want a form of encapsulation (which I realize isn't necessarily > guaranteed in all possible static typing implementations). I.e., I want > to ensure that any code which accesses a ChannelModel only calls those > methods that are part of the ChannelModel interface. If there's a > method RadioFrequencyChannelModel.setBroadcastDistance(...), which isn't > part of the generic ChannelModel interface, I don't want most of my code > to be able to start using that particular method, if the code need to be > able to work with all possible ChannelModel implementations. This is mostly a self-discipline issue. But FWIW, unit-testing should be enough here. And if you really want something more bondage-and-discipline, you can use some wrapper object to filter out the exposed interface. There's very few to do - here's a possible (while mostly dumb) home-made solution: class InterfaceType(type): def __new__(meta, class_name, bases, new_attrs): cls = type.__new__(meta, class_name, bases, new_attrs) cls._exposed = [name for name in new_attrs.keys() \ if not name.startswith('_')] return cls class Interface(object): __metatype__ = InterfaceType @classmethod def _expose(cls, name): return name in cls._exposed class InterfaceRestrictor(object): def __init__(self, obj, interface): self._interface = interface self._obj = obj def __getattr__(self, name): if self._interface._expose(name): return getattr(self._obj, name) else: raise AttributeError("name %s not allowed" % name) And you can use a decorator specifying arg names or types -> expected interface to automagically ensure you get correctly wrapped objects in the client code. NB : Don't use that code - here again, object-adaptation (which is at the core of Zope3 interfaces and Peak's Protocols) comes to mind... > (3) I like Interfaces as a matter of documentation. It helps me to > thing things through. I've got a lot of components that must support > interchangeable implementations: BTW, did I suggest to have a look at Zope3 interface or Peak's protocols ?-) > channels, modems, MAC layers, link > layers, etc. If I have an abstract MAC_layer interface, it helps me > think carefully about what every MAC layer ought to provide, and it also > helps me explain to other people what a MAC layer in my simulator must > provide. That is, it helps me better explain to other people how the > system's major components relate to each other. Ok, now this is a design issue. All you need here is an UML-aware drawing program. > Now, I could use Java or C# to get functionality such as interfaces, but > I loath giving up the general productive goodness of Python. That's why > I'm looking for something like interfaces. Given your motivations and requirements (which seems pretty sensible AFAIC), you definitively want to have a look at Zope3 Interfaces or Peak Protocol. They'll give you *much* more than Java's interfaces. > But even if we disagree about the wisdom of my intentions, We don't. The point on which we disagree is the proposed solution !-) > do you know > if/when Guido's planning to work that stuff into Python? The last post > I noticed from him on the topic was from 2005. At least back then he > sounded pretty into it. I don't think this will ever make it into Python. But you really don't need it anyway. Well, IMHO at least !-) From sluggoster at gmail.com Mon Jun 26 16:39:22 2006 From: sluggoster at gmail.com (Mike Orr) Date: 26 Jun 2006 13:39:22 -0700 Subject: 'r' vs 'rb' in csv (was Re: Python SHA-1 as a method for unique file identification ? [help!]) In-Reply-To: References: <1150873779.832601.154920@b68g2000cwa.googlegroups.com> Message-ID: <1151354361.950035.274210@u72g2000cwu.googlegroups.com> Tim Peters wrote: > [EP ] > > This inquiry may either turn out to be about the suitability of the > > SHA-1 (160 bit digest) for file identification, the sha function in > > Python ... or about some error in my script > > It's your script. Always open binary files in binary mode. It's a > disaster on Windows if you don't (if you open a file in text mode on > Windows, the OS pretends that EOF occurs at the first instance of byte > chr(26) -- this is an ancient Windows behavior that made an odd kind > of sense in the mists of history, and has persisted in worship of > Backward Compatibility despite that the original reason for it went > away _long_ ago). On a semi-related note, I have a database on Linux that imports from a Macintosh CSV file. The 'csv' module says to always open files in binary mode, but this didn't work in my case: I had to open it as 'rU' (text with universal newlines) or 'csv' misparsed it. I'd like the program to be portable to Windows and Mac. Is there a way around this? Will I really burn in hell for using 'rU'? What was the odd bit of sense? I know you end console input by typing ctrl-Z, but I thought it was just like Unix ctrl-D which ends the input but doesn't actually insert that character. -- Mike Orr From omouse at gmail.com Sun Jun 25 23:56:46 2006 From: omouse at gmail.com (OMouse) Date: 25 Jun 2006 20:56:46 -0700 Subject: languages with full unicode support In-Reply-To: <1151251736.590910.36050@u72g2000cwu.googlegroups.com> References: <1151251736.590910.36050@u72g2000cwu.googlegroups.com> Message-ID: <1151294206.255080.216880@m73g2000cwd.googlegroups.com> > As far as i know, here's few other lang's status: > > C ? No. I think C has the wchar type to handle larger values. And C++ has std::wstring. So really, the support is there. http://www.cl.cam.ac.uk/~mgk25/unicode.html#c I think the problem is that most C/C++ coders don't care about unicode support and so they stick to char and std::string. From irmen.NOSPAM at xs4all.nl Wed Jun 28 19:50:01 2006 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Thu, 29 Jun 2006 01:50:01 +0200 Subject: locating strings approximately In-Reply-To: <1151537334.900487.322980@75g2000cwc.googlegroups.com> References: <1151537334.900487.322980@75g2000cwc.googlegroups.com> Message-ID: <44a315ad$0$31638$e4fe514c@news.xs4all.nl> BBands wrote: > I'd like to see if a string exists, even approximately, in another. For > example if "black" exists in "blakbird" or if "beatles" exists in > "beatlemania". The application is to look though a long list of songs > and return any approximate matches along with a confidence factor. I > have looked at edit distance, but that isn't a good choice for finding > a short string in a longer one. I have also explored > difflib.SequenceMatcher and .get_close_matches, but what I'd really > like is something like: > > a = FindApprox("beatles", "beatlemania") > print a > 0.857 > > Any ideas? > > jab > I collected a few pointers in this article: http://www.razorvine.net/frog/user/irmen/article/2005-05-28/53 It contains one or two additional methods besides the ones you mentioned. Sorry, it's in Dutch, but you can find the links without much trouble i guess. --Irmen From steve at holdenweb.com Fri Jun 9 03:00:19 2006 From: steve at holdenweb.com (Steve Holden) Date: Fri, 09 Jun 2006 08:00:19 +0100 Subject: Importing again and again In-Reply-To: <1149796920.757115.290840@h76g2000cwa.googlegroups.com> References: <1149796920.757115.290840@h76g2000cwa.googlegroups.com> Message-ID: abcd wrote: > If I have code which imports a module over and over again...say each > time a function is called, does that cause Python to actually re-import > it...or will it skip it once the module has been imported?? > > for example: > > def foo(): > import bar > bar.printStuff() > > foo() > foo() > foo() > foo() > > ...will that re-import bar 4 times...or just import it once? is this a > big performance hit? > > thanks > To address the performance question, by the way, the first thing that the import process does is look in sys.modules to see whether the module has already been imported. If so then it uses the module referenced by sys.modules, so the overhead is pretty small (dicts being quite fast generally speaking). So your code is a reasonable way to defer the import of bar until the function is called, which is why I presumed you coded it that way. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From atwardoch at op.pl Fri Jun 16 00:13:49 2006 From: atwardoch at op.pl (atwardoch at op.pl) Date: 15 Jun 2006 21:13:49 -0700 Subject: MS VC++ Toolkit 2003 installer (VCToolkitSetup.exe) Message-ID: <1150431229.182271.61070@h76g2000cwa.googlegroups.com> I need to build some Win32 Python extensions. If somebody happens to have the Microsoft Visual C++ Toolkit 2003 installer (VCToolkitSetup.exe), please kindly contact me off-list at: list.adam [at] twardoch.com Thank you, Adam Twardoch From deets at nospam.web.de Tue Jun 13 12:49:01 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 13 Jun 2006 18:49:01 +0200 Subject: Decimals References: <1150188516.739925.102810@h76g2000cwa.googlegroups.com> <1150190908.231517.314040@h76g2000cwa.googlegroups.com> <1150191995.559582.140270@p79g2000cwp.googlegroups.com> Message-ID: <4f88llF1gsielU1@uni-berlin.de> Tgone wrote: > Sybren Stuvel wrote: >> Tgone enlightened us with: >> > Sorry, when I print out the variable it displays as '15.0'. The >> > price is '15.00' in the database though. >> >> That's the same thing, isn't it? 15.0 == 15.000000000 > > Yes, they're both mathematically the same. I never said they weren't... > >> > Here's my code: >> > >> > product = Product.get(2) >> > print product.price # 15.0 >> >> Try string formatting: >> >> print '%.2f' % product.price > > That works. I expected Python to display the data exactly as it is in > the database, like most languages. Care to give us an example of "one of those"? Diez From pmartin at snakecard.com Mon Jun 19 14:12:21 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Mon, 19 Jun 2006 13:12:21 -0500 Subject: Python with Eclipse References: <449679c3@news.uni-ulm.de> Message-ID: <9OBlg.6681$FR1.4810@dukeread05> Dennis Benzinger wrote: > Stan Cook wrote: >> I've been trying to use Eclipse with Python on Linux for a while and >> have noticed something odd. After running the code or debugging a few >> times, its responsiveness gets really bad. Upon checking the equivalent >> of the task manager, I find several instances of Python running. When I >> kill these instances, the responsiveness comes back. I'm not sure if >> there is a better place to post this, but it is Python related. Is this >> just an issue with Eclipse or is there something else I should inspect? >> >> Any help would be appreciated. >> >> Regards, >> >> S Cook > > Which Python plugin are you using? PyDev? > > > Bye, > Dennis Hi, What other plugins are there ? Regards, Philippe From theller at python.net Fri Jun 23 07:06:18 2006 From: theller at python.net (Thomas Heller) Date: Fri, 23 Jun 2006 13:06:18 +0200 Subject: Unicode problem with exec Message-ID: I'm using code.Interactive console but it doesn't work correctly with non-ascii characters. I think it boils down to this problem: Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> print u"?" ? >>> exec 'print u"?"' Traceback (most recent call last): File "", line 1, in ? File "", line 1, in ? File "c:\python24\lib\encodings\cp850.py", line 18, in encode return codecs.charmap_encode(input,errors,encoding_map) UnicodeEncodeError: 'charmap' codec can't encode character u'\x84' in position 0: character maps to >>> ^Z Why does the exec call fail, and is there a workaround? Thanks, Thomas From casevh at comcast.net Sun Jun 18 08:42:56 2006 From: casevh at comcast.net (casevh at comcast.net) Date: 18 Jun 2006 05:42:56 -0700 Subject: maximum integer length? In-Reply-To: References: Message-ID: <1150634576.017126.129210@c74g2000cwc.googlegroups.com> nate wrote: > So I am just wondering how long an integer can be with 400 megabytes of > memory. > > I guess this is a question of logic? > each integer takes up a byte right? If I have 400 megabytes that would > mean I could have a long integer with up to 419,430,400,000 integers? > Python longs are stored using 15 bits out of every 16 bits (2 bytes). So every 2 bytes will contain approximately 4.5154 decimal digits. Ignoring memory usage and overhead, the number of digits in the largest possible long integer that can fit in 400 megabytes is >>> import math >>> 200 * 1024 * 1024 * 15 * math.log10(2) 946958486.2000643 Since memory space is required for temporary storage of intermediate results, you won't actually be able to create a number that large if you only have 400 megabytes. casevh From girish at cse.iitb.ac.in Wed Jun 28 03:52:38 2006 From: girish at cse.iitb.ac.in (Girish Sahani) Date: Wed, 28 Jun 2006 13:22:38 +0530 (IST) Subject: How to measure execution time of a program Message-ID: <54032.10.209.4.1.1151481158.squirrel@10.105.1.3> Hi all, Can anyone tell me the simplest way to do it (some code snippet that could be included in the program's main function) ?? Thanks, girish From maric at aristote.info Tue Jun 20 13:26:08 2006 From: maric at aristote.info (Maric Michaud) Date: Tue, 20 Jun 2006 19:26:08 +0200 Subject: __getattribute__ doesn't work on 'type' type for '__class__' In-Reply-To: <8k8g92tgqmhu70au13od2fn1ihut04sr0o@4ax.com> References: <8k8g92tgqmhu70au13od2fn1ihut04sr0o@4ax.com> Message-ID: <200606201926.09060.maric@aristote.info> Le Mardi 20 Juin 2006 18:36, Barry Kelly a ?crit?: > Yet when I try this with the 'type' type, it doesn't work: > > ---8<--- > > >>> x.__class__.__class__ > > > > >>> x.__class__.__getattribute__('__class__') > you're looking for getattr : In [11]: getattr(object, '__class__') Out[12]: In [13]: getattr(str, 'translate') Out[13]: > Traceback (most recent call last): > ? File "", line 1, in ? > TypeError: descriptor '__getattribute__' requires a 'int' object but > received a 'str' > --->8--- > > Why is this? __getattribute__ is the descriptor interface, that means... humm see the doc i'm not enough skilled in english to explain in few words... but in python : In [27]: 'aaa'.replace('a', 'z') Out[27]: 'zzz' is exactly the same as : In [25]: str.__getattribute__('aaa', 'replace')('a', 'z') Out[25]: 'zzz' or even : In [26]: object.__getattribute__('aaa', 'replace')('a', 'z') Out[26]: 'zzz' -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From matt.hammond at rd.bbc.co.uk Mon Jun 26 04:00:02 2006 From: matt.hammond at rd.bbc.co.uk (Matt Hammond) Date: Mon, 26 Jun 2006 09:00:02 +0100 Subject: Kamaelia 0.4.0 RELEASED - Faster! More Tools! More Examples! More Docs! ; -) References: <4499c9de$0$69378$ed2619ec@ptn-nntp-reader01.plus.net> <449D4E3C.8080508@jessikat.plus.net> <449d763a$0$69376$ed2619ec@ptn-nntp-reader01.plus.net> Message-ID: >> This allows somethings to run eg >> >> AxonVisualiser.py --navelgaze >> >> but I'm not sure if the results are really unaffected by not having a >> real yielder. The diagram appears, but doesn't seem to settle down. > > I don't think the AxonVisualiser would be particularly affected by > this - any wobbling you'll see there is probably more down to the > simple physics model the visualiser uses not having sufficient > dampening for the layout you see. (The physics model was apparently > originally written by Matt for a lava lamp simulator, but has turned > out to be incredibly useful as a simple layout tool :-) > > A little bit of manual assistance to spread things out can sometimes > help it settle down though :) Michael's right: the wobble is due to the low level of dampening in the physics model and its discrete time step nature. Brief, non-methodical(!) experiments with increased dampening do lead to a more stable visualisation, but particles start to become 'sticky' and not always move when it would be helpful for them to do so! The physics code is not the fastest on the planet, so the number of simulation cycles per second is quite low - therefore to enable the particles to move quickly enough, the forces act quite strongly and the dampening is quite low. You therefore occasionally see a slight wobbling effect where a 'component' particle is being pulled and pushed quite strongly by its inbox and outbox particles in many different directions at once. Matt -- | Matt Hammond | Research Engineer, Tech. Group, BBC, Kingswood Warren, Tadworth, Surrey, UK | http://kamaelia.sf.net/ | http://www.bbc.co.uk/rd/ From nicogrubert at gmail.com Thu Jun 1 04:00:49 2006 From: nicogrubert at gmail.com (Nico Grubert) Date: Thu, 01 Jun 2006 10:00:49 +0200 Subject: os.popen3() - how to close cmd window automatically? In-Reply-To: References: Message-ID: <447E9EB1.6090506@gmail.com> > replace console=[... by windows=[... in your setup.py Works perfect. Thank you, Rony! From fabiofz at gmail.com Tue Jun 6 12:16:20 2006 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Tue, 6 Jun 2006 13:16:20 -0300 Subject: Pydev 1.1.0 Released Message-ID: Hi All, Pydev and Pydev Extensions 1.1.0 have been released Details on Pydev Extensions: http://www.fabioz.com/pydev Details on Pydev: http://pydev.sf.net Details on its development: http://pydev.blogspot.com Release Highlights in Pydev Extensions: ----------------------------------------------------------------- - Bug-fixes Release Highlights in Pydev: ---------------------------------------------- - Startup is now faster for the plugin: actions, scripts, etc. are now all initialized in a separate thread - Indentation engine does not degrade as document grows - Multiple-string does not mess up highlighting anymore - code completion issue with {} solved - Ctrl+W: now expands the selection to cover the whole word where the cursor is - Assign to attributes (provided by Joel Hedlund) was expanded so that Ctrl+1 on method line provides it as a valid proposal - A Typing preferences page was created so that the main page now fits in lower resolutions What is PyDev? --------------------------- PyDev is a plugin that enables users to use Eclipse for Python and Jython development -- making Eclipse a first class Python IDE -- It comes with many goodies such as code completion, syntax highlighting, syntax analysis, refactor, debug and many others. Cheers, -- Fabio Zadrozny ------------------------------------------------------ Software Developer ESSS - Engineering Simulation and Scientific Software http://www.esss.com.br Pydev Extensions http://www.fabioz.com/pydev Pydev - Python Development Enviroment for Eclipse http://pydev.sf.net http://pydev.blogspot.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From nmm1 at cus.cam.ac.uk Wed Jun 28 04:24:44 2006 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 28 Jun 2006 08:24:44 GMT Subject: Immutability References: Message-ID: In article , Robert Kern writes: |> Nick Maclaren wrote: |> > The way that I read it, Python allows only values (and hence types) |> > to be immutable, and not class members. The nearest approach to the |> > latter is to use the name hiding conventions. |> > |> > Is that correct? |> |> You can also make properties that don't allow writing. |> |> class Foo(object): |> |> def __init__(self, bar): |> self._bar = bar |> |> @property |> def bar(self): |> return self._bar Thanks very much. And, what's more, I have even found its documentation! Whatsnew2.2. The 2.4.2 reference is, er, unhelpful. One of Python's less-lovable attributes is the inscrutability of its documentation :-( But you knew that .... Regards, Nick Maclaren. From rhymes at myself.com Fri Jun 23 18:48:32 2006 From: rhymes at myself.com (Lawrence Oluyede) Date: Sat, 24 Jun 2006 00:48:32 +0200 Subject: Python on intel osx References: Message-ID: <1hhevh7.xdqhgs1x2v6i5N%rhymes@myself.com> John Lockwood wrote: > Can someone please suggest the most suitable python for mac osx 10.4.6 > Finding the right installs doesn't seem quite as cut and dried as it is for > linux or windows. open google, type "python osx" and go to the _second_ result. It's http://pythonmac.org/packages/ > I'm also looking for numeric and pyopengl. I compiled Numeric manually and it worked fine. Dunno about pyopengl -- Lawrence - http://www.oluyede.org/blog "Nothing is more dangerous than an idea if it's the only one you have" - E. A. Chartier From lucaberto at libero.it Fri Jun 16 17:50:48 2006 From: lucaberto at libero.it (luca72) Date: 16 Jun 2006 14:50:48 -0700 Subject: Pycrypto In-Reply-To: References: <1150446904.527285.255170@g10g2000cwb.googlegroups.com> <1150458752.342042.189650@h76g2000cwa.googlegroups.com> <1150462237.224431.213020@c74g2000cwc.googlegroups.com> <1150466793.537546.149690@p79g2000cwp.googlegroups.com> <1150470895.257327.302460@h76g2000cwa.googlegroups.com> Message-ID: <1150494648.623566.147500@y41g2000cwy.googlegroups.com> > In [26]:import binascii > > In [27]:binascii.unhexlify('ea523a664dabaa4476d31226a1e3bab0') > Out[27]:'\xeaR:fM\xab\xaaDv\xd3\x12&\xa1\xe3\xba\xb0' > > Ciao, > Marc 'BlackJack' Rintsch Ciao Marc Grazie Thanks From runlevelten at gmail.com Thu Jun 15 11:49:50 2006 From: runlevelten at gmail.com (Ten) Date: Thu, 15 Jun 2006 16:49:50 +0100 Subject: Python Help In-Reply-To: References: Message-ID: <200606151649.51070.runlevelten@gmail.com> On Wednesday 14 June 2006 16:57, Kathy Garcia wrote: > htmldiv style='background-color'DIV class=RTE > P BR FONT face="Courier New"To Whom it May Concern BR I have recently > downloaded Python 2.4.3 on Windows XP. The program does not recongnize when > I type in python " name 'python' is not defined". Please tell me how to > correct this./FONT BR /P DIV /DIV FONT color=#000000 /DIV > DIV /DIV /FONT /div br clear=allhrExpress yourself instantly with > MSN Messenger! a href="http://g.msn.com/8HMAEN/2731??PS=47575" > target="_top"MSN Messenger/a Download today it's FREE! /html Hi there. Seems like you're opening a python interpreter by running python, then typing "python" into that. Whatever you're trying to do, this probably isn't the way to go about it. :-) You seem to be successfully running python. Maybe if you let us know what you're trying to achieve other than that, it would be possible to help. Regards, Ten. PS: If you could manage it, sending plain text messages instead of html ones would be great. You'll notice html messages are virtually unheard of on most lists/groups. They make an awful unreadable mess for many of us and are kind of the newsgroup equivalent of breaking wind in an elevator. :-) -- There are 10 types of people in this world, those who understand binary, and those who don't. From ishoej at gmail.com Fri Jun 16 05:28:14 2006 From: ishoej at gmail.com (Holger) Date: 16 Jun 2006 02:28:14 -0700 Subject: Noob script needs some input: CVS PatchMaker Message-ID: <1150450094.544961.189540@i40g2000cwc.googlegroups.com> I needed a tool for extracting patches from CVS based on the log messages. I.e. we mark our fixes and features with a "Bugdb XYZ" And sometimes you need to move a fix/feature to another branch or maybe you just want to inspect exactly what changes were related to a specific bugdb issue. Now I've searched hi and low for this and I now it's out there somewhere bleeding obvious - can't imagine I'm the first to have this thought. I just haven't been able to find it... Well, that was an excellent opportunity to get some python practice, so below is my first shot at the problem. Any feedback on what would be "the pythonic way" to do this would be much appreciated! Usage: cd myproject patchmaker Ouput is a diff of involved files+revs Thank you, /Holger ---------------------------------------------------------------------------------------------------------------------- #!/usr/bin/env python # Copyright 2006 Holger Lindeberg Bille import sys, re, os import popen2 workingfile = re.compile("^Working file: *(.*)$") revision = re.compile("^revision *(.*)$") fileend = re.compile("^===========================================================================") details = re.compile("^date: *") entryend = re.compile("^----------------------------") branches = re.compile("^branches:( *(.*);)*") class LogEntry: def __init__(self): self.rev = 0 self.prevrev = 0 self.text = [] def setName(self, name): self.name = name def read(self, file): done = 0 for line in file: regx = details.search(line) if regx: pass else: if entryend.search(line): break else: if fileend.search(line): done = 1 break else: self.text.append(line.strip()) return done def GuessPrevRev(self): pass def filter(self, filter): found = 0 for line in self.text: if filter.search(line): found = 1 break return found def calcPrevRev(self): # todo: get this from CVS instead of guessing self.rev = "1.1" self.prevrev = "1.1" ver = self.name.split(".") n = int(ver.pop()) - 1 while len(ver) >= 1: if n >= 1: ver.append(str(n)) self.prevrev = ".".join(ver) self.rev = self.name break else: ver.pop() # throw this away n = int(ver.pop()) def patchDump(self, file): cmd = "cvs -q diff -u -b -r %s -r %s %s" % (self.prevrev, self.rev, file) # print cmd outp, inp = popen2.popen2(cmd) for line in outp: print line, outp.close() inp.close() def dump(self): print "------------------------------------------" print "rev = %s" % self.name for line in self.text: print line class FileLog: def __init__(self): self.revs = [] def setName(self, name): self.name = name def read(self, file): for line in file: regx = revision.search(line) if regx: rev = LogEntry() rev.setName(regx.group(1)) done = rev.read(file) self.revs.append(rev) if done: break def filter(self, filter): found = 0 newrevs = [] for rev in self.revs: if rev.filter(filter): found = 1 newrevs.append(rev) self.revs = newrevs return found def calcPrevRev(self): for rev in self.revs: rev.calcPrevRev() def patchDump(self): for rev in self.revs: rev.patchDump(self.name) def dump(self): print "File = %s" % self.name print "No. of revs %d" % len(self.revs) for rev in self.revs: rev.dump() print "===============================================" class LogDB: def __init__(self): self.flogs = [] def read(self): outp, inp = popen2.popen2('cvs -q log -N') found = 0 for line in outp: regx = workingfile.search(line) if regx: flog = FileLog() flog.setName(regx.group(1)) flog.read(outp) self.flogs.append(flog) outp.close() inp.close() def filter(self, filter): newflogs = [] for flog in self.flogs: if flog.filter(filter): newflogs.append(flog) self.flogs = newflogs def calcPrevRev(self): for flog in self.flogs: flog.calcPrevRev() def patchDump(self): for flog in self.flogs: flog.patchDump() def dump(self): print "Starting dump" print "===============================================" for flog in self.flogs: flog.dump() if len(sys.argv) != 2: sys.stderr.write("wrong number of args") sys.exit() a = sys.argv[1] a.encode('latin-1') #print "arg = %s" % a db = LogDB() db.read() #db.dump() myfilter = re.compile(a) db.filter(myfilter) #db.dump() db.calcPrevRev() db.patchDump() From fredrik at pythonware.com Wed Jun 28 11:31:51 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 28 Jun 2006 17:31:51 +0200 Subject: Immutability References: <4Qj*cEjkr@news.chiark.greenend.org.uk> Message-ID: Nick Maclaren wrote: > class fred : > @property > def joe (self) : > print "Inside /joe\n" > > a = fred() > a.joe() > > Traceback (most recent call last): > File "crap.py", line 14, in > a.joe() > TypeError: 'NoneType' object is not callable > > VERY weird - I could understand it if I got the error and DIDN'T succeed > in the call .... a property looks like an attribute, not a method, so you're trying to call whatever your "joe()" method returns. (that's what "a function for getting an attribute value" in the property documentation refers to). From jeremy+complangpython at jeremysanders.net Sun Jun 11 10:57:07 2006 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Sun, 11 Jun 2006 15:57:07 +0100 Subject: import hook Message-ID: Hi - Is it possible to override the import process so that if in my program I do import foo.bar Python will look for bar in a directory which isn't called foo? I want my module/program to be able to be run without being installed in site-packages, so by doing "import foo.bar", it should start looking for bar in the current directory which could be called "foo-0.43". I've tried overriding __import__, chopping out "foo." from package names, but that tends to break. I've also tried overriding imp.find_module() but Python never appears to use my version. Any ideas? Thanks Jeremy -- Jeremy Sanders http://www.jeremysanders.net/ From tim.golden at viacom-outdoor.co.uk Sat Jun 24 11:12:51 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: 24 Jun 2006 08:12:51 -0700 Subject: adad In-Reply-To: References: Message-ID: <1151161971.919663.276050@m73g2000cwd.googlegroups.com> edoardo batini wrote: > dvsdfvsdfvsdfvsf Oh no. Not another question about permutations! TJG From deets at nospam.web.de Tue Jun 20 06:17:14 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 20 Jun 2006 12:17:14 +0200 Subject: Specifing arguments type for a function References: Message-ID: <4fq09iF1k0h0eU1@uni-berlin.de> Paolo Pantaleo wrote: > I have a function > > def f(the_arg): > ... > > and I want to state that the_arg must be only of a certain type > (actually a list). Is there a way to do that? Yes and no. You can ensure that the passed object is a list, by calling e.g. def f(arg): if not isinstance(arg, list): raise "Not a list!" Alternatively, you can just use it as an iterable - and the exception will come from arg not being iterable. But what you can't do is make python complain about this: def f(arg): for e in arg: print e f(100) before actually calling f. It will always fail at runtime. Diez From jzgoda at o2.usun.pl Thu Jun 15 17:33:55 2006 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Thu, 15 Jun 2006 23:33:55 +0200 Subject: Which compiler will Python 2.5 / Windows (Intel) be built with? In-Reply-To: <4491c90f$1@nntp0.pdx.net> References: <1150367139.495114.148550@g10g2000cwb.googlegroups.com> <44917535$1@nntp0.pdx.net> <1150391891.130185.4640@f6g2000cwb.googlegroups.com> <4491b9e1$1@nntp0.pdx.net> <4491c90f$1@nntp0.pdx.net> Message-ID: Scott David Daniels napisa?(a): >> Sorry, gals and guys, but if you force us to buy something irrelevant >> like VC2003, you will not get our sympathy. > > Oh, no. And just when our bank account was getting full from your > appreciation of our efforts. Prepare to be happy, as you owe us $9999.98 for legal & financial assistance. We got a public record of your misbehaviour. -- Jarek Zgoda http://jpa.berlios.de From alanmk at hotmail.com Thu Jun 8 05:57:13 2006 From: alanmk at hotmail.com (Alan Kennedy) Date: 8 Jun 2006 02:57:13 -0700 Subject: language-x-isms References: <1149753206.451066.120960@h76g2000cwa.googlegroups.com> <1149759486.695563.110640@g10g2000cwb.googlegroups.com> Message-ID: <1149760633.796809.166430@h76g2000cwa.googlegroups.com> [Alan Kennedy] >> On jython 2.1, I use something like this >> >> #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= >> try: >> enumerate >> except NameError: >> def enumerate(iterable): >> results = [] ; ix = 0 >> for item in iterable: >> results.append( (ix, item) ) >> ix = ix+1 >> return results [Fredrik Lundh] > at least in CPython, using a user-defined enumerate function is a bit > slower than using the built-in version. Who's using a user-defined enumerate on cpython? The above code only defines a user-defined enumerate when the built-in one doesn't exist, i.e. on jython, which raises NameError on reference to the non-existent enumerate. On cpython, the reference to enumerate doesn't generate a NameError, therefore the user-supplied version never gets defined, and the builtin is used. regards, -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From fredrik at pythonware.com Thu Jun 29 13:18:43 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 29 Jun 2006 19:18:43 +0200 Subject: how do i make an array global In-Reply-To: <1151601017.583410.192120@y41g2000cwy.googlegroups.com> References: <1151472238.400461.42350@p79g2000cwp.googlegroups.com> <1151553485.378000.203760@p79g2000cwp.googlegroups.com> <1151601017.583410.192120@y41g2000cwy.googlegroups.com> Message-ID: a wrote: > i understand index error > but there is no index error in my code that is the problem! so who wrote the "c:\mark\web1\code.py" file ? > > File "c:\mark\web1\code.py", line 64, in GET > > l_code.append( len(d_list_code[i]['entries']) ) > > IndexError: list index out of range maybe you should talk to Mark ? From greg.kujawa at gmail.com Thu Jun 1 21:33:50 2006 From: greg.kujawa at gmail.com (gregarican) Date: 1 Jun 2006 18:33:50 -0700 Subject: New to Python: Do we have the concept of Hash in Python? References: <1149206685.768210.71990@i39g2000cwa.googlegroups.com> Message-ID: <1149212030.851030.257180@c74g2000cwc.googlegroups.com> Dear A.M., The day is complete. My TPS reports still aren't on my desk. Either with or without cover sheets. Not a good time to try to teach yourself a new language. Please gather your belongings and move down to basement storage C. That'd be great, Bill Lumberg John Machin wrote: > A.M wrote: > > > The application is not mission critical system. It is just a simple > > reporting tool. > > Famous last words. From diffuser78 at gmail.com Fri Jun 16 09:08:33 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 16 Jun 2006 06:08:33 -0700 Subject: GUI in Python using wxGlade In-Reply-To: References: <1150380251.279150.73620@u72g2000cwu.googlegroups.com> <1150386216.365531.157690@g10g2000cwb.googlegroups.com> <1150403353.755218.292100@c74g2000cwc.googlegroups.com> Message-ID: <1150463313.588433.248560@h76g2000cwa.googlegroups.com> Did you paste any code ? Also the link for the next message is not working ..... John Salerno wrote: > diffuser78 at gmail.com wrote: > > I am a newbie. I was looking for some code where I could a list of > > different items from a file and display it in a list box. Then give a > > user the capability to select some. > > > > Basically, reading and writing to a file and displaying them in > > different widgets...thats something I am looking for. If anybody can > > point me to some good example tutorials...I will be greatly helped. > > > > Thanks, > > > > Every help is appreciated > > > > Have you tried looking at the code in the wxPython demo? In the ListBox > control demo, it populates a ListBox with items from a list, but you > could easily translate that into reading from a file, I think. Here's > the full code in case you don't have the demo: > > > > > > import wx > > > > #--------------------------------------------------------------------------- > > > > # This listbox subclass lets you type the starting letters of what you want to > > # select, and scrolls the list to the match if it is found. > > class FindPrefixListBox(wx.ListBox): > > def __init__(self, parent, id, pos=wx.DefaultPosition, size=wx.DefaultSize, > > choices=[], style=0, validator=wx.DefaultValidator): > > wx.ListBox.__init__(self, parent, id, pos, size, choices, style, validator) > > self.typedText = '' > > self.log = parent.log > > self.Bind(wx.EVT_KEY_DOWN, self.OnKey) > > > > > > def FindPrefix(self, prefix): > > self.log.WriteText('Looking for prefix: %s\n' % prefix) > > > > if prefix: > > prefix = prefix.lower() > > length = len(prefix) > > > > # Changed in 2.5 because ListBox.Number() is no longer supported. > > # ListBox.GetCount() is now the appropriate way to go. > > for x in range(self.GetCount()): > > text = self.GetString(x) > > text = text.lower() > > > > if text[:length] == prefix: > > self.log.WriteText('Prefix %s is found.\n' % prefix) > > return x > > > > self.log.WriteText('Prefix %s is not found.\n' % prefix) > > return -1 > > > > > > def OnKey(self, evt): > > key = evt.GetKeyCode() > > > > if key >= 32 and key <= 127: > > self.typedText = self.typedText + chr(key) > > item = self.FindPrefix(self.typedText) > > > > if item != -1: > > self.SetSelection(item) > > > > elif key == wx.WXK_BACK: # backspace removes one character and backs up > > self.typedText = self.typedText[:-1] > > > > if not self.typedText: > > self.SetSelection(0) > > else: > > item = self.FindPrefix(self.typedText) > > > > if item != -1: > > self.SetSelection(item) > > else: > > self.typedText = '' > > evt.Skip() > > > > def OnKeyDown(self, evt): > > pass > > > > > > #--------------------------------------------------------------------------- > > > > class TestListBox(wx.Panel): > > def __init__(self, parent, log): > > self.log = log > > wx.Panel.__init__(self, parent, -1) > > > > sampleList = ['zero', 'one', 'two', 'three', 'four', 'five', > > 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', > > 'twelve', 'thirteen', 'fourteen'] > > > > wx.StaticText(self, -1, "This example uses the wx.ListBox control.", (45, 10)) > > wx.StaticText(self, -1, "Select one:", (15, 50)) > > self.lb1 = wx.ListBox(self, 60, (100, 50), (90, 120), sampleList, wx.LB_SINGLE) > > self.Bind(wx.EVT_LISTBOX, self.EvtListBox, self.lb1) > > self.Bind(wx.EVT_LISTBOX_DCLICK, self.EvtListBoxDClick, self.lb1) > > self.lb1.Bind(wx.EVT_RIGHT_UP, self.EvtRightButton) > > self.lb1.SetSelection(3) > > self.lb1.Append("with data", "This one has data"); > > self.lb1.SetClientData(2, "This one has data"); > > > > > > wx.StaticText(self, -1, "Select many:", (220, 50)) > > self.lb2 = wx.ListBox(self, 70, (320, 50), (90, 120), sampleList, wx.LB_EXTENDED) > > self.Bind(wx.EVT_LISTBOX, self.EvtMultiListBox, self.lb2) > > self.lb2.Bind(wx.EVT_RIGHT_UP, self.EvtRightButton) > > self.lb2.SetSelection(0) > > > > sampleList = sampleList + ['test a', 'test aa', 'test aab', > > 'test ab', 'test abc', 'test abcc', > > 'test abcd' ] > > sampleList.sort() > > wx.StaticText(self, -1, "Find Prefix:", (15, 250)) > > fp = FindPrefixListBox(self, -1, (100, 250), (90, 120), sampleList, wx.LB_SINGLE) > > fp.SetSelection(0) > > > > > > def EvtListBox(self, event): > > self.log.WriteText('EvtListBox: %s, %s, %s, %s\n' % > > (event.GetString(), > > event.IsSelection(), > > event.GetSelection(), > > event.GetClientData())) > > > > lb = event.GetEventObject() > > data = lb.GetClientData(lb.GetSelection()) > > > > if data is not None: > > self.log.WriteText('\tdata: %s\n' % data) > > > > > > def EvtListBoxDClick(self, event): > > self.log.WriteText('EvtListBoxDClick: %s\n' % self.lb1.GetSelection()) > > self.lb1.Delete(self.lb1.GetSelection()) > > > > def EvtMultiListBox(self, event): > > self.log.WriteText('EvtMultiListBox: %s\n' % str(self.lb2.GetSelections())) > > > > def EvtRightButton(self, event): > > self.log.WriteText('EvtRightButton: %s\n' % event.GetPosition()) > > > > if event.GetEventObject().GetId() == 70: > > selections = list(self.lb2.GetSelections()) > > selections.reverse() > > > > for index in selections: > > self.lb2.Delete(index) > > > > > > #--------------------------------------------------------------------------- > > > > def runTest(frame, nb, log): > > win = TestListBox(nb, log) > > return win > > > > #--------------------------------------------------------------------------- > > > > > > > > > > overview = """ > > A listbox is used to select one or more of a list of > > strings. The strings are displayed in a scrolling box, with the > > selected string(s) marked in reverse video. A listbox can be single > > selection (if an item is selected, the previous selection is removed) > > or multiple selection (clicking an item toggles the item on or off > > independently of other selections). > > > > """ > > > > > > if __name__ == '__main__': > > import sys,os > > import run > > run.main(['', os.path.basename(sys.argv[0])] + sys.argv[1:]) > > From michele.simionato at gmail.com Thu Jun 15 10:25:27 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 15 Jun 2006 07:25:27 -0700 Subject: Python is fun (useless social thread) ;-) In-Reply-To: References: Message-ID: <1150381527.698890.150610@p79g2000cwp.googlegroups.com> Thomas Guettler wrote: > There are some things in Python I don't know very well: Decorators and > generators. Then you should come at EuroPython and attend at my talk! ;) But if you can't come to Switzerland, you can always look at http://www.phyast.pitt.edu/~micheles/python/decorator.zip http://www.phyast.pitt.edu/~micheles/python/documentation.html Michele Simionato From paddy3118 at netscape.net Thu Jun 15 17:27:03 2006 From: paddy3118 at netscape.net (Paddy) Date: 15 Jun 2006 14:27:03 -0700 Subject: Regular expression for not-group In-Reply-To: <1150406322.094263.239930@g10g2000cwb.googlegroups.com> References: <1150405899.027971.256160@r2g2000cwb.googlegroups.com> <1150406322.094263.239930@g10g2000cwb.googlegroups.com> Message-ID: <1150406821.255904.59030@u72g2000cwu.googlegroups.com> P.S. kodos might help you: http://kodos.sourceforge.net/ - Pad. From niemand.leermann at thomas-guettler.de Wed Jun 7 10:53:45 2006 From: niemand.leermann at thomas-guettler.de (Thomas Guettler) Date: Wed, 07 Jun 2006 16:53:45 +0200 Subject: cgi and popen References: Message-ID: Am Wed, 07 Jun 2006 14:54:41 +0200 schrieb Maarten van Veen: > A long story made short, I've build a python/cgi website consisting of > two pages. Page1 has a html form in which you can input a series of > queries. Then via Popen it starts a pythons search script, which stores > the results in a python shelve. > As the Popen command is given it should redirect to page2, which will > check if the shelve is ready (search finished) and if not displays a > search page, refreshing itself after 10 seconds. > The Popen command works nice when tried out in the console. The script > isueing the Popen quits, and the other process keeps on running till > finished. Hi, You can find out where the process hangs, by sending SIGINT to the python script: kill -SIGINT PID This is like ctrl-c, you should get a traceback. If the page1 script is not alive anymore, during the unwanted waiting, this does not work. Which form of popen do you use? Popen4 is the best, because you cannot get a deadlock if there is output on stdout and stderr. I guess you have the same strange thing, if you ssh to the server, start the script1 and you want to logoff before the subprocesses is finished. You can try to start the script like this: nohup nice mein-script >> $HOME/log/mein-script.log 2>&1 References: <1150419503.224684.320550@c74g2000cwc.googlegroups.com> <1150502102.377475.38140@u72g2000cwu.googlegroups.com> <1150505289.249498.190450@i40g2000cwc.googlegroups.com> Message-ID: <4493F837.1010802@tim.thechases.com> > I will try to work through Tim's response. I tried using it > yesterday but I was really confused on what I was doing. I'll put my plug in for entering the code directly at the shell prompt while you're trying to grok new code or toy with an idea. It makes it much easier to see what is going on as you enter it. You can ask for any variables' value at any time. It's a small pain when you're entering some nested code, and biff up on the interior of it (throwing an exception, and having to restart the function-definition/loop/class-definition statement all over), but it certainly has its advantages for learning the language. On top of that, you can usually ask for help on any object, so if you wanted to know about the datetime module or the date object in the datetime module, you can just use >>> import datetime >>> help(datetime) >>> help(datetime.date) which will give you all sorts of documentation on a date object. I'm also partial to learning about what methods the object exposes via the dir() function: >>> dir(datetime.date) or >>> print "\n".join(dir(datetime.date)) IMHO, help() and dir() at the command-line combine to make one of Python's best selling points...ease of learning. I understand Perl and Ruby might have something similar, but I've never liked their idioms. Java/C/C++, you have the edit/compile/run cycle, so if you just want to explore some simple code ideas, you've got a 3-step process, not just a simple "try it out right here and now" method. I even stopped using "bc" as my command-line calculator, preferring the power of command-line python. :) Just a few thoughts on what made learning python easier for me. Again, if you have questions, and can't figure out the answers by stepping through the code in the command shell (or some strategically placed print statements), this is certainly the forum for asking those questions. It's full of smart and helpful folks. -tkc From vasudevram at gmail.com Thu Jun 8 14:12:57 2006 From: vasudevram at gmail.com (vasudevram) Date: 8 Jun 2006 11:12:57 -0700 Subject: wxpython: where is the demo? References: Message-ID: <1149790377.609121.130860@f6g2000cwb.googlegroups.com> John Salerno wrote: > I just realized that after installing wxPython, it did not add the usual > menu item to my Start menu (Windows), where I can access the docs and > demo. I searched through the wxPython folder in the site-packages > directory, but I can't seem to find it. > > Anyone know how I can get this back? > > Thanks. Its a separate download. See: http://wxpython.org/download.php#binaries Look down the page to the section Prebuilt Binaries - MS Windows - Docs, Demos, Samples. The direct link is: http://prdownloads.sourceforge.net/wxpython/wxPython2.6-win32-docs-demos-2.6.3.2.exe HTH Vasudev Ram Independent software consultant "On a clear day you can see the blue screen of death" - Me :-). http://www.geocities.com/vasudevram From aleax at mac.com Fri Jun 30 11:32:42 2006 From: aleax at mac.com (Alex Martelli) Date: Fri, 30 Jun 2006 08:32:42 -0700 Subject: Way for see if dict has a key References: <6V6pg.21624$_J1.271925@twister2.libero.it> Message-ID: <1hhql1m.grj1uv1lte1b1N%aleax@mac.com> Fredrik Lundh wrote: > Michele Petrazzo wrote: > > > what the preferred way for see if the dict has a key? > > We have a lot of solutions: > > > > key in dict > > new syntax (2.3 and later). Fine with Python 2.2 as well, actually -- so, "new" only in an _extremely_ loose sense of the word:-). Alex From maric at aristote.info Fri Jun 2 07:22:14 2006 From: maric at aristote.info (Maric Michaud) Date: Fri, 2 Jun 2006 13:22:14 +0200 Subject: Import Issue In-Reply-To: <1149230536.375190.12150@c74g2000cwc.googlegroups.com> References: <1149230536.375190.12150@c74g2000cwc.googlegroups.com> Message-ID: <200606021322.15743.maric@aristote.info> Le Vendredi 02 Juin 2006 08:42, praveenkumar.117 at gmail.com a ?crit?: > Hi all, > After doing import file i am updating that file. Later i am > accessing a dictionary contained in that > file. Eventhough changes are reflected in the file... When i > access a dictionary those changes are > not there. I believe that it is accessing from the object > file that is created when i did import at > the start of the script. I will be kind enough if somebody > suggest solution to this problem. Read in the doc the reload builtin description to understand what happens. But as Albert said before, don't do that ! -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From gh at ghaering.de Mon Jun 19 12:12:29 2006 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 19 Jun 2006 18:12:29 +0200 Subject: [pysqlite] memory-leak in pysqlite 2.3.0 ? In-Reply-To: <8289D4DDD352DF45B8DABD7D5852A59001C00D60@EUSRV-EXC1.eu.ta.global> References: <8289D4DDD352DF45B8DABD7D5852A59001C00D60@EUSRV-EXC1.eu.ta.global> Message-ID: <4496CCED.3020103@ghaering.de> Michael Husmann wrote: >> Michael Husmann wrote: >>> After upgrading from pysqlite 2.0.5 to pysqlite 2.3.0 writing into a >>> sqlite database increases memory consumption heavily. A similar program >>> with Ruby and sqlite-ruby 1.1.0 does not affect memory consumption at >>> all. >>> [...] >>> Python 2.4.1, Sqlite3 3.3.6, Pysqlite 2.3.0 >> You never COMMIT your changes here, that's probably what's causing >> memory consumption on the SQLite side of things. >> [...] > > I also tried that commit(). Memory consumption still grows permanently. Thanks for the report. Upon debugging this a little, there's indeed a bug which crept in in pysqlite 2.2.1 because of incorrect usage of the weak references (*). This leads to the list of weak references per connection to always grow and never shrink. I'll try to provide a fix real soon. -- Gerhard (*) A missing PyWeakref_GetObject(), but I'll have to take a more careful look. From subramanian2003 at indiatimes.com Thu Jun 29 07:00:25 2006 From: subramanian2003 at indiatimes.com (subramanian2003) Date: Thu, 29 Jun 2006 16:30:25 +0530 Subject: Python decompiler Message-ID: <200606291008.PAA19689@WS0005.indiatimes.com> Hello All, I have some compiled python 2.4 scripts. If anyone has python decompiler, pls send me. Thanks, subramanian. From akameswaran at gmail.com Mon Jun 12 23:46:07 2006 From: akameswaran at gmail.com (akameswaran at gmail.com) Date: 12 Jun 2006 20:46:07 -0700 Subject: "parent" in a class __init__ def? In-Reply-To: <448d295c$0$19196$636a55ce@news.free.fr> References: <1149999409.650251.251240@g10g2000cwb.googlegroups.com> <448d295c$0$19196$636a55ce@news.free.fr> Message-ID: <1150170367.294662.10330@y43g2000cwc.googlegroups.com> bruno at modulix wrote: > akameswaran at gmail.com wrote: > (meta : please don't top-post) > > Intuitively, the name lookup on > > self.parent.foo would be faster than if you passed in the object in > > question > > > Each dot means doing a lookup in a namespace. The more dots, the more > lookups. And lookups do have a cost. hmm, intuition may not be right in this case. Lookups do have a cost - now I"m almost tempted to write and run a test for this - but the cost of each lookup is also relative to the current scope. I haven't looked over the implementation of the python interpreter - but I would hope the lookup on self would be optimized and trivial. The next relevant question would be is it cheaper to lookup self.parent or to look up a method variable, which I supsect would depend on the number of names in self vs. number of names in the method. > > -- > bruno desthuilliers > python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for > p in 'onurb at xiludom.gro'.split('@')])" From tjreedy at udel.edu Thu Jun 8 18:30:39 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 8 Jun 2006 18:30:39 -0400 Subject: Allowing zero-dimensional subscripts References: <1149801040.936452.26270@i40g2000cwc.googlegroups.com> Message-ID: wrote in message news:1149801040.936452.26270 at i40g2000cwc.googlegroups.com... > Hello, > > I discovered that I needed a small change to the Python grammar. I > would like to hear what you think about it. > > In two lines: > Currently, the expression "x[]" is a syntax error. > I suggest that it will be evaluated like "x[()]", just as "x[a, b]" is > evaluated like "x[(a, b)]" right now. > > In a few more words: Currently, an object can be subscripted by a few > elements, separated by commas. It is evaluated as if the object was > subscripted by a tuple containing those elements. It is not 'as if'. 'a,b' *is* a tuple and the object *is* subcripted by a tuple. Adding () around the non-empty tuple adds nothing except a bit of noise. >>> dis(compile('x[a,b]','','eval')) 0 0 LOAD_NAME 0 (x) 3 LOAD_NAME 1 (a) 6 LOAD_NAME 2 (b) 9 BUILD_TUPLE 2 12 BINARY_SUBSCR 13 RETURN_VALUE >>> dis(compile('x[(a,b)]','','eval')) 0 0 LOAD_NAME 0 (x) 3 LOAD_NAME 1 (a) 6 LOAD_NAME 2 (b) 9 BUILD_TUPLE 2 12 BINARY_SUBSCR 13 RETURN_VALUE Parens around non-empty tuples are only needed for precedence grouping, the same as in (a+b)*c. >I suggest that an > object will also be subscriptable with no elements at all, and it will > be evaluated as if the object was subscripted by an empty tuple. Again, there would be no 'as if' about it. You are suggesting that the parens around a tuple nothing be optional in this particular context. While logically possible, Guido decided that tuple nothings should *always* be distinguished from other nothings and set off from surrounding code by parentheses. The reason is to avoid ambiguity and catch errors. I think this is overall a good choice. Terry Jan Reedy From bignose+hates-spam at benfinney.id.au Tue Jun 13 01:22:21 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 13 Jun 2006 15:22:21 +1000 Subject: Writing PNG with pure Python References: <1149853401.521169.112530@i39g2000cwa.googlegroups.com> <1149889778.182865.181600@f6g2000cwb.googlegroups.com> <1149910872.025017.60160@i40g2000cwc.googlegroups.com> <1150152913.315502.16840@u72g2000cwu.googlegroups.com> <1150163849.760259.25250@i40g2000cwc.googlegroups.com> Message-ID: <871wttd3zm.fsf@benfinney.id.au> "Johann C. Rocholl" writes: > Currently, I am considering the following options: > - LGPL > - Modified BSD License > - X11 License (aka MIT License) > > I appreciate the simplicity of the BSD and MIT Licenses, except for > the names. "BSD License" can be confused with the original BSD > License, while "MIT License" according to the FSF "is misleading, > since MIT has used many licenses for software." But perhaps these > drawbacks are just mentioned on the FSF page to get more people to > use the GPL or LGPL. :-) I think these are real concerns. Discussion of these licenses usually needs to be couched in clarifications, such as "the three-clause BSD-style license" or "the MIT X11 license"; but these clarifications are also often dropped, leaving ambiguity as to exactly which license terms are being discussed. If you want a permissive, GPL-compatible, copyright-preserving license, the Expat license is probably the simplest. > I don't want to start a holy war about the benefits of the GPL, but > I would like some more input about the choices of licensing. The FSF licensing webpage offers assistance via email in choosing a license: > If I ever want to contribute some of the code to the Python Software > Foundation, I can still license it to them under the Apache License, > right? This would be a reason to choose something like the Expat license; it isn't a copyleft, so others can take your code and redistribute it under a *different* license, such as the Apache license, without seeking extra permission from you. > But how about the parts of the code that others contribute to my > software while it's licensed under the LGPL? You could require that all contributions be licensed by the author under the Expat license, allowing you to take it into the whole without needing to seek out that author in future, while still preserving their copyright. -- \ "I was in the grocery store. I saw a sign that said 'pet | `\ supplies'. So I did. Then I went outside and saw a sign that | _o__) said 'compact cars'." -- Steven Wright | Ben Finney From fabiofz at gmail.com Mon Jun 19 07:10:24 2006 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Mon, 19 Jun 2006 08:10:24 -0300 Subject: Python with Eclipse In-Reply-To: References: Message-ID: On 6/18/06, Stan Cook wrote: > > I've been trying to use Eclipse with Python on Linux for a > while and have noticed something odd. After running the > code or debugging a few times, its responsiveness gets > really bad. Upon checking the equivalent of the task > manager, I find several instances of Python running. When I > kill these instances, the responsiveness comes back. I'm > not sure if there is a better place to post this, but it is > Python related. Is this just an issue with Eclipse or is > there something else I should inspect? > If you're using pydev, the problem might be that you have PyLint enabled. Having it enabled might have the effect of spawning several shells for doing code-analysis. You can try disabling it or using pydev extensions that gives you a faster code-analysis. You might also restrict the number of shells that PyDev can spawn at a given time in the pylint preferences (if that's not it, please report it as a bug in the pydev tracker at sourceforge, so that we can check other possibilities -- https://sourceforge.net/tracker/?group_id=85796&atid=577329). Cheers, Fabio -------------- next part -------------- An HTML attachment was scrubbed... URL: From jussij at zeusedit.com Thu Jun 15 20:53:21 2006 From: jussij at zeusedit.com (jussij at zeusedit.com) Date: 15 Jun 2006 17:53:21 -0700 Subject: code folding, a unique problem to python? In-Reply-To: References: Message-ID: <1150419201.825148.73380@y41g2000cwy.googlegroups.com> John Salerno wrote: > But my question is more general: is it possible to > implement code folding with Python given that it has > no real block delimiters? I can't speak for UltraEdit, but the Zeus will quite happily fold Python code: http://www.zeusedit.com/features.html Jussi Jumppanen Author: Zeus For Windows IDE From gandalf at designaproduct.biz Fri Jun 9 14:27:19 2006 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Fri, 09 Jun 2006 20:27:19 +0200 Subject: __getattr__ question In-Reply-To: <4489AE08.2080407@designaproduct.biz> References: <4489AE08.2080407@designaproduct.biz> Message-ID: <4489BD87.6020400@designaproduct.biz> Here is a horrible solution. I could make it thread-safe by adding +30 lines. There must be a better solution. class TemplateItem(object): def __init__(self,name): self.name = name self.items = [] def __getattr__(self,name): self._getattr_was_called = True for item in self.items: if hasattr(item,'name') and item.name == name: return item raise AttributeError("%s: attribute or item does not exists."%name) def getrealattr(self,name): self._getattr_was_called = False res = getattr(self,name) if self._getattr_was_called: raise AttributeError def hasrealattr(self,name): try: self.getrealattr(name) return True except AttributeError: return False def __str__(self): return "TemplateItem('%s')"%self.name class CustomTemplateItem(TemplateItem): pass # I could have been customized this... root = CustomTemplateItem('root') root.items.append(CustomTemplateItem('item1')) root.items.append(CustomTemplateItem('item2')) TemplateItem.item3 = TemplateItem('item3') print hasattr(root,'item1') # True print hasattr(root,'item3') # True print root.hasrealattr('item1') # False print root.hasrealattr('item3') # True Any ideas? -- Laszlo From jcrocholl at googlemail.com Fri Jun 9 10:28:33 2006 From: jcrocholl at googlemail.com (Johann C. Rocholl) Date: 9 Jun 2006 07:28:33 -0700 Subject: Writing PNG with pure Python References: <1149853401.521169.112530@i39g2000cwa.googlegroups.com> Message-ID: <1149863313.740709.88100@g10g2000cwb.googlegroups.com> > You should really also include the alpha channel. Without that, PNG is > crippled IMHO. I have now added simple transparency (marking one color as transparent with a tRNS chunk). If anybody wants full alpha channel support, ask kindly or send me a patch. I would like to avoid duplicating all the functions, so maybe we should introduce a parameter to switch between 3 and 4 bytes per pixel. Cheers, Johann From steve at holdenweb.com Tue Jun 13 12:36:38 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 13 Jun 2006 17:36:38 +0100 Subject: [newbie]apache authentication questions In-Reply-To: References: <1150132535.766644.99870@g10g2000cwb.googlegroups.com> <1150173351.116073.316640@u72g2000cwu.googlegroups.com> Message-ID: Michael Str?der wrote: > Steve Holden wrote: > >>grahamd at dscpl.com.au wrote: >> >> >>>It is not impossible though and in cases where you don't have a choice >>>but to use a HTTP authentication scheme, use of AJAX may be the >>>answer to still allowing use of a form based login scheme. See: >>> >>> http://www.peej.co.uk/articles/http-auth-with-html-forms.html >>> >> >>That's neat! > > > IMHO this makes things more complicated and error-prone. And it requires > Javascript. I also can't see why this is more secure than a proper > session management (using cookies or URL for passing the session ticket > around). > I don't believe I said it *was* any of those things. But I am constantly amazed at the lengths the world will go to just to prove me wrong! regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From robert.kern at gmail.com Wed Jun 28 14:12:45 2006 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 28 Jun 2006 13:12:45 -0500 Subject: ? on scipy.fftpack In-Reply-To: <1151513772.828636.225540@p79g2000cwp.googlegroups.com> References: <1151513772.828636.225540@p79g2000cwp.googlegroups.com> Message-ID: Mike Duffy wrote: > I've been debugging a simulation I wrote a while ago, and it seems that > the problem is in the fft module itself. I'm trying a simple test by > just feeding the function a basic real gaussian. Obviously, I should > get back the same real gaussian, but what I get is not even close. Can > anyone help me? Thanks in advance. You will probably want to ask scipy questions on scipy-user. There aren't many scipy people here. http://www.scipy.org/Mailing_Lists I haven't run your code, yet, but one of the things you are running into is the FFT packing convention for FFTs on real functions. Please read the docstring: Type: function Base Class: String Form: Namespace: Interactive File: /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/site-packages/scipy-0.5.0.1980-py2.4-mac osx-10.4-ppc.egg/scipy/fftpack/basic.py Definition: rfft(x, n=None, axis=-1, overwrite_x=0) Docstring: rfft(x, n=None, axis=-1, overwrite_x=0) -> y Return discrete Fourier transform of real sequence x. The returned real arrays contains [y(0),Re(y(1)),Im(y(1)),...,Re(y(n/2))] if n is even [y(0),Re(y(1)),Im(y(1)),...,Re(y(n/2)),Im(y(n/2))] if n is odd where y(j) = sum[k=0..n-1] x[k] * exp(-sqrt(-1)*j*k* 2*pi/n) j = 0..n-1 Note that y(-j) = y(n-j). Optional input: n Defines the length of the Fourier transform. If n is not specified then n=x.shape[axis] is set. If nx.shape[axis], x is zero-padded. axis The transform is applied along the given axis of the input array (or the newly constructed array if n argument was used). overwrite_x If set to true, the contents of x can be destroyed. Notes: y == rfft(irfft(y)) within numerical accuracy. -- 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 From fredrik at pythonware.com Thu Jun 15 12:12:20 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 15 Jun 2006 18:12:20 +0200 Subject: code folding, a unique problem to python? In-Reply-To: References: Message-ID: John Salerno wrote: > But my question is more general: is it possible to implement code > folding with Python given that it has no real block delimiters? Or is > this still a matter of which particular editor/IDE you use? since the Python syntax *has* real block delimiters (look up INDENT and DEDENT in the language reference), it's an editor issue. From jstroud at ucla.edu Fri Jun 9 18:15:38 2006 From: jstroud at ucla.edu (James Stroud) Date: Fri, 09 Jun 2006 15:15:38 -0700 Subject: Most elegant way to generate 3-char sequence In-Reply-To: <1149889784.391965.271570@h76g2000cwa.googlegroups.com> References: <1149889784.391965.271570@h76g2000cwa.googlegroups.com> Message-ID: <4489F30A.9000006@ucla.edu> Rob Cowie wrote: > Hi all, > > I wish to generate a sequence of the form 'aaa', 'aab', aac'.... 'aba', > 'abb', 'abc' etc. all the way to 'zzz'. > > How would you construct a generator to acheive this? > > A simple, working but somewhat inelegant solution is... > > alpha = ['a','b','c','d'] #shortened for brevity > alpha2 = ['a','b','c','d'] > alpha3 = ['a','b','c','d'] > > def generator(): > for char in alpha: > for char2 in alpha2: > for char3 in alpha3: > yield char + char2 + char3 > > x = generate() > x.next() # etc, etc, etc, > A touch more efficient: import string alpha = string.lowercase def generator(choices, length): length -= 1 for a in choices: if length: for g in generator(choices, length): yield a + g else: yield a for a in generator(alpha, 3): print a -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From deets at nospam.web.de Thu Jun 1 12:01:24 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 01 Jun 2006 18:01:24 +0200 Subject: image lib & Qt4 References: <1149173540.470829.34940@c74g2000cwc.googlegroups.com> Message-ID: <4e8haiF1dp2heU1@uni-berlin.de> aljosa wrote: > i'm looking for image lib which supports common image types (maybe > freeimagepy?) and is relatively easy to display image loaded through > that lib in PyQt4. > any ideas? Use PIL & StringIO to create a in-memory representation of the image as e.g. PNG. Load that using Qt. Diez From certo at comeno.it Sun Jun 11 09:45:47 2006 From: certo at comeno.it (imho) Date: Sun, 11 Jun 2006 13:45:47 GMT Subject: package search In-Reply-To: <1150032058.923953.134550@u72g2000cwu.googlegroups.com> References: <1150009850.738535.155550@m38g2000cwc.googlegroups.com> <1150032058.923953.134550@u72g2000cwu.googlegroups.com> Message-ID: boris ha scritto: > > COOL! You just saved me an awful lot of work. > > Thanks, Diego! > > Boris > ;-) Bye From kylotan at gmail.com Tue Jun 13 05:18:17 2006 From: kylotan at gmail.com (Ben Sizer) Date: 13 Jun 2006 02:18:17 -0700 Subject: numeric/numpy/numarray In-Reply-To: <1150188484.888977.189510@y43g2000cwc.googlegroups.com> References: <1150188484.888977.189510@y43g2000cwc.googlegroups.com> Message-ID: <1150190297.700680.20210@y43g2000cwc.googlegroups.com> Simon Percivall wrote: > Bryan wrote: > > hi, > > > > what is the difference among numeric, numpy and numarray? i'm going to start > > using matplotlib soon and i'm not sure which one i should use. > > Look again at numeric.scipy.org, and this time: read the whole page, > especially the section called "Older Array Packages". In particular, ignore any references to SciPy Core... Not to mention anything regarding older NumPy, which is nothing to do with newer NumPy, which is why common libraries (such as PyOpenGL) ask for NumPy v23 when the latest download on SourceForge is 0.9.8. Numeric libraries in Python are a nomenclatural nightmare. It's well past time that something made it into the standard library, I feel. -- Ben Sizer From jjlee at reportlab.com Mon Jun 12 18:53:56 2006 From: jjlee at reportlab.com (John J. Lee) Date: Mon, 12 Jun 2006 22:53:56 GMT Subject: urllib behaves strangely References: Message-ID: <87wtbmdlyz.fsf@reportlab.com> Duncan Booth writes: > Gabriel Zachmann wrote: > > > Here is a very simple Python script utilizing urllib: [...] > > "http://commons.wikimedia.org/wiki/Commons:Featured_pictures/chronologi > > cal" > > print url > > print > > file = urllib.urlopen( url ) [...] > > However, when i ecexute it, i get an html error ("access denied"). > > > > On the one hand, the funny thing though is that i can view the page > > fine in my browser, and i can download it fine using curl. [...] > > > > On the other hand, it must have something to do with the URL because > > urllib works fine with any other URL i have tried ... > > > It looks like wikipedia checks the User-Agent header and refuses to send > pages to browsers it doesn't like. Try: [...] If wikipedia is trying to discourage this kind of scraping, it's probably not polite to do it. (I don't know what wikipedia's policies are, though) John From buerklma at web.de Fri Jun 30 00:43:36 2006 From: buerklma at web.de (=?ISO-8859-15?Q?Martin_B=FCrkle?=) Date: Fri, 30 Jun 2006 06:43:36 +0200 Subject: No error while sending via TCP Socket Message-ID: Hi NG, I have writen a programm using TCP sockets. After i get the connection to another socket I cut the Ethernet cable. Then I send a message. The program doesnt raise any exception. Can somebody tell me why and give me a hint how to get an exception Thanks for your help. Martin From gene.tani at gmail.com Sun Jun 4 18:29:38 2006 From: gene.tani at gmail.com (gene tani) Date: 4 Jun 2006 15:29:38 -0700 Subject: Max function question: How do I return the index of the maximum value of a list? In-Reply-To: <1149459320.802652.186930@i40g2000cwc.googlegroups.com> References: <1149459320.802652.186930@i40g2000cwc.googlegroups.com> Message-ID: <1149460177.951294.30320@h76g2000cwa.googlegroups.com> jj_frap wrote: > I'm new to programming in Python and am currently writing a three-card > poker simulator. I have completed the entire simulator other than > determining who has the best hand (which will be far more difficult > than the aspects I've codes thus far)...I store each player's hand in a > list of hand objects and I determine hand strength via a handstrength > list with one element for each player. > > When I try to print the "winner" (I've not coded for kicker strength > and ties yet) via the max function, it returns the maximum value in the > list rather than the index associated with that value. > > How do I return the index? http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/306862 http://www.rubyquiz.com/quiz24.html From Serge.Orlov at gmail.com Fri Jun 16 13:56:35 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 16 Jun 2006 10:56:35 -0700 Subject: BeautifulSoup error References: Message-ID: <1150480595.935649.188270@h76g2000cwa.googlegroups.com> William Xu wrote: > Hi, all, > > This piece of code used to work well. i guess the error occurs after > some upgrade. > > >>> import urllib > >>> from BeautifulSoup import BeautifulSoup > >>> url = 'http://www.google.com' > >>> port = urllib.urlopen(url).read() > >>> soup = BeautifulSoup() > >>> soup.feed(port) > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/lib/python2.3/sgmllib.py", line 94, in feed Look at the traceback: you're not calling BeautifulSoup module! In fact, there is no feed method in the current BeautifulSoup documentation. Maybe it used to work well, but now it's definitely going to fail. As I understand documentation you need to write soup = BeautifulSoup(port) From beni.cherniavsky at gmail.com Sun Jun 4 18:23:05 2006 From: beni.cherniavsky at gmail.com (beni.cherniavsky at gmail.com) Date: 4 Jun 2006 15:23:05 -0700 Subject: Where is the ucs-32 codec? Message-ID: <1149459785.331497.203920@c74g2000cwc.googlegroups.com> Python seems to be missing a UCS-32 codec, even in wide builds (not that it the build should matter). Is there some deep reason or should I just contribute a patch? If it's just a bug, should I call the codec 'ucs-32' or 'utf-32'? Or both (aliased)? There should be '-le' and '-be' variats, I suppose. Should there be a variant without explicit endianity, using a BOM to decide (like 'utf-16')? And it should combine surrogates into valid characters (on all builds), like the 'utf-8' codec does, right? -- Beni Cherniavsky , who can only read email on weekends. From alanalan at newsgroup.nospam Thu Jun 1 10:42:40 2006 From: alanalan at newsgroup.nospam (A.M) Date: Thu, 1 Jun 2006 10:42:40 -0400 Subject: New to Python: Do we have the concept of Hash in Python? Message-ID: Hi, I am new to Python, with C#/Java background Is there any built-in Hash implementation in Python? I am looking for a container that I can access to it's items by name. Something like this: Print container["memeberName"] I am asking this because I learned that DB-API in Python doesn't offer access to cursor columns by name. The only option is access by index. I hope that I've got it wrong! I learned Ruby perfectly supports that. Thank you, Alan From fredrik at pythonware.com Fri Jun 30 02:56:24 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 30 Jun 2006 08:56:24 +0200 Subject: Bug reporting impossible References: <1151598979.369897.140770@x69g2000cwx.googlegroups.com> Message-ID: Nick Maclaren wrote: > |> Why would you have a file named '' in your current directory? > > Why would Python search for one? :-) > > In both cases, the normal answer is "Someone made a mistake" but, if > you have a script that creates a files of the same names specified in > the current directory, what name should it use if you specify stdin? given that "" is an invalid filename on some platforms, why would any serious programmer use "" for an external file ? > It is one of the standard conventions, which is (after all) why Python > is searching for it. the only reason Python's searching for it is that the CLI implementation passes "" as the second argument to compile: http://pyref.infogami.com/compile From jstobbs at gmail.com Tue Jun 6 03:11:59 2006 From: jstobbs at gmail.com (jstobbs at gmail.com) Date: 6 Jun 2006 00:11:59 -0700 Subject: python socket proxy Message-ID: <1149577919.811693.178730@f6g2000cwb.googlegroups.com> Hi all I am trying to create a lighweight tcp proxy server. I got this code from ActivePython documentation. What I am trying to accomplish, is I need to connect to local instance of the proxyserver (127.0.0.1). This server must then connect to a remote jabber server, send data, and listen to incoming data. When data arrives, it must relay it back thru 127.0.0.1. The reason why I need I am trying to get this to work, is I eventually want to make this server connect over ssl/tls (which macromedia flash doesnt support natively). The existing code only echoes back what it gets in, and note what it gets back from the remote server. Help would be appreciated [code] # Echo server program import socket HOST = '127.0.0.1' # Symbolic name meaning the local host PORT = 50007 # Arbitrary non-privileged port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) s.listen(1) conn, addr = s.accept() print 'Connected by', addr while 1: data = conn.recv(1024) print (data) if not data: break conn.send(data) conn.close() # Echo client program import socket HOST = 'remoteserver.com' # The remote host PORT = 5222 # The same port as used by the server s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) s.send('Hello, world') data = s.recv(1024) print data s.close() print 'Received', repr(data) [/code] thanks From pc at p-cos.net Fri Jun 23 07:32:22 2006 From: pc at p-cos.net (Pascal Costanza) Date: Fri, 23 Jun 2006 13:32:22 +0200 Subject: What is a type error? In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <7i3mg.204167$8W1.155367@fe1.news.blueyonder.co.uk> <44992e6c$2$664$bed64819@news.gradwell.net> <%Igmg.464974$xt.353729@fe3.news.blueyonder.co.uk> <4fv0v3F1kipa6U1@individual.net> Message-ID: <4g21q7F1lf5lsU1@individual.net> Matthias Blume wrote: > Pascal Costanza writes: > >> Chris Smith wrote: >> >>> While this effort to salvage the term "type error" in dynamic >>> languages is interesting, I fear it will fail. Either we'll all >>> have to admit that "type" in the dynamic sense is a psychological >>> concept with no precise technical definition (as was at least hinted >>> by Anton's post earlier, whether intentionally or not) or someone is >>> going to have to propose a technical meaning that makes sense, >>> independently of what is meant by "type" in a static system. >> What about this: You get a type error when the program attempts to >> invoke an operation on values that are not appropriate for this >> operation. >> >> Examples: adding numbers to strings; determining the string-length of >> a number; applying a function on the wrong number of parameters; >> applying a non-function; accessing an array with out-of-bound indexes; >> etc. > > Yes, the phrase "runtime type error" is actually a misnomer. What one > usually means by that is a situation where the operational semantics > is "stuck", i.e., where the program, while not yet arrived at what's > considered a "result", cannot make any progress because the current > configuration does not match any of the rules of the dynamic > semantics. > > The reason why we call this a "type error" is that such situations are > precisely the ones we want to statically rule out using sound static > type systems. So it is a "type error" in the sense that the static > semantics was not strong enough to rule it out. > >> Sending a message to an object that does not understand that message >> is a type error. The "message not understood" machinery can be seen >> either as a way to escape from this type error in case it occurs and >> allow the program to still do something useful, or to actually remove >> (some) potential type errors. > > I disagree with this. If the program keeps running in a defined way, > then it is not what I would call a type error. It definitely is not > an error in the sense I described above. If your view of a running program is that it is a "closed" system, then you're right. However, maybe there are several layers involved, so what appears to be a well-defined behavior from the outside may still be regarded as a type error internally. A very obvious example of this is when you run a program in a debugger. There are two levels involved here: the program signals a type error, but that doesn't mean that the system as a whole is stuck. Instead, the debugger takes over and offers ways to deal with the type error. The very same program run without debugging support would indeed simply be stuck in the same situation. So to rephrase: It depends on whether you use the "message not understood" machinery as a way to provide well-defined behavior for the base level, or rather as a means to deal with an otherwise unanticipated situation. In the former case it extends the language to remove certain type errors, in the latter case it provides a kind of debugging facility (and it indeed may be a good idea to deploy programs with debugging facilities, and not only use debugging tools at development time). This is actually related to the notion of reflection, as coined by Brian C. Smith. In a reflective architecture, you distinguish between various interpreters, each of which interprets the program at the next level. A debugger is a program that runs at a different level than a base program that it debugs. However, the reflective system as a whole is "just" a single program seen from the outside (with one interpreter that runs the whole reflective tower). This distinction between the internal and the external view of a reflective system was already made by Brian Smith. Pascal -- 3rd European Lisp Workshop July 3 - Nantes, France - co-located with ECOOP 2006 http://lisp-ecoop06.bknr.net/ From dnew at san.rr.com Tue Jun 20 11:52:46 2006 From: dnew at san.rr.com (Darren New) Date: Tue, 20 Jun 2006 15:52:46 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: <1150815461.210286.53120@r2g2000cwb.googlegroups.com> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <1150809118.677124.142230@u72g2000cwu.googlegroups.com> <1150815461.210286.53120@r2g2000cwb.googlegroups.com> Message-ID: Rob Thorpe wrote: > Yes, but the point is, as the other poster mentioned: values defined by > a class. A value can only represent one value, right? Or can a value have multiple values? > For example, in lisp: > "xyz" is a string, "xyz" cannot represent values from the class of strings. It can only represent one value. I think that's what the others are getting at. >>They all have - the whole purpose of a type system is to ensure that any >>expression of type T always evaluates to a value of type T. > > But it only gaurantees this because the variables themselves have a > type, the values themselves do not. Sure they do. 23.5e3 is a "real" in Pascal, and there's no variable there. ("hello" % "there") is illegal in most languages, because the modulo operator doesn't apply to strings. How could this be determined at compile time if "hello" and "there" don't have types? -- Darren New / San Diego, CA, USA (PST) My Bath Fu is strong, as I have studied under the Showerin' Monks. From night117 at gmail.com Thu Jun 8 10:11:56 2006 From: night117 at gmail.com (NightHawk) Date: 8 Jun 2006 07:11:56 -0700 Subject: From Python to Shell Message-ID: <1149775916.711309.260170@i40g2000cwc.googlegroups.com> Im not a total noob but i don't know the command and the module to go from python to the default shell. (not from interactive mode - $python) From reply.in.the.newsgroup at my.address.is.invalid Fri Jun 2 21:03:02 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Sat, 03 Jun 2006 03:03:02 +0200 Subject: beginner code problem References: <2006060218415316807-victimorcrime@yahoocom> Message-ID: <8on182l21bp9fg8omqiq68vddhc42j87d5@4ax.com> RJ: >import random >flip = random.randrange(2) >heads = 0 >tails = 0 >count = 0 >while count < 100: > if flip == 0: > heads += 1 > else: > tails += 1 > count += 1 Since flip isn't changed in the loop, this is going to report 100 heads or 100 tails, depending on the zeroness of flip. -- Ren? Pijlman From petr at tpc.cz Mon Jun 12 00:51:22 2006 From: petr at tpc.cz (Petr Jakes) Date: 11 Jun 2006 21:51:22 -0700 Subject: Most elegant way to generate 3-char sequence In-Reply-To: <1150061829.075501.117380@y43g2000cwc.googlegroups.com> References: <1149889784.391965.271570@h76g2000cwa.googlegroups.com> <1150061829.075501.117380@y43g2000cwc.googlegroups.com> Message-ID: <1150087882.546855.210320@c74g2000cwc.googlegroups.com> sam wrote: > I have found that the more elegant the code is, the harder it is for me > to understand what it is trying to accomplish. It is my opinion that > "Keep It Simple" wins over elegance. When I have had the urge to get > elegant, I make sure I comment the elegance so my less elegant > co-workers can figure out what I was trying to accomplish. > > Sam Schulenburg +1 Petr Jakes From jerry.levan at gmail.com Fri Jun 2 15:53:35 2006 From: jerry.levan at gmail.com (jerry.levan at gmail.com) Date: 2 Jun 2006 12:53:35 -0700 Subject: wxPython problems with Fedora Core 5 In-Reply-To: <1149271626.481398.34440@h76g2000cwa.googlegroups.com> References: <1149271626.481398.34440@h76g2000cwa.googlegroups.com> Message-ID: <1149278015.617652.23350@y43g2000cwc.googlegroups.com> writeson wrote: > Hi all, > > I'm trying to use wxPython from a fairly new installation of Fedora > Core 5. I installed wxPython using yum -y install wxPython and that all > seemed to work fine. However, when I run Python and do this: > > import wx > > I get this: > > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/lib/python2.4/site-packages/wx/__init__.py", line 45, in ? > from wxPython import wx > File "/usr/lib/python2.4/site-packages/wxPython/__init__.py", line > 20, in ? > import wxc > ImportError: /usr/lib/libwx_gtk2-2.4.so.0: undefined symbol: > pango_x_get_context > > Anyone have any ideas what's going on and what I can do to fix this? > > Thanks in advance, > Doug Check the FC5 Forums, I think the basic answer was to remove the python "compat" rpms. Jerry From ilias at lazaridis.com Mon Jun 5 06:44:10 2006 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Mon, 05 Jun 2006 13:44:10 +0300 Subject: HOST - dreamhost.com / Liberality (Hosting, Basic Requirement) In-Reply-To: <878xockoj5.fsf@tiger.rapttech.com.au> References: <4482CDDA.9060905@lazaridis.com> <878xockoj5.fsf@tiger.rapttech.com.au> Message-ID: Tim X wrote: [...] > I think the other point here is that everyone *assumes* Xah's account > was cancelled simply because of a campaign to report him for spamming > multiple newsgroups. I suspect there were other factors involved. for > all anyone knows, the provider might have been getting complaints from > people about Xah's account, website, e-mail and newsgorup posting for > ages and just decided it was more trouble than it was worth to keep > him as a customer. [...] > On usernet, I think the secret is "believe nothing, question > everything" and remember, on the net, nobody knows your a dog! I understand what you mean. I've written in my message: "It _seems_ that Mr. Xah Les's account was terminated by dreamhost.com because of " " To dreamhost.com: [...] Additionally, it would be gentle if your company would make a _public_ statement subjecting this case, thus any interested party can verify the validity of the statements. " . -- http://lazaridis.com From martin at v.loewis.de Fri Jun 30 19:34:07 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 01 Jul 2006 01:34:07 +0200 Subject: handling unicode data In-Reply-To: <1151684068.319765.42270@y41g2000cwy.googlegroups.com> References: <1151506510.391856.207460@y41g2000cwy.googlegroups.com> <1151514404.954008.282280@b68g2000cwa.googlegroups.com> <1151516742.596423.157450@b68g2000cwa.googlegroups.com> <1151684068.319765.42270@y41g2000cwy.googlegroups.com> Message-ID: <44a5b4f0$0$29917$9b622d9e@news.freenet.de> Filipe wrote: > ---- output ------------------------------------------- > u'Fran\xd8a' > Fran?a > -------------------------------------------------------- > > > What do you think? Might it be Pymssql doing something wrong? I think the data in your database is already wrong. Are you sure the value in question is really "Fran?a" in the database? Regards, Martin From andrewdalke at gmail.com Thu Jun 15 11:06:32 2006 From: andrewdalke at gmail.com (andrewdalke at gmail.com) Date: 15 Jun 2006 08:06:32 -0700 Subject: __lt__ slowing the "in" operator even if not called In-Reply-To: <1150318630.203249.191250@r2g2000cwb.googlegroups.com> References: <1150318630.203249.191250@r2g2000cwb.googlegroups.com> Message-ID: <1150383992.319124.128520@h76g2000cwa.googlegroups.com> Emanuele Aina wrote: > I have some code which does a lot of "in" on lists containing objects > with no __eq__ defined. > > It all goes fast until I add the __lt__() method: then I have a > slowdown comparable to the one I get using the overridden __eq__, while > the __lt__ method is never called. > > Someone can explain me why? The list's __contains__ method is very simple for (i = 0, cmp = 0 ; cmp == 0 && i < a->ob_size; ++i) cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i), Py_EQ); The PyObject_RichCompareBool becomes more complex. The relevant code occurs after the check for object identity. The next step is res = PyObject_RichCompare(v, w, op); which goes into your case /* If the types are equal, and not old-style instances, try to get out cheap (don't bother with coercions etc.). */ if (v->ob_type == w->ob_type && !PyInstance_Check(v)) { cmpfunc fcmp; richcmpfunc frich = RICHCOMPARE(v->ob_type); /* If the type has richcmp, try it first. try_rich_compare tries it two-sided, which is not needed since we've a single type only. */ if (frich != NULL) { res = (*frich)(v, w, op); if (res != Py_NotImplemented) goto Done; Py_DECREF(res); } /* No richcmp, or this particular richmp not implemented. Try 3-way cmp. */ fcmp = v->ob_type->tp_compare; One new-style class defines '__lt__' while the other does not. Here's where things get shaky for me. I think new-style classes are instances of PyInstanceObject (and not PyClassObject). Instances use 'instance_richcompare' to implement the rich comparison between two instances. This function does the lookup for '__eq__' in the two classes. The tp_richcompare slot is set to instance_richcompare when any of __lt__, __gt__, __eq_, etc. are defined in a new type. The macro- based code looks like TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt, "x.__lt__(y) <==> x x<=y"), TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq, "x.__eq__(y) <==> x==y"), TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne, "x.__ne__(y) <==> x!=y"), TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt, "x.__gt__(y) <==> x>y"), TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge, "x.__ge__(y) <==> x>=y"), So if you define "__lt__" in your object then the type gets a richcmp function and your == test implicit in the 'in' search always incurs the cost of figuring out that "__eq__" is not defined. Andrew dalke at dalkescientific.com From gandalf at designaproduct.biz Thu Jun 8 16:55:20 2006 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Thu, 08 Jun 2006 22:55:20 +0200 Subject: Importing again and again In-Reply-To: <1149796920.757115.290840@h76g2000cwa.googlegroups.com> References: <1149796920.757115.290840@h76g2000cwa.googlegroups.com> Message-ID: <44888EB8.1010605@designaproduct.biz> abcd ?rta: > If I have code which imports a module over and over again...say each > time a function is called, does that cause Python to actually re-import > it...or will it skip it once the module has been imported?? > > for example: > > def foo(): > import bar > bar.printStuff() > > foo() > foo() > foo() > foo() > > ...will that re-import bar 4 times...or just import it once? Just once. Try this: bar.py: print "I have been imported" def printStuff(): print "printStuff was called" foo.py: def foo(): import bar bar.printStuff() foo() foo() foo() The result is: I have been imported printStuff was called printStuff was called printStuff was called If you really need to reimport the module, you can do this: foo.py: import bar def foo(): global bar bar = reload(bar) bar.printStuff() foo() foo() foo() The result is: I have been imported I have been imported printStuff was called I have been imported printStuff was called I have been imported printStuff was called > Is this a big performance hit? > It depends on the size of your 'bar.py' module, and also it depends on how often you need to change/reload while your program is running. Best, Laszlo From uval at rz.uni-karlsruhe.de Thu Jun 8 20:39:55 2006 From: uval at rz.uni-karlsruhe.de (=?ISO-8859-1?Q?Sch=FCle_Daniel?=) Date: Fri, 09 Jun 2006 02:39:55 +0200 Subject: Importing again and again In-Reply-To: <1149796920.757115.290840@h76g2000cwa.googlegroups.com> References: <1149796920.757115.290840@h76g2000cwa.googlegroups.com> Message-ID: it's import-ed only once # magic.py file #!/usr/bin/python print "here" import magic # try to import itself then try # bad_magic.py #!/usr/bin/python print "here" import bad_magic reload(bad_magic) hth, Daniel From maric at aristote.info Mon Jun 26 12:42:11 2006 From: maric at aristote.info (Maric Michaud) Date: Mon, 26 Jun 2006 18:42:11 +0200 Subject: Replace Whole Object Through Object Method In-Reply-To: <1151337453.804750.293180@b68g2000cwa.googlegroups.com> References: <1151337453.804750.293180@b68g2000cwa.googlegroups.com> Message-ID: <200606261842.12403.maric@aristote.info> Le lundi 26 juin 2006 17:57, digitalorganics at gmail.com a ?crit?: > How can an object replace itself using its own method? See the > following code: > > class Mixin: > def mixin(object, *classes): > NewClass = type('Mixin', (object.__class__,) + classes, {}) > newobj = NewClass() > newobj.__dict__.update(object.__dict__) > return newobj > Variables in python are names, not the objects, and instances shouldn't know nothing about how they are referenced. I guess what you want to do is, in fact, very simple somethig like : a = SomeClass() a = a.some_method_wich_return_a_new_object() or : for k, v in globals().iteritems() : if isinstance(v, SomeClass) : globlals()[k] = v.some_method_wich_return_a_new_object() > def isClass(object): Don't mask builtin names. > if 'classobj' in str(type(object)): Why don't you test the type directly ? > return 1 Python has boolean for clarity. > elif "'type'" in str(type(object)): > return 1 > else: > return 0 should be : import types def isClass(object_) : if isinstance(object_, type) : return True # new style class elif isinstance(object_, types.ClassType) : return True # old-style class else : return False or if you don't need to diferentiate the cases : def isClass(object_) : return isinstance(object_, type) or \ isinstance(object_, types.ClassType) > def listClasses(): > classes = [] > for eachobj in globals().keys(): > if isClass(globals()[eachobj]): > classes.append(globals()[eachobj]) > print eachobj > return classes > > def MixInto(Class, Mixin): > if Mixin not in Class.__bases__: > Class.__bases__ += (Mixin,) This doesn't work in most cases (with new style classes), better recreat a type which inherit from Class and Mixin, or Class.__dict__ with Mixin.__dict__. > ------------------------------------------------------------------------ > > Okay, so the mixin function becomes part of whatever class I choose and > hence its instances, but the problem is that the way I currently have > it setup mixin() returns a new object, instead of replacing whatever > class instance that calls it into that new object. I hope I'm making > sense here. > > Basically what I need is for the method to be able to find out the name > of the instance, then I can just go to the globals dictionary to do the > replacement. > > Advance thanks to all who can help... -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From george.sakkis at gmail.com Wed Jun 14 23:56:43 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 14 Jun 2006 20:56:43 -0700 Subject: split with "*" in string and ljust() puzzles References: <1150330131.466322.135350@i40g2000cwc.googlegroups.com> Message-ID: <1150343803.705236.292650@r2g2000cwb.googlegroups.com> Serge Orlov wrote: > Sambo wrote: > > I have just (finally) realized that it is splitting and removing > > on single space but that seams useless, and split items > > 1 and 2 are empty strings not spaces?? > > What is useless for you is worth $1,000,000 for somebody else ;) > If you have comma separated list '1,,2'.split(',') naturally returns > ['1', '', '2']. I think you can get what you want with a simple regexp. No need for regexp in this case, just use None to specify one or more whitespace chars as delimiter: line.split(None,3) George From boris.lorbeer at science-computing.de Sun Jun 11 07:23:35 2006 From: boris.lorbeer at science-computing.de (boris) Date: 11 Jun 2006 04:23:35 -0700 Subject: package search In-Reply-To: References: <1150009850.738535.155550@m38g2000cwc.googlegroups.com> Message-ID: <1150025015.646123.278460@u72g2000cwu.googlegroups.com> Sybren Stuvel wrote: > Simplicity and explicitness. You have two packages 'foo', and it > simply loads the first one it finds. Yes, here you are right. It is indeed simple. Boris From sjmachin at lexicon.net Fri Jun 16 20:13:21 2006 From: sjmachin at lexicon.net (John Machin) Date: Sat, 17 Jun 2006 10:13:21 +1000 Subject: Noob script needs some input: CVS PatchMaker In-Reply-To: <1150450094.544961.189540@i40g2000cwc.googlegroups.com> References: <1150450094.544961.189540@i40g2000cwc.googlegroups.com> Message-ID: <44934921.7080208@lexicon.net> On 16/06/2006 7:28 PM, Holger wrote: > Well, that was an excellent opportunity to get some python practice, so > below is my first shot at the problem. > > Any feedback on what would be "the pythonic way" to do this would be > much appreciated! > > #!/usr/bin/env python > # Copyright 2006 Holger Lindeberg Bille > > import sys, re, os > import popen2 > > workingfile = re.compile("^Working file: *(.*)$") > revision = re.compile("^revision *(.*)$") > fileend = > re.compile("^===========================================================================") > details = re.compile("^date: *") > entryend = re.compile("^----------------------------") > branches = re.compile("^branches:( *(.*);)*") > > class LogEntry: > def __init__(self): > self.rev = 0 > self.prevrev = 0 > self.text = [] > > def setName(self, name): > self.name = name > > def read(self, file): > done = 0 > for line in file: > regx = details.search(line) > if regx: > pass > else: > if entryend.search(line): > break > else: > if fileend.search(line): > done = 1 > break > else: > self.text.append(line.strip()) > return done IMHO that flight of geese heading equatorwards for winter is not Xic for any language X. Compare with: | def read(self, file): | done = 0 | for line in file: | regx = details.search(line) | if regx: | pass | elif entryend.search(line): | break | elif fileend.search(line): | done = 1 | break | else: | self.text.append(line.strip()) | return done 2nd comment: Make a habit of NOT using the names of built-ins like "file" for your own names. Pretend they are reserved words. Doesn't matter in this case, but will save you grief some day soon. 3rd comment: Read the section in the re manual that explains the difference between search and match. Searching for "^foo" will give the same results as using match() with "foo" or the redundantly anchored "^foo". However some regex engines when presented with re.search("^foo", "x" * 10000) will note that there is no joy at offset 0, there is no point (given the anchor "^") of looking at offset 1, and return almost immediately. Others (cough, cough) will check at offset 1, 2, ... Ponder these results: python -mtimeit -s"import re;rx=re.compile('^foo');txt='x'*10000" "rx.match(txt)" 100000 loops, best of 3: 1.2 usec per loop python -mtimeit -s"import re;rx=re.compile('foo');txt='x'*10000" " rx.search(txt)" 10000 loops, best of 3: 19.8 usec per loop python -mtimeit -s"import re;rx=re.compile('^foo');txt='x'*10000" "rx.search(txt)" 1000 loops, best of 3: 201 usec per loop 4th comment: what you have called "regx" is a match object. "mobj" might be a better choice. The term "regex" is applied to a pattern, or sometimes to the compiled re object. > def GuessPrevRev(self): > pass > > def filter(self, filter): Ugh. THREE filters: the built-in, the argument, and the method. In any case, this method doesn't perform a filtering operation, and the arg is not a filter, it's an re pattern. Suggestion: def anyLinesMatch(self, pattern): > found = 0 > for line in self.text: > if filter.search(line): > found = 1 > break > return found [snip] > class FileLog: > def __init__(self): > self.revs = [] > [snip] > > def filter(self, filter): > found = 0 > newrevs = [] > for rev in self.revs: > if rev.filter(filter): Waahhh! The filter count has now hit 4. > found = 1 > newrevs.append(rev) > self.revs = newrevs > return found > [snip] > > class LogDB: > def __init__(self): > self.flogs = [] [snip] > def filter(self, filter): > newflogs = [] > for flog in self.flogs: > if flog.filter(filter): See above. > newflogs.append(flog) > self.flogs = newflogs > [snip] HTH, John From cdsmith at twu.net Wed Jun 21 23:29:09 2006 From: cdsmith at twu.net (Chris Smith) Date: Wed, 21 Jun 2006 21:29:09 -0600 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150892256.591282.43880@u72g2000cwu.googlegroups.com> Message-ID: Rob Warnock wrote: > Another language which has *neither* latent ("dynamic") nor > manifest ("static") types is (was?) BLISS[1], in which, like > assembler, variables are "just" addresses[2], and values are > "just" a machine word of bits. I'm unsure that it's correct to describe any language as having no latent typing, in the sense that's being used in this thread. It might be more correct to say "so specified latent typing" and/or "no latent typing beyond what is provided by the execution environment, including the CPU, virtual memory system, etc." as appropriate. I am aware of no hardware environment that really accepts all possible values for all possible operations without the potential of somehow signaling a type violation. -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation From tjreedy at udel.edu Fri Jun 2 15:15:37 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 2 Jun 2006 15:15:37 -0400 Subject: win32com: how to connect to a specific instance of a runningobject? References: <1149254270.790703.145700@j55g2000cwa.googlegroups.com><1149260253.337452.65770@c74g2000cwc.googlegroups.com> <1149273628.486179.224680@h76g2000cwa.googlegroups.com> Message-ID: "ago" wrote in message news:1149273628.486179.224680 at h76g2000cwa.googlegroups.com... > solved, if it can be useful to others here is my code: > > import pythoncom > import win32com.client > > def getWorkbook(workbookName): > lenstr = len(workbookName) > workbook = None > rot = pythoncom.GetRunningObjectTable() > rotenum = rot.EnumRunning() > while True: > monikers = rotenum.Next() > if not monikers: break > ctx = pythoncom.CreateBindCtx(0) > name = monikers[0].GetDisplayName(ctx, None); > if name[-lenstr:] == workbookName: > obj = rot.GetObject(monikers[0]) > workbook = > win32com.client.Dispatch(obj.QueryInterface(pythoncom.IID_IDispatch)) > return workbook Perhaps you can submit this to the Python Cookbook at oreilly.com (sp?) From jmdeschamps at gmail.com Thu Jun 15 16:04:50 2006 From: jmdeschamps at gmail.com (jmdeschamps at gmail.com) Date: 15 Jun 2006 13:04:50 -0700 Subject: billionlaughs, on me :-(( - on winXP help! In-Reply-To: References: <1150397596.520219.125780@c74g2000cwc.googlegroups.com> Message-ID: <1150401890.073634.131930@h76g2000cwa.googlegroups.com> Fredrik Lundh wrote: > jmdeschamps at gmail.com wrote: > > > Looking up different blogs etc on xml parsers I wind up on the site of > > Computer stuff, www.razorvine.net. > > And in the browser torture section, the billionlaughs.xml link (that > > you shouldn't use if you don't know what your doing, as was my case > > (mea culpa)) ... > > reboot as usual, and the next time you see a link that says "do NOT > click if you don't know what you're doing", don't click on it. > > Right ;-) and thanks for your very fast reply ! From johnlichtenstein at gmail.com Sun Jun 4 15:04:55 2006 From: johnlichtenstein at gmail.com (johnlichtenstein at gmail.com) Date: 4 Jun 2006 12:04:55 -0700 Subject: how not to run out of memory in cursor.execute Message-ID: <1149447895.037396.81550@j55g2000cwa.googlegroups.com> I am using cx_Oracle and MySQLdb to pull a lot of data from some tables and I find that the cursor.execute method uses a lot of memory that never gets garbage collected. Using fetchmany instead of fetchall does not seem to make any difference, since it's the execute that uses memory. Breaking the query down to build lots of small tables doesn't help, since execute doesn't give its memory back, after reading enough small tables execute returns a memory error. What is the trick to get memory back from execute in cx_Oracle and MySQLdb? From girish at cse.iitb.ac.in Wed Jun 7 02:11:06 2006 From: girish at cse.iitb.ac.in (Girish Sahani) Date: Wed, 7 Jun 2006 11:41:06 +0530 (IST) Subject: Reading from a file and converting it into a list of lines In-Reply-To: <44852F2C.80509@lexicon.net> References: <1149534126.129714.131860@f6g2000cwb.googlegroups.com> <1149535195.763340.220010@y43g2000cwc.googlegroups.com> <44851010.6070503@lexicon.net> <44852F2C.80509@lexicon.net> Message-ID: <40818.10.209.4.1.1149660666.squirrel@10.105.1.3> > On 6/06/2006 4:15 PM, Girish Sahani wrote: >> Really sorry for that indentation thing :) >> I tried out the code you have given, and also the one sreeram had >> written. >> In all of these,i get the same error of this type: >> Error i get in Sreeram's code is: >> n1,_,n2,_ = line.split(',') >> ValueError: need more than 1 value to unpack >> >> And error i get in your code is: >> for n1, a1, n2, a2 in reader: >> ValueError: need more than 0 values to unpack >> >> Any ideas why this is happening? > > In the case of my code, this is consistent with the line being empty, > probably the last line. As my mentor Bruno D. would say, your test data > does not match your spec :-) Which do you want to change, the spec or > the data? Thanks John, i just changed my Data file so as not to contain any empty lines, i guess that was the easier solution ;) > > You can change my csv-reading code to detect dodgy data like this (for > example): > > for row in reader: > if not row: > continue # ignore empty lines, wherever they appear > if len(row) != 4: > raise ValueError("Malformed row %r" % row) > n1, a1, n2, a2 = row > > In the case of Sreeram's code, perhaps you could try inserting > print "line = ", repr(line) > before the statement that is causing the error. > > >> >> Thanks a lot, >> girish >> >> >> > -- > http://mail.python.org/mailman/listinfo/python-list > From g.brandl-nospam at gmx.net Thu Jun 22 12:33:17 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Thu, 22 Jun 2006 18:33:17 +0200 Subject: struct.unpack on 64-bit platforms In-Reply-To: <1150993826.726685.301740@p79g2000cwp.googlegroups.com> References: <1150993826.726685.301740@p79g2000cwp.googlegroups.com> Message-ID: Nadav Samet wrote: > Hi, > > I am trying to unpack a 32-bit unsigned integer from a string using > struct.unpack. > so using string.unpack('L', data) would work fine on 32-bit systems, > > But apparently, on 64-bit platforms it tries to read 64-bit unsigned > integer (since > that's what the C Type unsigned long means on 64-bit platforms). > > So what's the way to make it read exactly 32-bits, on all platforms? Looking into the docs, prepending your format string with "=" should make "L" exactly 32 bits on each platform. Georg From rbann11 at hotmail.com Sat Jun 3 16:25:31 2006 From: rbann11 at hotmail.com (rbann11 at hotmail.com) Date: 3 Jun 2006 13:25:31 -0700 Subject: wxpython wxgrid question Message-ID: <1149366330.999234.299880@u72g2000cwu.googlegroups.com> Hi, I am looking for example code that consists of just a frame and a grid(10x2). The grid must fill the its parent even if the frame is resized. Thanks in advance, Roger From rogue_pedro at yahoo.com Fri Jun 30 21:34:44 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 30 Jun 2006 18:34:44 -0700 Subject: list comprehension In-Reply-To: <1151713797.748621.294120@i40g2000cwc.googlegroups.com> References: <1151600332.552024.119990@y41g2000cwy.googlegroups.com> <1151602493.629010.269360@i40g2000cwc.googlegroups.com> <1151713797.748621.294120@i40g2000cwc.googlegroups.com> Message-ID: <1151717684.199257.191880@m73g2000cwd.googlegroups.com> a wrote: > hi simon thanks for your reply You're most welcome > what if i want to do this > feed_list=[] > feed_id=[] > for ix in feeds_list_select: > global feeds_list > global feeds_id > feeds_list.append(ix.url) > feeds_id.append(ix.id) > > ie not one variable but more variables > thanks in a case like this I would usually reach for the zip() function, with the "varargs" * calling pattern N = [(ix.url, ix.id) for ix in feeds_list_select] feed_list, feed_id = zip(*N) or just feed_list, feed_id = zip(*[(ix.url, ix.id) for ix in feeds_list_select]) btw, please note that the global statements in your example are unnecessary.. *totally* unnecessary. :-D From greg.kujawa at gmail.com Thu Jun 1 13:17:45 2006 From: greg.kujawa at gmail.com (gregarican) Date: 1 Jun 2006 10:17:45 -0700 Subject: New to Python: Do we have the concept of Hash in Python? References: Message-ID: <1149182265.257263.159210@f6g2000cwb.googlegroups.com> Lemme see, starting *and* finishing a project in a language you've never practically used before within a day's time? Sounds like a clip from next season's opener of the TV show '24' to me. I came from using Ruby about a year or so and even then it took a couple of days of browsing through the Python docs and playing around until I could consider myself somewhat useful. Coming from Java and C# might make the departure a little steeper. Good luck! A.M wrote: > "Fredrik Lundh" wrote in message > news:mailman.6414.1149178232.27775.python-list at python.org... > > "A.M" wrote: > > > >> I am new to Python, with C#/Java background > > > > that's not really much of an excuse for not reading *any* Python tutorial > > before > > you jump in... > > Hi Fredrik, > > 1st of all, I am really impressed by this Python community. Answers are > helpful and I am having excellent progress. I appreciate everybody's help. > > > > This is my 1st day that I am seriously diving into Python and I have to > finish this application by the end of today. Maybe it wasn't a good idea to > choose the language that I don't know when I have to deliver my work in such > short time. I understand that my question might seems very trivial to you, > but please consider the fact that I am in time pressure and I cannot go > through a 400 book today. I promises I'll do that this weekend ;) Wish luck > for me! > > > > Thank you for your post, > > Alan From codecraig at gmail.com Mon Jun 12 13:30:02 2006 From: codecraig at gmail.com (abcd) Date: 12 Jun 2006 10:30:02 -0700 Subject: Network Ports - blocking / taking over Message-ID: <1150133401.974829.167550@g10g2000cwb.googlegroups.com> Just curious if anyone had any information, or links, regarding the blocking of network ports and/or taking over (hijacking) ports using Python. Any python modules/libs you could recommend? tutorials/reading materials? Thanks in advance. From bignose+hates-spam at benfinney.id.au Thu Jun 1 03:52:00 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 01 Jun 2006 17:52:00 +1000 Subject: shuffling elements of a list References: <1149045499.212967.13120@f6g2000cwb.googlegroups.com> <1149147164.012044.66960@u72g2000cwu.googlegroups.com> Message-ID: <87bqtdz527.fsf@benfinney.id.au> "Gerard Flanagan" writes: > Ben Finney wrote: > > pile_index = 0 > > for card in deck: > > piles[pile_index].append(card) > > pile_index = (pile_index + 1) % numpiles > > > > no need to maintain an index ;-) > > piles = [ list() for _ in range(n) ] > for i, card in enumerate(deck): > piles[i % numpiles].append(card) That's a matter of style. I prefer what I wrote, since I've given an explicit name to the calculation you're doing inside the [] operator; that way, anyone reading the code knows *why* the calculation is done in this particular case. If, of course, the index was a simple increment-by-one each time, your 'enumerate' usage would be clearer. -- \ "We spend the first twelve months of our children's lives | `\ teaching them to walk and talk and the next twelve years | _o__) telling them to sit down and shut up." -- Phyllis Diller | Ben Finney From girish at cse.iitb.ac.in Mon Jun 5 21:28:57 2006 From: girish at cse.iitb.ac.in (Girish Sahani) Date: Tue, 6 Jun 2006 06:58:57 +0530 (IST) Subject: How to generate all k-1 level substrings of a string? In-Reply-To: References: Message-ID: <36169.10.209.4.1.1149557337.squirrel@10.105.1.3> I want to generate all substrings of size k-1 from a string of size k. e.g 'abcd' should give me ['abc','abd','bcd','acd'] Order of these strings in the list doesnt matter. Also order doesnt matter inside the string e.g 'abc' or 'bca' or 'bac' is the same. I wrote the following code but it doesnt give the full output: subsetList = [] for element in prunedNew: for i in range(0,2): subsetList.append(element[i:i+len(element)-1]) continue continue return prunedNew Thanks in Advance, girish From fredrik at pythonware.com Wed Jun 28 03:58:29 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 28 Jun 2006 09:58:29 +0200 Subject: How to measure execution time of a program References: <54032.10.209.4.1.1151481158.squirrel@10.105.1.3> Message-ID: Girish Sahani wrote: > Can anyone tell me the simplest way to do it (some code snippet that > could be included in the program's main function) ?? simplest way: t0 = time.time() main() print time.time() - t0, "seconds" (assuming that you want to measure wall time, and that your program runs for at least a tenth of second, or so. for benchmarking of short code snippets, see the "timeit" module) From jmbc at nospam.fr Mon Jun 12 14:46:49 2006 From: jmbc at nospam.fr (jean-michel bain-cornu) Date: Mon, 12 Jun 2006 20:46:49 +0200 Subject: Boa constructor- is it still alive? In-Reply-To: References: Message-ID: <448db6db$0$7764$7a628cd7@news.club-internet.fr> tatamata a ?crit : > Does anyone know is Boa constructor project still alive? > I visited Boa web site and it seems that it hasn't been updated for a long > time.... > I downloaded the version 0.4.4 a couple of months ago, so I guess the project is alive (I have been used the 0.3.1 before). I hope so because I use it and I think there are some nice features (actually, I think it's the best IDE, above all if wx is needed). However, I tried the last year to suggest corrections, but without success. Also, it works better on windows than linux. Regards, jm From hancock at anansispaceworks.com Tue Jun 27 23:01:45 2006 From: hancock at anansispaceworks.com (Terry Hancock) Date: Tue, 27 Jun 2006 22:01:45 -0500 Subject: Verify PyProtocols interfaces? Message-ID: <44A1F119.6060802@anansispaceworks.com> Hi all, PyProtocols is a very nice interface/component/adapter library, but it appears to lack one thing I'm quite hooked on, which is the ability to verify that objects implement a given interface. I'd like something like the 'verify' functionality that Zope3 interfaces provide. Is there something 3rd party that would do the trick? I suppose it wouldn't be that hard to write something that will walk the Interface and check signatures and attributes against the object, but I was sort of hoping I wouldn't have to write this part. Unfortunately, this is kind of hard to google for, because all the relevant words are too common. Cheers, Terry -- Terry Hancock (hancock at AnansiSpaceworks.com) Anansi Spaceworks http://www.AnansiSpaceworks.com From kay.schluehr at gmx.net Fri Jun 30 06:20:12 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 30 Jun 2006 03:20:12 -0700 Subject: Reddit broke - should have remained on Lisp? In-Reply-To: <1151662301.891275.166300@d56g2000cwd.googlegroups.com> References: <1151626961.232761.255550@d56g2000cwd.googlegroups.com> <1151662301.891275.166300@d56g2000cwd.googlegroups.com> Message-ID: <1151662812.571023.205500@d56g2000cwd.googlegroups.com> Tayssir John Gabbour wrote: > Alok wrote: > > "reddit broke (sorry)" > > "looks like we shouldn't have stopped using lisp..." > > > > See screenshot at > > http://photos1.blogger.com/blogger/1773/1980/1600/reddit-broke.jpg > > > > Whether they truly repent not using lisp or otherwise, their site > > appears to be 3 times slower ... > > Hi Alok, > > Supposedly, the Reddit team had a bit of remorse (though of course, we > should take the following writeup with a grain of salt; maybe there are > more in-depth sources online): > "If we could do it all over again, we'd still be using Lisp. Probably." > "Reddit: Stick with Lisp. If you want it done right, do it yourself- > hosting- Avoid A+.net" > http://notelab.infogami.com/startupschool2006 Please, since this is a Python+Lisp cross-thread and you seem to have background info: can you explain why Lisp hackers have turned themselves into Python newbies for Reddit impl. and finally complain about the language switch? What was cause for their decision to use Python in the first place? From hacker1017 at yahoo.com Sun Jun 4 15:31:12 2006 From: hacker1017 at yahoo.com (hacker1017) Date: Sun, 04 Jun 2006 19:31:12 -0000 Subject: what are you using python language for? Message-ID: im just asking out of curiosity. From olsongt at verizon.net Tue Jun 20 10:00:06 2006 From: olsongt at verizon.net (olsongt at verizon.net) Date: 20 Jun 2006 07:00:06 -0700 Subject: Debugging C++ code called from Python 2.2 with Visual Studio.NET In-Reply-To: <1150799634.503338.302780@b68g2000cwa.googlegroups.com> References: <1150799634.503338.302780@b68g2000cwa.googlegroups.com> Message-ID: <1150812006.311261.99140@y41g2000cwy.googlegroups.com> egodet at equisys.com wrote: > Hi, > I'm trying to debug some VS native C++ code called from a python script > (version is 2.2). > For that, I added the _DEBUG macro in Setup.py but when I rebuild the > pyd file, I get a compilation error whereby it says that python22_d.lib > could not be found. > > I've seen in various groups that python22_d.lib is not available for > download anymore but that it is easy to recompile. Could someone send > it to me, explain how to build it or, even better, both. > > I expect that after that, if I recompile the python pyd file, I will be > able to attach a debugger to it. Could someone confirm this? > > Cheers, > Emmanuel > > PS: I'm new to Python and I'm using legacy code. To elaborate on Frederick's advice, the source .tgzs available on python.org contain everything you need to build the windows version, excluding a few modules that require third-party dependancies (tkinter, ssl, zip, bzip2 and probably a few others). You'll need VC6.0 as well for 2.2. From johnjsal at NOSPAMgmail.com Thu Jun 15 11:34:23 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 15 Jun 2006 15:34:23 GMT Subject: Python is fun (useless social thread) ;-) In-Reply-To: References: Message-ID: <36fkg.2312$No6.48470@news.tufts.edu> Jarek Zgoda wrote: > And I still don't get this "web application" hype, and all these "web > frameworks" scare me, as I internally don't trust any magic. > Yeah, I dabbled with CGI, but I haven't seriously looked into anything like TurboGears yet. Of course, my problem is that I don't *need* to learn TurboGears, Django, etc...I just feel the desire to learn them (which is bad, in a way, because then I have no reason to use them!) And of course learning a framework like this means learning a lot of other parts too, like CherryPy, Mochi or something like that, etc. :) From fuzzyman at gmail.com Mon Jun 5 18:11:55 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 5 Jun 2006 15:11:55 -0700 Subject: Python + WinCE + serial port In-Reply-To: <4482ac3c$0$12347$626a54ce@news.free.fr> References: <4481d342$0$21359$636a55ce@news.free.fr> <1149360567.824911.245750@c74g2000cwc.googlegroups.com> <4482ac3c$0$12347$626a54ce@news.free.fr> Message-ID: <1149545515.102850.272920@j55g2000cwa.googlegroups.com> pcm wrote: > Fuzzyman wrote: > > > > > pcm wrote: > >> Hi, > >> > >> Has anyone ever worked on a Python-WinCE-based program that involved > >> serial port management ? > >> > > > > Because of the size of the runtime and the fragility of the GUI > > toolkits, there has been little serious development with PythonCE. > > (Little not none - and it's great to have Python available.) > > > > There is no built in support for the serial port in PythonCE (AFAIK). > > Your best bet is using ctypes (for which a PythonCE port has been done) > > and the microsoft API. > > > > Fuzzyman > > http://www.voidspace.org.uk/python/index.shtml > > > >> Regards, > >> > >> Philippe > > > > > Thanks, does that mean that I need to write an extension to the WinCE API or > is that built-into the Python package ? > (Sorry for late reply.) There is a version of ctypes *compiled* for PythonCE (from the PythonCE sourceforge page). Using ctypes you should be able to use the Microsoft Win32 API to access the serial port from *pure Python* code. You will need to use the Microsoft docs to see which calls to make. Fuzzyman http://www.voidspace.org.uk/python/index.shtml > Regards, > Philippe From find at my.address.elsewhere Fri Jun 16 16:45:26 2006 From: find at my.address.elsewhere (Matthias Blume) Date: Fri, 16 Jun 2006 15:45:26 -0500 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <2006061410510511272-raffaelcavallaro@pasdespamsilvousplaitmaccom> <2006061501423327544-raffaelcavallaro@pasdespamsilvousplaitmaccom> <_eBkg.14895$uy3.4988@tornado.socal.rr.com> <1sBkg.14897$uy3.4884@tornado.socal.rr.com> Message-ID: Darren New writes: > Matthias Blume wrote: >> Very good statically typed versions of printf exist. See, e.g., >> Danvy's unparsing combinators. > > That seems to ignore the fact that the pattern is a string, which > means that printf's first argument in Danvy's mechanism has to be a > literal. In Danvy's solution, the format argument is not a string. > You can't read the printf format from a configuration file > (for example) to support separate languages. You don't need to do that if you want to support separate languages. Moreover, reading the format string from external input is a good way of opening your program to security attacks, since ill-formed data on external media are then able to crash you program. > It doesn't look like the > version of printf that can print its arguments in an order different > from the order provided in the argument list is supported either; > something like "%3$d" or some such. I am not familiar with the version of printf you are refering to, but I am sure one could adapt Danvy's solution to support such a thing. > Second, what's the type of the argument that printf, sprintf, fprintf, > kprintf, etc all pass to the subroutine that actually does the > formatting? (Called vprintf, I think?) Obviously, a Danvy-style solution (see, e.g., the one in SML/NJ's library) is not necessarily structured that way. I don't see the problem with typing, though. Matthias From jo at durchholz.org Mon Jun 26 17:45:27 2006 From: jo at durchholz.org (Joachim Durchholz) Date: Mon, 26 Jun 2006 23:45:27 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: <0FLng.159806$F_3.1840@newssvr29.news.prodigy.net> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150904134.520639.71070@b68g2000cwa.googlegroups.com> <0FLng.159806$F_3.1840@newssvr29.news.prodigy.net> Message-ID: Anton van Straaten schrieb: > Joachim Durchholz wrote: >> Anton van Straaten schrieb: >>> There's a close connection between latent types in the sense I've >>> described, and the "tagged values" present at runtime. However, as >>> type theorists will tell you, the tags used to tag values at runtime, >>> as e.g. a number or a string or a FooBar object, are not the same >>> thing as the sort of types which statically-typed languages have. >> >> Would that be a profound difference, or is it just that annotating a >> value with a full type expression would cause just too much runtime >> overhead? > > It's a profound difference. The issue is that it's not just the values > that need to be annotated with types, it's also other program terms. Yes - but isn't that essentially just auxiliary data from and for the data-flow analysis that tracks what values with what types might reach which functions? > In > addition, during a single run of a program, all it can ever normally do > is record the types seen on the path followed during that run, which > doesn't get you to static types of terms. To figure out the static > types, you really need to do static analysis. Agreed. Regards, Jo From yaru22 at gmail.com Tue Jun 27 22:42:00 2006 From: yaru22 at gmail.com (yaru22) Date: 27 Jun 2006 19:42:00 -0700 Subject: what is pygtk.require("2.0") for? Message-ID: <1151462520.184570.309240@p79g2000cwp.googlegroups.com> when I read a book, it just said we need to do import pygtk pygtk.require("2.0") import gtk in order to import gtk modules What is that pygtk.require("2.0") command for? From jzgoda at o2.usun.pl Thu Jun 15 10:33:29 2006 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Thu, 15 Jun 2006 16:33:29 +0200 Subject: Python is fun (useless social thread) ;-) In-Reply-To: References: Message-ID: John Salerno napisa?(a): > So out of curiosity, I'm just wondering how everyone else came to learn > it. If you feel like responding, I'll ask my questions for easy quoting: > > Did you have to learn it for a job? > > Or did you just like what you saw and decided to learn it for fun? > > Also, how did you go about learning it? (i.e., like I described above, I > started with the main stuff then moved on to the different available > frameworks) > > Was there any necessity in the specifics you learned, or did you just > dabble in something (e.g. wxPython) for fun? > > Are there still some things you feel you need to learn or improve? The very first encounter was with Red Hat 5.2, back in 1998. RH had an installer made with Python and NEWT toolkit. It looked great, just about as good as any of my Clipper or TurboVision programs. I looked at the code and it scared me (at this time, I was writing mostly in Clipper). Then in 2001 I came to work in another company, which has MS Proxy at its internet border. Being unable to use any of internet tool of my choice, I quickly found a solution, NTLM Authorization Proxy Server (NTLMAPS) by Dimitri Rozmanov. Which, to my surprise, is written in pure Python. This time I was ready to learn Python. I started using it for my spare-time projects and later I was able to "inject" Python to my organization. This can be concluded as "learned for fun", but now it takes part of my paid work. I started with writing "glue" code for various system tools (i.o.w. as a "shell scripting"), but now I tend to write standalone client tools, with GUI in various toolkits (wxPython at work, PyGTK in my spare time). They are mostly of "smart client" type, using various network interfaces (ftp, http, xmpp, MQSeries). And I still don't get this "web application" hype, and all these "web frameworks" scare me, as I internally don't trust any magic. -- Jarek Zgoda http://jpa.berlios.de/ From marc.t.davies at gmail.com Tue Jun 13 10:04:31 2006 From: marc.t.davies at gmail.com (MTD) Date: 13 Jun 2006 07:04:31 -0700 Subject: a string problem In-Reply-To: <1150206140.912224.113420@p79g2000cwp.googlegroups.com> References: <1150206140.912224.113420@p79g2000cwp.googlegroups.com> Message-ID: <1150207471.943197.143980@g10g2000cwb.googlegroups.com> > When i specify i only want to print the lines that contains "string" ie > the first line and not the others. If i use re module, how to compile > the expression to do this? I tried the re module and using simple > search() and everytime it gives me all the 3 lines that have "string" > in it, whereas i only need line 1. That's because all three lines DO include the substring "string" From dio.lee at gmail.com Tue Jun 27 02:01:22 2006 From: dio.lee at gmail.com (Dio) Date: 26 Jun 2006 23:01:22 -0700 Subject: Select in Python Message-ID: <1151388082.261840.306260@75g2000cwc.googlegroups.com> #!/usr/bin/env python2 from sys import stdin from select import select while 1: (rr, wr, er) = select([stdin], [], []) for fd in rr: print fd program block in the first select(), after I type something and "enter ", it never block in select() again,why? From steve at holdenweb.com Thu Jun 8 11:10:02 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 08 Jun 2006 16:10:02 +0100 Subject: Select hangs after some reads In-Reply-To: <1149779056.498540.46620@f6g2000cwb.googlegroups.com> References: <1149737234.816833.177710@j55g2000cwa.googlegroups.com> <1149764138.868847.326250@i39g2000cwa.googlegroups.com> <128g8uvi6aj4240@corp.supernews.com> <1149779056.498540.46620@f6g2000cwb.googlegroups.com> Message-ID: <44883DCA.4010602@holdenweb.com> alsmeirelles at gmail.com wrote: > Grant Edwards escreveu: > > >>On 2006-06-08, alsmeirelles at gmail.com wrote: >> >> >>>Well, actually I?m using a very simple protocol wich sends only >>>strings ended by newline. I need to send 3 chunks of information and a >>>newline after them. On the reader side I make 3 readline(), this way I >>>wouldn?t have to care about this problem, but maybe that?s where I?m >>>falling. If that?s the case, I?ll have to use a more complex >>>protocol. >> >>You can't use readline() with select(). Select tells you >>whether recv() called on the underlying socket will block or >>not. What's probably happening is that all of the data has >>been read from the underlying socket and is being held in a >>buffer waiting to be read by readline(). >> > > > Yes, as I expected, its the buffers. In my opinion the problem is that > the socket module > doesn't provide a way of reading all its internal buffer. > > readlines() just make subsequent calls to readline and readline may > call recv, so we have a locked scene. I want to know if I will block > anyway. Of course I can clean the buffer myself, but I think the socket > module should provide a way of doing this. It's not a big problem > though. > > > >>The Select call has no way of knowing about that buffered data. >>As far as it's concerned there's no more data left to read, so >>it block until the socket is closed. > > > You're very right. > thanks, > Of course, if the client forces the TCP PSH flag true then the receiver is guaranteed to debuffer the stream up to that point - this is how FTP clients work, for example. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From scott.daniels at acm.org Wed Jun 14 11:50:25 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Wed, 14 Jun 2006 08:50:25 -0700 Subject: convert floats to their 4 byte representation In-Reply-To: <1150297093.191223.152330@c74g2000cwc.googlegroups.com> References: <1150297093.191223.152330@c74g2000cwc.googlegroups.com> Message-ID: <44902b7c$1@nntp0.pdx.net> godavemon wrote: > I need to take floats and dump out their 4 byte hex representation. > This is easy with ints with the built in hex function or even better > for my purpose > > def hex( number, size ): > s = "%"+str(size) + "X" > return (s % number).replace(' ', '0') This should be a trifle nicer: def hexx(number, size): # don't shadow the "hex" builtin s = "%0s" + str(size) + "X" return s % number > but I haven't been able to find anything for floats. Any help would be > great. Getting to float bytes is tougher. First, python Floats are C Doubles, so you probably mean 8=byte hex. import array def eights(number, swap=False): data = array.array('d', [number]) if swap: data.byteswap() return ' '.join(hexx(ord(char), 2) for char in data.tostring()) def fours(number, swap=False): data = array.array('f', [number]) if swap: data.byteswap() return ' '.join(hexx(ord(char), 2) for char in data.tostring()) --Scott David Daniels scott.daniels at acm.org From micklee74 at hotmail.com Sun Jun 25 00:29:31 2006 From: micklee74 at hotmail.com (micklee74 at hotmail.com) Date: 24 Jun 2006 21:29:31 -0700 Subject: MSoffice metadata Message-ID: <1151209771.276872.299240@b68g2000cwa.googlegroups.com> hi is there a module in Python to extract metadata in MS office documents thanks From jstroud at ucla.edu Tue Jun 13 15:34:21 2006 From: jstroud at ucla.edu (James Stroud) Date: Tue, 13 Jun 2006 12:34:21 -0700 Subject: Tuple Syntax and () In-Reply-To: <1150226796.616272.223320@i40g2000cwc.googlegroups.com> References: <1150226796.616272.223320@i40g2000cwc.googlegroups.com> Message-ID: tactics40 at gmail.com wrote: > I keep accidently trying to declare t-tuples as mytuple = (myitem) > > I know this doesn't work and that you need the trailing comma, but > reading something online, I just came to realize.... the parenthesises > don't have any special meaning in relation to tuples at all, do they? > Aside from grouping, they are special to construct an empty tuple. py> () == tuple() True Also, don't underestimate their relationship with tuples when it comes to grouping: py> a, b, c = 1, 2, 3 py> py> a == a, b, c (True, 2, 3) py> a == (a, b, c) False James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From tim at thechases.com Thu Jun 8 12:39:55 2006 From: tim at thechases.com (Tim Chase) Date: Thu, 08 Jun 2006 11:39:55 -0500 Subject: Instead of saving text files i need as html In-Reply-To: References: <1149777499.506986.292830@j55g2000cwa.googlegroups.com> Message-ID: <448852DB.7000608@thechases.com> > Is this what you mean? > > -----begin----- > import urllib > urlfile = open(r'c:\temp\url.txt', 'r') > for lines in urlfile: > try: > outfilename = lines.replace('/', '-') > urllib.urlretrieve(lines.strip('/n'), 'c:\\temp\\' \ > + outfilename.strip('\n')[7:] + '.html') > except: > pass > -----end----- [laughs] I suspect the urlretrieve line should contain "strip('\n')" instead of "strip('/n')", but otherwise, the original code looked pretty kosher. I'm not sure what the odd slicing is for, but I'll presume the OP knows what they're doing. While not a python solution, the standard *nix tool would be either wget or curl: bash> wget -i listofurls.txt which is freely available with the Cygwin suite of GNU tools for Win32 platforms. -tkc From kay.schluehr at gmx.net Fri Jun 23 08:41:57 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 23 Jun 2006 05:41:57 -0700 Subject: code is data In-Reply-To: References: <44965f53$0$12743$636a55ce@news.free.fr> <4496b29f$0$27412$626a54ce@news.free.fr> <4496e9c9$0$14868$626a54ce@news.free.fr> <4fokj4F1ihat3U1@uni-berlin.de> <4497c20e$0$29656$636a55ce@news.free.fr> <4fpuh5F1i9bl1U1@uni-berlin.de> <4497d72d$0$30964$636a55ce@news.free.fr> <4fq5fkF1k346bU1@uni-berlin.de> <44982637$0$29812$626a54ce@news.free.fr> <1151013151.902103.32800@g10g2000cwb.googlegroups.com> Message-ID: <1151066517.354637.261440@y41g2000cwy.googlegroups.com> Anton Vredegoor wrote: > Paul Boddie wrote: > > > Anton Vredegoor wrote: > > >> Yes, but also what some other posters mentioned, making Pythons internal > >> parsing tree available to other programs (and to Python itself) by using > >> a widely used standard like XML as its datatype. > > > > http://pysch.sourceforge.net/ast.html > > Very interesting, it led me to some sxml describing pages and it also > tricked me into reading some Python documentation that I had always > considered to be hiding some arcane deep Python magic. I guess now that > Python is officially entering tree territory (as opposed to providing > third party functionality) it seems unavoidable that Python's officially > endorsed tree datatype will also be used for some of its internal > structures, thereby making it more accessible to programmers like me and > to outside programmers. I had the same initial impression with the "deep" aspects of Python parser API but I learned soon that I just stumbled about an awkward kind parse-tree representation. The structures are as simple as they could be - due to the nice LL(1) Python grammar which are reflected. I think node manipulation is just a first basic step for defining source transformers i.e. they provide a sound basis. For usability purposes a template language is a far better solution. Here is my own attempt. Defining a repeat statement ( for demonstration purposes ) using EasyExtend requires following translation: repeat: until: ==> while 1: if : break The placeholders and correspond to nodes in the parse-tree ( and constants in symbol.py ). The repeat-stmt is defined by an added grammar rule. The corresponding node in the parse-tree is dispatched against Transformer.handle_repeat_stmt() during parse-tree traversal. Matching against and in the repeat_stmt node is done by applying: suite_node = find_node(repeat_node, symbol.suite) test_node = find_node(repeat_node, symbol.test, level=1) What becomes tedious is the creation of the corresponding while_stmt node which is the expected result of the transformation. I actually want to use the declaration as it is written above and insert the suite_node and the test_node where the placeholders and are defined. Using EasyExtend one can define an extension language where the placeholders ( and some enhanced versions of those ) become language elements! Given this one can put everything together: import macro # module that corresonds to the macro extension language class FastTransformer(Transformer): def handle_repeat_stmt(self, repeat_node): suite_node = find_node(repeat_node, symbol.suite) test_node = find_node(repeat_node, symbol.test, level=1) target_stmt = """ while 1: if : break """ while_node = macro.expand(target_stmt, {'suite': suite_node, 'test': test_node}, goal = symbol.while_stmt) return any_stmt(while_node) This is pretty safe and works recursively: if the node contains another node it will be replaced as well. From sjmachin at lexicon.net Wed Jun 7 17:30:12 2006 From: sjmachin at lexicon.net (John Machin) Date: Thu, 08 Jun 2006 07:30:12 +1000 Subject: tempfile Question In-Reply-To: References: <4486161D.6060102@lexicon.net> <4486BE1E.5070107@lexicon.net> Message-ID: <44874564.8030305@lexicon.net> On 8/06/2006 2:57 AM, Dennis Lee Bieber wrote: > On Wed, 07 Jun 2006 21:53:02 +1000, John Machin > declaimed the following in comp.lang.python: > >> I passed over mkstemp() because (according to my reading of the manual), >> mkstemp() requires an *extra* step (close the file), leaving the >> situation then *exactly* the same as with mktemp() i.e. some pirate >> process may molest the file before the caller's child process can open >> the file. >> > mktemp() creates ONLY the file name, but not the file itself. This > means another process calling mktemp() has the possibility of generating > the SAME file name before the first opens/creates the named file. > Thanks, Dennis. You are quite correct. I'm a dill: I read """Return an absolute pathname of a file that did not exist at the time the call is made""" as implying that the file existed after the call, brushed aside my brief wonderment about what was deprecable about all that, and didn't even try it at the interactive prompt. Cheers, John From onurb at xiludom.gro Fri Jun 23 09:26:54 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Fri, 23 Jun 2006 15:26:54 +0200 Subject: Using metaclassed to dynamically generate a class based on a parameter to the objects init function. In-Reply-To: <1151061557.682689.189440@c74g2000cwc.googlegroups.com> References: <1151018669.849641.265990@g10g2000cwb.googlegroups.com> <449bb4d6$0$32258$626a54ce@news.free.fr> <1151061557.682689.189440@c74g2000cwc.googlegroups.com> Message-ID: <449bec1e$0$13891$626a54ce@news.free.fr> sashang at gmail.com wrote: > Bruno Desthuilliers wrote: > >>sashang at gmail.com wrote: >> >>>Hi >>> >>>I'd like to use metaclasses to dynamically generate a class based on a >>>parameter to the objects init function. >> >>Do you really need a metaclass for this ? >> >> >>>For example: >>> >>>class MetaThing(type): >>> def __init__(cls, name, bases, dict, extra_information): >>> super(MetaThing, cls).__init__(name, bases, dict) >>> #setup the class based on the parameter extra_information >>> >>>class Thing: >>> __metaclass__ = MetaThing >>> def __init__(self, extra_information): >>> #Somehow pass extra_information to the MetaThing >>> >>>extra_information = 1 >>>t = Thing(extra_information) >> >>Why would you want a new *class* here ? >> >> >>>The above sample won't work but I hope it demonstrates what I'm trying >>>to do. >> >>Not enough, I'm afraid - unless it's just me being dumb. From what I see >>here, you just can add the extra informations on the object in the >>initializer. What's your *real* use case ? >> > > The extra_information is used in MetaThing to tell it what attributes > to add to the class. For example: > > class MetaThing(type): > def __init__(cls, name, bases, dict, extra_information): > super(MetaThing, cls).__init__(name, bases, dict) > #setup the class based on the parameter extra_information > setattr(cls, make_name(extra_information), > make_object(extra_information)) > > Does that clarify things? I might have the wrong approach There's at least something wrong here : the metaclass code is executed when the class statement (the one for a class having this metaclass) is eval'd. It won't be called on class instanciation. http://www.python.org/download/releases/2.2.3/descrintro/#__new__ Also, you need to understand that modifying a class with impact all it's instances. > - I'm new to > metaclasses. However I do think the solution to my problem lies with > them since I have to dynamically generate a class You don't have to create classes for this - it's perfectly legal to set attributes (data or methods) on a per-object basis. Classes are more object-factories than rigid types. Just add the needed extra attributes in the __init__ (the class one, not the metaclass) and you should be done. > and metaclasses > provide a mechanism for doing this. Metaclasses provides a hook on class creation process. But AFAICT, you don't necessarily need metaclasses to dynamically create classes... -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From rtw at freenet.co.uk Thu Jun 15 19:17:02 2006 From: rtw at freenet.co.uk (Rob Williscroft) Date: Thu, 15 Jun 2006 18:17:02 -0500 Subject: Which compiler will Python 2.5 / Windows (Intel) be built with? References: <1150367139.495114.148550@g10g2000cwb.googlegroups.com> <44917535$1@nntp0.pdx.net> <1150391891.130185.4640@f6g2000cwb.googlegroups.com> <4491b9e1$1@nntp0.pdx.net> <1150406005.948538.188950@h76g2000cwa.googlegroups.com> <4491d3c0$1@nntp0.pdx.net> <1150410921.201231.277880@c74g2000cwc.googlegroups.com> Message-ID: wrote in news:1150410921.201231.277880 at c74g2000cwc.googlegroups.com in comp.lang.python: >> As nikie pointed out, you can buy a 1-year MSDN Pro Subscription that >> includes the VS2003 system. All that stopped is the free toolkit. > > The MSDN Pro Subscription is not really an option because we have no > use for the 2005 compiler at all if it doesn't work with Python. I > think we'll just try to get some boxed version of Visual Studio 2003 > Professional from somewhere. This is the .NET 11 SDK, I belive it includes the 2003 compiler (*): http://www.microsoft.com/downloads/thankyou.aspx?familyId=9b3a2ca6-3647- 4070-9f41-a333c6b9181d&displayLang=en&oRef= I found the link with google: net 1.1 sdk download its the first hit. *) I'm not going to check as I have VS2003 installed already. Rob. -- http://www.victim-prime.dsl.pipex.com/ From nmm1 at cus.cam.ac.uk Thu Jun 15 13:34:59 2006 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 15 Jun 2006 17:34:59 GMT Subject: Fun with complex and IEEE Message-ID: Try this one for size, noting especially the delightful eccentric value at i = 8. Your results may vary. m = 1.0e308 for i in range(0,20) : c = (1.0e308+1.0e308j)/(1.0e308+i*0.1*1.0e308j) print i, c On at least two systems, it gives: 0 (1+1j) 1 (1.08910891089+0.891089108911j) 2 (1.15384615385+0.769230769231j) 3 (1.19266055046+0.642201834862j) 4 (1.20689655172+0.51724137931j) 5 (1.2+0.4j) 6 (1.17647058824+0.294117647059j) 7 (1.14093959732+0.201342281879j) 8 (inf+0.121951219512j) 9 (nan+0j) 10 (nan+0j) 11 (nan-0j) 12 (nan-0j) 13 -0j 14 -0j 15 -0j 16 -0j 17 -0j 18 -0j 19 -0j Regards, Nick Maclaren. From klaus at seistrup.dk Fri Jun 9 01:14:05 2006 From: klaus at seistrup.dk (Klaus Alexander Seistrup) Date: Fri, 9 Jun 2006 05:14:05 +0000 (UTC) Subject: How to extract 2 integers from a string in python? References: <1149827496.857621.88550@h76g2000cwa.googlegroups.com> Message-ID: yinglcs at gmail.com skrev: > how can I extract 2 integers from a string in python? > > for example, my source string is this: > Total size: 173233 (371587) > > I want to extract the integer 173233 and 371587 from that > soource string, how can I do that? E.g.: #v+ >>> import re >>> re.findall(r'\d+', 'Total size: 173233 (371587)') ['173233', '371587'] >>> #v- Mvh, -- Klaus Alexander Seistrup Copenhagen, Denmark http://surdej.dk/ From skip at pobox.com Fri Jun 9 06:30:28 2006 From: skip at pobox.com (skip at pobox.com) Date: Fri, 9 Jun 2006 05:30:28 -0500 Subject: Amazon and Webservices In-Reply-To: <1149847249.123387.309650@f6g2000cwb.googlegroups.com> References: <1149847249.123387.309650@f6g2000cwb.googlegroups.com> Message-ID: <17545.19908.419074.478155@montanaro.dyndns.org> vpr> I've been trying to consume the webservices at Amazon using python. vpr> I have not been able to find a *good* webservices module... pyamazon. Skip From redefined.horizons at gmail.com Fri Jun 9 16:00:12 2006 From: redefined.horizons at gmail.com (Redefined Horizons) Date: Fri, 9 Jun 2006 13:00:12 -0700 Subject: Python or Ajax? Message-ID: I've been hearing a ot about AJAX lately. I may have to build a web application in the near future, and I was curoius: How does a web application that uses Python compare with one that uses AJAX? I've done some basic web page design with HTML and CSS, but never any web applications. I don't want to learn a new language if I can use Python. Would AJAX offer me any significant advantages? Thanks, Scott Huey From cginboston at hotmail.com Fri Jun 30 06:51:35 2006 From: cginboston at hotmail.com (Chance Ginger) Date: Fri, 30 Jun 2006 10:51:35 GMT Subject: Way for see if dict has a key References: <6V6pg.21624$_J1.271925@twister2.libero.it> Message-ID: On Fri, 30 Jun 2006 10:19:46 +0000, Michele Petrazzo wrote: > Hi ng, > what the preferred way for see if the dict has a key? > We have a lot of solutions: > > key in dict > key in dict.keys() > dict.has_key(key) > ... > > but what the better or the more "pythonic"? > > Thanks, > Michele It is a religious call.... From steven.bethard at gmail.com Wed Jun 21 12:11:33 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 21 Jun 2006 10:11:33 -0600 Subject: returning index of minimum in a list of lists In-Reply-To: <1150901648.832039.165590@b68g2000cwa.googlegroups.com> References: <1150901648.832039.165590@b68g2000cwa.googlegroups.com> Message-ID: JJLaRocque at gmail.com wrote: > Is there a simple python function to return the list index of the > minimum entry in a list of lists? > ie, for [[3,3,3,3], [3,3,3,1], [3,3,3,3]] to return 2,4. > Or, same question but just for a list of numbers, not a list of lists. In Python 2.5: Python 2.5a2 (trunk:46491M, May 27 2006, 14:43:55) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> x = [4, 4, 4, 1] >>> min(xrange(len(x)), key=x.__getitem__) 3 >>> y = [[3,3,3,3], [3,3,3,1], [3,3,3,3]] >>> min(xrange(len(y)), key=[min(z) for z in y].__getitem__) 1 >>> def multimin(listoflists): ... mins = [] ... min_indices = [] ... for sublist in listoflists: ... min_index = min(xrange(len(sublist)), ... key=sublist.__getitem__) ... min_indices.append(min_index) ... mins.append(sublist[min_index]) ... min_index = min(xrange(len(listoflists)), key=mins.__getitem__) ... return min_index, min_indices[min_index] ... >>> multimin([[3,3,3,3], [3,3,3,1], [3,3,3,3]]) (1, 3) STeVe From mystilleef at gmail.com Fri Jun 16 06:01:31 2006 From: mystilleef at gmail.com (mystilleef) Date: 16 Jun 2006 03:01:31 -0700 Subject: a good programming text editor (not IDE) In-Reply-To: <_xgkg.2317$No6.48542@news.tufts.edu> References: <_xgkg.2317$No6.48542@news.tufts.edu> Message-ID: <1150452091.269998.31000@f6g2000cwb.googlegroups.com> On linux, I recommend Scribes. It's simple, slim and sleek, yet powerful. Features: Automatic completion Automatic bracket completion and smart insertion Snippets (ala TextMate) Bookmarks Syntax highlight for more than 30 languages Launches faster than any IDE out their Has no learning curve. Features your typical text processing operations you'll find in VIM/Emacs. Remembers window position and size. Sexy interface that actually adheres to human interface guidlines And many more... The next version will even feature remote editing. website: ( http://scribes.sourceforge.net/ ) Flash Demo: ( http://scribes.sourceforge.net/snippets.htm ) GIF Demo: ( http://www.minds.may.ie/~dez/images/blog/scribes.html ) John Salerno wrote: > I know there's a request for a good IDE at least once a week on the ng, > but hopefully this question is a little different. I'm looking for > suggestions for a good cross-platform text editor (which the features > for coding, such as syntax highlighting, etc.) but not a full IDE with > all the fancy jazz (GUI developer, UML diagrams, etc.). > > Ideally, it would be something I could even put on a flash drive and > move from computer to computer, but this isn't necessary. Just something > I can immediately use in either Windows or Linux (or Mac, if necessary). > > Based on another thread, I tried out Scite, but no matter what I do it > doesn't seem to remember the window size and position, or any options I > choose (like showing line numbers). It seems to always reset itself each > time I open it. > > And naturally there are Emacs and Vim, but I just don't know if I need > to invest *that* much time into learning one of them (probably Vim, > since I hear it's lighter and faster). > > I've tried a few others, like TextPad and Crimson, and right now I use > UltraEdit, which I love actually, except for minor issues here and > there. But it'd be nice to make the move, as much as possible, to free, > open-source, cross-platform software. > > Thanks for any suggestions, and again I'm sorry if this feels like the > same question as usual (it's just that in my case, I'm not looking for > something like SPE, Komodo, Eric3, etc. right now). From tim.peters at gmail.com Tue Jun 20 18:20:28 2006 From: tim.peters at gmail.com (Tim Peters) Date: Tue, 20 Jun 2006 18:20:28 -0400 Subject: Iteration over recursion? In-Reply-To: <1150808045.539887.291180@i40g2000cwc.googlegroups.com> References: <1150808045.539887.291180@i40g2000cwc.googlegroups.com> Message-ID: <1f7befae0606201520h927d76naf65b5c742440808@mail.gmail.com> [MTD] > I've been messing about for fun creating a trial division factorizing > function and I'm naturally interested in optimising it as much as > possible. > > I've been told that iteration in python is generally more > time-efficient than recursion. Is that true? Since you heard it from me to begin with, I suppose saying "yes" again won't really help ;-) You can use time.time() or time.clock(), or the `timeit` module, to measure speed. Try timing a dead-simple factorial functions both ways. BTW, I've worked on Python's implementation for close to 15 years now, so when I say something about Python, it's _usually_ safe to just believe it :-) Questioning is fine, but in cases like this where it's easy to find out for yourself, I probably won't make time to respond. > Here is my algorithm as it stands. Any suggestions appreciated! > > from math import * > > def factorize(x): > """ Return factors of x """ > factors = [] > lim = int(sqrt(x)) Here you're limited to integers for which a floating sqrt is accurate. That's 53 bits on most platforms. For integers larger than that, the code may produce incorrect results in mysterious ways at times (because the square root may be inaccurate). > y = divmod(x,2) Most people would use "unpacking assignment" here instead, like q, r = divmod(x, 2) Then later code gets to use meaningful names instead of messing with mysterious little integer subscripts. It's also quicker to use local names than to build subscripting expressions. > if y[1] == 0: # x is even > factors = factors + [2] + factorize(y[0]) Since `factors` upon entry to this block must be [], it's kinda contorted. More obvious (if you _have_ to use recursion) would be: return [2] + factorize(y[0]) and then unindent the rest of the code a level. > else: # x is odd > i = 3 > while i <= lim: > y = divmod(x,i) Again more commonly written: q, r = divmod(x, i) > if y[1] == 0: > factors = factors + [i] + factorize(y[0]) It hardly matters in this context, but appending to a list is _generally_ much faster than building a brand new list from scratch. At a higher level, your recursions always start from 2 again; e.g., if i happens to be 434349 here, the factorize(y[0]) call starts over from 2, despite that you already know that no divisor less than 434349 can succeed. To do this _efficiently_ with recursion requires passing more knowledge across recursion levels. > i = lim+1 > else: > i += 2 > > if factors == []: # necessary step for correct recursion > factors = [x] > > return factors Recursion is pretty bizarre here. Not _wrong_, just "pretty bizarre", and is leading you into higher-level inefficiences. There are all sorts of ways to repair that, but I'm not going to talk about them because it's easy to write an iterative algorithm instead. Here's one way to do that, avoiding float sqrt (this works correctly for integers of any size, although trial division is hopelessly _inefficient_ for finding "large" factors), and skipping multiples of 3 in the inner loop too: def trial(n): if n <= 1: return [n] factors = [] for tiny in 2, 3: while n % tiny == 0: factors.append(tiny) n //= tiny delta = 2 d = 5 while 1: q, r = divmod(n, d) if r: if q < d: break d += delta delta = 6 - delta else: factors.append(d) n = q if n > 1: factors.append(n) return factors If we call the original input N, the key invariants holding at the top of the loop are: 1. N >= 2, and N == n * the product of the integers in `factors` 2. n is not divisible by any prime < d 3. all elements in `factors` are prime It may take a bit of thought to see that d marches over all integers >= 5 that aren't divisible by either 2 or 3: 5, 7, 11, 13, 17, 19, 23, 25, 29, 31, ... It's more-or-less generally true that establishing and proving loop invariants in an iterative algorithm is "the same thing" as establishing and proving pre- and post-conditions in a recursive algorithm. While it may feel strained at first, it's very much worthwhile learning how to do that. For example, from #2 it's easy to prove that if q < d, n must either be 1 or a prime. That's what justifies the "break" statement inside the loop. Then since that's the only way to get out of the loop, n is either 1 or a prime when the loop finishes, and that explains the rest of the code. From grante at visi.com Mon Jun 5 14:13:33 2006 From: grante at visi.com (Grant Edwards) Date: Mon, 05 Jun 2006 18:13:33 -0000 Subject: Expanding Search to Subfolders References: <1149526866.681348.273590@c74g2000cwc.googlegroups.com> Message-ID: <1288t2dn5i7bm61@corp.supernews.com> On 2006-06-05, PipedreamerGrey wrote: Just in case you really are trying to accomplish something other than learn Python, there are far easier ways to do these tasks: > This is the beginning of a script that I wrote to open all the > text files in a single directory, then process the data in the > text files line by line into a single index file. #!/bin/bash cat *.txt >outputfile > I'm now trying to the program to process all the text files in > subdirectories, so that I don't have to run the script more > than once. #!/bin/bash cat `find . -name '*.txt'` >outputfile -- Grant Edwards grante Yow! An INK-LING? Sure -- at TAKE one!! Did you BUY any visi.com COMMUNIST UNIFORMS?? From serge.orlov at gmail.com Wed Jun 28 05:38:40 2006 From: serge.orlov at gmail.com (Serge Orlov) Date: Wed, 28 Jun 2006 02:38:40 -0700 Subject: documentation for the change of Python 2.5 In-Reply-To: <002101c69a85$31eb2620$1a0aa8c0@Iris> References: <44a0f4d9$0$9022$626a54ce@news.free.fr> <002101c69a85$31eb2620$1a0aa8c0@Iris> Message-ID: On 6/28/06, bussiere wrote: > I've read thsi documentation n: > http://docs.python.org/dev/whatsnew/whatsnew25.html > is there a way to have it in a more printable form ? Yep: http://www.python.org/ftp/python/doc/2.5b1/ From danmcleran at yahoo.com Fri Jun 9 14:23:03 2006 From: danmcleran at yahoo.com (danmcleran at yahoo.com) Date: 9 Jun 2006 11:23:03 -0700 Subject: References and copying In-Reply-To: <44899cb3$0$21184$626a54ce@news.free.fr> References: <1149866118.229243.53290@g10g2000cwb.googlegroups.com> <44899cb3$0$21184$626a54ce@news.free.fr> Message-ID: <1149877383.608704.64110@f6g2000cwb.googlegroups.com> > Please verify before asserting: > > >>> a = [[1, 2], [3, 4]] > >>> b = a[1] > >>> b is a[1] > True > >>> id(b) > 46912496915448 > >>> id(a[1]) > 46912496915448 Right, I must have had slicing on the brain. From fredrik at pythonware.com Fri Jun 9 17:17:47 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 09 Jun 2006 23:17:47 +0200 Subject: More pythonic shell sort? In-Reply-To: <1149886830.566152.304500@h76g2000cwa.googlegroups.com> References: <1149886830.566152.304500@h76g2000cwa.googlegroups.com> Message-ID: akameswaran at gmail.com wrote: > An aside - can anyone tell me where the use += and -= is documented? http://docs.python.org/ref/augassign.html http://pyref.infogami.com/assignments From jes at nl.demon.net Fri Jun 30 16:08:31 2006 From: jes at nl.demon.net (Jim Segrave) Date: Fri, 30 Jun 2006 20:08:31 -0000 Subject: Regular Expression - old regex module vs. re module References: <1151607229.548737.145800@d56g2000cwd.googlegroups.com> <12aat51q5ubf1a3@corp.supernews.com> Message-ID: <12ab15v7251q1b2@corp.supernews.com> In article , Paul McGuire wrote: >"Jim Segrave" wrote in message >news:12aat51q5ubf1a3 at corp.supernews.com... > >I can see that the OP omitted the concept of "@|||" centering, since the >Python string interpolation forms only support right or left justified >fields, and it seems he is trying to do some form of format->string interp >automation. Adding centering would require not only composing a suitable >string interp format, but also some sort of pad() operation in the arg >passed to the string interp operation. I suspect this also rules out simple >handling of the '^' operator as mentioned in the spec, and likewise for the >trailing ellipsis if a field is not long enough for the formatted value. > >The '@' itself seems to be part of the field, so "@<<<<" would be a 5 >column, left-justified string. A bare '@' seems to be a single string >placeholder (meaningless to ask right or left justified :) ), since this is >used in the doc's hack for including a "@" in the output. (That is, as you >said, the original spec provides no mechanism for escaping in a '@' >character, it has to get hacked in as a value dropped into a single >character field.) > >The Perl docs say that fields that are too long are truncated. This does >not happen in Python string interps for numeric values, but it can be done >with strings (using the precision field). >>>> print "%-10s" % string.ascii_uppercase >ABCDEFGHIJKLMNOPQRSTUVWXYZ >>>> print "%-10.10s" % string.ascii_uppercase >ABCDEFGHIJ > >So if we were to focus on support for "@", "@>>>", "@<<<", "@###" and >"@###.##" (with and without leading or trailing digits about the decimal) >style format fields, this shouldn't be overly difficult, and may even meet >the OP's requirements. (The OP seemed to also want some support for >something like "@##.###****" for scientific notation, again, not a >dealbreaker.) One would need a much clearer spec on what the OP really wants to do - note that` Perl formats have the variable names embeeded as part of the format string, so writing a simple Perl->Python converter isn't going to work, I've given him a good start for an re based solution, you've given one for a pyparsing based one, at this point I'd hope the OP can take it from there or can come back with more specific questions on how to deal with some of the awfulness of the formats he's working with. -- Jim Segrave (jes at jes-2.demon.nl) From donn at u.washington.edu Fri Jun 9 13:54:35 2006 From: donn at u.washington.edu (Donn Cave) Date: Fri, 09 Jun 2006 10:54:35 -0700 Subject: References and copying References: <1149866118.229243.53290@g10g2000cwb.googlegroups.com> <44899cb3$0$21184$626a54ce@news.free.fr> Message-ID: In article <44899cb3$0$21184$626a54ce at news.free.fr>, bruno at modulix wrote: > danmcleran at yahoo.com wrote: ... > >>And I don't understand it. I thought, that b will be a reference to a, > >>so changing b should change a as well. > > > > > > No, you've set the name b to reference a slice of a. Slicing a list > > always returns a new list. > > Please verify before asserting: > > >>> a = [[1, 2], [3, 4]] > >>> b = a[1] > >>> b is a[1] > True > >>> id(b) > 46912496915448 > >>> id(a[1]) > 46912496915448 > >>> You're right - he actually didn't set the name b to reference a slice of a. But if he had - slicing a list does return a new list. Indexing, as in the example, returns the item object. Or, binds a reference to the left hand side identifier, whatever, but there is no way to bind anything to the list location. Donn Cave, donn at u.washington.edu From deets at nospam.web.de Tue Jun 20 07:45:47 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 20 Jun 2006 13:45:47 +0200 Subject: [OT] code is data References: <44965f53$0$12743$636a55ce@news.free.fr> <4496b29f$0$27412$626a54ce@news.free.fr> <4496e9c9$0$14868$626a54ce@news.free.fr> <4fokj4F1ihat3U1@uni-berlin.de> <4497c20e$0$29656$636a55ce@news.free.fr> <4fpuh5F1i9bl1U1@uni-berlin.de> <4497d72d$0$30964$636a55ce@news.free.fr> Message-ID: <4fq5fkF1k346bU1@uni-berlin.de> >> While the _result_ of a transformation might be a less efficient piece of >> code (e.g. introducing a lock around each call to enable concurrent >> access), the transformation itself is very - if not totally - static - > > really ? See below. > Nope, it's runned each time the module is loaded (with 'loaded' distinct > from 'imported') - which can make a real difference in some execution > models... I already mentioned that latency. If it for whatever reason really becomes important, it would be the best to cache the result of the transformation. Which would BTW eliminate any complexity driven runtime penalty - regardless of the tool used. So - loading time is _not_ an issue. And I spare you the premature optimization babble... :) >> So except from a start up latency, it has no impact. > > Having a high startup latency can be a problem in itself. See above. > But the problem may not be restricted to startup latency. If for example > you use a metaclasse and a function that *dynamically* creates new > classes using this metaclass, then both the class statement and the > metaclass code transformation will be executed on each call to this > function. This is an assumption I don't agree upon. The whole point of the OPs post was about creating DSLs or alter the syntax of python itself. All that to enhance expressiveness. But we are still talking about CODE here - things that get written by programmers. Even if that is piped through so many stages, it won't grow endlessly. Runtime (runtime meaning here not on a startup-phase, but constantly/later) feeding of something that generates new code - I wouldn't say that is unheard of, but I strongly doubt it occurs so often that it rules out tree transformations that don't try and squeeze the latest bit of performance out themselves. Which, BTW, would rule out python in itself as nothing beats runtime assembly generation BY assembly. Don't you think? > The whole point of a code transformation mechanism like the one Anton is > talking about is to be dynamic. Else one just needs a preprocessor... No, it is not the whole point. The point is "" The idea is that we now have a fast parser (ElementTree) with a reasonable 'API' and a data type (XML or JSON) that can be used as an intermediate form to store parsing trees. Especially statically typed little languages seem to be very swallow-able. Maybe I will be able to reimplement GFABasic (my first love computer language, although not my first relationship) someday, just for fun. """ No on-the-fly code generation here. He essentially wants lisp-style-macros with better parsing. Still a programming language. Not a data-monger. Diez From jes at nl.demon.net Fri Jun 30 06:45:51 2006 From: jes at nl.demon.net (Jim Segrave) Date: Fri, 30 Jun 2006 10:45:51 -0000 Subject: Regular Expression - old regex module vs. re module References: <1151607229.548737.145800@d56g2000cwd.googlegroups.com> Message-ID: <12aa06v4oema7cd@corp.supernews.com> In article <1151607229.548737.145800 at d56g2000cwd.googlegroups.com>, Steve wrote: >Hi All, > >I'm having a tough time converting the following regex.compile patterns >into the new re.compile format. There is also a differences in the >regsub.sub() vs. re.sub() > >Could anyone lend a hand? > > >import regsub >import regex > >import re # << need conversion to this module > >.... > > """Convert perl style format symbology to printf tokens. > > Take a string and substitute computed printf tokens for perl style > format symbology. > > For example: > > ###.## yields %6.2f > ######## yields %8d > <<<<< yields %-5s > """ Perhaps not optimal, but this processes things as requested. Note that all floats have to be done before any integer patterns are replaced. ========================== #!/usr/local/bin/python import re """Convert perl style format symbology to printf tokens. Take a string and substitute computed printf tokens for perl style format symbology. For example: ###.## yields %6.2f ######## yields %8d <<<<< yields %-5s """ # handle cases where there's no integer or no fractional chars floatPattern = re.compile(r'(?+)') def float_sub(matchobj): # fractional part may be in either groups()[1] or groups()[2] if matchobj.groups()[1] is not None: return "%%%d.%df" % (len(matchobj.groups()[0]), len(matchobj.groups()[1])) else: return "%%%d.%df" % (len(matchobj.groups()[0]), len(matchobj.groups()[2])) def unperl_format(s): changed_things = 1 while changed_things: # lather, rinse and repeat until nothing new happens changed_things = 0 mat_obj = leftJustifiedStringPattern.search(s) if mat_obj: s = re.sub(leftJustifiedStringPattern, "%%-%ds" % len(mat_obj.groups()[0]), s, 1) changed_things = 1 mat_obj = rightJustifiedStringPattern.search(s) if mat_obj: s = re.sub(rightJustifiedStringPattern, "%%%ds" % len(mat_obj.groups()[0]), s, 1) changed_things = 1 # must do all floats before ints mat_obj = floatPattern.search(s) if mat_obj: s = re.sub(floatPattern, float_sub, s, 1) changed_things = 1 # don't fall through to the int code continue mat_obj = integerPattern.search(s) if mat_obj: s = re.sub(integerPattern, "%%%dd" % len(mat_obj.groups()[0]), s, 1) changed_things = 1 return s if __name__ == '__main__': testarray = ["integer: ####, integer # integer at end #", "float ####.## no decimals ###. no int .### at end ###.", "Left string <<<<<< short left string <", "right string >>>>>> short right string >", "escaped chars \\#### \\####.## \\<\\<<<< \\>\\><<<"] for s in testarray: print("Testing: %s" % s) print "Result: %s" % unperl_format(s) print ====================== Running this gives Testing: integer: ####, integer # integer at end # Result: integer: %4d, integer %1d integer at end %1d Testing: float ####.## no decimals ###. no int .### at end ###. Result: float %7.2f no decimals %4.0f no int %4.3f at end %4.0f Testing: Left string <<<<<< short left string < Result: Left string %-6s short left string %-1s Testing: right string >>>>>> short right string > Result: right string %6s short right string %1s Testing: escaped chars \#### \####.## \<\<<<< \>\><<< Result: escaped chars \#%3d \#%6.2f \<\<%-3s \>\>%-3s -- Jim Segrave (jes at jes-2.demon.nl) From sjmachin at lexicon.net Tue Jun 6 03:30:52 2006 From: sjmachin at lexicon.net (John Machin) Date: Tue, 06 Jun 2006 17:30:52 +1000 Subject: Reading from a file and converting it into a list of lines In-Reply-To: References: <1149534126.129714.131860@f6g2000cwb.googlegroups.com> <1149535195.763340.220010@y43g2000cwc.googlegroups.com> <44851010.6070503@lexicon.net> Message-ID: <44852F2C.80509@lexicon.net> On 6/06/2006 4:15 PM, Girish Sahani wrote: > Really sorry for that indentation thing :) > I tried out the code you have given, and also the one sreeram had written. > In all of these,i get the same error of this type: > Error i get in Sreeram's code is: > n1,_,n2,_ = line.split(',') > ValueError: need more than 1 value to unpack > > And error i get in your code is: > for n1, a1, n2, a2 in reader: > ValueError: need more than 0 values to unpack > > Any ideas why this is happening? In the case of my code, this is consistent with the line being empty, probably the last line. As my mentor Bruno D. would say, your test data does not match your spec :-) Which do you want to change, the spec or the data? You can change my csv-reading code to detect dodgy data like this (for example): for row in reader: if not row: continue # ignore empty lines, wherever they appear if len(row) != 4: raise ValueError("Malformed row %r" % row) n1, a1, n2, a2 = row In the case of Sreeram's code, perhaps you could try inserting print "line = ", repr(line) before the statement that is causing the error. > > Thanks a lot, > girish > > > From python.list at tim.thechases.com Thu Jun 1 13:20:44 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 01 Jun 2006 12:20:44 -0500 Subject: Finding web host headers In-Reply-To: <447F1F0B.6000600@tim.thechases.com> References: <1149179050.315297.79470@j55g2000cwa.googlegroups.com> <447F1F0B.6000600@tim.thechases.com> Message-ID: <447F21EC.40801@tim.thechases.com> >> Is there any way to fetch a website's host/version headers using >> Python? > > >>> import httplib > >>> conn = httplib.HTTPConnection("docs.python.org") > >>> conn.connect() > >>> conn.request("HEAD", "/") > >>> response = dict([(k.lower(), v) for k,v in conn.getresponse()]) > >>> conn.close() > >>> server = response["server"] > >>> print server > Apache/2.0.54 (Debian GNU/Linux) DAV/2 SVN/1.1.4 mod_python/3.1.3 > Python/2.3.5 mod_ssl/2.0.54 OpenSSL/0.9.7e Dang, I copied that over by hand and miscopied it with a big error or two. It can also be cleaned up a bit, as I learned (the getheader() call is case-insensitive, and the connect() call was superfluous). Copying verbatim... >>> import httplib >>> conn = httplib.HTTPConnection("docs.python.org") >>> conn.request("HEAD", "/") >>> response = conn.getresponse() >>> conn.close() >>> server = response.getheader("server") >>> print server Apache/2.0.54 (Debian GNU/Linux) DAV/2 SVN/1.1.4 mod_python/3.1.3 Python/2.3.5 mod_ssl/2.0.54 OpenSSL/0.9.7e Sorry about the rubbish code the first time out the gate. -tkc From mikem76 at gmail.com Wed Jun 7 15:17:53 2006 From: mikem76 at gmail.com (mikem76 at gmail.com) Date: 7 Jun 2006 12:17:53 -0700 Subject: How do I automatically redirect stdout and stderr when using os.popen2? References: <1149696430.511354.276460@i40g2000cwc.googlegroups.com> <128dvl9f2hi91c5@corp.supernews.com> Message-ID: <1149707873.524861.90320@j55g2000cwa.googlegroups.com> Here is what I ended up doing: si = file('/dev/null', 'r') so = file('/dev/null', 'a+') i,o = os.popen2('some_command_that_prints_a_lot_to_stdout') os.dup2(so.fileno(), o.fileno()) os.dup2(si.fileno(), i.fileno()) Thanks for your help, Mike Grant Edwards wrote: > On 2006-06-07, mikem76 at gmail.com wrote: > > > How do I automatically redirect stdout and stderr when using os.popen2 > > to start a long running process. > > popen2 does redirect stdout to a file object. That's the whole > point of using it. If you don't want a file object that's > connected to the child's stdout, then don't use popen2. > > > If the process prints a lot of stuff to stdout it will > > eventually stop because it runs out of buffer space. Once I > > start reading the stdout file returned by os.popen2 then the > > process resumes. I know that I could just specify > /dev/null > > when starting the process but I'd like to know if there is a > > way to start a process using os.popen2 or some other way so > > that all standard out and standard error goes to /dev/null or > > some other file. > > Yes. Fork a child process then use the standard file > descriptor operators to open /dev/null or some other file and > then dup those file descriptors to stdout/stderr: > > http://docs.python.org/lib/os-fd-ops.html > > Then you can exec the program you want to run: > > http://docs.python.org/lib/os-process.html > > This is basically identical to the method use to do I/O > redirection in C, so any decent book on C programming under > Unix should have a good explanation. > > > Hmmm, it looks like it's simpler touse the subprocess module. > Just open /dev/null to get a file descriptor for it, and then > pass that to subprocess.Popen(): > > http://docs.python.org/lib/module-subprocess.html > > -- > Grant Edwards grante Yow! I selected E5... but > at I didn't hear "Sam the Sham > visi.com and the Pharoahs"! From cfbolz at googlemail.com Mon Jun 26 06:28:52 2006 From: cfbolz at googlemail.com (cfbolz at googlemail.com) Date: 26 Jun 2006 03:28:52 -0700 Subject: pypy-0.9.0: stackless, new extension compiler References: Message-ID: <1151317732.818032.162300@u72g2000cwu.googlegroups.com> Hi all! Michael Hudson wrote: > The PyPy development team has been busy working and we've now packaged > our latest improvements, completed work and new experiments as > version 0.9.0, our fourth public release. Unfortunately the download links for the release tarballs did not work until very recently. They are now working though. You can download the 0.9 release of PyPy under: http://codespeak.net/download/pypy/pypy-0.9.0.tar.bz2 http://codespeak.net/download/pypy/pypy-0.9.0.tar.gz http://codespeak.net/download/pypy/pypy-0.9.0.zip For detailed notes about how to get started into the world of PyPy see here: http://codespeak.net/pypy/dist/pypy/doc/getting-started.html Sorry for the fuss and cheers, Carl Friedrich Bolz From scott.daniels at acm.org Thu Jun 15 11:36:29 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Thu, 15 Jun 2006 08:36:29 -0700 Subject: Python is fun (useless social thread) ;-) In-Reply-To: References: Message-ID: <449179b2$1@nntp0.pdx.net> John Salerno wrote: When I was pursuing a PhD, I was working on query optimization in object-oriented databases. My thesis was that you could actually do query optimization without breaking encapsulation, and I had several tricks that I knew how to use to do that. I needed a language in the DB that had static typing but no implication of shared structure (implementation or class). In my investigation for the work, I kept seeing references to Python, but (A) the white- space issue made me think it was silly, and (B) I needed a static typing for my work. After graduate school, I returned to one of my hobby projects, a string search program, that I wanted to update to a more modern language. I ported the thing to C, but decided it was time to look at Python more closely, so I used it to experiment with some of my state machine building algorithms. By the end of the project, I had fallen in love with Python as both a programming language and a way of expressing algorithms to other programmers (who didn't necessarily know it was Python I was writing). --Scott David Daniels scott.daniels at acm.org From jim at trainplayer.com Wed Jun 21 07:03:40 2006 From: jim at trainplayer.com (Jim) Date: 21 Jun 2006 04:03:40 -0700 Subject: embedded Python calling app via COM Message-ID: <1150887820.604214.276880@i40g2000cwc.googlegroups.com> I have a C++ app which fires up a Python script using C API calls. That script operates the app via Automation calls, like this: from win32com.client import * from mywrapper import * myapp = Application() myapp.Visible = True mydoc = myapp.Documents.Open(...) My problem is to make sure the instance of myapp is the same one I am calling from. The above code starts up a new instance of the app, which is not what I want. In other words I need something like a GetObject instead of a CreateObject, and I need some way to identify the calling app so I can tell GetObject about it. Before I go and do something hack, I thought I'd see if anyone else is in this situation and knows a good way to do the job. -- Jim From steven.bethard at gmail.com Thu Jun 22 10:08:02 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 22 Jun 2006 08:08:02 -0600 Subject: The code that could not be... In-Reply-To: <1150936844.874347.163060@r2g2000cwb.googlegroups.com> References: <1150936844.874347.163060@r2g2000cwb.googlegroups.com> Message-ID: Alex A. Naanou wrote: > The object's __dict__ can only be a dict derivative and at that none of > the Python's mapping API will be used (the dict is accessed directly). [snip] > I wrote a patch some time back, it appears rather stable and is being > production tested. > > you can download it here: > http://pli.sourceforge.net/object_dict_interface_use_fix.patch Could you post this to Python's sourceforge tracker[1]? You're likely to get more reviewers that way. BTW, I too would like to see this happen -- thanks so much for providing an implementation! [1] http://sourceforge.net/tracker/?group_id=5470&atid=105470 STeVe From peter.mosley at talk21.com Mon Jun 19 08:40:43 2006 From: peter.mosley at talk21.com (peter) Date: 19 Jun 2006 05:40:43 -0700 Subject: Detecting key presses References: <1150607857.186185.183130@g10g2000cwb.googlegroups.com> Message-ID: <1150720843.091548.182270@h76g2000cwa.googlegroups.com> Not a stupid question at all - its something I was looking for, and was (and still am) surprised not to find a cross platform implementation. It must be possible - for a short while I dabbled with yabasic and there the same source code would recognise a keypress in both Windows and Linux. My solution was:- # Await key and return code - dos only def _keycode_msvcrt(self): #Loop till key pressed while 1: if msvcrt.kbhit(): k=ord(msvcrt.getch()) if k==0 or k==224: #Special keys k=1000+ord(msvcrt.getch()) #return 1000+ 2nd code pass break pass pass return k # Await key and return code - linux only def _keycode_linux2(self): # Loop till key pressed # Set up keycode list a=[0,0,0,0,0,0] # Press a key and populate list try: os.system('stty -icanon') os.system('stty -echo') a[0]=ord(sys.stdin.read(1)) if a[0]==27: a[1]=ord(sys.stdin.read(1)) if a[1]==91: a[2]=ord(sys.stdin.read(1)) if (a[2]>=49 and a[2]<=54) or a[2]==91: a[3]=ord(sys.stdin.read(1)) if a[3]>=48 and a[3]<=57: a[4]=ord(sys.stdin.read(1)) finally: os.system('stty echo') os.system('stty icanon') # Decode keypress if a==[ 10, 0, 0, 0, 0, 0]: k= 13 # Enter elif a==[ 27, 27, 0, 0, 0, 0]: k= 27 # Esc (double press) elif a==[ 27, 91, 91, 65, 0, 0]: k=1059 # F1 elif a==[ 27, 91, 91, 66, 0, 0]: k=1060 # F2 elif a==[ 27, 91, 91, 67, 0, 0]: k=1061 # F3 elif a==[ 27, 91, 91, 68, 0, 0]: k=1062 # F4 elif a==[ 27, 91, 91, 69, 0, 0]: k=1063 # F5 elif a==[ 27, 91, 49, 55, 126, 0]: k=1064 # F6 elif a==[ 27, 91, 49, 56, 126, 0]: k=1065 # F7 elif a==[ 27, 91, 49, 57, 126, 0]: k=1066 # F8 elif a==[ 27, 91, 50, 48, 126, 0]: k=1067 # F9 elif a==[ 27, 91, 50, 49, 126, 0]: k=1068 # F10 elif a==[ 27, 91, 50, 51, 126, 0]: k=1133 # F11 elif a==[ 27, 91, 50, 52, 126, 0]: k=1134 # F12 elif a==[ 27, 91, 50, 126, 0, 0]: k=1082 # Ins elif a==[ 27, 91, 51, 126, 0, 0]: k=1083 # Del elif a==[ 27, 91, 49, 126, 0, 0]: k=1071 # Home elif a==[ 27, 91, 52, 126, 0, 0]: k=1079 # End elif a==[ 27, 91, 53, 126, 0, 0]: k=1073 # Pg Up elif a==[ 27, 91, 54, 126, 0, 0]: k=1081 # Pg Dn elif a==[ 27, 91, 65, 0, 0, 0]: k=1072 # Up elif a==[ 27, 91, 66, 0, 0, 0]: k=1080 # Down elif a==[ 27, 91, 68, 0, 0, 0]: k=1075 # Left elif a==[ 27, 91, 67, 0, 0, 0]: k=1077 # Right elif a==[127, 0, 0, 0, 0, 0]: k= 8 # Backspace else: k=a[0] # Ascii code # Done return k # Return key code def key(self,case='NONE'): # Get OS name and call platform specific function a=sys.platform if a=='linux2': #Linux (works on Fedora Core 1 and 3) k=self._keycode_linux2() elif a=='win32': #windows k=self._keycode_msvcrt() else: #unknown k=ord(raw_input()) # Adjust case if case=='UPPER': if k>=97 and k<=122: k=k-32 if case=='LOWER': if k>=65 and k<=90: k=k+32 # Done return k A bit clumsy, I know (for example it needs a a double press to recognise the escape key), and I'm not sure I understand why it works, but for me it was a passable solution. Peter From digitalorganics at gmail.com Mon Jun 12 12:25:58 2006 From: digitalorganics at gmail.com (digitalorganics at gmail.com) Date: 12 Jun 2006 09:25:58 -0700 Subject: Bridge: Ruby to Python communication In-Reply-To: <1150128080.185666.5170@c74g2000cwc.googlegroups.com> References: <1150126134.802843.122890@h76g2000cwa.googlegroups.com> <1150128080.185666.5170@c74g2000cwc.googlegroups.com> Message-ID: <1150129558.507321.152340@h76g2000cwa.googlegroups.com> I'll check that out, thanks! vasudevram wrote: > digitalorganics at gmail.com wrote: > > Hello all. I want a ruby and a python module to be able to communicate > > with each other, access classes, instances and the like. Is there a > > bridge for this? I'm aware of rupy, but the documentation seems rather > > inadequate for the uninitiated. Are there other libraries/bridges or > > maybe a rupy tutorial? Thank you. > > Hi, > > Don't know if there is a specific Ruby/Python bridge, but one way that > will work for some needs is to use XML-RPC. Its not very difficult to > understand and to program. XML-RPC is a lightweight distributed > computing method, much simpler than say, CORBA. Also has less features, > but may suffice for your needs. It has support for many languages and, > as long as the needed libraries are there for your language, you can > use any language for the client and any language for the server. I know > for sure that XML-RPC supports Python and have used it with Python > myself. Check out http://xmlrpc.com (and also Google for more resources > on this topic) to learn more, download source code examples, and to > check if there is Ruby support for it. > > HTH > Vasudev Ram > Independent software consultant > http://www.geocities.com/vasudevram > PDF conversion tools: http://sourceforge.net/projects/xtopdf From will.ware at gmail.com Mon Jun 5 00:15:18 2006 From: will.ware at gmail.com (Will Ware) Date: 4 Jun 2006 21:15:18 -0700 Subject: Freezing a static executable Message-ID: <1149480918.713079.36870@y43g2000cwc.googlegroups.com> I am trying to freeze a static executable. I built a static Python executable this way: ./configure --disable-shared --prefix=/usr/local make make install Even that didn't give me a really static executable, though: $ ldd /usr/local/bin/python linux-gate.so.1 => (0xffffe000) libpthread.so.0 => /lib/tls/libpthread.so.0 (0xb7f44000) libdl.so.2 => /lib/libdl.so.2 (0xb7f40000) libutil.so.1 => /lib/libutil.so.1 (0xb7f3c000) libm.so.6 => /lib/tls/libm.so.6 (0xb7f17000) libc.so.6 => /lib/tls/libc.so.6 (0xb7de9000) /lib/ld-linux.so.2 (0xb7f70000) Then I typed this: /usr/local/bin/python /home/wware/Python-2.4.1/Tools/freeze/freeze.py foo.py ldd foo $ ldd foo linux-gate.so.1 => (0xffffe000) libpthread.so.0 => /lib/tls/libpthread.so.0 (0xb7f5a000) libdl.so.2 => /lib/libdl.so.2 (0xb7f56000) libutil.so.1 => /lib/libutil.so.1 (0xb7f52000) libm.so.6 => /lib/tls/libm.so.6 (0xb7f2d000) libc.so.6 => /lib/tls/libc.so.6 (0xb7dff000) /lib/ld-linux.so.2 (0xb7f86000) What stupid thing am I doing wrong? TIA for any advice Will Ware From steven.bethard at gmail.com Wed Jun 14 01:47:44 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 13 Jun 2006 23:47:44 -0600 Subject: python-dev Summary for 2006-04-16 through 2006-04-30 Message-ID: python-dev Summary for 2006-04-16 through 2006-04-30 ++++++++++++++++++++++++++++++++++++++++++++++++++++ .. contents:: [The HTML version of this Summary is available at http://www.python.org/dev/summary/2006-04-16_2006-04-30] ============= Announcements ============= --------------------------- Python 2.5 alpha 2 released --------------------------- Python 2.5 alpha 2 was released on April 27th. If you haven't tried it out yet, now's the time! `PEP 356`_ has more details and the full schedule. .. _PEP 356: http://www.python.org/dev/peps/pep-0356/ Contributing threads: - `TRUNK FREEZE from 00:00 UTC, 27th April 2006 for 2.5a2 `__ - `RELEASED Python 2.5 (alpha 2) `__ - `trunk is UNFROZEN `__ - `2.5 open issues `__ ---------------------------- QOTF: Quote of the Fortnight ---------------------------- Phillip J. Eby, on the social behavior of package distributors (and why setuptools goes to such efforts to guess what package distributors were really trying to do): The problem isn't fundamentally a technical one, but a social one. You can effect [sic] social change through technology, but not by being some random guy with a nagging 'bot. (And yes, Phillip, you can nominate yourself for QOTF.) ;-) Contributing thread: - `setuptools: past, present, future `__ ========= Summaries ========= ------------------------------- Adding setuptools to the stdlib ------------------------------- Phillip J. Eby started checking in some of the `setuptools`_ modules for Python 2.5. People started to get nervous about some of the modules because: * Setuptools changes the distutils "install" command to install everything as zipfile eggs * Setuptools changes the distutils "sdist" command to automate generation of MANIFEST.in and MANIFEST. * Setuptools adds 'site.py' files so that .pth files are processed in PYTHONPATH directories. * Setuptools monkey-patches three classes from distutils: Distribution, Command, and Extension. While most people recognized the need for the features that setuptools provides, a number of them objected to introducing setuptools as a new package and instead argued for merging setuptools into distutils. Phillip said that such a merge might be possible, but that there were a fair number of backwards compatibility concerns (e.g. its redefinition of the "install" and "sdist" commands) and that it would make it much harder for him to maintain external versions of setuptools compatible with Python 2.3 and 2.4. In the end, Phillip suggested withdrawing setuptools from Python 2.5, and figuring out how to merge setuptools into distutils for the 2.6 release. In particular, he asked for help with the mostly trivial porting of the "alias", "rotate", "saveopts" and "setopt" commands. Additionally, he made available some information about the `setuptools internals`_ for anyone who wanted to see better what was going on behind the scenes. .. _setuptools: http://peak.telecommunity.com/DevCenter/setuptools .. _setuptools internals: http://peak.telecommunity.com/DevCenter/EggFormats Contributing threads: - `[Python-checkins] r45510 - python/trunk/Lib/pkgutil.py python/trunk/Lib/pydoc.py `__ - `Place for setuptools manuals and source for .exe files? `__ - `setuptools in the stdlib ([Python-checkins] r45510 - python/trunk/Lib/pkgutil.py python/trunk/Lib/pydoc.py) `__ - `setuptools in the stdlib ( r45510 - python/trunk/Lib/pkgutil.py python/trunk/Lib/pydoc.py) `__ - `setuptools in the stdlib `__ - `Raising objections (was: setuptools in the stdlib) `__ - `Raising objections `__ - `3rd party extensions hot-fixing the stdlib (setuptools in the stdlib) `__ - `setuptools in 2.5. `__ - `magic in setuptools (Was: setuptools in the stdlib) `__ - `Distutils for Python 2.1 (was "Raising objections") `__ - `setuptools in 2.5. (summary) `__ - `Distutils thoughts `__ - `setuptools: past, present, future `__ - `Easy, uncontroversial setuptools->distutils tasks `__ - `Internal documentation for egg formats now available `__ ----------------------------- PEP 343: The "with" Statement ----------------------------- A.M. Kuchling asked about some terminology in the `PEP 343`_ documentation. Originally, the objects with ``__enter__`` and ``__exit__`` methods which were used in the with-statement were called "context managers". When the additional ``__context__`` method was introduced, the term "manageable context" was given to objects that provided it. At PyCon, the PEP was changed to switch the terms, though the names of ``decimal.Context`` and ``contextlib.contextmanager`` were not changed correspondingly. This all led to a rather confusing discussion where people argued over the terminology, appropriately summarized in this quote by Phillip J. Eby: ...everybody has been perfectly clear, we just haven't really gotten on the same page about which words mean what. People then played around with a variety of alternative terms ("context factory", "context specifier", etc.) but in the end, Guido decided that it was much clearer to just drop the ``__context__`` method entirely -- most use-cases at the time just had ``__context__`` returning self, and the few use-cases that didn't could be accomodated with an appropriately named method or function. And dropping the ``__context__`` method meant that only the term "context manager" was necessary, removing most of the earlier terminological confusion. .. _PEP 343: http://www.python.org/dev/peps/pep-0343/ Contributing threads: - `PEP 343: confusing context terminology `__ - `Why are contexts also managers? (was r45544 - peps/trunk/pep-0343.txt) `__ - `With context, please `__ - `PEP 343 update (with statement context terminology) `__ - `Must objects with __enter__/__exit__ also supply __context__? `__ - `Updated context management documentation `__ - `[Python-checkins] r45721 - python/trunk/Lib/test/test_with.py `__ - `More on contextlib - adding back a contextmanager decorator `__ ------------------------------------------------ Dropping __init__.py requirement for subpackages ------------------------------------------------ After some pressure from other Googlers, Guido suggested that Python drop the requirement that subpackages have an __init__.py file (though top-level packages would still require one). People were concerned that a number of non-subpackage directories would suddenly become packages, e.g. "test" in the Python distribution. There was also some concern about tools that depended on the current requirement -- any tool that currently searches directories for __init__.py files would have to be updated to work with the new semantics. In the end, `Thomas Wouters provided a patch`_ that makes Python now issue a warning when it would have imported a module but failed to because __init__.py was missing. .. _Thomas Wouters provided a patch: http://bugs.python.org/1477281 Contributing threads: - `Dropping __init__.py requirement for subpackages `__ - `[Python-checkins] r45770 - in python/trunk: `__ ------------------------------------- Python and Visual Studio 2005 Express ------------------------------------- Guido noticed that Microsoft had announced that `Visual Studio 2005 express will be free forever`_, and asked if Python should try to accomodate this. People seemed to think that switching to Visual Studio 2005 for Python 2.5 was too soon but that 2.6 might be a reasonable candidate, particularly since Microsoft no longer provides downloads for the Visual Studio 2003 compiler. .. _Visual Studio 2005 express will be free forever: http://msdn.microsoft.com/vstudio/express/ Contributing thread: - `Visual studio 2005 express now free `__ ---------------------------- Adding wsgiref to the stdlib ---------------------------- Guido suggested adding Phillip J. Eby's `reference implementation`_ of `PEP 333`_ (the Web Server Gateway Interface) to the standard library. People were generally in favor, though there was some brief discussion about adding a few extras including Ian Bicking's paste.lint validator and a simple dispatch mechanism. It looked like wsgiref would be added in time for Python 2.5. .. _reference implementation: http://svn.eby-sarna.com/wsgiref/ .. _PEP 333: http://www.python.org/dev/peps/pep-0333/ Contributing threads: - `Adding wsgiref `__ - `Adding wsgiref to stdlib `__ - `[Web-SIG] Adding wsgiref to stdlib `__ -------------------- Buildbots on Windows -------------------- Some of the Windows buildbots were hanging when the buildbot slave terminated the run early, but failed to terminate python_d.exe, thus making it impossible to recompile anything (since python_d.exe cannot be deleted while running on Windows). No one was certain what was causing the problems (though it seemed like it might be some sort of indexing service running in the background) but Martin v. L??wis was able to unstick the machines by creating a kill_python.exe application which looks for python_d.exe and kills it. Contributing thread: - `windows buildbot failures `__ ---------------------------------- Externally maintained packages PEP ---------------------------------- Following up on work from the last fortnight, Brett Cannon put together information on all the packages like sqlite and elementtree that are part of the Python standard library, but have their central repository somewhere else. It looked like a PEP would soon be forthcoming. Contributing threads: - `need info for externally maintained modules PEP `__ - `draft of externally maintained packages PEP `__ - `(hopefully) final draft of externally maintained code PEP `__ ----------------------------- PEP 359: The "make" statement ----------------------------- Discussion continued on `PEP 359`_'s "make" statement continued, looking in particular at ways that breaking the parallel with the class statement might make the "make" statement easier to use. In the end Guido asked me to kill the discussion, so I withdrew the PEP. .. _PEP 359: http://www.python.org/dev/peps/pep-0359/ Contributing threads: - `PEP 359: The "make" Statement `__ - `Updated: PEP 359: The make statement `__ -------------------------------- PEP 3102: Keyword-only arguments -------------------------------- Talin introduced `PEP 3102`_ which proposes support for "keyword-only" arguments, that is, arguments that must be specified with the name=value keyword syntax, not as positional arguments. The proposal came in two parts: * Allowing keyword arguments after varargs, e.g.:: def add_option(*opts, action='store', type='string', ...) * Allowing keyword arguments with no varargs, e.g.:: def compare(a, b, *, key=None): There was widespread support for the first part of the PEP, particularly since such signatures exist in functions like the builtin min and max already (which gained key= arguments in Python 2.5). The latter part people were unsure of, and suggested a variety of other syntaxes, though Guido had already decided on the "*" syntax. Discussion continued on this issue into the next fortnight. .. _PEP 3102: http://www.python.org/dev/peps/pep-3102/ Contributing thread: - `PEP 3102: Keyword-only arguments `__ ------------------------------------ String formatting for size_t objects ------------------------------------ Brett Cannon ran into some problems with the formatting of size_t objects. What was really needed was the C99 "z" printf modifier, but since Python aims for C89 conformance, that can't be used unconditionally. In the end, Brett Cannon modified Python's config to test if the "z" modifier is supported and then used that whenever possible. Contributing threads: - `PY_FORMAT_SIZE_T warnings on OS X `__ - `PY_FORMAT_SIZE_T warnings on OS X `__ --------------------------------- The Grammar file and SyntaxErrors --------------------------------- In working on a parser for a subset of the Python language, Michael Foord ran into some troubles using the Grammar/Grammar file in the Python distribution. In particular, the problem he was having was the entry:: list_for: 'for' exprlist 'in' testlist_safe [list_iter] which indicates that any expression list can be used as the assignment expression in a list comprehension, so that code like the following is valid by the Grammar file:: [1 for 1 in n] Of course Python doesn't allow this, but as Guido explained, the expression that Python really wants is not LL1, so Python fudges it in the parser, and then issues a SyntaxError later by checking that the nodes in the parse tree actually match the restricted type of nodes required. Contributing thread: - `Python Grammar Ambiguity `__ ------------------------- Pybench now in Python SVN ------------------------- Marc-Andre Lemburg offered to contribute pybench to Python in response to a previous thread indicating some of the problems with pystone. It's now checked in under the Tools directory. Contributing thread: - `2.5a1 Performance `__ --------------------------- Adding threading.released() --------------------------- Nick Coghlan asked if the ``released()`` function suggested in `PEP 343`_ should be added for Python 2.5 to support code like:: def thread_safe(): with sync_lock: # This is thread-safe with released(sync_lock): # Perform long-running or blocking operation # that doesn't need to hold the lock # We have the lock back here While it seemed occasionally useful (e.g. in the implementation of threading._Condition), this one looked like it would be put off until folks had had more experience with context managers. Contributing thread: - `Proposed addition to threading module - released `__ ------------------------------ Removing the me_hash for dicts ------------------------------ Kirat Singh asked about removing me_hash from the dict struct to save some space. People generally seemed opposed to trading off speed for space, particularly since it would slow down classes that define their own ``__hash__``. Contributing thread: - `Reducing memory overhead for dictionaries by removing me_hash `__ ------------------------------------ PEP 3101: Advanced String Formatting ------------------------------------ Talin introduced `PEP 3101`_ which proposes a new formatting system through a new ``string.format()`` method. This would allow specifying items through both positional and keyword arguments, as well as allowing user-defined classes to support their own set of format specifiers, e.g.:: "The story of {0}, {1}, and {c}".format(a, b, c=d) "Today is: {0:%x}".format(datetime.now()) There was some brief discussion about how to escape the brace characters, and some opposition to the compound name syntax (which allowed __getitem__-style access using a dotted notation) before the thread trailed off. .. _PEP 3101: http://www.python.org/dev/peps/pep-3101/ Contributing thread: - `PEP 3101: Advanced String Formatting `__ --------------------- Replacing SourceForge --------------------- Brett Cannon asked for some things that people liked and disliked about SourceForge as the Infrastructure committee moved forward on finding a replacement tracker for SF. There weren't too many positive comments, but some of the things SF was missing are: * A way to flag a patch as "reviewed"; "pending" won't work -- it just sets a timeout period and then deletes the message. * A way to tag a tracker item by the relevant documentation section (e.g. language reference, library reference, etc.) * The ability to participate in a bug discussion through email instead of the web interface * The ability to define a filter on tracker items so that you can be emailed when a new tracker item meets your criteria * A way to identify relations between bugs, e.g. this bug closes another bug. * The ability to close a bug with a checkin. A Call for Trackers was to be soon forthcoming. Contributing threads: - `Reviewed patches [was: SoC proposal: "fix some old, old bugs in sourceforge"] `__ - `what do you like about other trackers and what do you hate about SF? `__ - `Reviewed patches `__ ----------------------------------------------- Making decorated functions easier to introspect ----------------------------------------------- Nick Coghlan offered to add a function to the new functools module to make writing introspectable decorators easier. Many decorators that return new functions look something like:: def decorator(func): def new_func(*args, **kwargs): ... return new_func But the newly created function metadata (__name__, __doc__, etc.) is now inconsistent with the original function. Originally, Nick had proposed introducing a decorator function to do this, but he settled instead on a simple helper function, ``functools.update_wrapper``, which can be called by decorator writers to update the appropriate metadata. Contributing thread: - `Adding functools.decorator `__ --------------------------- Tkinter hangs due to Tk bug --------------------------- Thomas Wouters noticed that test_tcl locked up when Tcl and Tk were compiled with --enable-threads and he tried to refleaktest Tkinter. Seems that despite the lack of any note in the Tk documentation, Tk_Init() doesn't like being called twice even when the first call results in an error. Martin v. L??wis reported the bug to the Tk folks and added a workaround for the current behavior. Contributing thread: - `Tkinter lockups. `__ ================ Deferred Threads ================ - `introducing the experimental pyref wiki `__ - `methods on the bytes object `__ ================== Previous Summaries ================== - `[Python-checkins] r45321 - in python/trunk: Lib/test/test_traceback.py Lib/traceback.py Misc/NEWS `__ - `Py_Finalize does not release all memory, not even closely `__ - `Preserving the blamelist `__ - `PyObject_REPR() `__ - `New-style icons, .desktop file `__ - `Win64 AMD64 (aka x64) binaries available64 `__ =============== Skipped Threads =============== - `valgrind reports `__ - `Any reason that any()/all() do not take apredicateargument? `__ - `refleaks & test_tcl & threads `__ - `2.5 post-alpha1 broken on mac-intel machines `__ - `Summer of Code preparation `__ - `[C++-sig] GCC version compatibility `__ - `remote debugging with pdb `__ - `Py_BEGIN_ALLOW_THREADS around readdir()? `__ - `FYI: more clues re: tee+generator leak `__ - `[ python-Patches-790710 ] breakpoint command lists in pdb `__ - `FishEye on Python CVS Repository `__ - `problem installing current cvs - TabError `__ - `fat binaries for OSX `__ - `Returning -1 from function with unsigned long type `__ - `adding Construct to the standard library? `__ - `posix_confstr seems wrong `__ - `pdb segfaults in 2.5 trunk? `__ - `possible fix for recursive __call__ segfault `__ - `How to make _sre.c compile w/ C++? `__ - `Gentoo failures - it's blaming me... `__ - `a flattening operator? `__ - `[Python-checkins] r45505 - python/trunk/Modules/posixmodule.c `__ - `bug with __dict__? `__ - `Python Software Foundation seeks mentors and students for Google Summer of Code `__ - `PEP 355 (object-oriented paths) `__ - `proposal: evaluated string `__ - `SVN question `__ - `Google Summer of Code proposal: Pdb improvments `__ - `Stream codecs and _multibytecodec `__ - `python 2.5alpha and naming schemes `__ - `unrecognized command line option "-Wno-long-double" `__ - `extended bitwise operations `__ - `Weekly Python Patch/Bug Summary `__ - `[pypy-dev] Python Software Foundation seeks mentors and students for Google Summer of Code `__ - `Google Summer of Code proposal: improvement of long int and adding new types/modules. `__ - `bin codec + EOF `__ - `Module names in Python: was Re: python 2.5alpha and naming schemes `__ - `Removing Python 2.4 -m switch helpers from import.c `__ - `patch #1454481 - runtime tunable thread stack size `__ - `[Python-3000-checkins] r45617 - in python/branches/p3yk/Lib/plat-mac/lib-scriptpackages: CodeWarrior/CodeWarrior_suite.py CodeWarrior/__init__.py Explorer/__init__.py Finder/Containers_and_folders.py Finder/Files.py Finder/Finder_Basics.py Finder `__ - `[Python-3000-checkins] r45617 - in python/branches/p3yk/Lib/plat-mac/lib-scriptpackages: CodeWarrior/CodeWarrior_suite.py CodeWarrior/__init__.py Explorer/__init__.py Finder/Containers_and_folders.py Finder/Files.py Finder/Finder_Bas `__ - `Reject or update PEP 243? `__ - `IronPython Performance `__ - `[pypy-dev] Python Software Foundation seeksmentors and students for Google Summer of Code `__ - `New artwork for the osx port `__ - `[Python-checkins] Python Regression Test Failures refleak (1) `__ - `PEP 8 pylintrc? `__ - `Compiling w/ C++ (was: Reducing memory overhead for dictionaries by removing me_hash) `__ - `Builtin exit, good in interpreter, bad in code. `__ - `Buildbot messages and the build svn revision number `__ - `Google Summer of Code proposal: New class for work with binary trees AVL and RB as with the standard dictionary. `__ - `gettext.py bug #1448060 `__ - `SoC proposal: "fix some old, old bugs in sourceforge" `__ - `[Mono-dev] IronPython Performance `__ - `[IronPython] [Mono-dev] IronPython Performance `__ - `interested in Google Summer of Code: what should I do? `__ - `EuroPython 2006: Call for papers `__ - `GNU info version of documentation `__ - `big-memory tests `__ - `suggestion: except in list comprehension `__ - `Accessing DLL objects from other DLLs `__ - `Addressing Outstanding PEPs `__ - `PEP 304 (Was: Addressing Outstanding PEPs) `__ - `inheriting basic types more efficiently `__ - `Google Summer of Code proposal: New class for workwith binary trees AVL and RB as with the standard dictionary. `__ - `binary trees. Review obmalloc.c `__ - `A better and more basic array type `__ - `Type-Def-ing Python `__ - `traceback.py still broken in 2.5a2 `__ - `"mick-windows" buildbot uptime `__ - `rest2latex - was: Re: Raising objections `__ - `Is this a bad idea: picky floats? `__ - `Summer of Code mailing list `__ - `Bug day? `__ - `Float formatting and # `__ - `Crazy idea for str.join `__ - `rich comparisions and old-style classes `__ - `methods on the bytes object (was: Crazy idea for str.join) `__ - `Problem with inspect and PEP 302 `__ - `PyThreadState_SetAsyncExc and native extensions `__ - `__getslice__ usage in sre_parse `__ - `elimination of scope bleeding of iteration variables `__ - `[Python-3000] in-out parameters `__ - `socket module recvmsg/sendmsg `__ ======== Epilogue ======== This is a summary of traffic on the `python-dev mailing list`_ from April 16, 2006 through April 30, 2006. It is intended to inform the wider Python community of on-going developments on the list on a semi-monthly basis. An archive_ of previous summaries is available online. An `RSS feed`_ of the titles of the summaries is available. You can also watch comp.lang.python or comp.lang.python.announce for new summaries (or through their email gateways of python-list or python-announce, respectively, as found at http://mail.python.org). This python-dev summary is the 3rd written by the python-dev summary sucker, Steve Bethard. (Mmmmm... Summaries...) To contact me, please send email: - Steve Bethard (steven.bethard at gmail.com) Do *not* post to comp.lang.python if you wish to reach me. The `Python Software Foundation`_ is the non-profit organization that holds the intellectual property for Python. It also tries to advance the development and use of Python. If you find the python-dev Summary helpful please consider making a donation. You can make a donation at http://python.org/psf/donations.html . Every cent counts so even a small donation with a credit card, check, or by PayPal helps. -------------------- Commenting on Topics -------------------- To comment on anything mentioned here, just post to `comp.lang.python`_ (or email python-list at python.org which is a gateway to the newsgroup) with a subject line mentioning what you are discussing. All python-dev members are interested in seeing ideas discussed by the community, so don't hesitate to take a stance on something. And if all of this really interests you then get involved and join `python-dev`_! ------------------------- How to Read the Summaries ------------------------- That this summary is written using reStructuredText_. Any unfamiliar punctuation is probably markup for reST_ (otherwise it is probably regular expression syntax or a typo :); you can safely ignore it. We do suggest learning reST, though; it's simple and is accepted for `PEP markup`_ and can be turned into many different formats like HTML and LaTeX. Unfortunately, even though reST is standardized, the wonders of programs that like to reformat text do not allow us to guarantee you will be able to run the text version of this summary through Docutils_ as-is unless it is from the `original text file`_. .. _python-dev: http://www.python.org/dev/ .. _SourceForge: http://sourceforge.net/tracker/?group_id=5470 .. _python-dev mailing list: http://mail.python.org/mailman/listinfo/python-dev .. _c.l.py: .. _comp.lang.python: http://groups.google.com/groups?q=comp.lang.python .. _PEP Markup: http://www.python.org/peps/pep-0012.html .. _Docutils: http://docutils.sf.net/ .. _reST: .. _reStructuredText: http://docutils.sf.net/rst.html .. _PSF: .. _Python Software Foundation: http://python.org/psf/ .. _original text file: http://www.python.org/dev/summary/2006-04-16_2006-04-30.rst .. _archive: http://www.python.org/dev/summary/ .. _RSS feed: http://www.python.org/dev/summary/channews.rdf From samschul at pacbell.net Sat Jun 3 16:41:01 2006 From: samschul at pacbell.net (sam) Date: 3 Jun 2006 13:41:01 -0700 Subject: carshing the interpreter in two lines In-Reply-To: References: <1149343823.789918.210110@h76g2000cwa.googlegroups.com> <1149350854.072412.263920@f6g2000cwb.googlegroups.com> Message-ID: <1149367261.176919.134090@y43g2000cwc.googlegroups.com> Mel: Wow that book brings back memories. I scanned my copy to review the subject covered, and came to the conclusion that mind reading algorithms are the answer. Sam Schulenburg Mel Wilson wrote: > sam wrote: > > tomer: > > > > It is my opinion that you would loose performance if the Python > > interpreter had the additional task of verifying byte code. It might be > > more appropriate to have a preprocessor that did the verifying as it > > compiled the byte code. > > Possibly. A good book on the topic is Douglas Hofstadter's > _Goedel, Escher, Bach: an Eternal Golden Braid_. > > Particularly starting from the chapter "Contracrostipunctus". > > Cheers, Mel. > > > > > Sam Schulenburg > > > > gangesmaster wrote: > >> the following (random) code crashes my interpreter > >> (python 2.4.3/winxp): > >> > >> from types import CodeType as code > >> exec code(0, 5, 8, 0, "hello moshe", (), (), (), "", "", 0, "") > >> > >> i would expect the interpreter to do some verifying, at least for > >> sanity (valid opcodes, correct stack size, etc.) before executing > >> artbitrary code... after all, it was the BDFL who said """I'm not > >> saying it's uncrashable. I'm saying that if you crash it, it's a > >> bug unless proven harebrained.""" > >> > >> > >> -tomer > > From johnjsal at NOSPAMgmail.com Mon Jun 5 15:59:01 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 05 Jun 2006 19:59:01 GMT Subject: GUI Program Error In-Reply-To: <1149536396.375285.319390@y43g2000cwc.googlegroups.com> References: <1149536396.375285.319390@y43g2000cwc.googlegroups.com> Message-ID: <920hg.2238$No6.47697@news.tufts.edu> Byte wrote: > Hi, I'm using the "Learning to Program" GUI tutorial on > http://www.freenetpages.co.uk/hp/alan.gauld/ > and am trying to write my first GUI. However, the code the tutorial > gives for starting by making a window: > > > import Tkinter > > top = Tkinter.Tk() > > dir(top) > > Does not work. The Python interpreter does not complain about anything, > but the window the tutorial promises will apperar will not. I'm using > Python 2.4.2 and the Eric 3.7.0 IDE on Ubuntu 5.10. Anybody know what > to do? You have to call top.mainloop() for it work. What is dir(), btw? Is it a class for creating the application? From greg.kujawa at gmail.com Thu Jun 8 13:24:36 2006 From: greg.kujawa at gmail.com (gregarican) Date: 8 Jun 2006 10:24:36 -0700 Subject: what are you using python language for? In-Reply-To: References: <1149719891.761757.263650@c74g2000cwc.googlegroups.com> Message-ID: <1149787476.629293.266670@u72g2000cwu.googlegroups.com> Wow that's serious Old School. Reminds me of way-back-when in Data Processing class we used VisiCalc on the old Trash-80's for spreadsheet work. Cut a notch in those 5 1/4" floppies and voila, you doubled your storage capacity :-) Dennis Lee Bieber wrote: > On Thu, 08 Jun 2006 13:52:38 GMT, John Salerno > declaimed the following in comp.lang.python: > > > Jason wrote: > > > I've been working on an RPG character generator for consistent (yet > > > varied) set of role-playing systems. Nothing like a pen-and-pencil RPG > > > to throw in tons of special cases and strange rulesets. > > > > Sounds interesting. Something I've thought about as a project, but I'm > > not good enough yet! :) > > Many years ago I had the starship design tables from (first edition) > Traveller incorporated into a Multiplan spreadsheet running on a TRS-80 > Model 4 > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfraed at ix.netcom.com wulfraed at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-asst at bestiaria.com) > HTTP://www.bestiaria.com/ From lancepickens at gmail.com Tue Jun 27 14:08:12 2006 From: lancepickens at gmail.com (bio_enthusiast) Date: 27 Jun 2006 11:08:12 -0700 Subject: Questions about OSS projects. Message-ID: <1151431692.418333.123060@y41g2000cwy.googlegroups.com> I was wondering how to go about starting an open source project for doing routine biological problems? There is a plethora of scripts and a fairly large biopython project to back up anyone who tried, these however cater to the bioinformatics community and it loses the vast majority of the wet-lab scientists. How can someone who is used to writing small scripts and doing wet-lab work contribute to the open source community? Starting software projects seems to be the domain of people with much more experience and skill but there are some serious needs by people who do not have the skills to upkeep any software based project. From struggleyb at gmail.com Mon Jun 12 10:14:37 2006 From: struggleyb at gmail.com (Bo Yang) Date: Mon, 12 Jun 2006 22:14:37 +0800 Subject: Python or Ajax? In-Reply-To: References: Message-ID: <448D76CD.4030307@gmail.com> I think if you know java language very well but feel suffering with the error prone javascript , GWT is good choose for AJAX development . With the well-known IDE Eclipse your development time efficiency will promote fast ! From sjmachin at lexicon.net Fri Jun 2 19:25:28 2006 From: sjmachin at lexicon.net (John Machin) Date: Sat, 03 Jun 2006 09:25:28 +1000 Subject: beginner code problem In-Reply-To: <2006060218415316807-victimorcrime@yahoocom> References: <2006060218415316807-victimorcrime@yahoocom> Message-ID: <4480C8E8.50800@lexicon.net> On 3/06/2006 8:41 AM, RJ wrote: > I'm trying to teach myself Python (probably running into the old dog > new tricks issue) and I'm trying to start with the very basics to get a > handle on them. > > I'm trying to write code to get the computer to flip a coin 100 times > and give me the output of how many times heads and tails. After solving > a few syntax errors I seem to be stuck in an endless loop and have to > kill python. This can't happen with the code that you posted. It *could* happen if the statement count += 1 was not being executed once each time around the while loop -- like if it was *not* indented. # Bad code #1 import random flip = random.randrange(2) heads = tails = count = 0 while count < 100: if flip == 0: heads += 1 else: tails += 1 count += 1 print "The coin landed on heads", heads, 'times ' \ "and tails", tails, 'times' > A few times I would get it to print 'heads 0 (or 1) times > and tails 1 (or 0) times' 100 times. Again, can't happen with the code you have posted. If it is printing 100 times, that would be because you have indented the print statement so that it is being executed once each trip around the loop. # Bad code #2 import random flip = random.randrange(2) heads = tails = count = 0 while count < 100: if flip == 0: heads += 1 else: tails += 1 count += 1 print "The coin landed on heads", heads, 'times ' \ "and tails", tails, 'times' > > Here's the code I wrote: > > import random > > flip = random.randrange(2) > heads = 0 > tails = 0 > count = 0 > > while count < 100: To help you see what is happening, insert a print statement here; e.g.: print flip, count, heads, tails > > if flip == 0: > heads += 1 > > else: > tails += 1 > > > count += 1 > > > > print "The coin landed on heads", heads, 'times ' \ > "and tails", tails, 'times' > The code that you posted sets flip only once i.e. only 1 toss, not 100. If it is 0, you get 100 heads and 0 tails. Otherwise you get 0 heads and 100 tails. You need to get a new value for flip each trip. # Not quite so bad code import random heads = tails = count = 0 while count < 100: flip = random.randrange(2) # print flip, count, heads, tails # un-comment as/when required :-) if flip == 0: heads += 1 else: tails += 1 count += 1 print "The coin landed on heads", heads, 'times ' \ "and tails", tails, 'times' HTH, John From a at tempinbox.com Wed Jun 28 23:58:33 2006 From: a at tempinbox.com (a) Date: 28 Jun 2006 20:58:33 -0700 Subject: how do i use refreshCache with cheetah Message-ID: <1151553513.690286.127290@i40g2000cwc.googlegroups.com> how do i use refreshCache with cheetah From python.list at tim.thechases.com Mon Jun 19 12:23:16 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 19 Jun 2006 11:23:16 -0500 Subject: Formatted string to object In-Reply-To: <1150731552.799052.47320@r2g2000cwb.googlegroups.com> References: <1150731552.799052.47320@r2g2000cwb.googlegroups.com> Message-ID: <4496CF74.3070901@tim.thechases.com> > Can you use strings or %s strings like in the above or > > aaa = 'string' > aaa.%s() % 'upper' > > Somehow? Looks like you want to play with the eval() function. >>> aaa = 'hello' >>> result = eval("aaa.%s()" % 'upper') >>> result 'HELLO' Works for your second example. May work on your first example too. -tkc From sjmachin at lexicon.net Thu Jun 1 22:14:51 2006 From: sjmachin at lexicon.net (John Machin) Date: 1 Jun 2006 19:14:51 -0700 Subject: C# equivalent to range() In-Reply-To: <1149214153.359809.288610@i39g2000cwa.googlegroups.com> References: <1149214153.359809.288610@i39g2000cwa.googlegroups.com> Message-ID: <1149214491.034665.29030@j55g2000cwa.googlegroups.com> Neuruss wrote: > I'm sorry for asking about another language here, but since I only know > Python and I'm trying to write something in C#, I guess this is the > best place... > Bad guess. Ask questions about language X on comp.lang.X From anton at appsolutions.com Thu Jun 22 20:54:13 2006 From: anton at appsolutions.com (Anton van Straaten) Date: Fri, 23 Jun 2006 00:54:13 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150904134.520639.71070@b68g2000cwa.googlegroups.com> <4padnQn3SOWhkQfZnZ2dnUVZ_rqdnZ2d@speakeasy.net> Message-ID: Andreas Rossberg wrote: > Rob Warnock wrote: > >> >> Here's what the Scheme Standard has to say: >> >> http://www.schemers.org/Documents/Standards/R5RS/HTML/r5rs-Z-H-4.html >> 1.1 Semantics >> ... >> Scheme has latent as opposed to manifest types. Types are assoc- >> iated with values (also called objects) rather than with variables. >> (Some authors refer to languages with latent types as weakly typed >> or dynamically typed languages.) Other languages with latent types >> are APL, Snobol, and other dialects of Lisp. Languages with manifest >> types (sometimes referred to as strongly typed or statically typed >> languages) include Algol 60, Pascal, and C. > > > Maybe this is the original source of the myth that static typing is all > about assigning types to variables... > > With all my respect to the Scheme people, I'm afraid this paragraph is > pretty off, no matter where you stand. Besides the issue just mentioned > it equates "manifest" with static types. I understand "manifest" to mean > "explicit in code", which of course is nonsense - static typing does not > require explicit types. Also, I never heard "weakly typed" used in the > way they suggest - in my book, C is a weakly typed language (= typed, > but grossly unsound). That text goes back at least 20 years, to R3RS in 1986, and possibly earlier, so part of what it represents is simply changing use of terminology, combined with an attempt to put Scheme in context relative to multiple languages and terminology usages. The fact that we're still discussing this now, and haven't settled on terminology acceptable to all sides, illustrates the problem. The Scheme report doesn't actually say anything about how latent types relate to static types, in the way that I've recently characterized the relationship here. However, I thought this was a good place to explain how I got to where I am on this subject. There's been a lot of work done on soft type inference in Scheme, and other kinds of type analysis. The Scheme report talks about latent types as meaning "types are associated with values". While this might cause some teeth-grinding amongst type theorists, it's meaningful enough when you look at simple cases: cases where the type of a term is an exact match for the type tags of the values that flow through that term. When you get to more complex cases, though, most type inferencers for Scheme assign traditional static-style types to terms. If you think about this in conjunction with the term "latent types", it's an obvious connection to make that what the inferencer is doing is recovering types that are latent in the source. Once that connection is made, it's obvious that the tags associated with values are not the whole story: that the conformance of one or more values to a "latent type" may be checked by a series of tag checks, in different parts of a program (i.e. before, during and after the expression in question is evaluated). I gave a more detailed description of how latent types relate to tags in an earlier reply to Marshall (Spight, not Joe). Anton From k.retheesh at gmail.com Fri Jun 9 14:50:02 2006 From: k.retheesh at gmail.com (k.retheesh at gmail.com) Date: 9 Jun 2006 11:50:02 -0700 Subject: TypeError: unsubscriptable object In-Reply-To: References: <1149874726.470436.279200@i40g2000cwc.googlegroups.com> Message-ID: <1149879002.610430.72720@j55g2000cwa.googlegroups.com> So wat should I do ?? K.S.Sreeram wrote: > k.retheesh at gmail.com wrote: > > print template % (ID, IID, Function[:10], Description[:10], > > ErrorNumber, StatusCD) > > TypeError: unsubscriptable object > > It means either 'Function' or 'Description' is not a sequence. > Try inserting print statements to see what values they are. > > e.g: > > a = 2 > a[:10] > > will give me an 'unsubscriptable object' > > Regards > Sreeram > > > --------------enig08E562E3E8ED90BF5BC3C92B > Content-Type: application/pgp-signature > Content-Transfer-Encoding: base64 > Content-Disposition: inline; > filename="signature.asc" > Content-Description: OpenPGP digital signature > X-Google-AttachSize: 253 From fredrik at pythonware.com Sun Jun 11 16:18:52 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 11 Jun 2006 22:18:52 +0200 Subject: how to get the length of a number In-Reply-To: References: Message-ID: Stan Cook wrote: > Is there a function I've forgotten about to convert an > integer to a string? str(value) From rossberg at ps.uni-sb.de Fri Jun 23 05:55:06 2006 From: rossberg at ps.uni-sb.de (rossberg at ps.uni-sb.de) Date: 23 Jun 2006 02:55:06 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150904134.520639.71070@b68g2000cwa.googlegroups.com> Message-ID: <1151056505.908723.162580@u72g2000cwu.googlegroups.com> Anton van Straaten wrote: > > Languages with latent type systems typically don't include type > declarations in the source code of programs. The "static" type scheme > of a given program in such a language is thus latent, in the English > dictionary sense of the word, of something that is present but > undeveloped. Terms in the program may be considered as having static > types, and it is possible to infer those types, but it isn't necessarily > easy to do so automatically, and there are usually many possible static > type schemes that can be assigned to a given program. > > Programmers infer and reason about these latent types while they're > writing or reading programs. Latent types become manifest when a > programmer reasons about them, or documents them e.g. in comments. I very much agree with the observation that every programmer performs "latent typing" in his head (although Pascal Constanza's seems to have the opposite opinion). But I also think that "latently typed language" is not a meaningful characterisation. And for the very same reason! Since any programming activity involves latent typing - naturally, even in assembler! - it cannot be attributed to any language in particular, and is hence useless to distinguish between them. (Even untyped lambda calculus would not be a counter-example. If you really were to program in it, you certainly would think along lines like "this function takes two chuch numerals and produces a third one".) I hear you when you define latently typed languages as those that support the programmer's latently typed thinking by providing dynamic tag checks. But in the very same post (and others) you also explain in length why these tags are far from being actual types. This seems a bit contradictory to me. As Chris Smith points out, these dynamic checks are basically a necessaity for a well-defined operational semantics. You need them whenever you have different syntactic classes of values, but lack a type system to preclude interference. They are just an encoding for differentiating these syntactic classes. Their connection to types is rather coincidential. - Andreas From andrew at trevorrow.com Sun Jun 25 08:45:12 2006 From: andrew at trevorrow.com (Andrew Trevorrow) Date: Sun, 25 Jun 2006 22:45:12 +1000 Subject: Life + Python = Golly Message-ID: Golly is an open source, cross-platform Life app which features an unbounded universe and uses Gosper's hashlife algorithm to allow the exploration of patterns at unprecedented scales and speeds. We've just released version 1.0 and Python fans might be interested to hear that we're now using Python as our app's scripting language. More details, including screenshots and download links, are available at Golly's web site: http://golly.sourceforge.net/ The Python scripting interface is described here: http://golly.sourceforge.net/Help/scripting.html Any comments or suggestions are most welcome. Andrew From pc at p-cos.net Wed Jun 28 10:44:31 2006 From: pc at p-cos.net (Pascal Costanza) Date: Wed, 28 Jun 2006 16:44:31 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: <6gwog.488405$xt.80841@fe3.news.blueyonder.co.uk> References: <7zy7vt1mz2.fsf@app-3.diku.dk> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <1151384511.223582.305760@m73g2000cwd.googlegroups.com> <4gdkmiF1ldalhU3@individual.net> <4gfcclF1mpbg7U1@individual.net> <6gwog.488405$xt.80841@fe3.news.blueyonder.co.uk> Message-ID: <4gfiufF1mg6h9U1@individual.net> David Hopwood wrote: > Pascal Costanza wrote: >> David Hopwood wrote: >>> Pascal Costanza wrote: >>>> David Hopwood wrote: >>>>> Marshall wrote: >>>>> >>>>>> The real question is, are there some programs that we >>>>>> can't write *at all* in a statically typed language, because >>>>>> they'll *never* be typable? >>>>> In a statically typed language that has a "dynamic" type, all >>>>> dynamically typed programs are straightforwardly expressible. >>>> What about programs where the types change at runtime? >>> Staged compilation is perfectly compatible with static typing. >>> Static typing only requires that it be possible to prove absence >>> of some category of type errors when the types are known; it >>> does not require that all types are known before the first-stage >>> program is run. >> Can you change the types of the program that is already running, or are >> the levels strictly separated? > > In most staged compilation systems this is intentionally not permitted. > But this is not a type system issue. You can't change the types in a > running program because you can't change the program, period. And you > can't do that because most designers of these systems consider directly > self-modifying code to be a bad idea (I agree with them). Whether you consider something you cannot do with statically typed languages a bad idea or not is irrelevant. You were asking for things that you cannot do with statically typed languages. There are at least systems that a lot of people rely on (the JVM, .NET) that achieve runtime efficiency primarily by executing what is essentially self-modifying code. These runtime optimization systems have been researched primarily for the language Self, and also implemented in Strongtalk, CLOS, etc., to various degrees. Beyond that, I am convinced that the ability to update a running system without the need to shut it down can be an important asset. > Note that prohibiting directly self-modifying code does not prevent a > program from specifying another program to *replace* it. ...and this creates problems with moving data from one version of a program to the next. Pascal -- 3rd European Lisp Workshop July 3 - Nantes, France - co-located with ECOOP 2006 http://lisp-ecoop06.bknr.net/ From test at test.test Fri Jun 23 00:00:22 2006 From: test at test.test (test at test.test) Date: Thu, 22 Jun 2006 23:00:22 -0500 Subject: Python to PHP Login System (HTTP Post) References: <1151018390.792574.102920@b68g2000cwa.googlegroups.com> Message-ID: On 22 Jun 2006 16:19:50 -0700, "Justin Azoff" wrote: >Jeethu Rao wrote: >> You need to use httplib. >> http://docs.python.org/lib/httplib-examples.html >> >> Jeethu Rao > >Not at all. They need to read the documentation for urrlib: > >http://docs.python.org/lib/module-urllib.html >http://docs.python.org/lib/node483.html >"The following example uses the "POST" method instead:".... > >Additionally, they probably need to use cookielib, otherwise the logged >in state will not be persistant. Here's what's strange... I tried using urllib like this: ---------------------------------------------------------------------------------- try: msparams = urllib.urlencode({'user': self.components.User.text, 'pass': self.components.MagnetSharePassword.text, 'sublogin': 1}) f = urllib.urlopen("http://www.magnetshare.com/process.php", msparams) fc = f.read() fc.close() print fc except: self.statusBar.text = "Disconnected" result = dialog.alertDialog(self, 'Couldn\'t connect to MagnetShare.com! Please check your Internet connection, and then try again.') else: print fc ----------------------------------------------------------------------------------- ...and then I visited http://www.magnetshare.com/main.php to see if I was logged in. Sure enough I was logged in, but the exception was thrown anyway. I commented out the urlopen, f, and fc lines and tested it again. This time I made it to "else:" I'm stumped. I'm glad that the user can log in; however, the MagnetShare application needs to read in the response from the server, and then decide what to do with the information. From daniel.dittmar at sap.corp Wed Jun 21 12:01:20 2006 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Wed, 21 Jun 2006 18:01:20 +0200 Subject: 'module' object has no attribute 'ssl' In-Reply-To: References: Message-ID: Niurka Perez wrote: > ssl = socket.ssl(sock, self.key_file, > self.cert_file) > AttributeError: 'module' object has no attribute 'ssl' The socket module failed to import the _ssl module. And the ssl function gets only defined if _ssl could be imported. You probably haven't installed the OpenSSL-dev rpm. When the Python configure couldn't find the SSL header files, it struck _ssl from the list of compilable modules. Daniel From greg at cosc.canterbury.ac.nz Sat Jun 3 05:00:23 2006 From: greg at cosc.canterbury.ac.nz (greg) Date: Sat, 03 Jun 2006 21:00:23 +1200 Subject: import confused by contents of working directory In-Reply-To: <1149244708.049852.153980@i39g2000cwa.googlegroups.com> References: <1149244708.049852.153980@i39g2000cwa.googlegroups.com> Message-ID: <4ed1cvF1e4gqbU1@individual.net> Jon wrote: > It appears that (windows) python searches in the current working > directory before looking in the local site-packages directory, or that > '.' comes first in sys.path? Unless it behaves very differently on Windows from everything else, this isn't quite true. The current directory is only put in the path when using the interpreter interactively. When you do python somefile.py the directory containing somefile.py is put at the beginning of sys.path, not the current directory. So you'd still have the same problem even if you weren't cd'ed to the directory containing the test program. The moral is not to put your test program in the same directory as your package files. (Or if you must, have it delete sys.path[0] before importing anything.) -- Greg From __peter__ at web.de Thu Jun 1 08:03:27 2006 From: __peter__ at web.de (Peter Otten) Date: Thu, 01 Jun 2006 14:03:27 +0200 Subject: Function mistaken for a method References: Message-ID: Maric Michaud wrote: > Le Jeudi 01 Juin 2006 13:34, Peter Otten a ?crit?: >> A python-coded function has a __get__ attribute, a C-function doesn't. >> Therefore C1.f performs just the normal attribute lookup while C2.f also >> triggers the f.__get__(C2(), C2) call via the descriptor protocol which >> happens to return a bound method. > I don't think it's about c-coded versus python-coded stuff, C1.f is a > type, C2.f is a method. You are right, int is a type not a function, but presence (and implementation, of course) of __get__ is still the distinguishing factor: >>> class Int(int): ... class __metaclass__(type): ... def __get__(*args): print "XXX", args ... >>> class C: ... int = Int ... >>> C().int XXX (, <__main__.C instance at 0x402948cc>, ) Also: >>> from math import sin >>> sin >>> def son(x): pass ... >>> class C: ... sin = sin ... son = son ... >>> C().sin(0) 0.0 >>> C().son(0) Traceback (most recent call last): File "", line 1, in ? TypeError: son() takes exactly 1 argument (2 given) Peter From g.brandl-nospam at gmx.net Wed Jun 28 15:29:31 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Wed, 28 Jun 2006 21:29:31 +0200 Subject: Immutability In-Reply-To: References: Message-ID: Duncan Booth wrote: > Georg Brandl wrote: > >> In my opinion property isn't really meant to be used as a decorator since >> it's impossible to create a read-write property. The decorator pattern >> doesn't really fit here. >> > I agree that property isn't currently intended to be used as a decorator, > but it isn't actually *impossible* to create a read-write property using > decorators. Here is one way: Yes, I only wanted to say that it isn't possible by just using the builtin property function as a decorator. Georg From onurb at xiludom.gro Fri Jun 23 11:44:03 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Fri, 23 Jun 2006 17:44:03 +0200 Subject: Python in HTML In-Reply-To: <1151077239.840572.175120@y41g2000cwy.googlegroups.com> References: <1151077239.840572.175120@y41g2000cwy.googlegroups.com> Message-ID: <449c0c43$0$11196$636a55ce@news.free.fr> brochu121 at gmail.com wrote: > Does anyone know of a way to embed python scripts into html, much like > you would javascript or php? I think you'd better learn the profound difference between client-side and server-side scripting. > I do not want to use this to connect to a > database, but rather for a functional script to be called when a user > clicks on a link to open a page. If it's client-side scripting, javascript is the only option. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From michele.simionato at gmail.com Fri Jun 9 04:26:53 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 9 Jun 2006 01:26:53 -0700 Subject: tracking dependencies In-Reply-To: <4488679a$1@news.uni-ulm.de> References: <1149760106.420216.167790@g10g2000cwb.googlegroups.com> <4488679a$1@news.uni-ulm.de> Message-ID: <1149841613.469606.38660@c74g2000cwc.googlegroups.com> Dennis Benzinger wrote: > > I've never tried it, but http://www.tarind.com/depgraph.html looks like > what you are looking for. This is EXACTLY what I had in mind :-) Michele Simionato From cdsmith at twu.net Sat Jun 24 16:03:14 2006 From: cdsmith at twu.net (Chris Smith) Date: Sat, 24 Jun 2006 14:03:14 -0600 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> Message-ID: Chris F Clark wrote: > Chris Smith writes: > > I thought about this in the context of reading Anton's latest post to > > me, but I'm just throwing out an idea. > > I wrote: > > I think there is some sense of convergence here. > > Apologies for following-up to my own post, but I forgot to describe > the convergence. > > The convergence is there is something more general that what type > theorists talk about when discussing types. Type theory is an > abstraction and systemization of reasoning about types. This more > general reasoning doesn't need to be sound, it just needs to be based > aound "types" and computations. Unfortunately, I have to again reject this idea. There is no such restriction on type theory. Rather, the word type is defined by type theorists to mean the things that they talk about. Something becomes a type the instant someone conceives of a type system that uses it. We could try to define a dynamic type system, as you seem to say, as a system that checks against only what can be known about some ideal type system that would be able to prove the program valid... but I immediately begin to wonder if it would ever be possible to prove that something is a dynamic type system for a general-purpose (Turing- complete) language. If you could define types for a dynamic type system in some stand-alone way, then this difficulty could be largely pushed out of the way, because we could say that anything that checks types is a type system, and then worry about verifying that it's a sound type system without worrying about whether it's a subset of the perfect type system. So back to that problem again. You also wrote: > I consider any case where a program gives a function outside of its > domain a "type error", because an ideal (but unacheivable) type system > would have prevented it. That does not make all errors, type errors, > because if I give a program an input within its domain and it > mis-computes the result, that is not a type error. So what is the domain of a function? (Heck, what is a function? I'll neglect that by assuming that a function is just an expression; otherwise, this will get more complicated.) I see three possible ways to look at a domain. (I need a word here that implies something like a set, but I don't care to verify the axioms of set theory. I'm just going to use set. Hope that's okay.) 1. The domain is the set of inputs to that expression which are going to produce a correct result. 2. The domain is the set of inputs that I expected this expression to work with when I wrote it. 3. The domain is the set of inputs for which the expression has a defined result within the language semantics. So the problem, then, more clearly stated, is that we need something stronger than #3 and weaker than #1, but #2 includes some psychological nature that is problematic to me (though, admittedly, FAR less problematic than the broader uses of psychology to date.) Is that a fair description of where we are in defining types, then? -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation From bdesth.quelquechose at free.quelquepart.fr Thu Jun 1 19:37:02 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 02 Jun 2006 01:37:02 +0200 Subject: Function mistaken for a method In-Reply-To: References: <447ee701$0$22029$626a54ce@news.free.fr> Message-ID: <447f4a98$0$11216$636a55ce@news.free.fr> Eric Brunel a ?crit : > On Thu, 01 Jun 2006 15:07:26 +0200, bruno at modulix > wrote: > >> Do yourself a favour : use new-style classes. >> class C(object) > > > I would if I could: I'm stuck with Python 2.1 for the moment (I should > have mentionned it; sorry for that). Err, yes - it actually makes most of my explanations inaccurate. > [snip] (snip too) From david.nospam.hopwood at blueyonder.co.uk Tue Jun 27 10:03:27 2006 From: david.nospam.hopwood at blueyonder.co.uk (David Hopwood) Date: Tue, 27 Jun 2006 14:03:27 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: <1151384511.223582.305760@m73g2000cwd.googlegroups.com> References: <7zy7vt1mz2.fsf@app-3.diku.dk> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <1151384511.223582.305760@m73g2000cwd.googlegroups.com> Message-ID: Marshall wrote: > The real question is, are there some programs that we > can't write *at all* in a statically typed language, because > they'll *never* be typable? In a statically typed language that has a "dynamic" type, all dynamically typed programs are straightforwardly expressible. In a statically typed, Turing-complete language that does not have a "dynamic" type, it is always *possible* to express a dynamically typed program, but this may require a global transformation of the program or use of an interpreter -- i.e. the "Felleisen expressiveness" of the language is reduced. -- David Hopwood From maric at aristote.info Mon Jun 12 04:16:36 2006 From: maric at aristote.info (Maric Michaud) Date: Mon, 12 Jun 2006 10:16:36 +0200 Subject: Function to remove elements from a list not working In-Reply-To: <45877.10.209.4.1.1150099961.squirrel@10.105.1.3> References: <45877.10.209.4.1.1150099961.squirrel@10.105.1.3> Message-ID: <200606121016.37334.maric@aristote.info> Le Lundi 12 Juin 2006 10:12, Girish Sahani a ?crit?: > def getl5(): > ? ? l5 = [] > ? ? pairList = [[1,2],[3,4],[3,5],[3,6],[9,7],[8,9],[8,7],[7,9],[11,10]] > ? ? l4 = > [[4,2],[4,7],[4,10],[4,12],[9,2],[9,7],[9,10],[9,12],[11,2],[11,7]] for > pair in l4: > ? ? ? ? if pair not in pairList: > ? ? ? ? ? ? element.remove(l4) > ? ? l5.append(element) element ??? > ? ? print "l5 is",l5 -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From pc at p-cos.net Thu Jun 15 03:26:29 2006 From: pc at p-cos.net (Pascal Costanza) Date: Thu, 15 Jun 2006 09:26:29 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> Message-ID: <4fcgd5F1hv9ilU1@individual.net> Neelakantan Krishnaswami wrote: > In article <4fb97sF1if8l6U1 at individual.net>, Pascal Costanza wrote: >> Torben ?gidius Mogensen wrote: >> >>> On a similar note, is a statically typed langauge more or less >>> expressive than a dynamically typed language? Some would say less, as >>> you can write programs in a dynamically typed language that you can't >>> compile in a statically typed language (without a lot of encoding), >>> whereas the converse isn't true. >> It's important to get the levels right here: A programming language >> with a rich static type system is more expressive at the type level, >> but less expressive at the base level (for some useful notion of >> expressiveness ;). > > This doesn't seem obviously the case to me. If you have static > information about your program, the compiler can use this information > to automate a lot of grunt work away. > > Haskell's system of typeclasses work this way. If you tell the > compiler how to print integers, and how to print lists, then when you > call a print function on a list of list of integers, then the compiler > will automatically figure out the right print function using your base > definitions. This yields an increase in Felleisen-expressiveness over > a dynamically typed language, because you would need to globally > restructure your program to achieve a similar effect. > > More dramatic are the "polytypic" programming languages, which let you > automate even more by letting you write generic map, fold, and print > functions which work at every type. Yes, but these decisions are taken at compile time, without running the program. Pascal -- 3rd European Lisp Workshop July 3 - Nantes, France - co-located with ECOOP 2006 http://lisp-ecoop06.bknr.net/ From kentilton at gmail.com Tue Jun 13 12:36:15 2006 From: kentilton at gmail.com (Ken Tilton) Date: Tue, 13 Jun 2006 12:36:15 -0400 Subject: TONIGHT! Lisp group beerfest in NYC, PyCells to be discussed Message-ID: <2QBjg.497$Yq7.348@fe12.lga> The royal We has just learned that His Kennyness will be honoring the boozehounds of LispNYC with His Presence tonight (deets below). He will come bearing Celtk and news of PyCells, though the top billing tonight goes to SoC student Extraordinaire Samantha Kleinberg. kenzo > Please join us for our next meeting on Tuesday, June 13th from 7:00 > to 9:00 at Westside Brewery. > > With Summer of Code being here, this is a great opportunity to talk and > drink regarding the students and their projects! > > Hope to see you there! > > > > Directions: > > Westside Brewery in the VIP room > 340 Amsterdam Ave. > (On the West side of Amsterdam Ave., 76th-77th) > > Directions by subway: 1-2-3-9 (the red line) to 72nd or 79th and > Broadway. From 72nd, walk up Amsterdam (not Broadway). From 79th, walk > east one long block to Amsterdam and turn right/south. > > Directions by car: 79th street exit from west side highway, down West > End Ave or Broadway to 76th, turn left and one or two blocks to > Amsterdam. -- Cells: http://common-lisp.net/project/cells/ "I'll say I'm losing my grip, and it feels terrific." -- Smiling husband to scowling wife, New Yorker cartoon From pc at p-cos.net Thu Jun 22 08:15:13 2006 From: pc at p-cos.net (Pascal Costanza) Date: Thu, 22 Jun 2006 14:15:13 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150902275.129780.50260@p79g2000cwp.googlegroups.com> <1150918629.818145.143220@y41g2000cwy.googlegroups.com> <4fv081F1jh4ifU1@individual.net> <1150967543.947096.72840@g10g2000cwb.googlegroups.com> <4fv84rF1kp06kU1@individual.net> Message-ID: <4fvfuiF1kncqtU1@individual.net> Andreas Rossberg wrote: > Pascal Costanza wrote: >> >> Consider a simple expression like 'a + b': In a dynamically typed >> language, all I need to have in mind is that the program will attempt >> to add two numbers. In a statically typed language, I additionally >> need to know that there must a guarantee that a and b will always hold >> numbers. > > I'm confused. Are you telling that you just write a+b in your programs > without trying to ensure that a and b are in fact numbers?? Basically, yes. Note that this is a simplistic example. Consider, instead, sending a message to an object, or calling a generic function, without ensuring that there will be applicable methods for all possible cases. When I get a "message not understood" exception, I can then decide whether that kind of object shouldn't be a receiver in the first place, or else whether I should define an appropriate method. I don't want to be forced to decide this upfront, because either I don't want to be bothered, or maybe I simply can't because I don't understand the domain well enough yet, or maybe I want to keep a hook to be able to update the program appropriately while it is running. Pascal -- 3rd European Lisp Workshop July 3 - Nantes, France - co-located with ECOOP 2006 http://lisp-ecoop06.bknr.net/ From learner404 at gmail.com Fri Jun 16 04:37:23 2006 From: learner404 at gmail.com (learner404 at gmail.com) Date: 16 Jun 2006 01:37:23 -0700 Subject: pyHook equivalent on Linux ? (mouse and keyboard events without focus) Message-ID: <1150447043.199307.256990@c74g2000cwc.googlegroups.com> Hello, I have a Windows Pyhon-Tk app which need to capture mouse end keyboard events even when the app is not in focus. On Windows so far I've used the excellent PyHook which does the job perfectly: " The pyHook library wraps the low-level mouse and keyboard hooks in the Windows Hooking API for use in Python applications." http://www.cs.unc.edu/~parente/tech/tr08.shtml Is there something similar on Linux (I'm using Ubuntu/Kubuntu) ? Should I go down down to the Windows Manager ? Can my Python-Tkinter app communicate with KDE or Gnome to know and use these events ? Any suggestions/leads would me much appreciated. :) learner404 From mahs at telcopartners.com Tue Jun 20 18:55:18 2006 From: mahs at telcopartners.com (Michael Spencer) Date: Tue, 20 Jun 2006 15:55:18 -0700 Subject: Getting external name of passed variable In-Reply-To: <4498420F.1050504@ilm.com> References: <4498420F.1050504@ilm.com> Message-ID: David Hirschfield wrote: > I'm not sure this is possible, but it sure would help me if I could do it. > > Can a function learn the name of the variable that the caller used to > pass it a value? For example: > > def test(x): > print x > > val = 100 > test(val) > > Is it possible for function "test()" to find out that the variable it is > passed, "x", was called "val" by the caller? > Some kind of stack inspection? Perhaps, but don't try it ;-) > > Any help greatly appreciated, > -David > Can't you use keyword arguments? >>> def test(**kw): ... print kw ... >>> test(val=3) {'val': 3} >>> test(val=3, otherval = 4) {'otherval': 4, 'val': 3} >>> Michael From sambo at void.com Sun Jun 4 12:05:03 2006 From: sambo at void.com (Sambo) Date: Sun, 04 Jun 2006 12:05:03 -0400 Subject: mutable member, bug or ... Message-ID: By accident I assigned int to a class member 'count' which was initialized to (empty) string and had no error till I tried to use it as string, obviously. Why was there no error on assignment( near the end ). class Cgroup_info: group_name = "" count = "0" #last time checked and processed/retrieved first = "0" last = "" retrieval_type = "" # allways , ask( if more than some limit), none date_checked = "" time_checked = "" new_count = "" new_first = "" new_last = "" # local storage maintanance vars pointer_file = "" message_file = "" #maintanance vars cur_mess_num = 0 cur_mess_id = "" def __init__( self ): group_name = "" count = "0" #last time checked and processed/retrieved def get_count( self ): print self.count, type( self.count ) return string.atoi( self.count, 10 ) class server_info: def "(server_info::)"get_group_stat( self, grp ): gr_info = Cgroup_info() gr_info.group_name = grp try: ind = self.group_list.index( grp ) except ValueError: gr_info.count(0) return ( gr_info ) print ind if len( self.group_list[ind].split() ) == 4: gr_info.count = self.group_list[ind].split()[1] gr_info.first = self.group_list[ind].split()[2] gr_info.last = self.group_list[ind].split()[3] else: gr_info.count = gr_info.first = gr_info.last = "0" return( gr_info ) From kapil.sundrani at wipro.com Thu Jun 1 03:08:25 2006 From: kapil.sundrani at wipro.com (kapil.sundrani at wipro.com) Date: Thu, 1 Jun 2006 12:38:25 +0530 Subject: problem with file upload... Message-ID: <865660148009AD47BBBFD82BFED3A92601E785A1@BLR-EC-MBX04.wipro.com> I have a problem in uploading a file. The input tag looks like and the form tag looks like.
But still after form submission I don't get the file data. Debugging shows that the input field is being taken as a MinifieldStorage instead of FieldStorage. Thanks in advance for any help :-) Regards, Kapil The information contained in this electronic message and any attachments to this message are intended for the exclusive use of the addressee(s) and may contain proprietary, confidential or privileged information. If you are not the intended recipient, you should not disseminate, distribute or copy this e-mail. Please notify the sender immediately and destroy all copies of this message and any attachments. WARNING: Computer viruses can be transmitted via email. The recipient should check this email and any attachments for the presence of viruses. The company accepts no liability for any damage caused by any virus transmitted by this email. www.wipro.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From cdsmith at twu.net Mon Jun 26 19:33:29 2006 From: cdsmith at twu.net (Chris Smith) Date: Mon, 26 Jun 2006 17:33:29 -0600 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> Message-ID: Chris F Clark wrote: > Ok, we'll get there. First, we need to step back in time, to when there > was roughly algol, cobol, fortran, and lisp. Back then, at least as I > understood things, there were only a few types that generally people > understood integer, real, and (perhaps) pointer. In order to continue my tradition of trying to be as precise as possible, let me point out that of course there were more "candidate types", as it were, and that people understood them just fine. They just didn't have a type system in place to make them into real types, so they didn't think to call them types. > The important thing is the dynamicism of lisp allowed one to write > polymorphic programs, before most of us knew the term. Sure. In exchange for giving up the proofs of the type checker, you could write all kinds of programs. To this day, we continue to write programs in languages with dynamic checking features because we don't have powerful enough type systems to express the corresponding type system. > Thus, as we traverse a list, the first element might be an integer, > the second a floating point value, the third a sub-list, the fourth > and fifth, two more integers, and so on. If you look statically at > the head of the list, we have a very wide union of types going by. > However, perhaps there is a mapping going on that can be discerned. > For example, perhaps the list has 3 distinct types of elements > (integers, floating points, and sub-lists) and it circles through the > types in the order, first having one of each type, then two of each > type, then four of each type, then eight, and so on. The world is now > patterned. > > However, I don't know how to write a static type annotation that > describes exactly that type. I believe that, in fact, it would be trivial to imagine a type system which is capable of expressing that type. Okay, not trivial, since it appears to be necessary to conceive of an infinite family of integer types with only one value each, along with range types, and relationships between them; but it's probably not completely beyond the ability of a very bright 12-year-old who has someone to describe the problem thoroughly and help her with the notation. The more interesting problem is whether this type system could be made: (a) unobstrusive enough, probably via type inference or something along those lines, that it would be usable in practice; and (b) general enough that you could define a basic type operator that applies to a wide range of problems rather than revising your type operator the first time you need a complete 3-tree of similar form. > That may just be my lack of experience > in writing annotations. You would, of course, need a suitable type system first. For example, it appears to me that there is simply no possible way of expressing what you've described in Java, even with the new generics features. Perhaps it's possible in ML or Haskell (I don't know). My point is that if you were allowed to design a type system to meet your needs, I bet you could do it. > And, this brings us to the point, if the data that my program > encounters doesn't match the model I have formulated, then something > is of the wrong "type". Equally importantly, the dynamic tags, have > helped me discover that type error. Sure. The important question, then, is whether there exists any program bug that can't be formulated as a type error. And if so, what good does it do us to talk about type errors when we already have the perfectly good word "bug" to describe the same concept? > Now, the example may have seemed arbitrary to you, and it was in some > sense arbitrary. Arbitrary is good. One of the pesky things that keeps getting in the way here is the intuition attached to the word "type" that makes everyone think "string or integer". -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation From scott.daniels at acm.org Sun Jun 25 12:53:53 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Sun, 25 Jun 2006 09:53:53 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: <1151244628.566060.40500@p79g2000cwp.googlegroups.com> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150908952.804184.218990@r2g2000cwb.googlegroups.com> <1150991074.705803.211570@m73g2000cwd.googlegroups.com> <1151244628.566060.40500@p79g2000cwp.googlegroups.com> Message-ID: <449eba8d$1@nntp0.pdx.net> rossberg at ps.uni-sb.de wrote: > Huh? There is a huge, fundamental difference: namely whether a type > system is sound or not. A soundness proof is obligatory for any serious > type theory, and failure to establish it simply is a bug in the theory. So you claim Java and Objective C are "simply bugs in the theory." --Scott David Daniels scott.daniels at acm.org From a at tempinbox.com Thu Jun 29 12:58:52 2006 From: a at tempinbox.com (a) Date: 29 Jun 2006 09:58:52 -0700 Subject: list comprehension Message-ID: <1151600332.552024.119990@y41g2000cwy.googlegroups.com> can someone tell me how to use them thanks From rpdooling at gmail.com Sun Jun 25 07:45:45 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 25 Jun 2006 04:45:45 -0700 Subject: Python taught in schools? In-Reply-To: <1151220913.406987.162420@u72g2000cwu.googlegroups.com> References: <1151220913.406987.162420@u72g2000cwu.googlegroups.com> Message-ID: <1151235945.569325.68430@r2g2000cwb.googlegroups.com> dan>> but out of curiousity does dan>> anyone know of a school that teaches Python? http://www.python.org/about/quotes/ University of Maryland "I have the students learn Python in our undergraduate and graduate Semantic Web courses. Why? Because basically there's nothing else with the flexibility and as many web libraries," said Prof. James A. Hendler. rd From per9000 at gmail.com Wed Jun 28 17:46:33 2006 From: per9000 at gmail.com (per9000) Date: 28 Jun 2006 14:46:33 -0700 Subject: compiling python (or ironpython) to .exe or .dll for or not for .NET References: <1151501398.664329.142920@d56g2000cwd.googlegroups.com> Message-ID: <1151531193.852307.223440@x69g2000cwx.googlegroups.com> Update: I have found a holy handgrenade. I found something that seems to work fine for me - I've only tried it for 5 minutes but seems to work very smoothly. Open-source, Mozilla license, you know the drill... http://www.py2exe.org/ py2exe (the name makes me fall in love) creates some dll's for me containing python I guess. 2006-06-28 23:26 . 2006-06-28 23:26 .. 2005-09-28 13:41 77 824 bz2.pyd 2006-06-28 23:26 19 456 fib.exe 2006-06-28 23:26 641 449 library.zip 2003-02-21 04:42 348 160 MSVCR71.dll 2005-09-28 13:41 1 867 776 python24.dll 2005-09-28 13:41 405 504 unicodedata.pyd 2005-09-28 13:41 4 608 w9xpopen.exe 2005-09-28 13:41 69 632 zlib.pyd 8 File(s) 3 434 409 bytes My goal here is some kind of fibonacci stuff, preferably for dot net, but the extremely clean code in python (that deals with fibonaccinumbers that are large beyond being silly) dies in C*. I have to build my own sillyINT class and I don't like building sillyINT classes. Before I depress the enter button it finds that the number 123456789012345678901234567890123 has the nearest smaller and larger fibonacci numbers: 110560307156090817237632754212345 and 178890334785183168257455287891792. And my code remains hidden (I guess). Has someone tried some other (costless) holy handgrenade that does the trick? /Per Erik Strandberg yet another FibonacciNumerologist From pc at p-cos.net Wed Jun 21 09:01:33 2006 From: pc at p-cos.net (Pascal Costanza) Date: Wed, 21 Jun 2006 15:01:33 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <4fpvbvF1keed1U1@individual.net> <4fqonoF1kfkapU1@individual.net> <1150824752.799997.206210@p79g2000cwp.googlegroups.com> <4fqt33F1kfd1jU1@individual.net> <2N3mg.462963$xt.331923@fe3.news.blueyonder.co.uk> <4fsbivF1jqb81U1@individual.net> Message-ID: <4fsu9dF1k21c9U1@individual.net> Joachim Durchholz wrote: > Pascal Costanza schrieb: >> (It's really important to understand that the idea is to use this for >> deployed programs - albeit hopefully in a more structured fashion - >> and not only for debugging. The example I have given is an extreme one >> that you would probably not use as such in a "real-world" setting, but >> it shows that there is a boundary beyond which static type systems >> cannot be used in a meaningful way anymore, at least as far as I can >> tell.) > > As soon as the running program can be updated, the distinction between > "static" (compile time) and "dynamic" (run time) blurs. > You can still erect a definition for such a case, but it needs to refer > to the update process, and hence becomes language-specific. In other > words, language-independent definitions of dynamic and static typing > won't give any meaningful results for such languages. > > I'd say it makes more sense to talk about what advantages of static vs. > dynamic typing can be applied in such a situation. > E.g. one interesting topic would be the change in trade-offs: making > sure that a type error cannot occur becomes much more difficult > (particularly if the set of available types can change during an > update), so static typing starts to lose some of its appeal; OTOH a good > type system can give you a lot of guarantees even in such a situation, > even if it might have to revert to the occasional run-time type check, > so static checking still has its merits. I am not opposed to this view. The two examples I have given for things that are impossible in static vs. dynamic type systems were intentionally extreme to make the point that you have to make a choice, that you cannot just blindly throw (instances of) both approaches together. Static type systems potentially change the semantics of a language in ways that cannot be captured by dynamically typed languages anymore, and vice versa. There is, of course, room for research on performing static type checks in a running system, for example immediately after or before a software update is applied, or maybe even on separate type checking on software increments such that guarantees for their composition can be derived. However, I am not aware of a lot of work in that area, maybe because the static typing community is too focused on compile-time issues. Personally, I also don't think that's the most interesting issue in that area, but that's of course only a subjective opinion. Pascal -- 3rd European Lisp Workshop July 3 - Nantes, France - co-located with ECOOP 2006 http://lisp-ecoop06.bknr.net/ From andrewdalke at gmail.com Mon Jun 19 16:51:34 2006 From: andrewdalke at gmail.com (andrewdalke at gmail.com) Date: 19 Jun 2006 13:51:34 -0700 Subject: Seeking regex optimizer In-Reply-To: <1150650439.651839.38180@y41g2000cwy.googlegroups.com> References: <1150650439.651839.38180@y41g2000cwy.googlegroups.com> Message-ID: <1150750294.232093.304230@p79g2000cwp.googlegroups.com> Kay Schluehr wrote: > I have a list of strings ls = [s_1,s_2,...,s_n] and want to create a > regular expression sx from it, such that sx.match(s) yields a SRE_Match > object when s starts with an s_i for one i in [0,...,n]. Why do you want to use a regex for this? When you have constant strings there are other solutions. For example, this uses Nicolas Lehuen's pytst module from http://nicolas.lehuen.com/index.php/Pytst >>> import tst >>> tree = tst.TST() >>> tree["aa"] = (1, "String with 'aa'") >>> tree["aahhh"] = (2, "At the doctor's") >>> tree["a"] = (3, "indefinite article") >>> tree.scan("This is a bunch of text. Have you seen an aardvark?", ... tst.TupleListAction()) [('This is ', -8, None), ('a', 1, (3, 'indefinite article')), (' bunch of text. H', -18, None), ('a', 1, (3, 'indefinite article')), ('ve you seen ', -12, None), ('a', 1, (3, 'indefinite article')), ('n ', -2, None), ('aa', 2, (1, "String with 'aa'")), ('rdv', -3, None), ('a', 1, (3, 'indefinite article')), ('rk?', -3, None)] >>> Each returned tuple has three elements: For a substring which is not a match these are: - the unmatched substring - the negative length of the substring - None For a substring which matches: - the matched substring - the positive length of the substring - the value of the match in the TST (the tree) It uses Aho-Corasick for the implementation which is fast and does what you expect it to do. Nor does it have a problem of matching more than 99 possible strings as the regexp approach may have. Andrew dalke at dalkescientific.com From robert.thorpe at antenova.com Tue Jun 20 05:12:25 2006 From: robert.thorpe at antenova.com (Rob Thorpe) Date: 20 Jun 2006 02:12:25 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> Message-ID: <1150794745.148997.245840@b68g2000cwa.googlegroups.com> Chris Smith wrote: > Rob Thorpe wrote: > > A language is latently typed if a value has a property - called it's > > type - attached to it, and given it's type it can only represent values > > defined by a certain class. > > I'm assuming you mean "class" in the general sense, rather than in the > sense of a specific construct of some subset of OO programming > languages. Yes. > Now I define a class of values called "correct" values. I define these > to be those values for which my program will produce acceptable results. > Clearly there is a defined class of such values: (1) they are > immediately defined by the program's specification for those lines of > code that produce output; (2) if they are defined for the values that > result from any expression, then they are defined for the values that > are used by that expression; and (3) for any value for which correctness > is not defined by (1) or (2), we may define its "correct" values as the > class of all possible values. I'm not talking about correctness, I'm talking about typing. > Now, by your definition, any language > which provides checking of that property of correctness for values is > latently typed. No, that isn't what I said. What I said was: "A language is latently typed if a value has a property - called it's type - attached to it, and given it's type it can only represent values defined by a certain class." I said nothing about the values producing correct outputs, or being correct inputs. I only said that they have types. What I mean is that each value in the language is defined by two peice of information, its contents X and its type T. > Of course, there are no languages that assign this > specific class of values; but ANY kind of correctness checking on values > that a language does (if it's useful at all) is a subset of the perfect > correctness checking system above. Apparently, we should call all such > systems "latent type systems". No, I'm speaking about type checking not correctness. > Can you point out a language that is not > latently typed? Easy, any statically typed language is not latently typed. Values have no type associated with them, instead variables have types. If I tell a C program to print out a string but give it a number it will give an error telling me that the types mismatch where the variable the number is held in is used to assign to a variable that must hold a string. Similarly if I have a lisp function that prints out a string it will also fail when given a number, but it will fail at a different point, it will fail when the type of the value is examined and found to be incorrect. > I'm not trying to poke holes in your definition for fun. I am proposing > that there is no fundamental distinction between the kinds of problems > that are "type problems" and those that are not. Types are not a class > of problems; they are a class of solutions. Exactly. Which is why they are only tangentially associated with correctness. Typing is a set of rules put in place to aid correctness, but it is not a system that attempts to create correctness itself. > Languages that solve > problems in ways that don't assign types to variables are not typed > languages, even if those same problems may have been originally solved > by type systems. Well, you can think of things that way. But to the rest of the computing world languages that don't assign types to variables but do assign them to values are latently typed. > > Untyped and type-free mean something else: they mean no type checking > > is done. > > Hence, they don't exist, and the definitions being used here are rather > pointless. No they aren't, types of data exist even if there is no system in place to check them. Ask an assembly programmer whether his programs have string and integers in them and he will probably tell you that they do. From find at my.address.elsewhere Wed Jun 21 11:53:25 2006 From: find at my.address.elsewhere (Matthias Blume) Date: Wed, 21 Jun 2006 10:53:25 -0500 Subject: What is Expressiveness in a Computer Language References: <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <1150809118.677124.142230@u72g2000cwu.googlegroups.com> <1150815461.210286.53120@r2g2000cwb.googlegroups.com> <1150823297.816352.75370@u72g2000cwu.googlegroups.com> <7zzmg6amm1.fsf@app-3.diku.dk> <1150904475.363283.234730@y41g2000cwy.googlegroups.com> Message-ID: "Marshall" writes: > Torben ?gidius Mogensen wrote: >> >> That's not true. ML has variables in the mathematical sense of >> variables -- symbols that can be associated with different values at >> different times. What it doesn't have is mutable variables (though it >> can get the effect of those by having variables be immutable >> references to mutable memory locations). > > While we're on the topic of terminology, here's a pet peeve of > mine: "immutable variable." > > immutable = can't change > vary-able = can change > > Clearly a contradiction in terms. No, it is not a contradiction. See the mathematical usage of the word "variable". Immutable variables can stand for different values at different times, even without mutation involved, usually because they are bound by some construct such as lambda. > If you have a named value that cannot be updated, it makes > no sense to call it "variable" since it isn't *able* to *vary.* Mutation is not the only way for an expression to evaluate to different values over time. From geskerrett at hotmail.com Tue Jun 13 10:35:43 2006 From: geskerrett at hotmail.com (geskerrett at hotmail.com) Date: 13 Jun 2006 07:35:43 -0700 Subject: "groupby" is brilliant! In-Reply-To: <1150180151.643245.148210@y43g2000cwc.googlegroups.com> References: <1150180151.643245.148210@y43g2000cwc.googlegroups.com> Message-ID: <1150209343.924778.322900@g10g2000cwb.googlegroups.com> Frank; I would just like to thank-you for this timely post. I am working on a reporting project that needed "groupby" functionality and I was going to sit down this morning to rework some "very ugly code" into some "not quite so ugly code". Your post got me pointed to in the "right" direction and the end results will be much more flexible and ALOT more maintainable. Thanks. From marshall.spight at gmail.com Wed Jun 21 15:37:09 2006 From: marshall.spight at gmail.com (Marshall) Date: 21 Jun 2006 12:37:09 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150902275.129780.50260@p79g2000cwp.googlegroups.com> Message-ID: <1150918629.818145.143220@y41g2000cwy.googlegroups.com> Chris Smith wrote: > Marshall wrote: > > I think what this highlights is the fact that our existing terminology > > is not up to the task of representing all the possible design > > choices we could make. Some parts of dynamic vs. static > > a mutually exclusive; some parts are orthogonal. > > Really? I can see that in a strong enough static type system, many > dynamic typing features would become unobservable and therefore would be > pragmatically excluded from any probable implementations... but I don't > see any other kind of mutual exclusion between the two. Well, it strikes me that some of what the dynamic camp likes is the actual *absence* of declared types, or the necessity of having them. At the very least, requiring types vs. not requiring types is mutually exclusive. But again, my dynamic kung fu is very weak, so I may not know what I'm talking about when I represent the dynamic side. Marshall From brendan.rankin at gmail.com Tue Jun 27 17:58:06 2006 From: brendan.rankin at gmail.com (slacker) Date: 27 Jun 2006 14:58:06 -0700 Subject: Exchanging data with a C program using shared memory (sysV IPC) References: Message-ID: <1151445486.353407.32930@75g2000cwc.googlegroups.com> Al wrote: > I want my python application to communicate with an legacy C program which > read/write data in a shared memory (Unix Sys V IPC). Have you looked at the dl module? Types and portability aside, it might provide you with what you need. Cheers, - slacker From noway at sorry.com Thu Jun 1 07:52:56 2006 From: noway at sorry.com (Giovanni Bajo) Date: Thu, 01 Jun 2006 11:52:56 GMT Subject: struct: type registration? References: <447e4b98$1@news.eftel.com> Message-ID: John Machin wrote: >> given the ongoing work on struct (which I thought was a dead >> module), I was wondering if it would be possible to add an API to >> register custom parsing codes for struct. Whenever I use it for >> non-trivial tasks, I always happen to write small wrapper functions >> to adjust the values returned by struct. >> >> An example API would be the following: >> >> ============================================ >> def mystring_len(): >> return 20 >> >> def mystring_pack(s): >> if len(s) > 20: >> raise ValueError, "a mystring can be at max 20 chars" >> s = (s + "\0"*20)[:20] > > Have you considered s.ljust(20, "\0") ? Right. This happened to be an example... >> s = struct.pack("20s", s) >> return s > > I am an idiot, so please be gentle with me: I don't understand why you > are using struct.pack at all: Because I want to be able to parse largest chunks of binary datas with custom formatting. Did you miss the whole point of my message: struct.unpack("3liiSiiShh", data) You need struct.unpack() to parse these datas, and you need custom packer/unpacker to avoid post-processing the output of unpack() just because it just knows of basic Python types. In binary structs, there happen to be *types* which do not map 1:1 to Python types, nor they are just basic C types (like the ones struct supports). Using custom formatter is a way to better represent these types (instead of mapping them to the "most similar" type, and then post-process it). In my example, "S" is a basic-type which is a "A 0-terminated 20-byte string", and expressing it in the struct format with the single letter "S" is more meaningful in my code than using "20s" and then post-processing the resulting string each and every time this happens. >>>>> import struct >>>>> x = ("abcde" + "\0" * 20)[:20] >>>>> x > 'abcde\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' >>>>> len(x) > 20 >>>>> y = struct.pack("20s", x) >>>>> y == x > True >>>>> > > Looks like a big fat no-op to me; you've done all the heavy lifting > yourself. Looks like you totally misread my message. Your string "x" is what I find in binary data, and I need to *unpack* into a regular Python string, which would be "abcde". > >> idx = s.find("\0") >> if idx >= 0: >> s = s[:idx] >> return s > > Have you considered this: > >>>>> z.rstrip("\0") > 'abcde' This would not work because, in the actual binary data I have to parse, only the first \0 is meaningful and terminates the string (like in C). There is absolutely no guarantees that the rest of the padding is made of \0s as well. -- Giovanni Bajo From wahab at chemie.uni-halle.de Sun Jun 18 17:58:22 2006 From: wahab at chemie.uni-halle.de (Mirco Wahab) Date: Sun, 18 Jun 2006 23:58:22 +0200 Subject: Seeking regex optimizer In-Reply-To: <1150650439.651839.38180@y41g2000cwy.googlegroups.com> References: <1150650439.651839.38180@y41g2000cwy.googlegroups.com> Message-ID: Thus spoke Kay Schluehr (on 2006-06-18 19:07): > I have a list of strings ls = [s_1,s_2,...,s_n] and want to create a > regular expression sx from it, such that sx.match(s) yields a SRE_Match > object when s starts with an s_i for one i in [0,...,n]. There might > be relations between those strings: s_k.startswith(s_1) -> True or > s_k.endswith(s_1) -> True. An extreme case would be ls = ['a', 'aa', > ...,'aaaa...ab']. For this reason SRE_Match should provide the longest > possible match. With some ideas from Kay and Paddy, it tried to get along with Python in doing this. If its allowed to spread the individual strings into alterations, the following would imho do: #!/usr/bin/python # -*- coding: iso-8859-15 -*- text = r'this is a text containing aaa???aaa?aaa and more'; lstr = [ 'a', 'aa', 'aaaaa', 'aaa???aaa?aaa', 'aaaaaaaaaaaaaaab' ] import re pat = re.compile( \ '(' + \ '|'.join(sorted(lstr,lambda a,b: len(b)-len(a))) + \ ')', re.VERBOSE); hits = sorted( pat.findall(text), lambda a,b: len(b)-len(a) ) print 'Longest: ', hits[0] This will print 'aaa???aaa?aaa' from the text and won't complain about specuial characters used. in Perl, you could build up the regex by dynamic evaluation (??{..}), but I didn't manage to get this working in Python, so here is (in Perl) how I thougt it would work: my $text = "this is a text containing aaa???aaa?aaa and more"; my @lstr = ( 'a', 'aa', 'aaaaa', 'aaa???aaa?aaa', 'aaaaaaaaaaaaaaab', ); my $re = qr{ (??{ join '|', map { quotemeta } sort{ length $b <=> length $a } @lstr }) }x; $_ = $text; print "Longest: ", (my $hit) = reverse sort /$re/g; Maybe the experts can bring some light to it. Regards Mirco From rasmussen.bryan at gmail.com Mon Jun 19 09:01:04 2006 From: rasmussen.bryan at gmail.com (bryan rasmussen) Date: Mon, 19 Jun 2006 15:01:04 +0200 Subject: crawlers in python with graphing? Message-ID: <3bb44c6e0606190601n58392f23y622424b53df768d2@mail.gmail.com> Hi I'm wondering if there is a toolkit in python anywhere for doing at a high level web crawling, dumping links to a data set that could be imported into R relatively easy or used in python natively to generate a graph over the website. It should hopefully be as high level as Wget, not download the pages but just follow the links, and output graphs. Cheers Bryan Rasmussen From fanmail at micah-wedemeyer.net Fri Jun 2 16:30:04 2006 From: fanmail at micah-wedemeyer.net (Micah) Date: 2 Jun 2006 13:30:04 -0700 Subject: Reversible replacement of whitespace characters with visible characters Message-ID: <1149280203.974237.209080@y43g2000cwc.googlegroups.com> Hi, I'm looking for a tool to do the following 2 things: 1) Given a string (ie. file, std input, whatever), replace all whitespace characters with visible characters (like their Unicode value or something). The end result will be one long unbroken line 2) Given a string altered as in step 1, "decode" it back to the original string. Note: The original string (it will usually be source files) might already contain Unicode values, and these must remain and not be altered in step 2. Note 2: I'm working in a Windows XP environment, but I have access to cygwin if that makes a difference. Can anyone think of a tool that already does this? I could probably whip something up, but if there's already something that does it I'd rather just use it. Micah From anatoli.barski at googlemail.com Thu Jun 1 16:39:13 2006 From: anatoli.barski at googlemail.com (anatoli.barski at googlemail.com) Date: 1 Jun 2006 13:39:13 -0700 Subject: how to print newline in xml? In-Reply-To: References: <1149023930.292203.152540@u72g2000cwu.googlegroups.com> <1149145466.190011.146250@i39g2000cwa.googlegroups.com> <1149186989.073062.230220@f6g2000cwb.googlegroups.com> Message-ID: <1149194353.343074.15140@h76g2000cwa.googlegroups.com> I use Python/XML packages are xml.dom.minidom and xml.dom.ext (second just for PrettyPrint) From tjreedy at udel.edu Thu Jun 8 17:31:05 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 8 Jun 2006 17:31:05 -0400 Subject: Importing again and again References: <1149796920.757115.290840@h76g2000cwa.googlegroups.com> Message-ID: "John Bokma" wrote in message news:Xns97DCA4EEBEBEEcastleamber at 130.133.1.4... >> def foo(): >> import bar >> bar.printStuff() > I am new to Python so this might be a weird question, but it there a > reason why you import bar inside foo? Two possible reasons: 1) delay import until actually needed, if ever. 2) put 'bar' into the function local namespace instead of the module global namespace Terry Jan Reedy From fredrik at pythonware.com Wed Jun 28 04:34:48 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 28 Jun 2006 10:34:48 +0200 Subject: How to measure execution time of a program References: <54032.10.209.4.1.1151481158.squirrel@10.105.1.3> Message-ID: Pete Forman wrote: > > t0 = time.time() > > You can get better resolution by using time.clock() instead of > time.time(). depends on the platform, and whether you want wall time or process time. From vinay_sajip at yahoo.co.uk Fri Jun 9 13:51:16 2006 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 9 Jun 2006 10:51:16 -0700 Subject: shared logs and multiple configurations References: <1149772672.279705.316220@i40g2000cwc.googlegroups.com> Message-ID: <1149875476.645790.92850@c74g2000cwc.googlegroups.com> Chris Curvey wrote: > 1) Can I share log files between processes? Log messages seem to get > written, but when it comes time to roll over a log, I generally get a > "IO operation on closed file" error. (I'm thinking that I may have to > set up a logging service if I want to do this, but I'm hoping there's a > simpler way.) For multi-process logging, I would advise that all processes use a SocketHandler to send their events to a listener. You can use the example code in the documentation at http://docs.python.org/lib/network-logging.html to get a working example of a server which listens on a socket and processes logging events received via the socket. > 2) When I want to use logging from within a multi-threaded server > (built using the Threading module), do I create one global logger > reference, and then have each thread refer to that instance, or do I > have each thread grab it's own reference using getLogger()? Logger instances are singletons, so multiple calls to getLogger() with a given name will always return the same instance. There's usually no need to create a single global reference, though you could for example create a logger as a class attribute in your Thread subclass (assuming you're subclassing Thread), or an appopriate class which implements the functionality which runs in different threads. > 3) It seems like you can't make multiple calls to logging.fileConfig(). > If I call this twice with different ini files, it appears that any > handlers set up in the first call are silently dropped when the second > call is made. (Strangely, log messages sent to loggers set up in the > first call seem to just be silently dropped.) Am I diagnosing this > behavior properly? Is there a way > to work around it? fileConfig() is not meant to do incremental configurations, so it does its best to disable any previous configuration.It does this by clearing out the list of previously defined handlers and disabling any previously defined loggers. You can find the code easily enough and comment it out if you wish not to disable old loggers. Regards, Vinay Sajip From fredrik at pythonware.com Thu Jun 29 13:03:48 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 29 Jun 2006 19:03:48 +0200 Subject: Bug reporting impossible In-Reply-To: References: Message-ID: Nick Maclaren wrote: > It's definitely worth fixing, but not as a high priority. Invoking a > file spuriously is potentially serious, with very low probability. the traceback printer is reading the file (using a very robust reader), it's not "invoking" it. From dima at 127.0.0.1 Thu Jun 22 12:29:26 2006 From: dima at 127.0.0.1 (Dimitri Maziuk) Date: Thu, 22 Jun 2006 16:29:26 +0000 (UTC) Subject: What is Expressiveness in a Computer Language References: <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <34aj92h0g7tqi9amhh7k3ieq5n568t0e6f@4ax.com> Message-ID: George Neuner sez: > On Wed, 21 Jun 2006 16:12:48 +0000 (UTC), Dimitri Maziuk > wrote: > >>George Neuner sez: >>> On Mon, 19 Jun 2006 22:02:55 +0000 (UTC), Dimitri Maziuk >>> wrote: >>> >>>>Yet Another Dan sez: >>>> >>>>... Requiring an array index to be an integer is considered a typing >>>>> problem because it can be checked based on only the variable itself, >>>>> whereas checking whether it's in bounds requires knowledge about the array. >>>> >>>>You mean like >>>> subtype MyArrayIndexType is INTEGER 7 .. 11 >>>> type MyArrayType is array (MyArrayIndexType) of MyElementType >>>> >>> >>> If the index computation involves wider types it can still produce >>> illegal index values. The runtime computation of an illegal index >>> value is not prevented by narrowing subtypes and cannot be statically >>> checked. >> >>My vague recollection is that no, it won't unless _you_ explicitly code an >>unchecked type conversion. But it's been a while. > > > You can't totally prevent it ... if the index computation involves > types having a wider range ... > The point is really that the checks that prevent these things must be > performed at runtime and can't be prevented by any practical type > analysis performed at compile time. I'm not a type theorist but my > opinion is that a static type system that could, a priori, prevent the > problem is impossible. Right, but if you look carefully at the paragraph I originally fup'ed to, you'll notice that it doesn't say "runtime" or "compile-time". I was commenting on "array bounds not a typing problem" bit -- it is if you define the index as distinct type, and there is at least one language that supports it. In this context I don't think it matters when the check is performed. It does matter in the larger context of this thread, though. IMO the important part here is that the crash report clearly points to the caller code that generated illegal index, not to my library code. That is the basic argument in favour of compile time error checking, extended to runtime errors. I don't really care if it's the compiler or runtime that tells the luser "your code is broken", as long as it makes it clear it's *his* code that's broken, not mine. Dima -- I like the US government, makes the Aussie one look less dumb and THAT is a pretty big effort. -- Craig Small From imcsee at gmail.com Wed Jun 14 13:28:16 2006 From: imcsee at gmail.com (imcs ee) Date: Thu, 15 Jun 2006 01:28:16 +0800 Subject: prog1 | prog2 . How not to make prog2 block if not piped? In-Reply-To: <1150297984.798904.229730@h76g2000cwa.googlegroups.com> References: <1150297984.798904.229730@h76g2000cwa.googlegroups.com> Message-ID: do u really need read something even when you run the scripts2.py directly? why not just change script2.py to #script2.py if __name__ == "__main__": x=sys.stdin.read() print 'passed' else: print 'passed from else branch' is it what you want? or anything i misunderstand. On 14 Jun 2006 08:13:04 -0700, riquito at gmail.com wrote: > I googled around, but couldn't understand how to solve this problem. > I have 2 scripts > > # script1.py # > print 'something' > > #script2.py > x=sys.stdin.read() > print 'passed' > > if I run > script1.py | script2.py > all goes well. > > But if I run just > script2.py > the program blocks waiting forever for input. > > On *nix I used select.select to solve this problem, but on windows? > I read that maybe I should use, from win32api, GetStdHandle and > WaitForMultipleObjects, but how to do it it's far from my knowledge. > > Any help? > > Thank you, > Riccardo > > -- > http://mail.python.org/mailman/listinfo/python-list > From nomail at nixmail.com Mon Jun 19 10:23:27 2006 From: nomail at nixmail.com (DarkBlue) Date: Mon, 19 Jun 2006 22:23:27 +0800 Subject: wxPython GUI designer References: <1150661348.837969.46870@r2g2000cwb.googlegroups.com> <1150664728.435902.210930@y41g2000cwy.googlegroups.com> Message-ID: <4496b343@127.0.0.1> Take a look at pythoncard , we use it to produce database frontends , but apparently it also can be used for simple graphics apps and others. However if you are used to things like the Delphi IDE to build a gui app , then prepare to shed lots of tears before overcoming the initial disbelieve, that there is nothing better available for python. From gherron at islandtraining.com Sun Jun 25 12:19:39 2006 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 25 Jun 2006 09:19:39 -0700 Subject: array manipulation without for loops In-Reply-To: <1151251578.463273.24370@m73g2000cwd.googlegroups.com> References: <1151251578.463273.24370@m73g2000cwd.googlegroups.com> Message-ID: <449EB79B.10300@islandtraining.com> Sheldon wrote: > Hi, > > I have two arrays that are of the same dimension but having 3 different > values: 255, 1 or 2. > I would like to set all the positions in both arrays having 255 to be > equal, i.e., where one array has 255, I set the same elements in the > other array to 255 and visa versa. Does anyone know how to do this > without using for loops? > > Sincerely, > Sheldon > > Whatever for? Have you got something against for loops? However... You could roll you own loop: i=0 while i < whatever: # ... do something with i i += 1 But what's the point? This does the same as a for loop but slower. If you don't want any kind of a loop (again, What's the point?) you could write something recursive: def proc(i, ...): # ... do something with i if i < whatever: proc(i+1, ...) But this would be even slower. Gary Herron From nyamatongwe+thunder at gmail.com Sun Jun 4 01:08:15 2006 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Sun, 04 Jun 2006 05:08:15 GMT Subject: Python less error-prone than Java In-Reply-To: References: <1149378739.429512.26310@f6g2000cwb.googlegroups.com> Message-ID: <3Vtgg.2967$ap3.12@news-server.bigpond.net.au> Alan Morgan wrote: > Since Java doesn't allow function overloading that clearly can't be > the way. J2SE 5.0 allows generic classes and functions that operate > on generic containers. There are some gotchas, but it's not drastically > more complex than the original int-only java code. Doesn't Java restrict generics to only operate on reference types so you can't produce a generic binary search that operates on arrays where the item type may be int? Neil From python.list at tim.thechases.com Thu Jun 1 11:27:21 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 01 Jun 2006 10:27:21 -0500 Subject: os.walk trouble In-Reply-To: <1149173920.903876.68370@c74g2000cwc.googlegroups.com> References: <1149173920.903876.68370@c74g2000cwc.googlegroups.com> Message-ID: <447F0759.1030300@tim.thechases.com> > but I am stuck with incorrect understanding of > os.walk. I've tried: > > root, dirs, files = os.walk(dirname) os.walk returns an iteratable sequence of those tuples. Thus, you want to have for filepath, dirs, files in os.walk(dirname): #you're looking at the "dirs" and "files" in filepath print "Currently in %s" % filepath print "\t[Directories in %s]" % filepath print "\n\t".join(dirs) print "\t[Files in %s]" % filepath print "\n\t".join(files) print "=" * 50 HTH, -tkc From johnjsal at NOSPAMgmail.com Wed Jun 7 15:14:05 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 07 Jun 2006 19:14:05 GMT Subject: tkinter: native look to windows? In-Reply-To: References: <89Fhg.2258$No6.47844@news.tufts.edu> Message-ID: <1AFhg.2259$No6.47594@news.tufts.edu> Fredrik Lundh wrote: > John Salerno wrote: > >> I'm a little confused. I was under the impression (perhaps >> incorrectly) that Tkinter will create GUI widgets that are native to >> your OS > > only for some widgets; some native widgets are not flexible enough. > > and even native widgets don't always look like XP widgets (windows uses > a rather obscure manifest XML resource file to control the look and feel > for a specific application). > > to get better XP styling, you can use the Tile library: > > http://tkinter.unpythonic.net/wiki/UsingTile > > http://tktable.sourceforge.net/tile/screenshots/windowsxp.html > > or an 8.5 development version (which, afaik, includes the Tile library). > > > Thanks for the suggestions. I definitely miss Visual Studio's drag and drop GUI developer. But I definitely don't miss trying to figure out how to write something in C#! :) From micklee74 at hotmail.com Fri Jun 9 20:44:42 2006 From: micklee74 at hotmail.com (micklee74 at hotmail.com) Date: 9 Jun 2006 17:44:42 -0700 Subject: regexp questoin In-Reply-To: References: <1149868825.331142.280180@f6g2000cwb.googlegroups.com> Message-ID: <1149900282.616379.216200@h76g2000cwa.googlegroups.com> Fredrik Lundh wrote: > micklee74 at hotmail.com wrote: > > > pat = re.compile(r"%s" %(userinput) ) #userinput is passed from > > command line argument > > that r"%s" % (userinput) thing is a pointless operation: the "r" prefix > controls how backslashes in a string literal is parsed; the result is an > ordinary string ("%s" in this case). > > in other words, > > pat = re.compile(r"%s" % (userinput)) > > is just a slightly convoluted way to write > > pat = re.compile(str(userinput)) > > and since you know that userinput is a string (at least if you got it > from sys.argv), you might as well write > > pat = re.compile(userinput) > > > if the user key in a pattern , eg [-] , and my script will search some > > lines that contains [-] > > > > pat.findall(lines) > > > > but the script produce some error: sre_constants.error: unexpected end > > of regular expression > > for what pattern? "[-]" is a valid regular expression (it matches a > single minus), but e.g. "[-" is invalid. to deal with this, catch the > exception: > > try: > pat = re.compile(userinput) > except re.error: > print "invalid regular expression:", userinput > sys.exit() > > hope this helps! > > hi. thanks for all the help. actually, i am doing an application that allows user to delete files by entering an input pattern. so if he has files that have special characters such as [-] or others, then i want to filter them off .... the solution for re.compile(re.escape(userinput)) might work, i have to give it a try. thanks again. From bencvt at gmail.com Thu Jun 1 20:15:59 2006 From: bencvt at gmail.com (Ben Cartwright) Date: 1 Jun 2006 17:15:59 -0700 Subject: Can Python format long integer 123456789 to 12,3456,789 ? In-Reply-To: <1149207047.692374.114300@h76g2000cwa.googlegroups.com> References: <8oKfg.1621$Su3.139425@news20.bellglobal.com> <1149207047.692374.114300@h76g2000cwa.googlegroups.com> Message-ID: <1149207358.977942.245060@c74g2000cwc.googlegroups.com> John Machin wrote: > A.M wrote: > > Hi, > > > > Is there any built in feature in Python that can format long integer > > 123456789 to 12,3456,789 ? > > > > Sorry about my previous post. It would produce 123,456,789. > "12,3456,789" is weird -- whose idea PHB or yours?? If it's not a typo, it's probably a regional thing. See, e.g., http://en.wikipedia.org/wiki/Indian_numbering_system --Ben From invalidemail at aerojockey.com Thu Jun 29 10:37:17 2006 From: invalidemail at aerojockey.com (Carl Banks) Date: 29 Jun 2006 07:37:17 -0700 Subject: Numeric help! References: <1151510615.139278.167520@j72g2000cwa.googlegroups.com> <1151540468.434688.242530@75g2000cwc.googlegroups.com> <1151573125.651727.322660@i40g2000cwc.googlegroups.com> Message-ID: <1151591837.540485.80860@j72g2000cwa.googlegroups.com> Sheldon wrote: >Carl Banks wrote: >> I'm not sufficiently sure this isn't a homework problem, so here's a >> partial answer. [snip] > > My days as a student is over for the most part. I am learning python on > my own and Numeric is not properly documented so I am learning by doing > and copying from others. Are you aware of this guide? http://numeric.scipy.org/numpydoc/numdoc.htm I've seen better documents but it's fairly complete--I wouldn't call it improper. > I thought about the problem and a solution > another problem given to me earlier using "putmask" is the solution but > there is a bug that I cannot figure out: > ************************ > index = 0 > for z in range_va: > wk = msgva # working arrary > sattmp = sat_id # working array This appears to be doing something you don't expect. In Python all names are references; assignments don't create new objects but rather new names for the same object. In the above, wk and msvga are the same array: any changes in wk also appear in msvga. So wk[1,1] = 4 also causes msgva[1,1] to be 4. Numeric arrays even share data when slicing. If you were to take a slice of wk, for example, a = wk[0:10,0:10], then modifying a would also show up in wk (and msvga). (However, slicing most other objects copies rather than shares the data.) It's completely different from Matlab, which always copies data. Here's what you should do: wk = array(msgva) # this creates a new array for wk sattmp = array(sat_id) > mask = where(equal(wk,z),1,0) # creating a mask of > valid data pixs Note that the "where" is unnecessary here. equal creates an array of ones and zeros. > putmask(sattmp,mask==0,-999) # since zero is valid > data, -999 is used instead This would overwrite sat_id unless you copy the array as I've shown above. > rdata = > compress(ravel(not_equal(sattmp,-999)),ravel(sattmp)) I believe you could avoid the above putmask above step and just use ravel(mask) as the first argument of compress here, or even just equal(wk,z). "equal(wx,z)", "mask", and "not_equal(sattmp,-999)" are all equal arrays. > if sum(sum(rdata)) == 0: > av = 0 rdata is one-dimensional, so you only need one sum call; but why do this? average will still work if the sum is zero. > else: > av = average(rdata,axis=None) axis argument isn't necessary here since rdata is one-dimesional. > tmparray[0,index] = av > tmparray[1,index] = z > index += 1 > print tmparray > *********************************** > But the tmparray is returning zeros as averages. When I try just one > value for z everything works. I can't see where I going wrong. I am not > using the original arrays, only the copies and when a new z is chosen > then these are recreated. > Care to help out with this? > /Sheldon Other than the array sharing mistake, it looks like it should work. Also, note that this group disdains top-posting; replies should go below the quoted text because in these sorts of discussions it's best to keep things in conversational order, especially for the sake of other interested readers. Good luck. Carl Banks From jmbc at nospam.fr Thu Jun 15 02:04:32 2006 From: jmbc at nospam.fr (jean-michel bain-cornu) Date: Thu, 15 Jun 2006 08:04:32 +0200 Subject: Newbie wxpython staticbitmap help please In-Reply-To: <1150325882.038508.122780@g10g2000cwb.googlegroups.com> References: <1150325882.038508.122780@g10g2000cwb.googlegroups.com> Message-ID: <4490f8b6$0$7766$7a628cd7@news.club-internet.fr> janama a ?crit : > Can somewhone add a wx.Timer example to this to make it check > if the file exists every minute or so , instead of clicking the button > to check and update this? Or is there a better way of auto updating my > little gui apps StaticBitmap if a file exists? Why won't you write it yourself using the demo ? It's clear and well documented. Regards, jm From johnjsal at NOSPAMgmail.com Tue Jun 6 10:51:35 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 06 Jun 2006 14:51:35 GMT Subject: retaining newline characters when writing to file Message-ID: If I read a string that contains a newline character(s) into a variable, then write that variable to a file, how can I retain those newline characters so that the string remains on one line rather than spans multiple lines? Example: In a CGI script, I'm reading the address field from an HTML form. Almost always the person will press ENTER so they can enter a second or third line. If I then want to write all the field values of this form to a CSV file, so that each person's entries takes one line, how can I ensure that the address string stays on one line despite the newline characters? (Or is it better to just use separate text fields for each line of the address?) Thanks. From rossberg at ps.uni-sb.de Sun Jun 25 13:44:40 2006 From: rossberg at ps.uni-sb.de (rossberg at ps.uni-sb.de) Date: 25 Jun 2006 10:44:40 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150908952.804184.218990@r2g2000cwb.googlegroups.com> <1150991074.705803.211570@m73g2000cwd.googlegroups.com> <1151244628.566060.40500@p79g2000cwp.googlegroups.com> <1151252226.104247.62960@b68g2000cwa.googlegroups.com> Message-ID: <1151257480.183097.165640@b68g2000cwa.googlegroups.com> Gabriel Dos Reis wrote: > rossberg at ps.uni-sb.de writes: > > | Gabriel Dos Reis wrote: > | > | > | > | (Unfortunately, you can hardly write interesting programs in any safe > | > | subset of C.) > | > > | > Fortunately, some people do, as living job. > | > | I don't think so. Maybe the question is what a "safe subset" consists > | of. In my book, it excludes all features that are potentially unsafe. > > if you equate "unsafe" with "potentially unsafe", then you have > changed gear and redefined things on the fly, and things that could > be given sense before ceases to have meaning. I decline following > such an uncertain, extreme, path. An unsafe *feature* is one that can potentially exhibit unsafe behaviour. How else would you define it, if I may ask? A safe *program* may or may not use unsafe features, but that is not the point when we talk about safe *language subsets*. > I would suggest you give more thoughts to the claims made in > > http://www.seas.upenn.edu/~sweirich/types/archive/1999-2003/msg00298.html Thanks, I am aware of it. Taking into account the hypothetical nature of the argument, and all the caveats listed with respect to C, I do not think that it is too relevant for the discussion at hand. Moreover, Harper talks about a relative concept of "C-safety". I assume that everybody here understands that by "safe" in this discussion we mean something else (in particular, memory safety). Or are you trying to suggest that we should indeed consider C safe for the purpose of this discussion? - Andreas From Bulkan at gmail.com Sun Jun 25 09:16:09 2006 From: Bulkan at gmail.com (placid) Date: 25 Jun 2006 06:16:09 -0700 Subject: HTTP server In-Reply-To: <1151162732.819264.190560@i40g2000cwc.googlegroups.com> References: <1151134073.393065.187500@c74g2000cwc.googlegroups.com> <1151162732.819264.190560@i40g2000cwc.googlegroups.com> Message-ID: <1151241369.138325.173690@r2g2000cwb.googlegroups.com> Simon Forman wrote: > > > Ok, seriously, I don't know how pydoc does it, but when I need a > quick-and-dirty http server [written in python] I use something like > this: > > from BaseHTTPServer import HTTPServer > from SimpleHTTPServer import SimpleHTTPRequestHandler > > HTTPServer(('', 8000), SimpleHTTPRequestHandler).serve_forever() > > For what you're asking about you'd probably want to use the > CGIHTTPRequestHandler from the CGIHTTPServer module instead. Check out > http://docs.python.org/lib/module-CGIHTTPServer.html This is what i was after, thanks for the tip. > Then you'd just write one or more cgi scripts (they can be in python > IIRC) to run the commands you want. Im having trouble running the following cgi script on windows #!c:/Python/python.exe -u text = """Content-type: text/html CGI 101

A Second CGI script


Hello, CGI World!

""" print text
using this http server from http://effbot.org/librarybook/cgihttpserver.htm import CGIHTTPServer import BaseHTTPServer class Handler(CGIHTTPServer.CGIHTTPRequestHandler): cgi_directories = ["/cgi"] PORT = 8000 httpd = BaseHTTPServer.HTTPServer(("", PORT), Handler) print "serving at port", PORT httpd.serve_forever() i get the error number 403, when i try to access the cgi script which is located in a subdirectory called cgi where this file is (http server). I have a feeling that i need to change the Handler class or something, implement , but i couldnt find any examples other then this from eff-bot. It could also be this line of code, that a google search turned up, its the way of running cgi scripts on windows #!c:/Python/python.exe -u Cheers From fredrik at pythonware.com Tue Jun 13 13:17:19 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 13 Jun 2006 19:17:19 +0200 Subject: .py and running in Windows: In-Reply-To: References: <1150206503.313636.50130@c74g2000cwc.googlegroups.com> Message-ID: Michael Yanowitz wrote: > I never specified a thread. I think perhaps though because I did > open another message in this mailing list (to get the correct > email address to send to), but I deleted all its contents i put > it under that other thread, however there is no indication of a > thread in Outlook email. I am sorry if it came up in another > thread that was not my intention. your message contains the line In-Reply-To: <1150203354.861658.181110 at h76g2000cwa.googlegroups.com> which indicates that you pressed "reply to", rather than "new message". changing the subject doesn't change that; your mail program still does what you asked it to do. From ak at silmarill.org Sat Jun 17 20:48:48 2006 From: ak at silmarill.org (ak at silmarill.org) Date: 17 Jun 2006 17:48:48 -0700 Subject: Tkinter question. Message-ID: <1150591728.235667.319230@p79g2000cwp.googlegroups.com> Hi, I'd like to create buttons on the fly that will call the same function, and the function in question has to know what was the name of the button that called it. Unless there is a preferred way for doing this.. Perhaps creating a new function on the fly along with the new button? Please help.. thanks! From sdcook55 at sbcglobal.net Sun Jun 18 22:28:07 2006 From: sdcook55 at sbcglobal.net (Stan Cook) Date: Mon, 19 Jun 2006 02:28:07 GMT Subject: Python with Eclipse Message-ID: I've been trying to use Eclipse with Python on Linux for a while and have noticed something odd. After running the code or debugging a few times, its responsiveness gets really bad. Upon checking the equivalent of the task manager, I find several instances of Python running. When I kill these instances, the responsiveness comes back. I'm not sure if there is a better place to post this, but it is Python related. Is this just an issue with Eclipse or is there something else I should inspect? Any help would be appreciated. Regards, S Cook From fredrik at pythonware.com Fri Jun 9 16:18:24 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 09 Jun 2006 22:18:24 +0200 Subject: Questions about extending Python... In-Reply-To: References: Message-ID: Redefined Horizons wrote: > I've got a third-part application that exposes a C API. I'd like to > wrap it in Python. Is there a specific forum that covers extending and > embedding Python, or are those type of questions O.K. on this list? those type of questions are perfectly okay on this list, but if you're using SWIG or Pyrex: http://www.swig.org/ http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/ (which are probably the most commonly used tools for this kind of task), you might get quicker/better responses on the tool-specific lists. if you prefer to "handroll" your C wrapper, start here: http://docs.python.org/ext/ext.html (to get more examples, look in the Modules directory in the Python distribution). hope this helps! From fuzzyman at gmail.com Mon Jun 5 18:41:44 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 5 Jun 2006 15:41:44 -0700 Subject: C# equivalent to range() In-Reply-To: References: <1149468919.951745.163700@g10g2000cwb.googlegroups.com> <1149481675.192638.275140@c74g2000cwc.googlegroups.com> <1149509893.031953.19310@i40g2000cwc.googlegroups.com> <1149545140.011616.130610@y43g2000cwc.googlegroups.com> <1149546736.728440.74700@i39g2000cwa.googlegroups.com> Message-ID: <1149547304.607625.101670@j55g2000cwa.googlegroups.com> Robert Kern wrote: > Fuzzyman wrote: > > Erik Max Francis wrote: > > >>Here were the "harsh" and "whining" responses to his question he's > >>complaining about: > > > > Fair enough. Maybe they weren't "harsh" and "whining", just patronising > > and abrupt. > > Welcome to USENET! Well, this is true. Doesn't make it a *good* thing of course... :-) Fuzzyman http://www.voidspace.org/python/shareware.shtml > > -- > 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 From czajnik at czajsoft.pl Mon Jun 12 10:27:18 2006 From: czajnik at czajsoft.pl (czajnik at czajsoft.pl) Date: 12 Jun 2006 07:27:18 -0700 Subject: (pre)forking server framework? In-Reply-To: <4f5a2lF1h6t38U1@uni-berlin.de> References: <1150118572.252707.57460@i40g2000cwc.googlegroups.com> <4f5a2lF1h6t38U1@uni-berlin.de> Message-ID: <1150122438.336065.224640@f14g2000cwb.googlegroups.com> Diez B. Roggisch napisal(a): > Why do you care if the asynchronous model is overkill or the performance is > good? Twisted comes close to what you want - and using its strength as > arguments against it strikes me as odd. I was unclear :) I mean I don't like using asynchronous model for the kind of job I have to do, as it's more complicated I think. Simple blocking synchronous communication, with one process per connection is all I need. Also this is going to be a kind of system management software, and forking has other advantages to me. Maybe I'll give Twisted a chance, need to spend some time experimenting with it. BR, Przemek From michael.f.ellis at gmail.com Thu Jun 1 12:00:18 2006 From: michael.f.ellis at gmail.com (michael.f.ellis at gmail.com) Date: 1 Jun 2006 09:00:18 -0700 Subject: An oddity in list comparison and element assignment References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> Message-ID: <1149177617.985251.74560@c74g2000cwc.googlegroups.com> Hi Alex, With all due respect to your well-deserved standing in the Python community, I'm not convinced that equality shouldn't imply invariance under identical operations. Perhaps the most fundamental notion is mathematics is that the left and right sides of an equation remain identical after any operation applied to both sides. Our experience of the physical world is similar. If I make identical modifications to the engines of two identical automobiles, I expect the difference in performance to be identical. If my expectation is met, I would assert that either the two vehicles were not identical to begin with or that my modifications were not performed identically. As to containers, would you say that envelope containing five $100 bills is the same as an envelope containing a single $100 bill and 4 xerox copies of it? If so, I'd like to engage in some envelope exchanges with you :-) As I see it, reference copying is a very useful performance and memory optimization. But I don't think it should undermine the validity of assert(a==b) as a predictor of invariance under identical operations. Cheers, Mike Ellis Alex Martelli wrote: > wrote: > Wrong; equality does not imply any check on identity. You can consider > the definition of "list A equals list B" as: > > -- len(A) == len(B), AND, > -- for each valid index i, A[i] == B[i] > > This is an extremely natural definition of "equality" for containers: > "they have EQUAL items" [[in the same order, for containers for which > order is relevant]]. Nowhere in this extremely natural definition does > the IDENTITY of the items come into play. From sjmachin at lexicon.net Tue Jun 13 18:47:18 2006 From: sjmachin at lexicon.net (John Machin) Date: Wed, 14 Jun 2006 08:47:18 +1000 Subject: "groupby" is brilliant! In-Reply-To: References: <1150180151.643245.148210@y43g2000cwc.googlegroups.com> <448F351A.7000201@lexicon.net> <448F36D3.1070003@islandtraining.com> Message-ID: <448F4076.6090407@lexicon.net> On 14/06/2006 8:38 AM, Robert Kern wrote: > Gary Herron wrote: >> John Machin wrote: >> >>> On 13/06/2006 6:28 PM, Paul McGuire wrote: >>> >>>> (Oh, and I like groupby too! Combine it with sort to quickly create >>>> histograms.) >>>> >>>> # tally a histogram of a list of values from 1-10 >>>> dataValueRange = range(1,11) >>>> data = [random.choice(dataValueRange) for i in xrange(10000)] >>>> >>>> hist = [ (k,len(list(g))) for k,g in itertools.groupby(sorted(data)) ] >>> That len(list(g)) looks like it uses O(N) memory just to find out what N >>> is :-( >> Not at all! A python list *knows* its length at all times. len() is a >> constant time lookup of an internal attribute. > > The point is that you had to create the list in the first place. g is an iterator. > I didn't have to create a list in the first place. Paul did. The point of my post was to avoid the memory grab caused by list(g) by seeking a way that just counted g's output. Sorry for the confusion my lack of clarity has evidently caused. I'll rephrase: That whole construct len(list(g)) looks like it uses O(N) memory just to find out what N is. Better? From tylertacky at gmail.com Sun Jun 18 01:17:37 2006 From: tylertacky at gmail.com (tylertacky at gmail.com) Date: 17 Jun 2006 22:17:37 -0700 Subject: Detecting key presses Message-ID: <1150607857.186185.183130@g10g2000cwb.googlegroups.com> Ok, I'm pretty new to python, so this might be a stupid question. I'm trying to write a simple text-based pong clone, and I can't figure out how to read key presses to move the paddles. I just need something that does the same thing as getch() and kbhit(). I can't use those because their windows only, and I'm running Linux. Someone suggested using curses, but that does crazy things with my output, and leaves the terminal unusable after the program closes. From orome.the.valar at gmail.com Thu Jun 15 08:14:50 2006 From: orome.the.valar at gmail.com (sinan nalkaya) Date: Thu, 15 Jun 2006 12:14:50 -0000 Subject: popen and password entry In-Reply-To: References: <200604141852.59515.erchamion.beren@gmail.com> <200604151200.06995.erchamion.beren@gmail.com> Message-ID: <200604151515.03206.erchamion.beren@gmail.com> finally following code works, import pexpect, sys cmd = '/usr/bin/rsync config root at 10.1.1.2:/tmp/.' #cmd = 'ssh root at 10.1.1.2' child = pexpect.spawn(cmd) child.logfile = sys.stdout passwd = 'qwe123' i = 0 try: while i == 0: i = child.expect(['Password:','Password: ',pexpect.EOF,pexpect.TIMEOUT]) if i == 0: child.sendline(passwd) elif i == 1: print 1 elif i == 2: print 2 elif i == 3: print 3 except EOF: print 'EOF' except TIMEOUT: print 'TIMEOUT' From ray_usenet at yahoo.com Thu Jun 1 04:56:54 2006 From: ray_usenet at yahoo.com (Ray) Date: 1 Jun 2006 01:56:54 -0700 Subject: How do you practice Python? In-Reply-To: <447eaae0$0$20867$636a55ce@news.free.fr> References: <1149150517.034409.292530@g10g2000cwb.googlegroups.com> <447eaae0$0$20867$636a55ce@news.free.fr> Message-ID: <1149152214.215907.31800@i39g2000cwa.googlegroups.com> bruno at modulix wrote: > > In our field, we don't always get to program in the language we'd like > > to program. So... how do you practice Python in this case? Say you're > > doing J2EE right now. > > Hopefully not ! I am :-( > > How do you practice Python to keep your skills > > sharp? > > How *would* I do ? Well, perhaps I'd use Jython ? Um, I mean, what if you have to use something other than Python/Jython/IronPython? :) How do you keep your Python skill sharp? > -- > bruno desthuilliers > python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for > p in 'onurb at xiludom.gro'.split('@')])" From tim.peters at gmail.com Wed Jun 21 21:44:34 2006 From: tim.peters at gmail.com (Tim Peters) Date: Wed, 21 Jun 2006 21:44:34 -0400 Subject: Iteration over recursion? In-Reply-To: <1150891093.829475.202600@i40g2000cwc.googlegroups.com> References: <1150808045.539887.291180@i40g2000cwc.googlegroups.com> <1150873424.345733.165730@m73g2000cwd.googlegroups.com> <1150891093.829475.202600@i40g2000cwc.googlegroups.com> Message-ID: <1f7befae0606211844o10b0e383i6dbd2d830e5687fa@mail.gmail.com> [MTD ] > I've been testing my recursive function against your iterative > function, and yours is generally a quite steady 50% faster on > factorizing 2**n +/- 1 for 0 < n < 60. If you're still not skipping multiples of 3, that should account for most of it. > I think that, for a challenge, I'll try to make a recursive function that > matche or beats the iterative function -- it's worth the experiment! Don't stop on that one before you succeed ;-) Provided you make no more than one recursive call per factor, you can't make more than log(n, 2) recursive calls in total, and _typically_ far fewer than that. IOW, the number of recursive calls should generally be trivial, and factoring 2**n will be the worst case. From bblais at bryant.edu Tue Jun 27 07:24:20 2006 From: bblais at bryant.edu (Brian Blais) Date: Tue, 27 Jun 2006 07:24:20 -0400 Subject: pyrex functions to replace a method (Re: replace a method in class: how?) In-Reply-To: <44A06A6B.6010200@bryant.edu> References: <44A06A6B.6010200@bryant.edu> Message-ID: <44A11564.9030009@bryant.edu> Thanks for all who replied to this question about replacing a method. I feel a little sheepish for not having caught that I have to replace it in the class, not the instance, but I have found a very similar problem trying to replace a method using a function defined in pyrex. I post all of the code below, but there are several files. The main code is: import module_py # import a function from a python module import module_pyrex # import a function from a pyrex extension module class This(object): def update1(self,val): print val def update2(self,val): print "2",val def update3(self,val): print "3",val def local_update(obj,val): print "local",val This.update1=local_update # replace the method from a local function This.update2=module_py.python_update # replace the method from a python module This.update3=module_pyrex.pyrex_update # replace the method from a pyrex module t=This() t.update1('local') # works fine t.update2('python') # works fine t.update3('pyrex') # gives a typeerror function takes exactly 2 arguments (1 given) #--------------------------------------------------------------------------------- #module_py.py def python_update(self,val): print "python module",val #--------------------------------------------------------------------------------- #module_pyrex.pyx def pyrex_update(self,val): print "pyrex module",val #--------------------------------------------------------------------------------- any ideas why the pyrex function fails? thanks, bb -- ----------------- bblais at bryant.edu http://web.bryant.edu/~bblais From cdsmith at twu.net Fri Jun 23 13:20:29 2006 From: cdsmith at twu.net (Chris Smith) Date: Fri, 23 Jun 2006 11:20:29 -0600 Subject: What is Expressiveness in a Computer Language References: <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <0%Wlg.3521$MF6.947@tornado.socal.rr.com> <44992e6c$0$664$bed64819@news.gradwell.net> <449aaea0$0$656$bed64819@news.gradwell.net> <449bde5e$1$663$bed64819@news.gradwell.net> <1151082956.067238.45100@b68g2000cwa.googlegroups.com> Message-ID: Marshall wrote: > Java has a static type system. > Java has runtime tags and tag checks. Yes. > The two are distinct, and neither one is less than complete How is neither one less than complete? -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation From geskerrett at hotmail.com Thu Jun 29 09:58:17 2006 From: geskerrett at hotmail.com (geskerrett at hotmail.com) Date: 29 Jun 2006 06:58:17 -0700 Subject: Event notification system - where to start ? Message-ID: <1151589497.327662.115100@p79g2000cwp.googlegroups.com> We have been asked to develop and application for a client that is a 'notification" system. We would like to use python, but are struggling to find the right starting point. Any suggestions, tips or sample code would be appreciated. Application outline; Machine A is running a "listener" application that is connected to a another device via the serial post and waits for events. We have not problem working with the serial port, or the waiting for the event to happen. When A received a specific event, it needs to send a message to machine B that and event has occurred and that type of event. Machine B will take the event notification, processes some additional information (ie. database lookups) and then notify a series of clients that have "registered" with machine B to receive events. I think this is sometimes called "published/subscriber" ??? We have looked at xmlrpc, but at there would be no outside clients, it seems to have a little more overhead than we need. We also looked at the asyncore and asynchat, but are having difficulty gettng starting with these. If someone has a working example of a "chat" server using these modules they could share it would be very helpful. So ... any suggestions ? From subscriber100 at rjs.org Sat Jun 10 11:34:29 2006 From: subscriber100 at rjs.org (Ray Schumacher) Date: Sat, 10 Jun 2006 08:34:29 -0700 Subject: from foo imprt * in package __init__ ? Message-ID: <6.2.3.4.2.20060610081501.02d108d0@pop-server.san.rr.com> What is the Pythonic-ness of using from foo imprt * in a package's __init__.py? I import my own (~8) module files in the package this way, and import standard modules with "import bar". Ray From maric at aristote.info Thu Jun 15 08:24:17 2006 From: maric at aristote.info (Maric Michaud) Date: Thu, 15 Jun 2006 14:24:17 +0200 Subject: __lt__ slowing the "in" operator even if not called In-Reply-To: <1150373671.227640.50910@f6g2000cwb.googlegroups.com> References: <1150318630.203249.191250@r2g2000cwb.googlegroups.com> <1150373671.227640.50910@f6g2000cwb.googlegroups.com> Message-ID: <200606151424.17333.maric@aristote.info> Le Jeudi 15 Juin 2006 14:14, Emanuele Aina a ?crit?: > But I hoped in a more exaustive answer: why python has to do this > lookup when the __lt__ method is not involved at all? It is not the case, that's what my program shows : in operator at the beginning of list: 173 in operator at the end of list: 28249 <- here converting to dict : 79 in operator for a dict for 60000 elements: 14 in operator at the beginning of list: 202 in operator at the end of list: 30472 <- and here -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From martin at v.loewis.de Fri Jun 9 18:26:34 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 10 Jun 2006 00:26:34 +0200 Subject: Where is the ucs-32 codec? In-Reply-To: <1149860078.334793.308420@y43g2000cwc.googlegroups.com> References: <1149459785.331497.203920@c74g2000cwc.googlegroups.com> <4483EB71.9090509@v.loewis.de> <4483FD63.2080502@v.loewis.de> <1149860078.334793.308420@y43g2000cwc.googlegroups.com> Message-ID: <4489F59A.5020205@v.loewis.de> cben at users.sf.net wrote: >> I would like to see it correct, unlike the current UTF-16 codec. Perhaps >> whoever contributes an UTF-32 codec could also deal with the defects of >> the UTF-16 codec. >> > Now this is interesting, as I hoped to base my code on UTF-16 (and > perhaps UTF-8 for combining surrogates)... Can you elaborate? The codec doesn't do line-oriented input correctly (i.e. readline); it raises NotImplementedError. Regards, Martin From micklee74 at hotmail.com Wed Jun 7 12:46:33 2006 From: micklee74 at hotmail.com (micklee74 at hotmail.com) Date: 7 Jun 2006 09:46:33 -0700 Subject: printing backslash Message-ID: <1149698793.422979.148770@i40g2000cwc.googlegroups.com> hi i want to print something like this |\| first i tried it as string a = "|\|" it prints ok but when i put it to a list a = ["|\|"] it gives me '|\\|' .there are 2 back slashes...i only want one.. how can i properly escape it? I have tried [r"|\|"] , [r'\\'] but they do not work... thanks From aleax at mac.com Sun Jun 25 12:38:10 2006 From: aleax at mac.com (Alex Martelli) Date: Sun, 25 Jun 2006 09:38:10 -0700 Subject: array manipulation without for loops References: <1151251578.463273.24370@m73g2000cwd.googlegroups.com> Message-ID: <1hhhebn.1edgy6213txfh4N%aleax@mac.com> Sheldon wrote: > I have two arrays that are of the same dimension but having 3 different > values: 255, 1 or 2. > I would like to set all the positions in both arrays having 255 to be > equal, i.e., where one array has 255, I set the same elements in the > other array to 255 and visa versa. Does anyone know how to do this > without using for loops? Python's Numeric extension package (still available, but not actively developed any more) and its successors (numarray, and the even newer numpy) are replete with such functionality -- indeed, to really use arrays in Python you should get any one of these packages (Python offers arrays only in the very limited incarnation of the standard library module named array -- better than nothing, but little built-in functionality, while those packages have plenty). Of course, if you say "array" when actually you mean "list", the situation is completely different (it may be worth turning list into Numeric arrays for manipulation, then back when you're done, if speed is absolutely of the essence and you desperately need lists as inputs and outputs but a lot of manipulation in-between). Alex From greg.kujawa at gmail.com Wed Jun 7 11:00:37 2006 From: greg.kujawa at gmail.com (gregarican) Date: 7 Jun 2006 08:00:37 -0700 Subject: 10GB XML Blows out Memory, Suggestions? References: <1149594519.098115.8980@u72g2000cwu.googlegroups.com> <4eleh3F1eguosU1@uni-berlin.de> <1149648187.891942.258300@i40g2000cwc.googlegroups.com> Message-ID: <1149692437.283605.74410@f6g2000cwb.googlegroups.com> Am I missing something? I don't read where the poster mentioned the operation as being CPU intensive. He does mention that the entirety of a 10 GB file cannot be loaded into memory. If you discount physical swapfile paging and base this assumption on a "normal" PC that might have maybe 1 or 2 GB of RAM is his assumption that out of line? And I don't doubt that Python is efficient as possible for I/O operations. But since it is an interpreted scripting language how could it be "just as fast as any language" as you claim? C would have to be faster. Machine language would have to be faster. And even other interpreted languages *could* be faster, given certain conditions. A generalization like the claim kind of invalidates the remainder of your assertion. fuzzylollipop wrote: > K.S.Sreeram wrote: > > Diez B. Roggisch wrote: > > > What the OP needs is a different approach to XML-documents that won't > > > parse the whole file into one giant tree - but I'm pretty sure that > > > (c)ElementTree will do the job as well as expat. And I don't recall the > > > OP musing about performances woes, btw. > > > > > > There's just NO WAY that the 10gb xml file can be loaded into memory as > > a tree on any normal machine, irrespective of whether we use C or > > Python. So the *only* way is to perform some kind of 'stream' processing > > on the file. Perhaps using a SAX like API. So (c)ElementTree is ruled > > out for this. > > > > Diez B. Roggisch wrote: > > > No what exactly makes C grok a 10Gb file where python will fail to do so? > > > > In most typical cases where there's any kind of significant python code, > > its possible to achieve a *minimum* of a 10x speedup by using C. In most > > cases, the speedup is not worth it and we just trade it for the > > increased flexiblity/power of the python language. But in this situation > > using a bit of tight C code could make the difference between the > > process taking just 15mins or taking a few hours! > > > > Ofcourse I'm not asking him to write the entire application in C. It > > makes sense to just write the performance critical sections in C, and > > wrap it in Python, and write the rest of the application in Python. > > > you got no idea what you are talking about, anyone knows that something > like this is IO bound. > CPU is the least of his worries. And for IO bound applications Python > is just as fast as any other language. From bdesth.quelquechose at free.quelquepart.fr Sun Jun 4 22:17:56 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 05 Jun 2006 04:17:56 +0200 Subject: [OT] in python , could I accomplish the purpose that "a=Console.read()" used in C? In-Reply-To: <1149423026.134144.58940@i40g2000cwc.googlegroups.com> References: <1149423026.134144.58940@i40g2000cwc.googlegroups.com> Message-ID: <448364b7$0$31935$626a54ce@news.free.fr> python a ?crit : > in python , could I accomplish the purpose that "a=Console.read()" used > in C? There's nothing like "Console.read()" in ansi-C. (see Dennis's post for the answer to your question) From grante at visi.com Thu Jun 15 10:05:26 2006 From: grante at visi.com (Grant Edwards) Date: Thu, 15 Jun 2006 14:05:26 -0000 Subject: Python is fun (useless social thread) ;-) References: Message-ID: <1292q9629nem735@corp.supernews.com> On 2006-06-15, John Salerno wrote: > So out of curiosity, I'm just wondering how everyone else came > to learn it. If you feel like responding, I'll ask my > questions for easy quoting: I didn't want to use Outlook to read my e-mail, so I needed a way to get them onto a non-MS box. The only way to suck my e-mails out of the MS server was to use the COM API built into Outlook. I didn't have any development tools on the Windows machine and wasn't about to pay MS for a C/C++ compiler. Google found me an example of doing COM stuff using Python. It turns out that using Python was way easier than using C would have been. -- Grant Edwards grante Yow! This is a NO-FRILLS at flight -- hold th' CANADIAN visi.com BACON!! From gandalf at designaproduct.biz Wed Jun 7 06:53:34 2006 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Wed, 07 Jun 2006 12:53:34 +0200 Subject: secure xmlrpc server? Message-ID: <4486B02E.70705@designaproduct.biz> Hello, I'm trying to create a simple XMLRPC server and a client. It is a small application, but the connection needs to be secure. I would like the client to be as thin as possible. Ideally, the client should only require the basic python library, nothing else. I found many examples on the net. But I could not find secure ones (except twisted/xmlrpc, but I would like to use the basic python lib on the client side, if possible). I know that python supports HTTPS. In theory, this could be used to bulild a secure xmlrpc server. I think that the client would work with this code: # Connect to server server = ServerProxy("https://myserver.com:8000") But I do not know how to create an XML RPC server in Python that uses HTTPS for XML transports. (The server may use other libraries, just the client needs to be thin.) Can you help me please? Thanks, Laszlo From duncan.booth at invalid.invalid Fri Jun 9 08:51:56 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 9 Jun 2006 12:51:56 GMT Subject: Large Dictionaries References: <1147699064.107490@teuthos> Message-ID: Marcin Ciura wrote: > Duncan Booth wrote: >> Marcin Ciura wrote: >>>See Figure 8 in >>>http://sun.iinf.polsl.gliwice.pl/~mciura/shellsort.pdf >> That isn't what the reference says. It only covers N up to a few >> thousand. Practical values of N need to at least go up into the >> millions. > > Please look at the performance graph of Tokuda's increment sequence. > You can see that it scales pretty well at least up to 100 million. Ah sorry, I misread it. It was sequences with several thousand elements, which corresponds to N of 100 million. From jimburton1 at gmail.com Thu Jun 15 11:07:54 2006 From: jimburton1 at gmail.com (jimburton) Date: 15 Jun 2006 08:07:54 -0700 Subject: distutils `requires' tag In-Reply-To: <4fd2mpF1hnhinU1@uni-berlin.de> References: <1150366092.188588.57940@g10g2000cwb.googlegroups.com> <4fd2mpF1hnhinU1@uni-berlin.de> Message-ID: <1150384074.485548.290350@c74g2000cwc.googlegroups.com> Diez B. Roggisch wrote: > jimburton schrieb: > > Hi, I'm using python 2.3.5 and want to use distutils to distribute a > > module that depends on another - is there any way to specify that? > > Use setuptools. It can do such a thing. > > Diez Many thanks. From nmm1 at cus.cam.ac.uk Wed Jun 28 05:23:22 2006 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 28 Jun 2006 09:23:22 GMT Subject: Immutability References: Message-ID: In article , Georg Brandl writes: |> > |> > Thanks very much. And, what's more, I have even found its documentation! |> > Whatsnew2.2. The 2.4.2 reference is, er, unhelpful. |> |> Is it? |> |> http://docs.python.org/lib/built-in-funcs.html |> |> documents "property" quite well. Sigh. No. It's terrible. What it documents is the use of the property FUNCTION. It does not document what properties ARE, and how they interact with the rest of the language. Until you know that, it is so ambiguous as to be almost totally useless - and it is THAT information that needs to be in the reference manual, but is only in whatsnew2.2. Regards, Nick Maclaren. From nexu.jin at gmail.com Mon Jun 5 15:37:26 2006 From: nexu.jin at gmail.com (Nexu) Date: Mon, 05 Jun 2006 21:37:26 +0200 Subject: ConfigParser, no attribute Message-ID: <1149536246.5979.24.camel@localhost.localdomain> Hello, I'm not sure exactly what i'm doing wrong here. I asked around on IRC and i was told the code is correct. The purpose of Settings() is that whenever Settings() or any of its methods are called. It should pick up the latest settings from file instead of returning what was in the buffer. This allow other scripts to change the value and my program and pick these changes up. Everything else should work exact same as ConfigParser(). ----------------------------------------------------------------------------- class Settings(ConfigParser.SafeConfigParser): def __init__(self): self.filename = os.path.join(xchat.get_info('xchatdir'), 'nxscript', 'nxscript.conf') try: config_file = file(self.filename, 'r') self.readfp(config_file, self.filename) if self.sections() == []: self.add_section('Global') if self.has_section('Global'): self.set('Global', 'ProtectME', 'false') config_file.close() except IOError: nx.sysmsg('Configuration file not found') def update_file(self): try: config_file = file(self.filename, 'w') self.write(config_file) except IOError: nx.sysmsg('Could not write to configuration file') ----------------------------------------------------------------------------- SAMPLE CODE (what i want to able to do): setting = Settings() if setting.get('Global', 'ProtectME'): print 'protection enabled' ----------------------------------------------------------------------------- ERRORS: File "/home/nexu/.xchat2/nxscript/nx.py", line 43, in ? setting = Settings() File "/home/nexu/.xchat2/nxscript/nx.py", line 24, in __init__ self.readfp(config_file, self.filename) File "/usr/lib/python2.4/ConfigParser.py", line 286, in readfp self._read(fp, filename) File "/usr/lib/python2.4/ConfigParser.py", line 451, in _read if sectname in self._sections: AttributeError: Settings instance has no attribute '_sections' From raffaelcavallaro at pas-d'espam-s'il-vous-plait-mac.com Thu Jun 15 01:42:33 2006 From: raffaelcavallaro at pas-d'espam-s'il-vous-plait-mac.com (Raffael Cavallaro) Date: Thu, 15 Jun 2006 01:42:33 -0400 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <2006061410510511272-raffaelcavallaro@pasdespamsilvousplaitmaccom> Message-ID: <2006061501423327544-raffaelcavallaro@pasdespamsilvousplaitmaccom> On 2006-06-14 15:04:34 -0400, Joachim Durchholz said: > Um... heterogenous lists are not necessarily a sign of expressiveness. > The vast majority of cases can be transformed to homogenous lists > (though these might then contain closures or OO objects). > > As to references to nonexistent functions - heck, I never missed these, > not even in languages without type inference :-) > > I don't hold that they are a sign of *in*expressiveness either. They > are just typical of highly dynamic programming environments such as > Lisp or Smalltalk. This is a typical static type advocate's response when told that users of dynamically typed languages don't want their hands tied by a type checking compiler: "*I* don't find those features expressive so *you* shouldn't want them." You'll have to excuse us poor dynamically typed language rubes - we find these features expressive and we don't want to give them up just to silence a compiler whose static type checks are of dubious value in a world where user inputs of an often unpredictable nature can come at a program from across a potentially malicious internet making run-time checks a practical necessity. From anton.vredegoor at gmail.com Sat Jun 3 01:36:37 2006 From: anton.vredegoor at gmail.com (anton.vredegoor at gmail.com) Date: Sat, 03 Jun 2006 07:36:37 +0200 Subject: An oddity in list comparison and element assignment In-Reply-To: <1hgbhhi.mcrge51cyj2isN%aleax@mac.com> References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> <1hg9nl6.xivwcd7n0j5N%aleax@mac.com> <1149277242.199765.213600@g10g2000cwb.googlegroups.com> <1hgbhhi.mcrge51cyj2isN%aleax@mac.com> Message-ID: Alex Martelli wrote: [snip] Can somebody please shut down this bot? I think it's running out of control. It seems to be unable to understand that "don't be evil" might be good when you're small (at least it's not very bad) but that it becomes distinctly evil when you're big. What is good when you're big? I really don't know and I think there's even not many other people who do. But simply forbidding things that are not precisely definable -the way mathematicians have been doing before physicists shook them out of it- seems to do more harm than good. In my opinion it looks like there is a path from rigid rule adherence to slowly accepting more doubt and inconsistencies -because we're all adults here- and this has something to do with letting go of things like childish adherence to static typing and confusion between equality and identity. Let me qualify that last paragraph before anyone concludes I have become disfunctional too and will lead everyone to their destruction. There seem to always be certain unclear parts in a programming language and people are constantly trying out new structures in order to map some new territory. I remember sets, generators and metaclasses. Only after people noticing problems (don't modify the thing you're iterating over) ways are found to solve them (you can if you put everything back just at the right moment) and finally these ways are condensed into officially endorsed coding practices. Now we're struggling with immutability and sequences. They're not a problem if you know what you're doing, but what exactly is it that those who know what they're doing do? It indicates that maybe it's the birth of a new language construct. But why should it stop there? I expect a certain openness and willingness to discuss controversial matters from a community even if it were only to educate newcomers. But it might be the case that such willingness to accept doubt, without it turning into actively seeking it -that seems to be foolish, but who am I to judge even that- is what makes it possible to develop higher language and cognitive structures. Anton 'even if it means turning into lisp before moving on' From marshall.spight at gmail.com Fri Jun 23 12:45:29 2006 From: marshall.spight at gmail.com (Marshall) Date: 23 Jun 2006 09:45:29 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: <4g22l7F1j8p4mU1@individual.net> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150902275.129780.50260@p79g2000cwp.googlegroups.com> <1150918629.818145.143220@y41g2000cwy.googlegroups.com> <4fv081F1jh4ifU1@individual.net> <1150967543.947096.72840@g10g2000cwb.googlegroups.com> <4fv84rF1kp06kU1@individual.net> <1150988625.527780.148710@c74g2000cwc.googlegroups.com> <4g22l7F1j8p4mU1@individual.net> Message-ID: <1151081129.290382.297530@r2g2000cwb.googlegroups.com> Pascal Costanza wrote: > Marshall wrote: > > Pascal Costanza wrote: > >> Consider a simple expression like 'a + b': In a dynamically typed > >> language, all I need to have in mind is that the program will attempt to > >> add two numbers. In a statically typed language, I additionally need to > >> know that there must a guarantee that a and b will always hold numbers. > > > > I still don't really see the difference. > > > > I would not expect that the dynamic programmer will be > > thinking that this code will have two numbers most of the > > time but sometimes not, and fail. I would expect that in both > > static and dynamic, the thought is that that code is adding > > two numbers, with the difference being the static context > > gives one a proof that this is so. > > There is a third option: it may be that at the point where I am writing > this code, I simply don't bother yet whether a and b will always be > numbers. In case something other than numbers pop up, I can then > make a decision how to proceed from there. Ouch; I have a really hard time understanding this. I can't see how you'd call + on a and b if you think they might not be numbers. If they could be something other than numbers, and you're treating them as if they are, is that sort of like doing a case analysis and only filling in one of the cases? If so, wouldn't you want to record that fact somehow? Marshall From nmm1 at cus.cam.ac.uk Wed Jun 28 11:57:30 2006 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 28 Jun 2006 15:57:30 GMT Subject: Immutability References: <4Qj*cEjkr@news.chiark.greenend.org.uk> Message-ID: In article , "Fredrik Lundh" writes: |> |> a property looks like an attribute, not a method, so you're trying to call whatever |> your "joe()" method returns. Well, yes, that was pretty obvious - but what was NOT obvious is why it should do that for one of two identical methods. |> (that's what "a function for getting an attribute value" in the property documentation |> refers to). Well, as joe is an attribute of the class fred, and the decorator is applied to the declaration of joe within fred, I assumed that it referred to getting joe from fred. That certainly doesn't appear to be the case, and I don't see how it helps with my original request if not. Regards, Nick Maclaren. From jjl at pobox.com Thu Jun 1 18:02:17 2006 From: jjl at pobox.com (John J. Lee) Date: 01 Jun 2006 22:02:17 +0000 Subject: Finding a lost PYTHONPATH with find References: <87zmh2oxwr.fsf@pobox.com> Message-ID: <87ac8wedqu.fsf@pobox.com> Edward Elliott writes: > John J. Lee wrote: > > > find / -maxdepth 3 -size -100k -type f -exec grep -sli pythonpath '{}' \; > > > > > > The minus in '-100k' (meaning "less than 100k") seems to be > > undocumented, at least on my system. > > It should be standard in linux man pages, can't speak for other unices: > > TESTS > Numeric arguments can be specified as > > +n for greater than n, > > -n for less than n, > > n for exactly n. > > Maybe you were fooled because it's not directly under the description of > -size. Yes, that's right -- thanks. > > I suppose the -maxdepth is > > redundant since I think find searches breadth-first by default. > > ??? maxdepth determines how deep the search will look, not the order the > search occurs. Your search only find things within 3 levels of the root, > unless your directory tree goes no deeper than that (very unlikely) the > maxdepth can't be redundant. It can if you hit Control-C as soon as it finds the damn thing :-) -- which is exactly what I would have done, of course. John From michael.f.ellis at gmail.com Thu Jun 1 16:31:01 2006 From: michael.f.ellis at gmail.com (michael.f.ellis at gmail.com) Date: 1 Jun 2006 13:31:01 -0700 Subject: An oddity in list comparison and element assignment In-Reply-To: <447f34ec$1_2@newspeer2.tds.net> References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> <447f34ec$1_2@newspeer2.tds.net> Message-ID: <1149193861.211385.141940@c74g2000cwc.googlegroups.com> Considering the number of new programmers who get bit by automatic coercion, I wish Dennis Ritchie had made some different choices when he designed C. But then I doubt he ever dreamed it would become so wildly successful. Being a curmudgeon purist I'd actually prefer it if Python raised a TypeError on float vs integer comparisons. Cheers, Mike Kent Johnson wrote: > michael.f.ellis at gmail.com wrote: > > Hi Alex, > > With all due respect to your well-deserved standing in the Python > > community, I'm not convinced that equality shouldn't imply invariance > > under identical operations. > > > > Perhaps the most fundamental notion is mathematics is that the left and > > right sides of an equation remain identical after any operation applied > > to both sides. Our experience of the physical world is similar. If I > > make identical modifications to the engines of two identical > > automobiles, I expect the difference in performance to be identical. > > If my expectation is met, I would assert that either the two vehicles > > were not identical to begin with or that my modifications were not > > performed identically. > > But programming is not mathematics and assignment is not an equation. > How about this: > > In [1]: a=3.0 > > In [2]: b=3 > > In [3]: a==b > Out[3]: True > > In [4]: a/2 == b/2 > Out[4]: False > > Kent From fuzzyman at gmail.com Sat Jun 3 14:49:27 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 3 Jun 2006 11:49:27 -0700 Subject: Python + WinCE + serial port In-Reply-To: <4481d342$0$21359$636a55ce@news.free.fr> References: <4481d342$0$21359$636a55ce@news.free.fr> Message-ID: <1149360567.824911.245750@c74g2000cwc.googlegroups.com> pcm wrote: > Hi, > > Has anyone ever worked on a Python-WinCE-based program that involved serial > port management ? > Because of the size of the runtime and the fragility of the GUI toolkits, there has been little serious development with PythonCE. (Little not none - and it's great to have Python available.) There is no built in support for the serial port in PythonCE (AFAIK). Your best bet is using ctypes (for which a PythonCE port has been done) and the microsoft API. Fuzzyman http://www.voidspace.org.uk/python/index.shtml > Regards, > > Philippe From onurb at xiludom.gro Fri Jun 30 11:17:48 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Fri, 30 Jun 2006 17:17:48 +0200 Subject: Way for see if dict has a key In-Reply-To: References: <6V6pg.21624$_J1.271925@twister2.libero.it><44a5041f$0$29637$636a55ce@news.free.fr><4F7pg.21676$_J1.272665@twister2.libero.it> <1151666867.604260.116320@h44g2000cwa.googlegroups.com> <44a51f34$0$6794$626a54ce@news.free.fr> Message-ID: <44a5409c$0$8389$626a54ce@news.free.fr> Fredrik Lundh wrote: > Bruno Desthuilliers wrote: > >>> on my machine, "key in dict" is about twice as fast as the full > >>> try/getitem construct when the key is present in the dict, > >> >> Doesn't it depends on the number of keys in the dict ? > > > why would it depend on the number of keys in the dict ? > > Seems that if "key in dict" do a simple linear search, it depends on the number of keys in dict (and the position of the searched key etc...). And if I'm missing the point and you it and you know why, it would be simple to explain than to answer my question with another question. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From kydavis77 at gmail.com Mon Jun 26 13:36:23 2006 From: kydavis77 at gmail.com (kydavis77 at gmail.com) Date: 26 Jun 2006 10:36:23 -0700 Subject: Beginner Programmer Question In-Reply-To: References: <1151342733.742416.180370@r2g2000cwb.googlegroups.com> Message-ID: <1151343383.139891.219270@u72g2000cwu.googlegroups.com> Claudio Grondi wrote: > kydavis77 at gmail.com wrote: > > I am doing alot of reading and trying to teach myself how to program. > > I can not figure out how to make "Write a program that continually > > reads in numbers from the user and adds them together until the sum > > reaches 100." this work. If someone could show me the correct code so i > > can learn from that it would be much appreciated. Thanks > > > Isn't it your homework? > Why can't you figure it out? > What have you tried? > > Claudio I am doing alot of reading, and the problem didnt come with an answer. I dont understand how to get it to continually input numbers and add all those together From mahs at telcopartners.com Tue Jun 20 18:48:24 2006 From: mahs at telcopartners.com (Michael Spencer) Date: Tue, 20 Jun 2006 15:48:24 -0700 Subject: Running code on assignment/binding In-Reply-To: <44984283.4020807@ilm.com> References: <44984283.4020807@ilm.com> Message-ID: David Hirschfield wrote: > Another deep python question...is it possible to have code run whenever > a particular object is assigned to a variable (bound to a variable)? > > So, for example, I want the string "assignment made" to print out > whenever my class "Test" is assigned to a variable: > > class Test: > ... > > x = Test > > would print: > > "assignment made" > > Note that there's no "()" after x = Test, I'm not actually instantiating > Test, just binding the class to the variable "x" > Make sense? Possible? > -David > Not in general (you can't "override" assignment), but here are some possible workarounds for special cases: 1. If this is for some interactive use, you could call gc.get_referrers each time round the REPL to see how many names have been bound to each object you care about. 2. Alternatively, you could exec your code in an instance of a dict subclass that overrides setitem. >>> class chatty_dict(dict): ... def __setitem__(self, k, v): ... print "Binding %s to %r" % (k, v) ... dict.__setitem__(self, k, v) ... >>> d= chatty_dict() >>> source = """ ... class Test: pass ... a = Test""" >>> >>> exec source in d Binding Test to Binding a to >>> (With a little more work, you can make a chatty_dict that wraps the __dict__ of a loaded module) 3. Limit yourself to attribute assignment, which can be overridden: >>> SomeInstance.a = Test Then you can use __setattr__ or a data descriptor to customize the assignment HTH Michael From sreeram at tachyontech.net Mon Jun 5 23:07:27 2006 From: sreeram at tachyontech.net (K.S.Sreeram) Date: Tue, 06 Jun 2006 08:37:27 +0530 Subject: How to generate all k-1 level substrings of a string? In-Reply-To: <36169.10.209.4.1.1149557337.squirrel@10.105.1.3> References: <36169.10.209.4.1.1149557337.squirrel@10.105.1.3> Message-ID: <4484F16F.3030306@tachyontech.net> Girish Sahani wrote: > I want to generate all substrings of size k-1 from a string of size k. > e.g 'abcd' should give me ['abc','abd','bcd','acd'] def get_sub_set( s ) : return [s[:i]+s[i+1:] for i in range(len(s))] >>> print get_sub_set( 'abcd' ) ['bcd', 'acd', 'abd', 'abc'] Regards Sreeram -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 260 bytes Desc: OpenPGP digital signature URL: From benji at benjiyork.com Tue Jun 13 10:47:31 2006 From: benji at benjiyork.com (Benji York) Date: Tue, 13 Jun 2006 10:47:31 -0400 Subject: "groupby" is brilliant! In-Reply-To: <1150180151.643245.148210@y43g2000cwc.googlegroups.com> References: <1150180151.643245.148210@y43g2000cwc.googlegroups.com> Message-ID: <448ED003.7080900@benjiyork.com> Frank Millman wrote: > reader = csv.reader(open('trans.csv', 'rb')) > rows = [] > for row in reader: > rows.append(row) Why do you create a list of rows instead of just iterating over the reader directly? -- Benji York From chris.uppal at metagnostic.REMOVE-THIS.org Wed Jun 21 05:31:31 2006 From: chris.uppal at metagnostic.REMOVE-THIS.org (Chris Uppal) Date: Wed, 21 Jun 2006 10:31:31 +0100 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <0%Wlg.3521$MF6.947@tornado.socal.rr.com> Message-ID: <44992e6c$0$664$bed64819@news.gradwell.net> Darren New wrote: [me:] > > Personally, I would be quite happy to go there -- I dislike the idea > > that a value has a specific inherent type. > > Interestingly, Ada defines a type as a collection of values. It works > quite well, when one consistantly applies the definition. I have never been very happy with relating type to sets of values (objects, whatever). I'm not saying that it's formally wrong (but see below), but it doesn't fit with my intuitions very well -- most noticeably in that the sets are generally unbounded so you have to ask where the (intentional) definitions come from. Two other notions of what "type" means might be interesting, both come from attempts to create type-inference mechanisms for Smalltalk or related languages. Clearly one can't use the set-of-values approach for these purposes ;-) One approach takes "type" to mean "set of classes" the other takes a finer-grained approach and takes it to mean "set of selectors" (where "selector" is Smalltalk for "name of a method" -- or, more accurately, name of a message). But I would rather leave the question of what a type "is" open, and consider that to be merely part of the type system. For instance the hypothetical nullability analysis type system I mentioned might have only three types NULLABLE, ALWAYSNULL, and NEVERNULL. It's worth noting, too, that (in some sense) the type of an object can change over time[*]. That can be handled readily (if not perfectly) in the informal internal type system(s) which programmers run in their heads (pace the very sensible post by Anton van Straaten today in this thread -- several branches away), but cannot be handled by a type system based on sets-of-values (and is also a counter-example to the idea that "the" dynamic type of an object/value can be identified with its tag). ([*] if the set of operations in which it can legitimately partake changes. That can happen explicitly in Smalltalk (using DNU proxies for instance if the proxied object changes, or even using #becomeA:), but can happen anyway in less "free" languages -- the State Pattern for instance, or even (arguably) in the difference between an empty list and a non-empty list). -- chris From marshall.spight at gmail.com Thu Jun 22 10:35:01 2006 From: marshall.spight at gmail.com (Marshall) Date: 22 Jun 2006 07:35:01 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: <4fv081F1jh4ifU1@individual.net> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150902275.129780.50260@p79g2000cwp.googlegroups.com> <1150918629.818145.143220@y41g2000cwy.googlegroups.com> <4fv081F1jh4ifU1@individual.net> Message-ID: <1150986901.299913.139200@m73g2000cwd.googlegroups.com> Pascal Costanza wrote: > > A statically type language requires you to think about two models of > your program at the same time: the static type model and the dynamic > behavioral model. A static type system ensures that these two > _different_ (that's important!) perspectives are always in sync. This is > especially valuable in settings where you know your domain well and want > to rely on feedback by your compiler that you haven't made any mistakes > in encoding your knowledge. (A static type system based on type > inferencing doesn't essentially change the requirement to think in two > models at the same time.) > > A dynamically typed language is especially well suited when you don't > (yet) have a good idea about your domain and you want to use programming > especially to explore that domain. Some static typing advocates claim > that static typing is still suitable for exploring domains because of > the compiler's feedback about the preliminary encoding of your > incomplete knowledge, but the disadvantages are a) that you still have > to think about two models at the same time when you don't even have > _one_ model ready and b) that you cannot just run your incomplete > program to see what it does as part of your exploration. > > A statically typed language with a dynamic type treats dynamic typing as > the exception, not as the general approach, so this doesn't help a lot > in the second setting (or so it seems to me). > > A language like Common Lisp treats static typing as the exception, so > you can write a program without static types / type checks, but later on > add type declarations as soon as you get a better understanding of your > domain. Common Lisp implementations like CMUCL or SBCL even include > static type inference to aid you here, which gives you warnings but > still allows you to run a program even in the presence of static type > errors. I guess the feedback you get from such a system is probably not > "strong" enough to be appreciated by static typing advocates in the > first setting (where you have a good understanding of your domain). I am sceptical of the idea that when programming in a dynamically typed language one doesn't have to think about both models as well. I don't have a good model of the mental process of working in a dynamically typed language, but how could that be the case? (I'm not asking rhetorically.) Do you then run your program over and over, mechanically correcting the code each time you discover a type error? In other words, if you're not thinking of the type model, are you using the runtime behavior of the program as an assistant, the way I use the static analysis of the program as an assistant? I don't accept the idea about pairing the appropriateness of each system according to whether one is doing exploratory programming. I do exploratory programming all the time, and I use the static type system as an aide in doing so. Rather I think this is just another manifestation of the differences in the mental processes between static typed programmers and dynamic type programmers, which we are beginning to glimpse but which is still mostly unknown. Oh, and I also want to say that of all the cross-posted mega threads on static vs. dynamic typing, this is the best one ever. Most info; least flames. Yay us! Marshall From jmcmonagle at velseis.com.au Thu Jun 22 00:24:46 2006 From: jmcmonagle at velseis.com.au (John McMonagle) Date: Thu, 22 Jun 2006 14:24:46 +1000 Subject: Mouse wheel event for Canvas Message-ID: <1150950286.5055.12.camel@kuepper.vels-int.com.au> I tried binding mouse wheel events (, ) to a Tkinter Canvas widget with the hope of using the event.delta value to subsequently scroll the Canvas. However, it seems that event.delta always returns 0. For example, from Tkinter import * r = Tk() c = Canvas(r, scrollregion=(0,0,500,500), height=200, width=200) s = Scrollbar(r, command=c.yview) c.pack(side=LEFT) s.pack(side=RIGHT, fill=Y) c.configure(yscrollcommand=s.set) c.create_rectangle(10,10,100,100) c.create_rectangle(10,200,100,300) def rollWheel(event): print event.delta c.bind('', rollWheel) c.bind('', rollWheel) c.focus_set() r.mainloop() Has anyone successfully managed to wheel scroll a Tkinter Canvas widget ? Regards, John -- This message has been scanned for viruses and dangerous content by MailScanner, and is believed to be clean. From nun at example.com Fri Jun 23 15:00:40 2006 From: nun at example.com (Mitja Trampus) Date: Fri, 23 Jun 2006 21:00:40 +0200 Subject: Python in HTML In-Reply-To: <1151077239.840572.175120@y41g2000cwy.googlegroups.com> References: <1151077239.840572.175120@y41g2000cwy.googlegroups.com> Message-ID: brochu121 at gmail.com wrote: > Does anyone know of a way to embed python scripts into html, much like > you would javascript or php? Two very different things, JS and PHP... First make sure you know what you're after. If you want PHP-like embedding of code, google for "python server pages". Several implementations are available: - an apache handler that comes with mod_python - a java servlets based one (were not aware of it before, doesn't seem very practical) - spyce - can act as a simple standalone http server or can be used with apache/IIS/whatever (by proxying requests) - probably more From axwack at gmail.com Tue Jun 6 07:48:39 2006 From: axwack at gmail.com (axwack at gmail.com) Date: 6 Jun 2006 04:48:39 -0700 Subject: 10GB XML Blows out Memory, Suggestions? Message-ID: <1149594519.098115.8980@u72g2000cwu.googlegroups.com> I wrote a program that takes an XML file into memory using Minidom. I found out that the XML document is 10gb. I clearly need SAX or something else? Any suggestions on what that something else is? Is it hard to convert the code from DOM to SAX? From iant at the-wire.com Thu Jun 8 12:00:20 2006 From: iant at the-wire.com (moonman) Date: 8 Jun 2006 09:00:20 -0700 Subject: cos: "Integer Required"?!?!?!? In-Reply-To: References: <1149777499.262577.318070@u72g2000cwu.googlegroups.com> <2aqdnQ8uYZLpoxXZnZ2dnUVZ_qadnZ2d@comcast.com> <1149780685.768525.276850@h76g2000cwa.googlegroups.com> Message-ID: <1149782419.886876.145060@c74g2000cwc.googlegroups.com> I'm using ActiveState PythonV2.4.1 I'm certainly not affecting 'math'. I wonder if the XPlane SDK Python binding is touching anything. I'll download the latest ActiveState Python and keep on plugging. Thanks! Mikael Olofsson wrote: > moonman wrote: > > print self.ACphi, type(self.ACphi) yields: > > 19412557 > > > > value = XPLMGetDataf(self.ACphi); print value type(value ) yields: > > -0.674469709396 > > > > print math.radians(XPLMGetDataf(self.ACphi)), > > type(math.radians(XPLMGetDataf(self.ACphi))) yields: > > > > TypeError > > : > > an integer is required > > > > Am I totally missing something about 'math'. Does it really expect an > > int? > > Not my Python: > > >>> math.radians(-0.674469709396) > -0.011771717133929535 > > This all seems very confusing. Have you tried exactly the above? > > Do you perhaps have a module of your own called math, that Python might > be importing? Or is your math not a module, but some other object that > happens to have a method called radians, that expects an int? Or have > you accidentally redefined math.radians? > > /MiO From pc at p-cos.net Wed Jun 28 15:06:06 2006 From: pc at p-cos.net (Pascal Costanza) Date: Wed, 28 Jun 2006 21:06:06 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <7zy7vt1mz2.fsf@app-3.diku.dk> <1151384511.223582.305760@m73g2000cwd.googlegroups.com> <4gdkmiF1ldalhU3@individual.net> <4gfcclF1mpbg7U1@individual.net> <6gwog.488405$xt.80841@fe3.news.blueyonder.co.uk> <4gfiufF1mg6h9U1@individual.net> <4gfo6tF1cju7vU1@individual.net> Message-ID: <4gg291F1lsqo9U1@individual.net> Matthias Blume wrote: > Pascal Costanza writes: > >>> And I am convinced that updating a running system in the style of, >>> e.g., Erlang, can be statically typed. >> Maybe. The interesting question then is whether you can express the >> kinds of dynamic updates that are relevant in practice. Because a >> static type system always restricts what kinds of runtime behavior you >> can express in your language. I am still skeptical, because changing >> the types at runtime is basically changing the assumptions that the >> static type checker has used to check the program's types in the first >> place. > > That's why I find the Erlang model to be more promising. > > I am extremely skeptical of code mutation at runtime which would > "change types", because to me types are approximations of program > invariants. So if you do a modification that changes the types, it is > rather likely that you did something that also changed the invariants, > and existing code relying on those invariants will now break. ...no, it will throw exceptions that you can catch and handle, maybe interactively. >> For example, all the approaches that I have seen in statically typed >> languages deal with adding to a running program (say, class fields and >> methods, etc.), but not with changing to, or removing from it. > > Of course, there are good reasons for that: removing fields or > changing their invariants requires that all /deployed/ code which > relied on their existence or their invariants must be made aware of > this change. This is a semantic problem which happens to reveal > itself as a typing problem. By making types dynamic, the problem does > not go away but is merely swept under the rug. ...and yet this requirement sometimes comes up. >>>>> Note that prohibiting directly self-modifying code does not prevent a >>>>> program from specifying another program to *replace* it. >>>> ...and this creates problems with moving data from one version of a >>>> program to the next. >>> How does this "create" such a problem? The problem is there in >>> either >>> approach. In fact, I believe that the best chance we have of >>> addressing the problem is by adopting the "replace the code" model >>> along with a "translate the data where necessary at the time of >>> replacement". Translating the data, i.e., re-establishing the >>> invariants expected by the updated/replaced code, seems much harder >>> (to me) in the case of self-modifying code. Erlang got this one >>> right. >> ...and the "translate the date where necessary" approach is >> essentially triggered by a dynamic type test (if value x is of an old >> version of type T, update it to reflect the new version of type T >> [1]). QED. > > But this test would have to already exist in code that was deployed > /before/ the change! How did this code know what to test for, and how > did it know how to translate the data? In CLOS, the test is indeed already there from the beginning. It's part of the runtime semantics. The translation of the data is handled by 'update-instance-for-redefined-class, which is a generic function for which you can define your own methods. So this is user-extensible and can, for example, be provided as part of the program update. Furthermore, slot accesses typically go through generic functions (aka setters and getters in other languages) for which you can provide methods that can perform useful behavior in case the corresponding slots have gone. These methods can also be provided as part of the program update. Note that I am not claiming that CLOS provides the perfect solution, but it seems to work reasonably well that people use it in practice. > Plus, how do you detect that > some piece of data is "of an old version of type T"? If v has type T > and T "changes" (whatever that might mean), how can you tell that v's > type is "the old T" rather than "the new T"! Are there two different > Ts around now? If so, how can you say that T has changed? Presumably, objects have references to their class metaobjects which contain version information and references to more current versions of themselves. This is not rocket science. > The bottom line is that even the concept of "changing types at > runtime" makes little sense. Until someone shows me a /careful/ > formalization that actually works, I just can't take it very > seriously. Maybe this feature just isn't made for you. Pascal -- 3rd European Lisp Workshop July 3 - Nantes, France - co-located with ECOOP 2006 http://lisp-ecoop06.bknr.net/ From fredrik at pythonware.com Wed Jun 28 13:16:28 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 28 Jun 2006 19:16:28 +0200 Subject: handling unicode data In-Reply-To: <1151514404.954008.282280@b68g2000cwa.googlegroups.com> References: <1151506510.391856.207460@y41g2000cwy.googlegroups.com> <1151514404.954008.282280@b68g2000cwa.googlegroups.com> Message-ID: Filipe wrote: > Thanks for the reply. > Instead of: > term = row[1] > I tried: > term = unicode(row[1], "iso-8859-1") > > but the following error was returned when printing "term": > Traceback (most recent call last): > File "test.py", line 11, in ? > print term > File "c:\Program Files\Python24\lib\encodings\cp437.py", line 18, in > encode > return codecs.charmap_encode(input,errors,encoding_map) > UnicodeEncodeError: 'charmap' codec can't encode character u'\xd8' in > position 31: character maps to works for me, given your example: >>> s = "Fran\xd8a" >>> unicode(s, "iso-8859-1") u'Fran\xd8a' what does print repr(row[1]) print in this case ? From DustanGroups at gmail.com Wed Jun 7 08:37:04 2006 From: DustanGroups at gmail.com (Dustan) Date: 7 Jun 2006 05:37:04 -0700 Subject: Again, Downloading and Displaying an Image from the Internet in Tkinter In-Reply-To: References: <1149555597.559051.162590@i39g2000cwa.googlegroups.com> <1149556130.667899.199470@j55g2000cwa.googlegroups.com> <1149563528.127044.32210@y43g2000cwc.googlegroups.com> <1149601541.489425.248880@y43g2000cwc.googlegroups.com> Message-ID: <1149683824.326370.314540@f6g2000cwb.googlegroups.com> Fredrik Lundh wrote: > Dustan wrote: > > > Ok, that worked (was it plain w or the writelines/readlines that messed > > it up?). > > the plain "w"; very few image files are text files. > > > But Tkinter still can't find the image. I'm getting an error > > message: > > > > TclError: image "C:\Documents and [pathname snipped]" doesn't exist > > > > If it makes a difference, I'm on a Windows XP machine, and don't have > > to go cross-platform. > > the "image" option takes a PhotoImage object, not a file name: > > http://effbot.org/tkinterbook/photoimage.htm > > note that the built-in PhotoImage type only supports a few image > formats; to get support for e.g. PNG and JPEG, you can use PIL which > ships with it's own PhotoImage replacement: > > http://effbot.org/imagingbook/imagetk.htm Thanks for the information. The reason I hadn't made any attempt before is well illustrated here; I didn't have enough information at my disposal to know where to start and how I it works. My references are more basic-level than that (I do have a better reference to look to, but it's currently inaccessible). From orome.the.valar at gmail.com Thu Jun 15 04:59:55 2006 From: orome.the.valar at gmail.com (sinan nalkaya) Date: Thu, 15 Jun 2006 08:59:55 -0000 Subject: popen and password entry In-Reply-To: References: <200604141852.59515.erchamion.beren@gmail.com> <8c05f79c0606142358n5fbafc3xd859a63909f11e90@mail.gmail.com> Message-ID: <200604151200.06995.erchamion.beren@gmail.com> thanks for reply, i add the line you suggested, thats what i get sinan at sinan:~/tmp/multi_server$ python deneme.py Password: qwe123 finished Exception pexpect.ExceptionPexpect: in > ignored does rsync may cause a problem while trying to fork-exec ssh ? > Add "child.logfile = sys.stdout" here and check what's going on. > > Ganesan > > -- > Ganesan Rajagopal From onurb at xiludom.gro Mon Jun 19 05:09:57 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Mon, 19 Jun 2006 11:09:57 +0200 Subject: Check if a file is closed In-Reply-To: <1150706423.217609.164870@y41g2000cwy.googlegroups.com> References: <1150706423.217609.164870@y41g2000cwy.googlegroups.com> Message-ID: <449669e6$0$5281$636a55ce@news.free.fr> camillo at rockit.it wrote: > How to check if a file is closed? >>> f = open('trashme.txt', 'w') >>> f >>> dir(f) ['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__iter__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'close', 'closed', 'encoding', 'fileno', 'flush', 'isatty', 'mode', 'name', 'newlines', 'next', 'read', 'readinto', 'readline', 'readlines', 'seek', 'softspace', 'tell', 'truncate', 'write', 'writelines', 'xreadlines'] >>> f.closed False >>> f.close() >>> f.closed True -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From bearophileHUGS at lycos.com Fri Jun 16 05:20:13 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 16 Jun 2006 02:20:13 -0700 Subject: Extracting values from text file References: Message-ID: <1150449613.053205.187170@r2g2000cwb.googlegroups.com> First try, probably there are better ways to do it, and it's far from resilient, it breaks in lot of different ways (example: more than one number in one line, number with text on both sides of the line, etc.) I have divided the data munging in many lines so I can see what's happening, and you can fix/modify the code quikly. Bye, bearophile data1 = """ Some text that can span some lines. More text Apples 34 56 Ducks Some more text. 0.5 g butter """ import re # Separate lines in a list data2 = data1.split("\n") print data2, "\n" # clear lines from trailing and leading spaces, newlines, etc. data3 = map(str.strip, data2) print data3, "\n" # remove blank lines after the stripping data4 = filter(None, data3) print data4, "\n" # create a list of (lines, numbers) of only the lines with a number inside patt1 = re.compile("\d+\.?\d*") # No scientific notation data5 = [(line, n) for line in data4 for n in patt1.findall(line)] print data5, "\n" # remove the number from the lines, and strip such lines data6 = [(line.replace(num, "").strip(), num) for line, num in data5] print data6, "\n" def nconv(num): "To convert a number to an int, and if not possible to a float" try: result = int(num) except ValueError: result = float(num) return result # convert the number strings into ints or floats data7 = [(line, nconv(num)) for line, num in data6] print data7, "\n" # build the final dict of (line: number) result = dict(data7) print result, "\n" From steve at holdenweb.com Thu Jun 8 06:22:16 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 08 Jun 2006 11:22:16 +0100 Subject: language-x-isms In-Reply-To: <1149760633.796809.166430@h76g2000cwa.googlegroups.com> References: <1149753206.451066.120960@h76g2000cwa.googlegroups.com> <1149759486.695563.110640@g10g2000cwb.googlegroups.com> <1149760633.796809.166430@h76g2000cwa.googlegroups.com> Message-ID: Alan Kennedy wrote: > [Alan Kennedy] > >>>On jython 2.1, I use something like this >>> >>>#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= >>>try: >>> enumerate >>>except NameError: >>> def enumerate(iterable): >>> results = [] ; ix = 0 >>> for item in iterable: >>> results.append( (ix, item) ) >>> ix = ix+1 >>> return results > > > [Fredrik Lundh] > >>at least in CPython, using a user-defined enumerate function is a bit >>slower than using the built-in version. > > > Who's using a user-defined enumerate on cpython? > > The above code only defines a user-defined enumerate when the built-in > one doesn't exist, i.e. on jython, which raises NameError on reference > to the non-existent enumerate. > > On cpython, the reference to enumerate doesn't generate a NameError, > therefore the user-supplied version never gets defined, and the builtin > is used. > You are assuming a relatively recent release of CPython. If you look at the stuff that the effbot distributes you will see that most of it supports CPython all the way back to 1.5.2. I don't think many of us have the right to be telling Fredrik what's pythonic and what's not ... regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From fredrik at pythonware.com Tue Jun 6 11:04:59 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 06 Jun 2006 17:04:59 +0200 Subject: retaining newline characters when writing to file In-Reply-To: References: Message-ID: John Salerno wrote: > If I read a string that contains a newline character(s) into a variable, > then write that variable to a file, how can I retain those newline > characters so that the string remains on one line rather than spans > multiple lines? you cannot: the whole point of a newline character is to start a new line. however, some file formats let you "escape" the newline. for example, in Python source code, you can use end a line with a backslash. in CSV, you can put the string with newlines inside quotes, and Python's "csv" module knows how to do that: import csv, sys row = ("One\nTwo\nThree", 1, 2, 3) writer = csv.writer(sys.stdout) writer.writerow(row) prints "One Two Three",1,2,3 (not all CSV readers can handle multiline rows, though) From find at my.address.elsewhere Wed Jun 21 11:05:53 2006 From: find at my.address.elsewhere (Matthias Blume) Date: Wed, 21 Jun 2006 10:05:53 -0500 Subject: What is Expressiveness in a Computer Language References: <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <1150809118.677124.142230@u72g2000cwu.googlegroups.com> <1150815461.210286.53120@r2g2000cwb.googlegroups.com> <1150822150.701434.296460@u72g2000cwu.googlegroups.com> <1150883442.498308.226730@b68g2000cwa.googlegroups.com> <1150899429.801658.16120@r2g2000cwb.googlegroups.com> Message-ID: "Rob Thorpe" writes: >> >> > No it doesn't. Casting reinterprets a value of one type as a value of >> >> > another type. >> >> > There is a difference. If I cast an unsigned integer 2000000000 to a >> >> > signed integer in C on the machine I'm using then the result I will get >> >> > will not make any sense. >> >> >> >> Which result are you getting? What does it mean to "make sense"? >> > >> > Well the right one actually, bad example. >> > >> > But, if I cast an unsigned int 2500000000 to signed I get -1794967296. >> >> So, why do you think this "does not make sense"? > > Well, it makes sense in terms of the C spec certainly. > It does not make sense in that it does not emit an error. Why not? From bapolis at gmail.com Tue Jun 13 05:46:35 2006 From: bapolis at gmail.com (Tgone) Date: 13 Jun 2006 02:46:35 -0700 Subject: Decimals In-Reply-To: References: <1150188516.739925.102810@h76g2000cwa.googlegroups.com> <1150190908.231517.314040@h76g2000cwa.googlegroups.com> Message-ID: <1150191995.559582.140270@p79g2000cwp.googlegroups.com> Sybren Stuvel wrote: > Tgone enlightened us with: > > Sorry, when I print out the variable it displays as '15.0'. The > > price is '15.00' in the database though. > > That's the same thing, isn't it? 15.0 == 15.000000000 Yes, they're both mathematically the same. I never said they weren't... > > Here's my code: > > > > product = Product.get(2) > > print product.price # 15.0 > > Try string formatting: > > print '%.2f' % product.price That works. I expected Python to display the data exactly as it is in the database, like most languages. From rabkinDELETE at mweb.co.za Thu Jun 1 16:01:54 2006 From: rabkinDELETE at mweb.co.za (Max) Date: Thu, 01 Jun 2006 22:01:54 +0200 Subject: how to create a cgi folder??? In-Reply-To: <1149174196.582085.5150@y43g2000cwc.googlegroups.com> References: <1149174196.582085.5150@y43g2000cwc.googlegroups.com> Message-ID: elekis wrote: > So I would like to know how to create a CGI folder ??? I installed > apache (I m under Ubuntu-linux) php and mysql cause in a first time it > was that I used. but... AFAIR it's all in the apache docs. When I did my first CGI I had no web access (still don't on this PC), so if I managed to do it, it must have been in the apache docs or python docs (and I did manage). --Max From fcorreia at gmail.com Wed Jun 28 13:06:45 2006 From: fcorreia at gmail.com (Filipe) Date: 28 Jun 2006 10:06:45 -0700 Subject: handling unicode data In-Reply-To: References: <1151506510.391856.207460@y41g2000cwy.googlegroups.com> Message-ID: <1151514404.954008.282280@b68g2000cwa.googlegroups.com> Hi Fredrik, Thanks for the reply. Instead of: term = row[1] I tried: term = unicode(row[1], "iso-8859-1") but the following error was returned when printing "term": Traceback (most recent call last): File "test.py", line 11, in ? print term File "c:\Program Files\Python24\lib\encodings\cp437.py", line 18, in encode return codecs.charmap_encode(input,errors,encoding_map) UnicodeEncodeError: 'charmap' codec can't encode character u'\xd8' in position 31: character maps to Is it possible some unicode strings are not printable to the console? It's odd, because I can manually write in the console the same string I'm trying to print. I also tried other encodings, besides iso-8859-1, but got the same error. Do you think this has something to do with the DB-API driver? I don't even know where to start if I have to change something in there :| Cheers, Filipe From fcorreia at gmail.com Wed Jun 28 13:32:12 2006 From: fcorreia at gmail.com (Filipe) Date: 28 Jun 2006 10:32:12 -0700 Subject: handling unicode data In-Reply-To: <44a2af7d$0$7205$9b622d9e@news.freenet.de> References: <1151506510.391856.207460@y41g2000cwy.googlegroups.com> <44a2af7d$0$7205$9b622d9e@news.freenet.de> Message-ID: <1151515932.365483.311890@m73g2000cwd.googlegroups.com> Hi, Martin v. L?wis wrote: > Also, it appears that DB-Library (the API used by pymssql) always > returns CP_ACP characters (unless ANSI-to-OEM conversion is enabled); > so the "right" encoding to use is "mbcs". do you mean using something like the following line? term = unicode(row[1], "mbcs") What do you mean by "ANSI-to-OEM conversion is enabled"? (sorry, I'm quite a newbie to python) > Notice that Microsoft plans to abandon DB-Library, so it might be > best to switch to a different module for SQL Server access. I've done some searching and settled for pymssql, but it's not too late to change yet. I've found these options to connect to a MSSqlServer database: Pymssql http://pymssql.sourceforge.net/ ADODB for Python (windows only) http://phplens.com/lens/adodb/adodb-py-docs.htm SQLServer for Python (discontinued?) http://www.object-craft.com.au/projects/mssql/ mxODBC (commercial license) http://www.egenix.com/files/python/mxODBC.html ASPN Recipe http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/144183 Pymssql seemed like the best choice. The ASPN Recipe I mention doesn't look bad either, but there doesn't seem to be as many people using it as using pymssql. I'll look a little further though. From onurb at xiludom.gro Fri Jun 30 06:59:42 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Fri, 30 Jun 2006 12:59:42 +0200 Subject: Way for see if dict has a key In-Reply-To: <6V6pg.21624$_J1.271925@twister2.libero.it> References: <6V6pg.21624$_J1.271925@twister2.libero.it> Message-ID: <44a5041f$0$29637$636a55ce@news.free.fr> Michele Petrazzo wrote: > Hi ng, > what the preferred way for see if the dict has a key? > We have a lot of solutions: > > key in dict > key in dict.keys() > dict.has_key(key) > ... try: dict[key] except KeyError: ... else: ... > but what the better Depends on the context. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From fredrik at pythonware.com Wed Jun 7 14:30:42 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 07 Jun 2006 20:30:42 +0200 Subject: xml processing speed test In-Reply-To: <44871850.2070404@tachyontech.net> References: <44870F5C.8010407@tachyontech.net> <44871850.2070404@tachyontech.net> Message-ID: K.S.Sreeram wrote: > From what i understand, the iterparse interface constructs the xml tree, > but gives you hooks into the tree construction process itself, so that > the programmer can control how much state he wants to retain and how > much state he can discard. > > I wanted the test program to maintain as little state as possible, so > i'm discarding all state at the earliest. which means that your program is doing a lot more work than it has to do: instead of using the data structure iterparse is providing, you're building your own parallel data structure instead. > So can you tell me how i can use iterparse more effeciently? by using it to split your document into reasonably-sized chunks (one record, one expression, one text block, one paragraph, etc), and using Python code to process the chunks. if you're not interested in iterparse's tree-building functionality, use the bare parser interface instead (XMLParser). From brian at sweetapp.com Wed Jun 28 12:34:42 2006 From: brian at sweetapp.com (Brian Quinlan) Date: Wed, 28 Jun 2006 18:34:42 +0200 Subject: VPW: early registration deadline Message-ID: <44A2AFA2.1030906@sweetapp.com> What's New? =========== The deadline for early-bird registration for the Vancouver Python Workshop is this Friday, June 30th. Early-bird registration is significantly discounted over normal registration, so register now at: http://www.vanpyz.org/conference/registration.html About the Vancouver Python Workshop =================================== The conference will begin with keynote addresses on August 4st by Guido van Rossum [1] and Jim Hugunin [2]. Further talks (and tutorials for beginners) will take place on August 5th and 6th. Ian Cav?n [3] will give the closing address. The Vancouver Python Workshop is a community organized and designed for both the beginner and for the experienced Python programmer with: * tutorials for beginning programmers * advanced lectures for Python experts * case studies of Python in action * after-hours social events * informative keynote speakers More information see: http://www.vanpyz.org/conference/ or contact Brian Quinlan at: brian at sweetapp.com Vancouver ========= In addition to the opportunity to learn and socialize with fellow Pythonistas, the Vancouver Python Workshop also gives visitors the opportunity to visit one of the most extraordinary cities in the world [4]. For more information about traveling to Vancouver, see: http://www.vanpyz.org/conference/vancouver.html http://www.tourismvancouver.com http://en.wikipedia.org/wiki/Vancouver Important dates =============== Early registration (discounted): May 22nd to June 30th Normal registration: from July 1st Keynotes: August 4th Conference and tutorial dates: August 5th and 6th [1] Guido van Rossum (Google) is the inventor of Python and has managed its growth and development for more than a decade. Guido was awarded the Free Software Foundation Award in 2002 and Dr.Dobb's 1999 Excellence in Programming Award. Guido works at Google and spends half of his time on Python. [2] Jim Hugunin (Microsoft) is the creator of numerous innovations that take Python into new application domains. Jim's most recent project, IronPython integrates Python into Microsoft's .NET runtime. Jim's previous project, Jython is Python for the Java runtime and was the second production-quality implementation of Python. Before that, Jim's Numeric Python adapted Python to the needs of number crunching applications. Jim works at Microsoft adapting the .NET runtime to the needs of dynamic languages like Python. [3] Ian Cav?n is the primary developer of the Lowry Digital Images motion picture restoration system. This Python and Zope-based system has been used to restore over 150 motion pictures. Highlights include Citizen Kane, Sunset Boulevard and both the Indiana Jones and Star Wars trilogies. While Ian was Chief Scientist at Lowry Digital, his rack of computers grew from a few Macintoshes on his desktop to over six hundred Macintosh and Linux servers - at one point earning Lowry the title as the second biggest installation of parallel processing Maintoshes in the world. In 2005, Lowry Digital Images was acquired by DTS (the famous movie audio company) and renamed DTS Digital Images. The motion picture restoration system has been discussed in publications as diverse as IEEE Spectrum, USA Today, the BBC NEWS, the New York Times and Apple.com. Ian has been a Python enthusiast since 1999. [4] http://news.bbc.co.uk/2/hi/business/2299119.stm http://edition.cnn.com/2006/BUSINESS/06/15/btn.cities/index.html Cheers, Brian From Serge.Orlov at gmail.com Fri Jun 9 12:54:05 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 9 Jun 2006 09:54:05 -0700 Subject: Getting start/end dates given week-number References: Message-ID: <1149872045.876974.200050@h76g2000cwa.googlegroups.com> Tim Chase wrote: > I've been trying to come up with a good algorithm for determining > the starting and ending dates given the week number (as defined > by the strftime("%W") function). I think you missed %U format, since later you write: > My preference would be for a Sunday->Saturday range rather than a > Monday->Sunday range. Thus, > Any thoughts/improvements/suggestions would be most welcome. If you want to match %U: def weekBoundaries(year, week): startOfYear = date(year, 1, 1) week0 = startOfYear - timedelta(days=startOfYear.isoweekday()) sun = week0 + timedelta(weeks=week) sat = sun + timedelta(days=6) return sun, sat From nmm1 at cus.cam.ac.uk Wed Jun 21 13:45:56 2006 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 21 Jun 2006 17:45:56 GMT Subject: How to truncate/round-off decimal numbers? References: <1150875897.866447.312150@g10g2000cwb.googlegroups.com> <44997ea8$1@nntp0.pdx.net> Message-ID: In article <44997ea8$1 at nntp0.pdx.net>, Scott David Daniels writes: |> Nick Maclaren wrote: (of fixed point) |> > .... I am (just) old enough to remember when it was used for |> > numeric work, and to have used it for that myself, but not old enough |> > to have done any numeric work using fixed-point hardware. |> |> You are using fixed point hardware today. Fixed point tracked the |> "decimal point" (or "binary point" or whatever) in the mind of the |> programmer, not in the state of the hardware. There never was |> "fixed point hardware," it was simply a way of viewing the results |> of the gates of the same hardware we use today. Er, no. Analogue hardware never was fixed-point, and I have used that :-) More relevantly, you are using a very parochial and unusual interpretation of the word 'hardware'. In normal usage, it includes everything below the instruct set specification (now often called the ABI). And I can assure you that there is a considerable difference between the hardware that provides a floating-point interface at the ABI and that which provides a fixed-point interface. Regards, Nick Maclaren. From chris at kateandchris.net Fri Jun 16 15:16:12 2006 From: chris at kateandchris.net (Chris Lambacher) Date: Fri, 16 Jun 2006 15:16:12 -0400 Subject: Problem on win xp and run time error In-Reply-To: References: Message-ID: <20060616191532.GA4344@kateandchris.net> On Fri, Jun 16, 2006 at 06:11:53PM +0000, Michele Petrazzo wrote: > Hi list, > just found in this moment that my applications stop to work with win xp > and receive this error: > > """ > This application has requested the Runtime to terminate it in an unusual > way. Please contact the application's support team for more information. > """ > > (Note that the same application [python source code + py2exe] with > python 2.3.x work well!) Don't use the single file executatble option with py2exe and the problem will go away. -Chris > > With a little google search I found that this is a win xp sp2 problem > *without* apparently solution :( > > http://support.microsoft.com/kb/884538/en-us > > I see that the page says: > """ > This problem may occur when you use the /GR and the /MD compiler switches > """ > > so my question are: python are compiled with that switches? If yes, can > someone try to compile it without that switches, if it can of course, > and publish the new installer? I'm can't work until microsoft solve that > issue! :( > > Thanks, > Michele > -- > http://mail.python.org/mailman/listinfo/python-list From steve at holdenweb.com Wed Jun 7 08:37:57 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 07 Jun 2006 13:37:57 +0100 Subject: tempfile Question In-Reply-To: <4486BE1E.5070107@lexicon.net> References: <4486161D.6060102@lexicon.net> <4486BE1E.5070107@lexicon.net> Message-ID: John Machin wrote: > On 7/06/2006 3:57 PM, Dennis Lee Bieber wrote: > >>On Wed, 07 Jun 2006 09:56:13 +1000, John Machin >>declaimed the following in comp.lang.python: >> >> >>>The dir, prefix and suffix parameters are passed to mkstemp(). >> >> >> >>>So I'd be thinking about using the (deprecated) mktemp() instead, >> >> I think you passed over the mkstemp() variation. Granted, it, too, >>returns an opened file, along with the full pathname of the file, but it >>requires the caller to handle eventual disposal of the file. >> >> Merely close the opened file; pass the pathname to the subprocess, >>await completion of subprocess, reopen the file for use in Python... >>Then at the end, close the file and use the pathname to delete the file >>from the system. > > > I passed over mkstemp() because (according to my reading of the manual), > mkstemp() requires an *extra* step (close the file), leaving the > situation then *exactly* the same as with mktemp() i.e. some pirate > process may molest the file before the caller's child process can open > the file. > Surely if you set permissions correctly on /tmp (sticky-but to require ownership for deletion) and you create your temporary file with sensible ownership and permissions then rogue processes without root privileges can't do anything bad to your files. Or am I wrong? Of course if a rogue process has root privileges then all security bets are off anyway. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From a at tempinbox.com Thu Jun 29 12:53:54 2006 From: a at tempinbox.com (a) Date: 29 Jun 2006 09:53:54 -0700 Subject: what do you guys prefer for ajax? Message-ID: <1151600034.678929.90210@y41g2000cwy.googlegroups.com> what do you guys prefer for ajax? dojo mochikit prototype or somehting else/ From faulkner612 at comcast.net Mon Jun 5 17:07:41 2006 From: faulkner612 at comcast.net (faulkner) Date: 5 Jun 2006 14:07:41 -0700 Subject: ConfigParser, no attribute In-Reply-To: References: Message-ID: <1149541661.747743.294000@i40g2000cwc.googlegroups.com> Settings.__init__ needs to call ConfigParser.SafeConfigParser.__init__ before it calls self.readfp. Nexu wrote: > Hello, > > I'm not sure exactly what i'm doing wrong here. I asked around on IRC > and i was told the code is correct. > The purpose of Settings() is that whenever Settings() or any of its > methods are called. It should pick up the latest settings from file > instead of returning what was in the buffer. This allow other scripts to > change the value and my program and pick these changes up. > Everything else should work exact same as ConfigParser(). > ----------------------------------------------------------------------------- > class Settings(ConfigParser.SafeConfigParser): > def __init__(self): > self.filename = os.path.join(xchat.get_info('xchatdir'), 'nxscript', > 'nxscript.conf') > try: > config_file = file(self.filename, 'r') > self.readfp(config_file, self.filename) > if self.sections() == []: > self.add_section('Global') > if self.has_section('Global'): > self.set('Global', 'ProtectME', 'false') > config_file.close() > except IOError: > nx.sysmsg('Configuration file not found') > > def update_file(self): > try: > config_file = file(self.filename, 'w') > self.write(config_file) > except IOError: > nx.sysmsg('Could not write to configuration file') > ----------------------------------------------------------------------------- > SAMPLE CODE (what i want to able to do): > setting = Settings() > if setting.get('Global', 'ProtectME'): > print 'protection enabled' > ----------------------------------------------------------------------------- > ERRORS: > File "/home/nexu/.xchat2/nxscript/nx.py", line 43, in ? > setting = Settings() > File "/home/nexu/.xchat2/nxscript/nx.py", line 24, in __init__ > self.readfp(config_file, self.filename) > File "/usr/lib/python2.4/ConfigParser.py", line 286, in readfp > self._read(fp, filename) > File "/usr/lib/python2.4/ConfigParser.py", line 451, in _read > if sectname in self._sections: > AttributeError: Settings instance has no attribute '_sections' From find at my.address.elsewhere Wed Jun 21 09:39:57 2006 From: find at my.address.elsewhere (Matthias Blume) Date: Wed, 21 Jun 2006 08:39:57 -0500 Subject: What is Expressiveness in a Computer Language References: <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <1150809118.677124.142230@u72g2000cwu.googlegroups.com> <1150815461.210286.53120@r2g2000cwb.googlegroups.com> <1150822150.701434.296460@u72g2000cwu.googlegroups.com> <1150883442.498308.226730@b68g2000cwa.googlegroups.com> Message-ID: "Rob Thorpe" writes: > Matthias Blume wrote: >> "Rob Thorpe" writes: >> >> > I think we're discussing this at cross-purposes. In a language like C >> > or another statically typed language there is no information passed >> > with values indicating their type. >> >> You seem to be confusing "does not have a type" with "no type >> information is passed at runtime". >> >> > Have a look in a C compiler if you don't believe me. >> >> Believe me, I have. > > In a C compiler the compiler has no idea what the values are in the > program. It is no different from any other compiler, really. If the compiler sees the literal 1 in a context that demands type int, then it knows perfectly well what value that is. > It knows only their type in that it knows the type of the variable they > are contained within. > Would you agree with that? > >> > No it doesn't. Casting reinterprets a value of one type as a value of >> > another type. >> > There is a difference. If I cast an unsigned integer 2000000000 to a >> > signed integer in C on the machine I'm using then the result I will get >> > will not make any sense. >> >> Which result are you getting? What does it mean to "make sense"? > > Well the right one actually, bad example. > > But, if I cast an unsigned int 2500000000 to signed I get -1794967296. So, why do you think this "does not make sense"? And, as this example illustrates, casting in C maps values to values. Depending on the types of the source and the target, a cast might change the underlying representation, or it might leave it the same. But it does produce a value, and the result value is usually not the same as the argument value, even if the representation is the same. Matthias From grante at visi.com Tue Jun 6 12:05:30 2006 From: grante at visi.com (Grant Edwards) Date: Tue, 06 Jun 2006 16:05:30 -0000 Subject: what are you using python language for? References: <128b8cg1d0p7uce@corp.supernews.com> Message-ID: <128b9uanf0euh95@corp.supernews.com> On 2006-06-06, Tim Chase wrote: >> 4) Miscellaneous other stuff like grabbing all of the comic >> strips I like every day and putting them on a local web >> page so I can read them all in one place > > I wonder how many other folks have done this too. It was my > first pet Python project, converting a Java rendition of the same > app into Python. Shorter, clearer, faster, better... > > Mine uses my older Java config file (which, while tinkering with > Java's XML libraries, ended up being XML), Mine just has lists of strip/source pairs at the top of the source code. > supports Referrer/Referer spoofing, Yup. Although I wouldn't actually call mine "spoofing". Since I do grab the end URL from the referrer every time, it really is referring me to the server where the image is. > searches pages for regexps so that I can find image URLs that > have been munged with random numbers (like dilbert.com does). > It then builds a local HTML file that points at all the > locally-saved images. > I wonder what other sorts of features folks have added in their > comic-snatchers... Mine scales the images up by 50% -- the native image size provided by the distributors is just too small on my 19" 1280x1024 screen. > I tried a multi-threaded version in Java, but had problems > with it saturating my dialup connection, and returning some > sort of errors (perhaps in violation of HTTP's suggestion that > one only have, IIRC, 2 connections to a server at a given > time). I might try it again with Python. I saw some > function-call fly by recently that looked like it took a > function reference and an array of parameter-arrays, and > spawned a thread for each function. I foolishly deleted that > message, but it shouldn't be too hard to scare up again. I > think it involved importing something from the future. A nice > little status-GUI would be a nice addition, but I'm too lazy > to go that far, leaving it with just a TUI. Might be a good > way to learn Python GUI programming... Mine runs as a cron job every morning before I get to the office (which is where I read them -- don't tell anybody). -- Grant Edwards grante Yow! Why was I BORN? at visi.com From carpentier.th at free.fr Tue Jun 20 18:35:55 2006 From: carpentier.th at free.fr (thomas carpentier) Date: Wed, 21 Jun 2006 00:35:55 +0200 Subject: Problem Py2exe pygtk and Pil Message-ID: <44987851$0$29874$636a55ce@news.free.fr> Hello, I have created a program with a GUI ( glade). In this script I call the Python Imaging Library. I have developped this program onto linux, but il would like export it on Windows, however I have a problem with py2exe. If the new user has not python and library(PIL, GLADE) installed, it doesn't work. I don't know how integrate library into my setup. Thank you for your help. Thomas From pmartin at snakecard.com Fri Jun 23 12:31:26 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Fri, 23 Jun 2006 11:31:26 -0500 Subject: USB and Python Message-ID: Hi, I need to talk to a USB device (PC or other) from Python - I am not talking about mounting a file system but sharing information as you would though a TCP-IP socket layer or an RS232 interface. Is there such "low-level" module available for Windows / Linux ? Thanks, Philippe From shekhar.kaushik at gmail.com Wed Jun 28 08:37:30 2006 From: shekhar.kaushik at gmail.com (Chandrashekhar kaushik) Date: Wed, 28 Jun 2006 18:07:30 +0530 Subject: to py or not to py ? In-Reply-To: References: Message-ID: > it is going to be multi-threaded. > >... because? one thread listens for incoming requests . as soon as a request arrives ( a connection is made ) the thread verifies the request and starts another thread where the request is processed ( typically some algorithm is run on the data ).The first thread immediately goes back to listening for new connections. On 6/28/06, Robert Kern wrote: > > Chandrashekhar kaushik wrote: > > okay > > so much for a few spelling errors and abbreviations used by me !! > > we are losing the main point ! > > i had a look at mercurial . It deals with SCM . I am typically > > looking at an application thats to deal with geometry data ( tetras ) , > > process millions of them and may be process them repeatedly ( iterative > ). > > It would basically involve client-server operations to first distribute > data > > over a computing network and then send requests to process the data > > at the various nodes that contain the data. > > I do essentially the same thing (only with pickles of constructive solid > geometry definitions). > > > it is going to be multi-threaded. > > ... because? > > > Carl , what are the problems that could arise with threading ?? > > An old, but still relevant overview is here: > > http://www.softpanorama.org/People/Ousterhout/Threads/index.shtml > > A good event-driven framework for Python is Twisted. It's what I use for > the > program I mention above. > > http://twistedmatrix.com/trac/ > > -- > 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 > -- -- shekhar -------------- next part -------------- An HTML attachment was scrubbed... URL: From david.foster at citigroup.com Mon Jun 5 10:57:20 2006 From: david.foster at citigroup.com (Fozzie) Date: 5 Jun 2006 07:57:20 -0700 Subject: embedding Python in COM server loaded with win32com Message-ID: <1149519440.318504.253670@i40g2000cwc.googlegroups.com> Hi, I have a problem which is quite circular, and hopefully either someone has encountered something similar or has a reason why this will not work. We have a COM library providing mathematics to various systems, most functions are hard-coded but we want to embed a scripting language to allow arbitrary functions to be used in the numeric engines within the library, and am using Python for this. This seems to work fine called from standalone apps, and from VB, however, Python scripts, which access the scripts via win32com.client fail in the embedding code in C++ whenever I attempt to call PyImport_AddModule. As a concrete example, consider the following minimal interface, (created using an ATL project in VC7), which has a single property, the user supplied script, and a single function 'findRoot', which in this case is nothing more than an indicator that the embedding worked, ------------------------------------------------------------- STDMETHODIMP CMinEmbed::get_script(BSTR* pVal) { USES_CONVERSION; *pVal = SysAllocString(A2OLE(__script.c_str())); return S_OK; } STDMETHODIMP CMinEmbed::put_script(BSTR newVal) { USES_CONVERSION; __script = std::string( OLE2A( newVal)); return S_OK; } STDMETHODIMP CMinEmbed::findRoot(DOUBLE* root) { std::string progress; PyObject * main, * globals, * res, * func; try { progress = "calling PyInitialize"; if(!Py_IsInitialized()) Py_Initialize(); progress = "get __main__ module"; main = PyImport_AddModule("__main__"); progress = "get __main__module dictionary"; globals = PyModule_GetDict(main); progress = "Run the script."; res = PyRun_String(__script.c_str(), Py_file_input, globals, globals); progress = "Get the function from main dictionary."; func = PyDict_GetItemString(globals, "func"); progress = "test function, and return indicator"; if(NULL != func && PyCallable_Check(func)) { *root = 1.0; } else { *root = -1.0; } progress = "clean up"; Py_XDECREF(res); Py_Finalize(); return S_OK; } catch(...) { // SetFailString just sets the ISupportErrorInfo interface SetFailString(IID_IMinEmbed, progress.c_str()); return E_FAIL; } } ------------------------------------------------------------- When I build my server with the above method and run it at the Python interpretor I get, >>> from win32com.client import Dispatch >>> s = Dispatch('minServer.MinEmbed') >>> s.script = 'def func(x) : return x*x' >>> s.findRoot() Traceback (most recent call last): File "", line 1, in ? File "", line 2, in findRoot File "i:\1111\Python24\lib\site-packages\win32com\client\dynamic.py", line 251, in _ApplyTypes_ result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args) pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, 'Failure to get main module', None, 0, -2147467259), None) However, works fine from VB and standalone apps. Is this approach even doable? Thanks in advance Dave Foster From Mike.S.Duffy at gmail.com Wed Jun 28 12:56:12 2006 From: Mike.S.Duffy at gmail.com (Mike Duffy) Date: 28 Jun 2006 09:56:12 -0700 Subject: ? on scipy.fftpack Message-ID: <1151513772.828636.225540@p79g2000cwp.googlegroups.com> I've been debugging a simulation I wrote a while ago, and it seems that the problem is in the fft module itself. I'm trying a simple test by just feeding the function a basic real gaussian. Obviously, I should get back the same real gaussian, but what I get is not even close. Can anyone help me? Thanks in advance. from scipy import * import pylab fft, ifft = fftpack.rfft, fftpack.irfft def main(): sigma = 50. x = arange(-100, 100, 1, 'f') g = exp(-x**2 / (2 * sigma)) / sqrt(2 * pi) testFFT(x, g) def testFFT(x, f): pylab.plot(x, f) pylab.title('Initial gaussian') pylab.show() pylab.clf() f = fft(f) pylab.plot(x, f) pylab.title('After first FFT') pylab.show() pylab.clf() f = fft(f) pylab.plot(x, f) pylab.title('After first iFFt') pylab.show() pylab.clf() if __name__ == '__main__': main() From stylecomputers at gmail.com Tue Jun 20 21:51:22 2006 From: stylecomputers at gmail.com (stylecomputers at gmail.com) Date: 20 Jun 2006 18:51:22 -0700 Subject: Absolute noob to Linux programming needs language choice help Message-ID: <1150854682.904891.274480@c74g2000cwc.googlegroups.com> Hey guys, I am absolutely new to Linux programming, with no w######s programming experience except a small amount of C++ console apps. Reasonably new to Linux, BSD etc, got good sound networking base of knowledge and dont have any problem working the command line etc. I want to learn a language that I can use in my networking duties that is most likely to be of use to me. I have a few choices I can think of being: Python Perl C Any other Langs out there that would be better suited? I want to be able to use the app's I write in OpenBSD and RH versions of Linux What would you reccomend (Unbiased opinion please, I'm after the functionality I'll love it later :) ) Cheers Ty From ptmcg at austin.rr._bogus_.com Tue Jun 27 09:18:03 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Tue, 27 Jun 2006 13:18:03 GMT Subject: classes and interfaces References: <1151401318.703216.288850@x69g2000cwx.googlegroups.com> Message-ID: "Paul McGuire" wrote in message news:ZO9og.26787$JW5.1066 at tornado.texas.rr.com... > > Lastly, you should look into > ... this blog post: http://dirtsimple.org/2004/12/python-is-not-java.html, and its partner http://dirtsimple.org/2004/12/python-is-not-java.html. Unfortunately, many who ask "How do I implement a Java interface in Python?" are met with some defensiveness on this list, as if the OP is asking "What's wrong with stupid Python language that it doesn't have something as basic as interfaces?". Sometimes this is attitude on the OP's part, sometimes just presumption on the part of the various readers. Some responses are of an indignant "Interfaces? We don't need no stinkin' interfaces!" variety - unfortunately, most of these shed more heat than light to the discussion, usually omitting the important details as to *why* Python don't need those malodorous code devices. Java uses interfaces for two purposes: 1. to enforce at compile time whether a particular class implements a set of methods, and correspondingly enforce that only instances of such classes are permitted as arguments to functions/methods that declare arguments to be of the interface type 2. as a workaround for not directly supporting multiple inheritance Informally (and in design practices such as UML class diagrams), interfaces also serve to document expected class capabilities - which in the case of Java and C++, have the added support of compile-time checking to verify the class contains methods corresponding to those in the interface. Note that I've been careful *not* to imply that Java classes that pass this compile-time check actually *implement* the interface, as is often assumed. The only thing one knows for sure when Java accepts a class as being an interface implementer is that the class provides all the corresponding method definitions - but it cannot know if all expectations of behavior and pre- and post-conditions are actually implemented within those methods. While compile-time checking is a decent crutch 95% of the time, it will never catch errors like this: int passBackSomethingImportant() { // be sure to come back and implement this before production release! return 0; } Very few "how do I implement Java interfaces in Python" posters ever get specific about which purpose they are trying to address with their Python interface renditions. It is entirely possible that the posters don't *know* why the interface is there, they are just trying to directly port some Java code to Python. So specifically: 1. Python does not do any compile-time enforcement of method implementations in classes of objects. While some think this is like trapeze flying without a net, Pythoneers will reply that the net is a false assurance anyway (based on the example I show above). So to "port" this type of interface, the only thing to do is, well, ignore the interface - Python really doesn't require it. You *could* create a class such as: class ISomethingOrOther: def whatSomethingsDo(blah, blah2): raise NotImplementedError, "derived class failed to implement 'whatSomethingsDo' method" and then have target classes include ISomethingOrOther in their base class lists. But Python does not do any compile-time enforcement with these definitions. You *still* have to do runtime testing to see if the NotImplemented exceptions get thrown. 2. Python supports multiple inheritance without the indirection of interfaces, so you can just inherit implementation classes directly: class Swimmer: def swim(): pass class Flyer: def fly(): pass class Duck(Swimmer,Flyer): pass and merrily write: dd = Duck() dd.fly() dd.swim() Sorry for the long discourse, I didn't have time to make it shorter. HTH, -- Paul From pc at p-cos.net Mon Jun 19 14:34:33 2006 From: pc at p-cos.net (Pascal Costanza) Date: Mon, 19 Jun 2006 20:34:33 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> Message-ID: <4fo91pF1jr7gpU1@individual.net> Matthias Blume wrote: > "Rob Thorpe" writes: > >> I don't think dynamic typing is that nebulous. I remember this being >> discussed elsewhere some time ago, I'll post the same reply I did then >> .. >> >> >> A language is statically typed if a variable has a property - called >> it's type - attached to it, and given it's type it can only represent >> values defined by a certain class. > > By this definition, all languages are statically typed (by making that > "certain class" the set of all values). Moreover, this "definition", > when read the way you probably wanted it to be read, requires some > considerable stretch to accommodate existing static type systems such > as F_\omega. > > Perhaps better: A language is statically typed if its definition > includes (or ever better: is based on) a static type system, i.e., a > static semantics with typing judgments derivable by typing rules. > Usually typing judgmets associate program phrases ("expressions") with > types given a typing environment. How does your definition exclude the trivial type system in which the only typing judgment states that every expression is acceptable? Pascal -- 3rd European Lisp Workshop July 3 - Nantes, France - co-located with ECOOP 2006 http://lisp-ecoop06.bknr.net/ From cvanarsdall at mvista.com Fri Jun 9 20:08:42 2006 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Fri, 09 Jun 2006 17:08:42 -0700 Subject: Killing a thread In-Reply-To: <1149889827.2754.6.camel@kenshin.CASA> References: <7c8a9a970606091338t174fbcb0wc73cdb8b385f8ccd@mail.gmail.com> <7c8a9a970606091354u73308bf8o2758eea5ef690c39@mail.gmail.com> <1149889827.2754.6.camel@kenshin.CASA> Message-ID: <448A0D8A.4000008@mvista.com> Felipe Almeida Lessa wrote: > Em Sex, 2006-06-09 ?s 13:54 -0700, Manish Marathe escreveu: > >> On 6/9/06, Fredrik Lundh wrote: >> Manish Marathe wrote: >> >> > I am creating threads using my self defined class which >> inherits the >> > threading.Thread class. I want to know how can I kill the >> threads which >> > are being created by the object of my self defined class. >> >> you cannot kill a thread "from the outside"; you have to >> design your >> thread tasks so they can kill themselves, when asked to do >> that. >> >> Thanks for the reply. So can a thread listen to an event i.e. can we >> send an event to the thread indicating to kill itself. >> > > A plain simple boolean flag will certainly do the job. For example > > def run(self): > self.running = True > while self.running: > blah() > > def stop(self): > self.running = False > > Well, this works if your threads are able to poll. If you had a thread doing lengthy IO you could end up waiting a long time until the thread gets an opportunity to kill itself. Are there any plans in the future to add the capability to kill threads from the outside? Better yet, an interruptable thread so instead of using a polling loop you could send a DIE_THREAD_DIE signal or something. I think at present its not possible (or a really bad idea) to put signal handlers in threads. Anyone have thoughts on this? I toyed with another idea (this is a big problem for me), but I noticed that each python thread spawns a new interpreter. If python is doing this, I would think that each thread could be associated with PIDs or something. I haven't thought about it too much, its a little to crazy/brute force for me, but I thought i'd throw it out there so you guys could tell me if that one is a little too far fetched. -carl -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From bdesth.quelquechose at free.quelquepart.fr Fri Jun 2 21:42:23 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 03 Jun 2006 03:42:23 +0200 Subject: Replace one element of a tuple (LONG) In-Reply-To: <127upu8k63qnu10@corp.supernews.com> References: <127ulhn6h7hvj22@corp.supernews.com> <1149198946.567904.260480@f6g2000cwb.googlegroups.com> <127upu8k63qnu10@corp.supernews.com> Message-ID: <4480b971$0$29643$636a55ce@news.free.fr> Captain Dondo a ?crit : (snip) > c=masterDB.cursor() > c.execute("""SELECT title, subtitle, starttime FROM recorded""") > > # build our dialog checkbox > > d = dialog.Dialog(dialog="dialog") > d.add_persistent_args(["--backtitle", "Myth2Go"]) > > recordings=[] > for listing in c.fetchall(): > recordings.append( > (listing[0]+'|'+listing[2].isoformat(), > listing[1],0)) > > recordings.sort() Why don't you just add an order by clause in your sql statement ??? > (retcode, itemlist) = d.checklist(text="", > height=15, width=70, list_height=7, > choices=recordings, > title="Which recordings do you want to transfer?") > > selectlist=[] > for listing in itemlist: > print listing > (rectitle, recdate) = listing.split('|',1) > c.execute("""SELECT * FROM recorded WHERE title=%s AND > starttime=%s""",(rectitle,recdate)) is the combination of title and starttime a unique key ? Also, unless you have lots of records with huge blobs in 'recorded' table, this smells like a WTF. > selectlist.append(c.fetchone()) > The problem is the last line. I'm afraid this is not the only problem... > I am creating a bunch of tuples that are, > for my purposes, incorrect. selectlist.append(list(c.fetchone)) would create a bunch of lists instead. > I would like to create them with > masterBackend replaced by toGoBackend. > > Currently (I corrected a small bug based on another post) after a user > selects what recordings s/he wants, selectlist contains: > > [ > > (1028L, datetime.datetime(2006, 5, 26, 7, 0), datetime.datetime(2006, 5, > 26, 7, 30), 'Arthur', "What's Cooking?; Buster's Special Delivery", '', > 'Children', 'tooth.seiner.lan', None, 0L, None, 1L, 1L, 'Default', 9L, > 'SH044107', 'EP0441070207', datetime.datetime(2006, 5, 26, 7, 31, 1), > 1162899392L, 0.0, 0, datetime.date(2006, 5, 26), 0, 0L, 0), No huge blob in sight. And since the list of records fits on a dialog with checkboxes, I think you could easily avoid querying the DB that many times. FWIW, you could probably query it once only. > (1028L, datetime.datetime(2006, 5, 27, 9, 0), datetime.datetime(2006, 5, > 27, 9, 30), 'Arthur', 'Unfinished; D.W., Bossy Boots', '', 'Children', > 'tooth.seiner.lan', None, 0L, None, 1L, 1L, 'Default', 9L, 'SH044107', > 'EP0441070204', datetime.datetime(2006, 5, 27, 9, 31, 26), 1164783552L, > 0.0, 0, datetime.date(2006, 5, 23), 0, 0L, 0), > > (1028L, datetime.datetime(2006, 5, 30, 7, 0), datetime.datetime(2006, 5, > 30, 7, 30), 'Arthur', 'Prunella Sees the Light; Return of the Snowball', > 'Prunella prepares for a sleepover with Marina; D.W. protects a > snowball.', 'Children', 'tooth.seiner.lan', None, 0L, None, 1L, 1L, > 'Default', 9L, 'SH044107', 'EP0441070123', datetime.datetime(2006, 5, > 30, 7, 31, 24), 1164179392L, 0.0, 1, datetime.date(2002, 11, 28), 0, 0L, 0) > > ] > > which is the correct format to insert into the new database. > > What I'd like to do is build the correct selectlist in the first place, > rather than build the wrong one and then rebuild a correct one. > > I can't find a replace method that would work on a tuple (not surprising > since they're immutable) but I also can't find a replace function that > would replace an element of a tuple and return a new tuple. You can of course turn a tuple into a list, then modify the list. But it would still be a waste of time. Learning the full syntax for a SQL select might be more useful. You can do something like: select item1, item2, 'someconstant', item3, ..., from sometable (...) which avoid having anything to replace. Assuming that title + starttime is the primary key, and - not knowing the structure of your table - assuming that starttime is the second field, title the 5th and subtitle the 6th : # --------------------- sql = """ SELECT f1, starttime, f3, f4, title, subtitle, f7, '%s', f9, (..etc...), f24 FROM recorded ORDER BY title, starttime """ % toGoBackend c.execute(sql) rows = c.fetchall() # seems like dialog.checklist wants strings as tags # tried with ints, but it crashed... choices = [(str(i), row[5], 0) for row in rows] d = dialog.Dialog(dialog="dialog") d.add_persistent_args(["--backtitle", "Myth2Go"]) retcode, indices = d.checklist('', choices=choices) if retcode: # exit or return selectlist = [rows[i] for i in map(int, indices)] # --------------------- HTH From joncle at googlemail.com Tue Jun 20 15:02:59 2006 From: joncle at googlemail.com (Jon Clements) Date: 20 Jun 2006 12:02:59 -0700 Subject: Iteration over recursion? In-Reply-To: <1150828012.837354.160110@u72g2000cwu.googlegroups.com> References: <1150808045.539887.291180@i40g2000cwc.googlegroups.com> <1150816827.826028.114740@h76g2000cwa.googlegroups.com> <4498211b$0$8390$626a54ce@news.free.fr> <1150828012.837354.160110@u72g2000cwu.googlegroups.com> Message-ID: <1150830179.428181.263660@i40g2000cwc.googlegroups.com> Sudden Disruption wrote: > Bruno, > > > It doesn't. Technical possible, but BDFL's decision... > > Sure. But why bother? > I agree. > Anything that can be done with recursion can be done with iteration. > Turng proved that in 1936. > > Recursion was just an attempt to "unify" design approach by abstracting > itteration and creating a new context. It allowed the programmer to > isolate himself from the reality that he was actually iterating. Talk > about mind fuck. > Well, unless I'm seriously mistaken, it also breaks good design. If a function calls another function, it's because it requires that function's specific service. If the service it requires is itself, then the function should iterate over a set of data and accumulate/reduce or whatever else it needs to do. As well as that, I can imagine exception handling becoming quite cumbersome/clumsy. > It seems things were just to simple the way they were. > > Like all fashion, this too shall pass. Be great if it does; but I don't imagine this will happen until examples of traversing a binary tree using recursion disappear from computer science text books (the ones I have seen anyway...). Unless, later in the course (they might do this, I don't know for sure), they then say, "BTW people, this is the correct way to do it, because the previous way isn't too good an idea...". > Sudden Disruption > -- > Sudden View... > the radical option for editing text > http://www.sudden.net/ > http://suddendisruption.blogspot.com Just my little rant, Jon. From colincolehour at gmail.com Thu Jun 15 20:58:23 2006 From: colincolehour at gmail.com (colincolehour at gmail.com) Date: 15 Jun 2006 17:58:23 -0700 Subject: Need Help comparing dates Message-ID: <1150419503.224684.320550@c74g2000cwc.googlegroups.com> I am new to Python and am working on my first program. I am trying to compare a date I found on a website to todays date. The problem I have is the website only shows 3 letter month name and the date. Example: Jun 15 How would I go about comparing that to a different date? The purpose of my program is to load a webpage and see if the content on the front page is fresh or stale as in older than a few days. Any help in the right direction would be great! From xi at gamma.dn.ua Mon Jun 19 14:17:30 2006 From: xi at gamma.dn.ua (Kirill Simonov) Date: Mon, 19 Jun 2006 21:17:30 +0300 Subject: [ANN] PyYAML-3.03: YAML parser and emitter for Python Message-ID: <20060619181730.GA12310@58sirius016.dc.ukrtel.net> ======================== Announcing PyYAML-3.03 ======================== A new bug-fix release of PyYAML is now available: http://pyyaml.org/wiki/PyYAML Changes ======= * Fix Python 2.5 compatibility issues. * Fix numerous bugs in the float handling. * Fix scanning some ill-formed documents. * Other minor fixes. Resources ========= PyYAML homepage: http://pyyaml.org/wiki/PyYAML PyYAML documentation: http://pyyaml.org/wiki/PyYAMLDocumentation TAR.GZ package: http://pyyaml.org/download/pyyaml/PyYAML-3.03.tar.gz ZIP package: http://pyyaml.org/download/pyyaml/PyYAML-3.03.zip Windows installer: http://pyyaml.org/download/pyyaml/PyYAML-3.03.win32.exe PyYAML SVN repository: http://svn.pyyaml.org/pyyaml Submit a bug report: http://pyyaml.org/newticket?component=pyyaml YAML homepage: http://yaml.org/ YAML-core mailing list: http://lists.sourceforge.net/lists/listinfo/yaml-core About PyYAML ============ YAML is a data serialization format designed for human readability and interaction with scripting languages. PyYAML is a YAML parser and emitter for Python. PyYAML features a complete YAML 1.1 parser, Unicode support, pickle support, capable extension API, and sensible error messages. PyYAML supports standard YAML tags and provides Python-specific tags that allow to represent an arbitrary Python object. PyYAML is applicable for a broad range of tasks from complex configuration files to object serialization and persistance. Example ======= >>> import yaml >>> yaml.load(""" ... name: PyYAML ... description: YAML parser and emitter for Python ... homepage: http://pyyaml.org/wiki/PyYAML ... keywords: [YAML, serialization, configuration, persistance, pickle] ... """) {'keywords': ['YAML', 'serialization', 'configuration', 'persistance', 'pickle'], 'homepage': 'http://pyyaml.org/wiki/PyYAML', 'description': 'YAML parser and emitter for Python', 'name': 'PyYAML'} >>> print yaml.dump(_) name: PyYAML homepage: http://pyyaml.org/wiki/PyYAML description: YAML parser and emitter for Python keywords: [YAML, serialization, configuration, persistance, pickle] Copyright ========= The PyYAML module is written by Kirill Simonov . PyYAML is released under the MIT license. From ronnyma at math.uio.no Tue Jun 6 08:09:13 2006 From: ronnyma at math.uio.no (RonnyM) Date: 6 Jun 2006 05:09:13 -0700 Subject: Vectorization Message-ID: <1149595753.611358.189070@i39g2000cwa.googlegroups.com> Hi! Need to vectorize this, but do not have a clue. a = n*m matrix x and y are n and m vectors Suggestions? def fill(a, x, y): for i in range(1,a.shape[0]): xp = x[i] for j in range(a.shape[1]): yp = y[j] a[i,j] = sin(xp*yp)*exp(-xp*yp) + a[i-1,j] return a Thanks in advance, Ronny Mandal From gyows at sbcglobal.net Tue Jun 6 14:52:39 2006 From: gyows at sbcglobal.net (Ransom) Date: 6 Jun 2006 11:52:39 -0700 Subject: Newbie: returning dynamicly built lists (using win32com) (SOLVED) In-Reply-To: <1149613586.862299.125070@u72g2000cwu.googlegroups.com> References: <1149613586.862299.125070@u72g2000cwu.googlegroups.com> Message-ID: <1149619959.189730.105750@i40g2000cwc.googlegroups.com> Thanks folks! I had just gotten myself into a blind rut, apparently. Adding the .Value attribute to the com object does strip all the other messaging returning from Excel so I could then populate my list and return out of the function normally. I had tried that earlier, but had used the .Value attribute incorrectly ( Cells.Value(x,y) instead of Cells(x.y).Value. Cheers, G Ransom wrote: > Very newb here, but my question will hopefully be obvious to someone. > > Code: > > import string > from win32com.client import Dispatch > docdir = 'E:\\scripts\\Python\\RSAutomation\\' > > def getOldData(testcases): > > excel = Dispatch("Excel.Application") > excel.Workbooks.Open(docdir + 'FILE.xls') > > # load and create list from file (testcases.csv) > for rsinput in testcases.xreadlines(): > > inputlist = string.split(rsinput, ',') > > > # iterate through and update spreadsheet input > cellx = range(3,51) > values = range(0,48) > for i,r in zip(cellx, values): > > excel.ActiveSheet.Cells(i,2).Value = inputlist[r] > > # TODO: read output from cell 32,6 into a tuple or list and > then return list to __main__ > > [THIS IS WHERE I AM HAVING A PROBLEM] > print excel.ActiveSheet.Cells(32,6) <--This prints properly > as loop executes > > excel.ActiveWorkbook.Close(SaveChanges=0) > excel.Quit() > > if __name__ == "__main__": > csv_testcases = open('arse_testcases.csv','r') > getOldData(csv_testcases) > > OK, so what is happening is that I am sending a list of data to an > overly complicated spreadsheet that produces it's own output (in cell > 32,6). As I loop through multiple test cases, the print statement > calling into COM for the cell data seems to be printing out results > just fine. But when I try and put the output from the spreadsheet into > a dynamic list after the TODO section thusly: > > outputlist = [] > outputlist.extend(excel.ActiveSheet.Cells(32,6) > return outputlist > > I get an error like: > [ 0x15450880>] > > I need to be able to return the dynamically generated built up by the > responses from the spreadsheet lookup call (the exce.Activesheet > thingy). Is there a better way to get this dynamically built list out > of the funtion? > > Thanks!!! From alanalan at newsgroup.nospam Mon Jun 12 11:00:31 2006 From: alanalan at newsgroup.nospam (A.M) Date: Mon, 12 Jun 2006 11:00:31 -0400 Subject: Win XP: Problem with shell scripting in Python References: <4489efa0@news.eftel.com> Message-ID: >Does it overcome the problem that you reported earlier, that the contents of the output file from BCP were out of order? Yes, it does. But, to be honest, I don't know how!!! "John Machin" wrote in message news:4489efa0 at news.eftel.com... > On 10/06/2006 3:00 AM, A.M wrote: >> Here is what I came up with after John and Fredrik's help. >> >> import os >> import sys >> def Execute(shell_command,logStream = sys.stdout): >> print >>logStream, shell_command >> child_stdin, child_stdout_and_stderr = os.popen4(shell_command) >> commad_output = child_stdout_and_stderr.read() >> print >>logStream, commad_output >> return_code = child_stdout_and_stderr.close() >> return_code = return_code or child_stdin.close() >> print >>logStream, "Return Code: " , return_code >> >> Execute ("DIR") >> >> Execute ("MD :") >> >> I tested it and so far it behaves the way that I want. >> > > Does it overcome the problem that you reported earlier, that the contents > of the output file from BCP were out of order? If not, you may like to try > popen3(). It's quite possible (and indeed desirable) that the child's > stderr is not buffered (so that error messages appear immediately) but the > child's stdout is buffered (for efficiency), and when the buffer is > flushed governs the order of appearance in a single output stream. >> >> >> The tricky part is that when you use popen4, you have to close both >> returned streams to be able to get the return code. I wasn't able to find >> that in the documentation. > > In general it is good practice to hand back resources (e.g. close files) > explicitly as soon as you are finished with them. This is especially > important for files open for writing, in case there are problems like out > of disk space, device not functioning etc. Also when you are dealing with > a child process it makes some sense to close its stdin first just in case > it is waiting for that, and will then write something to stdout, which may > fail, causing it to write to stderr. So I guess that the documenter didn't > stumble onto the "tricky part" :-) > > The "tricky part" for popen and friends seems to be that the return code > is handed back upon close of the *last* file: > > |>>> h = os.popen3('md : ') > |>>> [h[x].close() for x in 2, 1, 0] > [None, None, 1] > > Looks like you get to report a documentation "problem" after all :-) > > Cheers, > John > > From alsmeirelles at gmail.com Thu Jun 8 06:55:38 2006 From: alsmeirelles at gmail.com (alsmeirelles at gmail.com) Date: 8 Jun 2006 03:55:38 -0700 Subject: Select hangs after some reads In-Reply-To: References: <1149737234.816833.177710@j55g2000cwa.googlegroups.com> Message-ID: <1149764138.868847.326250@i39g2000cwa.googlegroups.com> Steve Holden wrote: > alsmeirelles at gmail.com wrote: > > Hi, > > > > I'm building a multithreaded application and I encountered a tiny and > > annoying problem. I use a select to wait for data to be read from a > > socket, after some reads, the select simply blocks and stays that way > > until I close the connection on the other side of the socket. When the > > socket is closed on the writer end the select releases and then I get > > only empty strings from the socket. > > That's to be expected: the first return of a zero-length string from > socket.read() indicates end of file. > > > My question is this: Why did it block? The reading has never ended, > > every test I make I write 50 requests (wich are strings) to the socket > > and I have read the maximum of 34 requests. I'm using winPdb to take a > > closer look on what's happening and I see the threads blocked on this > > same select. If I send anything more through the socket, the select > > releases for a thread, despite the other data that is still unread. > > > Are you sure that the received data is presenting in block the same size > as are being sent? There's no guarantee this will be so on a TCP socket, > and it may be that multiple sends are being coalesced into a single > read. The important thing to focus on is the total number of bytes sent > and received. Well, actually I?m using a very simple protocol wich sends only strings ended by newline. I need to send 3 chunks of information and a newline after them. On the reader side I make 3 readline(), this way I wouldn?t have to care about this problem, but maybe that?s where I?m falling. If that?s the case, I?ll have to use a more complex protocol. > > > This is the select: > > rd,w,e = select.select([self.rfd],[],[]) > > > > self.rfd is the fileno of the file object returned by the makefile > > method from the socket object. > > > It would be simpler to use the result of the socket's .fileno() method > directly. > Yes, you are right, this is something remanescent from old ideas. > > I know that's some buffer behavior that I'm missing but I don't know > > what it is. > > > > anything is helpfull, If I'm beeing stupid you can say it. > > thanks > > > Without being able to see all your code it's hard to say whether or not > you are doing something daft, but you give a general impression of > competence. > Thanks, the code has a significant size now, if I don?t solve it quickly I?ll post the most important parts. thanks again, Andre LS Meirelles > regards > Steve > -- > Steve Holden +44 150 684 7255 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Love me, love my blog http://holdenweb.blogspot.com > Recent Ramblings http://del.icio.us/steve.holden From josef.cihal at siemens.com Fri Jun 30 09:22:23 2006 From: josef.cihal at siemens.com (Cihal Josef) Date: Fri, 30 Jun 2006 15:22:23 +0200 Subject: Way for see if dict has a key Message-ID: <94CEBD2AC72A3D478BC8381A196FD7CCA0084D@vie012.at.sat-automation.com> If dict.has_key('key'): print dict[''] Josef Cihal -----Original Message----- From: python-list-bounces+josef.cihal=sat-automation.com at python.org [mailto:python-list-bounces+josef.cihal=sat-automation.com at python.org] On Behalf Of Georg Brandl Sent: Friday, June 30, 2006 5:07 PM To: python-list at python.org Subject: Re: Way for see if dict has a key Bruno Desthuilliers wrote: > looping wrote: >> Michele Petrazzo wrote: >> >>>Bruno Desthuilliers wrote: >>> >>>>>but what the better >>>> >>>>Depends on the context. >>>> >>> >>>If know only one context: see if the key are into the dict... What >>>other context do you know? >>> >> >> Why do you want to do that ? >> >> if key in dict: >> value = dict[key] >> else: >> value = None >> >> could be write: > > value = dict.get(key, None) value = dict.get(key) ;) Georg -- http://mail.python.org/mailman/listinfo/python-list From maric at aristote.info Wed Jun 14 11:40:36 2006 From: maric at aristote.info (Maric Michaud) Date: Wed, 14 Jun 2006 17:40:36 +0200 Subject: prog1 | prog2 . How not to make prog2 block if not piped? In-Reply-To: <1150297984.798904.229730@h76g2000cwa.googlegroups.com> References: <1150297984.798904.229730@h76g2000cwa.googlegroups.com> Message-ID: <200606141740.36502.maric@aristote.info> Le Mercredi 14 Juin 2006 17:13, riquito at gmail.com a ?crit?: > # script1.py # > print 'something' > > #script2.py > x=sys.stdin.read() read() will read a file object to the end, i guess you want to use readline() instead or the builtin raw_input. > print 'passed' > > if I run > script1.py | script2.py > all goes well. This is because when script1.py ends, it will send an 'EOF' char to script2.py, wich terminate the read method. > > But if I run just > script2.py > the program blocks waiting forever for input. here, newlines ('\n'), doesn't terminate the read call, you can stop the read by typing ctrl+d at the beginnning of a new line in a normal unix terminal. -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From mwilson-to at sympatico.ca Sat Jun 3 14:11:54 2006 From: mwilson-to at sympatico.ca (Mel Wilson) Date: Sat, 03 Jun 2006 14:11:54 -0400 Subject: carshing the interpreter in two lines In-Reply-To: <1149350854.072412.263920@f6g2000cwb.googlegroups.com> References: <1149343823.789918.210110@h76g2000cwa.googlegroups.com> <1149350854.072412.263920@f6g2000cwb.googlegroups.com> Message-ID: sam wrote: > tomer: > > It is my opinion that you would loose performance if the Python > interpreter had the additional task of verifying byte code. It might be > more appropriate to have a preprocessor that did the verifying as it > compiled the byte code. Possibly. A good book on the topic is Douglas Hofstadter's _Goedel, Escher, Bach: an Eternal Golden Braid_. Particularly starting from the chapter "Contracrostipunctus". Cheers, Mel. > Sam Schulenburg > > gangesmaster wrote: >> the following (random) code crashes my interpreter >> (python 2.4.3/winxp): >> >> from types import CodeType as code >> exec code(0, 5, 8, 0, "hello moshe", (), (), (), "", "", 0, "") >> >> i would expect the interpreter to do some verifying, at least for >> sanity (valid opcodes, correct stack size, etc.) before executing >> artbitrary code... after all, it was the BDFL who said """I'm not >> saying it's uncrashable. I'm saying that if you crash it, it's a >> bug unless proven harebrained.""" >> >> >> -tomer > From per9000 at gmail.com Wed Jun 21 03:48:07 2006 From: per9000 at gmail.com (per9000) Date: 21 Jun 2006 00:48:07 -0700 Subject: How to truncate/round-off decimal numbers? References: <1150875897.866447.312150@g10g2000cwb.googlegroups.com> Message-ID: <1150876087.707092.50040@r2g2000cwb.googlegroups.com> oops, should be something like this: "int / int" = "int / int, int % int" /per9000 From aisaac0 at verizon.net Fri Jun 9 17:11:46 2006 From: aisaac0 at verizon.net (David Isaac) Date: Fri, 09 Jun 2006 21:11:46 GMT Subject: Writing PNG with pure Python References: <1149853401.521169.112530@i39g2000cwa.googlegroups.com> Message-ID: > Em Sex, 2006-06-09 ?s 12:30 -0400, Alan Isaac escreveu: > > It's your code, so you get to license it. > > But if you wish to solicit patches, > > a more Pythonic license is IMHO more likely > > to prove fruitful. "Felipe Almeida Lessa" wrote in message news:mailman.6833.1149887132.27775.python-list at python.org... > "Pythonic license"? That's new to me. I can figure out what a > "Python-like license" is, but I'm clueless about a "Pythonic license". http://www.panikon.com/phurba/alteng/i.html hth, Alan Isaac From timothy.williams at nvl.army.mil Tue Jun 27 14:10:14 2006 From: timothy.williams at nvl.army.mil (timw.google) Date: 27 Jun 2006 11:10:14 -0700 Subject: using pydoc in an application References: <1151415185.842258.27440@c74g2000cwc.googlegroups.com> Message-ID: <1151431814.696482.135420@y41g2000cwy.googlegroups.com> I went and looked at the pydoc.py code, and it looks like it isn't really meant to be used from inside another python program. After some tinkering arond with my code, I ended up with this: (Google is messing up my indentation) (in my __init__ function) ... menuBar.addmenuitem('Help', 'command', '', command=self.run_pydoc, label='Run pydoc (module help GUI)') ... def run_pydoc(self): """Run pydoc -g for gui based help""" if 'linux' in sys.platform: os.system('pydoc -g') if 'win32' in sys.platform: os.system(os.path.join(sys.prefix, 'Tools', 'Scripts', 'pydocgui.pyw')) return A bit of a kludge, but it works for me. timw.google wrote: > Hi all, > > I'm discovering pydoc, and it seems to me that this is a great way to > have online documentation for my application. Are there any examples of > using this in some kind of help menu in an application? I've tried to > just bind pydoc.gui() to a menu item, but this just brings up the GUI > for pydoc, and the user still needs to search for the module before the > browser comes up, and when I quit serving pydoc.gui(), my application > dies along with it. Also, I need to get out of python to use pydoc.gui > again, or I get > > error: (98, 'Address already in use') > > I'm sure there's a better way to take advantage of this module and my > docstrings to get some online help. I'm using Tkinter and Pmw, but > maybe it's time to convert all this to wxWidgets? > > Thanks for any help. From lhw1 at netspace_no_s_pa_m.net.au Mon Jun 26 21:51:42 2006 From: lhw1 at netspace_no_s_pa_m.net.au (Luke) Date: Tue, 27 Jun 2006 11:51:42 +1000 Subject: Beginner question: use function to read text file References: Message-ID: Thanks to both of you for the help, much appreciated! Luke From ray223 at gmail.com Fri Jun 30 03:59:27 2006 From: ray223 at gmail.com (ray223 at gmail.com) Date: 30 Jun 2006 00:59:27 -0700 Subject: Py2exe make wxPython window looks bad In-Reply-To: <1151653241.416599.6450@i40g2000cwc.googlegroups.com> References: <1151653241.416599.6450@i40g2000cwc.googlegroups.com> Message-ID: <1151654367.250645.189020@d56g2000cwd.googlegroups.com> zdp wrote: > Dear all: > > I made a window program by wxPython. Split windows, treectrl, listctrl > and textctrl are used. When I program in python, the look & feel of the > window controls are like the windos XP look & feel, with thin and flat > border (My os is window XP). It's natural because, as I know, wxPython > use native look and feel. [snip] http://wiki.wxpython.org/index.cgi/FAQ#head-4cc058aed6216dd200d55a6e4c077ccbe82bd142 Regards, Ray Smith http://RaymondSmith.com From find at my.address.elsewhere Tue Jun 20 11:49:23 2006 From: find at my.address.elsewhere (Matthias Blume) Date: Tue, 20 Jun 2006 10:49:23 -0500 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <1150809118.677124.142230@u72g2000cwu.googlegroups.com> Message-ID: David Squire writes: > Andreas Rossberg wrote: >> Rob Thorpe wrote: >>>> >>>>> No, that isn't what I said. What I said was: >>>>> "A language is latently typed if a value has a property - called it's >>>>> type - attached to it, and given it's type it can only represent values >>>>> defined by a certain class." >>>> >>>> "it [= a value] [...] can [...] represent values"? >>> >>> ??? >> I just quoted, in condensed form, what you said above: namely, that >> a value represents values - which I find a strange and circular >> definition. >> > > But you left out the most significant part: "given it's type it can > only represent values *defined by a certain class*" (my emphasis). In > C-ish notation: > > unsigned int x; > > means that x can only represent elements that are integers elements of > the set (class) of values [0, MAX_INT]. Negative numbers and > non-integer numbers are excluded, as are all sorts of other things. This x is not a value. It is a name of a memory location. > You over-condensed. Andreas condensed correctly. From dannycolligan at gmail.com Fri Jun 2 12:58:36 2006 From: dannycolligan at gmail.com (dannycolligan at gmail.com) Date: 2 Jun 2006 09:58:36 -0700 Subject: os.chdir doesn't accept variables sometimes Message-ID: <1149267516.348440.60290@u72g2000cwu.googlegroups.com> I have a strange problem with os.chdir... here is my script that I am using to edit the filenames of my music library: #!/usr/bin/python from os import * chdir("/home/chainlynx/Desktop/Music") for artist in listdir(getcwd()): print "===ARTIST: "+artist chdir(artist) for album in listdir(getcwd()): print "---ALBUM: "+album print "CWD: " + getcwd() chdir(album) ######ERROR ON THIS LINE for string in listdir(album): print "-SONG "+ string if string[-3:] == "mp3": print "CONVERTING "+string+" to "+string[:string.index(".")]+".mp3" # string = string[:string.index(".")]+".mp3" The dummy file structure that I set up to run this: chainlynx at cronus:~/Desktop/Music$ find . . ./AAAAA ./AAAAA/Album1 ./AAAAA/Album2 ./AAAAA/Album3 ./AAAAA/Album3/song1.m4a.x.mp3 ./BBBBB ./CCCCC ./CCCCC/Albummmmm ./CCCCC/Albummmmm/asdfasdf.ogg ./CCCCC/Albummmmm/blah.m4a.wav.mp3 ./CCCCC/Albummmmm/good.mp3 The error I get: chainlynx at cronus:~/workspace/PyTest/src/pypack$ python __init__.py ===ARTIST: AAAAA ---ALBUM: Album1 CWD: /home/chainlynx/Desktop/Music/AAAAA Traceback (most recent call last): File "/home/chainlynx/workspace/PyTest/src/pypack/__init__.py", line 12, in ? for string in listdir(album): OSError: [Errno 2] No such file or directory: 'Album1' Does anyone know why this is choking? Clearly, because of the second chdir(), chdir() can accept variables like this... what am I doing wrong? Thanks in advance, Danny P.S. Bonus points: is there any way to bash shell script this on the command line instead (recursively)? From george.sakkis at gmail.com Sun Jun 18 18:25:50 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 18 Jun 2006 15:25:50 -0700 Subject: any subway web dev experiences References: <1150533811.911621.112430@y41g2000cwy.googlegroups.com> <1150664491.533947.61090@p79g2000cwp.googlegroups.com> Message-ID: <1150669550.758889.28070@g10g2000cwb.googlegroups.com> a wrote: > subway is pythons ruby on rails competitor > pls tell me if u hav any expereinces > thanks u wanna know reils n subway ur so kewl omg! no expereinces watsoevah, sori dud PS: If you want to be taken seriously, put at least some effort to make a readable english sentence. This is comp.lang.python, not Myspace. From runlevelten at gmail.com Tue Jun 20 07:58:37 2006 From: runlevelten at gmail.com (Ten) Date: Tue, 20 Jun 2006 12:58:37 +0100 Subject: Calling every method of an object from __init__ In-Reply-To: <1150746953.156851.92820@r2g2000cwb.googlegroups.com> References: <1150746953.156851.92820@r2g2000cwb.googlegroups.com> Message-ID: <200606201258.37299.runlevelten@gmail.com> On Monday 19 June 2006 20:55, Rob Cowie wrote: > Hi all, > > Is there a simple way to call every method of an object from its > __init__()? > > For example, given the following class, what would I replace the > comment line in __init__() with to result in both methods being called? > I understand that I could just call each method by name but I'm looking > for a mechanism to avoid this. > > class Foo(object): > def __init__(self): > #call all methods here > def test(self): > print 'The test method' > def hello(self): > print 'Hello user' > > Thanks, > > Rob C May I ask what the intended application is? Calling *everything* callable in an instance is pretty much guaranteed to cause a problem, and a reusable external function might be better in any case. The code posted kinda-sorta implies that you're looking to call only *your created* methods, is that what you mean? If so, you probably need to bite the bullet and stick to a naming convention which excludes __class__, __init__, __call__ and so on, ie: no leading underscores a la public methods, as well as making sure your methods actually support being called with no args. Assuming all that, let me be the first in this thread to pointlessly use a list comprehension: class bork(object): def __init__(self): #in __init__ method as requested... [self.__getattribute__(i)() for i in dir(self) if not i.startswith('__') and callable(self.__getattribute__(i))] def hello(self): print 'hello' def testyflops(self): print 'breasts' x=bork() hello breasts or, nicer, you could have: def callall(x): [x.__getattribute__(i)() for i in dir(x) if not i.startswith('__') and callable(x.__getattribute__(i))] then use: class bink(object): def __init__(self): callall(self) def hatstand(self): print 'Argh!' def jackbenimble(self): print 'Freud!' y=bink() Argh! Freud! as well as being able to callall(anInstanceOfSomeOtherClass) ...with other objects if you're just so wild and rebellious that you don't care about errors, and laugh in the face of arguments. :) HTH, Ten PS: Just out of curiosity, would you mind saying what this is for? -- There are 10 types of people in this world, those who understand binary, and those who don't. From joh12005 at yahoo.fr Thu Jun 1 17:17:22 2006 From: joh12005 at yahoo.fr (joh12005 at yahoo.fr) Date: 1 Jun 2006 14:17:22 -0700 Subject: grouping a flat list of number by range Message-ID: <1149196642.001466.53990@c74g2000cwc.googlegroups.com> hello, i'm looking for a way to have a list of number grouped by consecutive interval, after a search, for example : [3, 6, 7, 8, 12, 13, 15] => [[3, 4], [6,9], [12, 14], [15, 16]] (6, not following 3, so 3 => [3:4] ; 7, 8 following 6 so 6, 7, 8 => [6:9], and so on) i was able to to it without generators/yield but i think it could be better with them, may be do you an idea? best regards, J. From aleax at mac.com Sun Jun 11 11:22:08 2006 From: aleax at mac.com (Alex Martelli) Date: Sun, 11 Jun 2006 08:22:08 -0700 Subject: import hook References: Message-ID: <1hgrdu7.1djmypwdlt2uN%aleax@mac.com> Jeremy Sanders wrote: > Hi - Is it possible to override the import process so that if in my program > I do > > import foo.bar > > Python will look for bar in a directory which isn't called foo? > > I want my module/program to be able to be run without being installed in > site-packages, so by doing "import foo.bar", it should start looking for > bar in the current directory which could be called "foo-0.43". > > I've tried overriding __import__, chopping out "foo." from package names, > but that tends to break. I've also tried overriding imp.find_module() but > Python never appears to use my version. > > Any ideas? Yes, PEP 302 (which despite being marked as "draft" has in fact been already mostly implemented, since it's used by the zipimport mechanism) allows you to perform such feats. Study it at ... Alex From rune.strand at gmail.com Tue Jun 13 05:49:09 2006 From: rune.strand at gmail.com (Rune Strand) Date: 13 Jun 2006 02:49:09 -0700 Subject: Screen capturing on Windows Message-ID: <1150192149.757557.163820@y43g2000cwc.googlegroups.com> Is it possible by use of pyWin32 or ctypes to make a screen capture of an inactive, or a hidden window if the hwnd/WindowName/ClassName is known? I've seen dedicated screen capture software do this. While PIL.ImageGrab.grab() is excellent, it will only capture the foreground of the desktop. I've tried for hours, but I soon get helplessly lost in the labyrinths of the Win32API. From trodemaster at gmail.com Tue Jun 20 02:34:28 2006 From: trodemaster at gmail.com (Blake Garner) Date: Mon, 19 Jun 2006 23:34:28 -0700 Subject: replacing choice.exe function with python script.. Message-ID: <55a5c7c50606192334i7261572ava399be4417c3c6be@mail.gmail.com> Hi list,I'm looking for suggestions to replace choice.exe on windows with a python script. With choice.exe you can ask for input from the command line. Then choice.exewill set a variable that can later be used to do usefull things. The tricky part is that it allows you to set a default selection that will be entered after a timeout. Anybody have some code examples or suggestions? some details on how choice.exe works.. http://www.ss64.com/nt/choice.html Blake- -------------- next part -------------- An HTML attachment was scrubbed... URL: From grante at visi.com Thu Jun 29 12:42:24 2006 From: grante at visi.com (Grant Edwards) Date: Thu, 29 Jun 2006 16:42:24 -0000 Subject: Bug reporting impossible References: Message-ID: <12a80ngnmfe9a79@corp.supernews.com> On 2006-06-29, Nick Maclaren wrote: > Currently logins are disabled to sourceforge.net, and (despite the > comments) it won't let me report a bug anonymously. Does anyone > know whether this is short or long term? I have a bug in 2.5 to > report - which has been there for a while and isn't overwhelmingly > critical and has been there for a while. > > Create a file called '' in your current directory containing > 'print "Oh, yeah?\n"' and then import a module that doesn't exist. > Don't include the single quotes. Cute. :) 2.4 has the same bug I'm guessing: $ echo "Oh, yeah?" >\ $ python Python 2.4.2 (#1, Feb 17 2006, 12:02:16) [GCC 3.4.4 (Gentoo 3.4.4-r1, ssp-3.4.4-1.0, pie-8.7.8)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import asdfasdf Traceback (most recent call last): File "", line 1, in ? Oh, yeah? ImportError: No module named asdfasdf >>> -- Grant Edwards grante Yow! Hello. I know at the divorce rate among visi.com unmarried Catholic Alaskan females!! From david.nospam.hopwood at blueyonder.co.uk Mon Jun 26 18:23:25 2006 From: david.nospam.hopwood at blueyonder.co.uk (David Hopwood) Date: Mon, 26 Jun 2006 22:23:25 GMT Subject: Termination and type systems In-Reply-To: <20060626111326.18B1.0.NOFFLE@dthierbach.news.arcor.de> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <86Qmg.10725$o4.1907@newsread2.news.pas.earthlink.net> <0neng.213767$8W1.1948@fe1.news.blueyonder.co.uk> <1151171209.684163.143410@c74g2000cwc.googlegroups.com> <4ving.213803$8W1.62401@fe1.news.blueyonder.co.uk> <20060626111326.18B1.0.NOFFLE@dthierbach.news.arcor.de> Message-ID: Dirk Thierbach wrote: > David Hopwood wrote: >>Marshall wrote: >>>David Hopwood wrote: > >>>>A type system that required an annotation on all subprograms that >>>>do not provably terminate, OTOH, would not impact expressiveness >>>>at all, and would be very useful. > >>>Interesting. I have always imagined doing this by allowing an >>>annotation on all subprograms that *do* provably terminate. > > Maybe the paper "Linear types and non-size-increasing polynomial time > computation" by Martin Hofmann is interesting in this respect. > From the abstract: > > We propose a linear type system with recursion operators for inductive > datatypes which ensures that all definable functions are polynomial > time computable. The system improves upon previous such systems in > that recursive definitions can be arbitrarily nested; in particular, > no predicativity or modality restrictions are made. > > It does not only ensure termination, but termination in polynomial time, > so you can use those types to carry information about this as well. That's interesting, but linear typing imposes some quite severe restrictions on programming style. From the example of 'h' on page 2, it's clear that the reason for the linearity restriction is just to ensure polynomial-time termination, and is not needed if we only want to prove termination. >>If the annotation marks not-provably-terminating subprograms, then it >>calls attention to those subprograms. This is what we want, since it is >>less safe/correct to use a nonterminating subprogram than a terminating >>one (in some contexts). > > That would be certainly nice, but it may be almost impossible to do in > practice. It's already hard enough to guarantee termination with the > extra information present in the type annotation. If this information > is not present, then the language has to be probably restricted so > severely to ensure termination that it is more or less useless. I think you're overestimating the difficulty of the problem. The fact that *in general* it can be arbitrarily hard to prove termination, can obscure the fact that for large parts of a typical program, proving termination is usually trivial. I just did a manual termination analysis for a 11,000-line multithreaded C program; it's part of a control system for some printer hardware. This program has: - 212 functions that trivially terminate. By this I mean that the function only contains loops that have easily recognized integer loop variants, and only calls other functions that are known to trivially terminate, without use of recursion. A compiler could easily prove these functions terminating without need for any annotations. - 8 functions that implement non-terminating event loops. - 23 functions that intentionally block. All of these should terminate (because of timeouts, or because another thread should do something that releases the block), but this cannot be easily proven with the kind of analysis we're considering here. - 3 functions that read from a stdio stream into a fixed-length buffer. This is guaranteed to terminate when reading a normal file, but not when reading from a pipe. In fact the code never reads from a pipe, but that is not locally provable. - 2 functions that iterate over a linked list of network adaptors returned by the Win32 GetAdaptorsInfo API. (This structure could be recognized as finite if we were calling a standard library abstraction over the OS API, but we are relying on Windows not to return a cyclic list.) - 1 function that iterates over files in a directory. (Ditto.) - 2 functions that iterate over a queue, implemented as a linked list. The queue is finite, but this is not locally provable. Possibly an artifact of the lack of abstraction from using C, where the loop is not easily recognizable as an iteration over a finite data structure. - 1 function with a loop that terminates for a non-trivial reason that involves some integer arithmetic, and is probably not expressible in a type system. The code aready had a comment informally justifying why the loop terminates, and noting a constraint needed to avoid an arithmetic overflow. (Bignum arithmetic would avoid the need for that constraint.) - 2 functions implementing a simple parsing loop, which terminates because the position of the current token is guaranteed to advance -- but this probably would not be provable given how the loop is currently written. A straightforward change (to make the 'next token' function return the number of characters to advance, asserted to be > 0, instead of a pointer to the next token) would make the code slightly clearer, and trivially terminating. So for this program, out of 254 functions: - 83.5% are trivially terminating already. - 12.2% would need annotations saying that they are intended to block or not to terminate. This is largely an artifact -- we could remove the need for *all* of these annotations by adopting an event-loop concurrency model, and only attempting to prove termination of functions within a "turn" (one iteration of each top-level loop). - 2.4% would need annotations saying that termination is too hard to prove -- but only because they interact with the operating system. This is obviously not a type system problem; fixing it requires careful design of the language's standard library. - 0.8% would need annotations only in C; in a language with standard libraries that provide data structures that are guaranteed to be finite, they probably would not. - 1.2% would need changes to the code, or are genuinely too difficult to prove to be terminating using a type system. This is obviously not a large program (although I wouldn't want to do a manual analysis like this for a much larger one), and it may be atypical in that it has almost no use of recursion (or maybe that *is* typical for C programs). It would be interesting to do the same kind of analysis for a functional program, or one that does a more "algorithmically intensive" task. -- David Hopwood From onurb at xiludom.gro Tue Jun 20 12:23:54 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Tue, 20 Jun 2006 18:23:54 +0200 Subject: Iteration over recursion? In-Reply-To: References: <1150808045.539887.291180@i40g2000cwc.googlegroups.com> <1150816827.826028.114740@h76g2000cwa.googlegroups.com> Message-ID: <4498211b$0$8390$626a54ce@news.free.fr> Nick Maclaren wrote: (snip) > Tail recursion removal can often eliminate the memory drain, but the > code has to be written so that will work - and I don't know offhand > whether Python does it. It doesn't. Technical possible, but BDFL's decision... -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From afa at neuf.fr Mon Jun 26 17:11:36 2006 From: afa at neuf.fr (Amaury Forgeot d'Arc) Date: Mon, 26 Jun 2006 23:11:36 +0200 Subject: psyco+webpy In-Reply-To: <1151348303.344822.18720@u72g2000cwu.googlegroups.com> References: <1151348303.344822.18720@u72g2000cwu.googlegroups.com> Message-ID: a a ?crit : > hi i tried psyco+webpy > > here is the error that i got > please let me know if any of you has success run psyco+webpy > thanks > > import web, psyco > urls = ( > '/', 'view', > '/add','add' > ) > psyco.full() > psyco.log() > psyco.profile() > > Launching server: http://0.0.0.0:8080/ > Traceback (most recent call last): > File "C:\Python24\lib\site-packages\web.py", line 2054, in > run_wsgi_app > result = self.server.app(env, self.wsgi_start_response) > File "C:\Python24\lib\site-packages\web.py", line 1894, in wsgifunc > result = func() > File "C:\Python24\lib\site-packages\web.py", line 1872, in > func = lambda: handle(getattr(mod, name), mod) > File "C:\Python24\lib\site-packages\web.py", line 1051, in handle > return tocall(*([urllib.unquote(x) for x in args] + fna)) > File "C:\mark\web1\codepsyco.py", line 27, in GET > web.render('view.html') > File "C:\Python24\lib\site-packages\web.py", line 1707, in render > terms.update(sys._getframe(1).f_locals) > File "C:\Python24\Lib\site-packages\psyco\support.py", line 129, in > __getattr__ Functions optimized by Psyco have limitations concerning access of their local variables, as stated there: http://psyco.sourceforge.net/psycoguide/bugs.html As a workaround, you should prevent psyco from optimizing the functions calling render(). psyco.cannotcompile(web.djangoerror) psyco.cannotcompile(??.GET) P.S. I just had a look at the web.py code and it seems that there are several uses of _getframe(x).f_locals. I find this trick not very pythonic (a function's docstring even says:"""Guido van Rossum doesn't want you to use this function.""") and anyway psyco will not appreciate it. -- Amaury From python.list at tim.thechases.com Fri Jun 9 10:07:31 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 09 Jun 2006 09:07:31 -0500 Subject: Getting start/end dates given week-number Message-ID: <448980A3.2030202@tim.thechases.com> I've been trying to come up with a good algorithm for determining the starting and ending dates given the week number (as defined by the strftime("%W") function). My preference would be for a Sunday->Saturday range rather than a Monday->Sunday range. Thus, >>> startDate, stopDate = weekBoundaries(2006, 23) would yield a start-date of June 4, 2006 and an end-date of June 10, 2006 in this hypothetical function (as strftime("%W") for today, June 9th, 2006 returns 23). I've posted my first round of code below, but I'm having problems with dates early in 2005, as the tests show. Any thoughts/improvements/suggestions would be most welcome. Thanks, -tkc from datetime import date, timedelta from time import strptime DEBUG = False tests = [ #test date start end (date(2006,1,1), (date(2006,1,1), date(2006,1,7))), (date(2006,1,2), (date(2006,1,1), date(2006,1,7))), (date(2006,1,3), (date(2006,1,1), date(2006,1,7))), (date(2006,1,4), (date(2006,1,1), date(2006,1,7))), (date(2006,1,5), (date(2006,1,1), date(2006,1,7))), (date(2006,1,6), (date(2006,1,1), date(2006,1,7))), (date(2006,1,7), (date(2006,1,1), date(2006,1,7))), (date(2006,1,8), (date(2006,1,8), date(2006,1,14))), (date(2005,1,1), (date(2004,12,26), date(2005,1,1))), (date(2005,1,2), (date(2005,1,2), date(2005,1,8))), ] def weekBoundaries(year, week): startOfYear = date(year, 1, 1) now = startOfYear + timedelta(weeks=week) # isoweekday() % 7 returns Sun=0 ... Sat=6 sun = now - timedelta(days=now.isoweekday() % 7) sat = sun + timedelta(days=6) if DEBUG: print "DEBUG: now = %s/%s" % (now, now.strftime("%a")) print "DEBUG: sun = %s/%s" % (sun, sun.strftime("%a")) print "DEBUG: sat = %s/%s" % (sat, sat.strftime("%a")) return sun, sat for test, expectedResult in tests: print "Testing %s" % test year = test.year # jigger it so that %W is Sun->Sat rather than Mon->Sun weekNum = int((test + timedelta(days=1)).strftime("%W")) - 1 results = weekBoundaries(year, weekNum) passed = (expectedResult == results) print "Week#%s: %s" % (weekNum, passed) print "=" * 50 From grflanagan at yahoo.co.uk Fri Jun 30 05:22:09 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 30 Jun 2006 02:22:09 -0700 Subject: How to get indices of a two dimensional list In-Reply-To: <1151655165.022076.95460@x69g2000cwx.googlegroups.com> References: <1151639976.664310.183620@x69g2000cwx.googlegroups.com> <1151655165.022076.95460@x69g2000cwx.googlegroups.com> Message-ID: <1151659328.989880.193050@b68g2000cwa.googlegroups.com> Gerard Flanagan wrote: > sramaswamy at gmail.com wrote: > > I have a list > > > > x = [0] * 2 > > x = x * [2] > > x[1,1] = 7 > > > > This gives me the x value > > [[0,0] [0,0] [0,0] [0,7]] > > > > I want to get the indices of the value 7. > > i.e. something like > > i = a.index(max(a)) gives me '1' > > > > This only gives me the index in one dimension. Is there any method by > > which I can get (1,1) as the answer. > > > > Thanks in advance. > > If you post code that doesn't work, people won't treat you seriously. > I have some code that might help if you'd like to try again. > > All the best > Ok, that was mean-spirited. The code is below - it's related to another problem but maybe it can be adapted to your own. Good luck! def irows(n): i=0 while True: yield divmod(i,n) i += 1 x = [0,0,0,7,0,0,0,0] d = dict(zip(enumerate(x), irows(2))) assert d[x.index(7),7] == (1,1) assert d[x.index(0),0] == (0,0) d = dict(zip(irows(2),x)) assert d[1,1] == 7 sudoku = dict(zip(irows(9),[[0]]*81)) From micklee74 at hotmail.com Thu Jun 1 09:44:42 2006 From: micklee74 at hotmail.com (micklee74 at hotmail.com) Date: 1 Jun 2006 06:44:42 -0700 Subject: default argument values qns Message-ID: <1149169482.717737.241410@g10g2000cwb.googlegroups.com> hi i have declared a function like this: def aFunction ( arg1 , arg2 = 0): .... print type(arg2) when i try to print the type of arg2, it gives me 'str' type..why is it not integer type, since i have declared it as 0 ?? thanks From py.adriano at gmail.com Fri Jun 9 10:43:19 2006 From: py.adriano at gmail.com (py.adriano at gmail.com) Date: 9 Jun 2006 07:43:19 -0700 Subject: Interacting with a process that I ran with subprocess module Message-ID: <1149864190.134947.178000@g10g2000cwb.googlegroups.com> Hi folks, I'm trying to use the nmap runtime interaction feature while using it with the subprocess module. For those not familiar with nmap, the runtime interaction feature allow users to get informations about the scan stats during the nmap execution. More at: http://www.insecure.org/nmap/man/man-runtime-interaction.html If someone want to try, just run nmap and try to type some keys to see what happens. This only works with nmap 4.00 and above. Ok.. What I've tried is shown below: from subprocess import Popen, PIPE nmap = Popen("nmap -T3 -A 10.0.0.1-254", stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True, bufsize=1) To interact with nmap, I tried: nmap.communicate("?") And I tried this, also: nmap.stdin.write("?") nmap.stdout.read() What's wrong? Is that suposed to be this way? Is there a better way to interact with it that I've missed? Any help is very welcome. Thanks in advance! Cheers! From rogue_pedro at yahoo.com Thu Jun 29 13:34:53 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 29 Jun 2006 10:34:53 -0700 Subject: list comprehension References: <1151600332.552024.119990@y41g2000cwy.googlegroups.com> Message-ID: <1151602493.629010.269360@i40g2000cwc.googlegroups.com> a wrote: > can someone tell me how to use them > thanks basically, a list comprehension is just like a for loop, if you wrote it out the "long way" it would be something like this: results = [] for var in some_iterable: if some condition: results.append(some expression) The list comprehension version: results = [some expression for var in some_iterable if some condition] There's more to it, but that's the basic idea. Hope this helps, ~Simon From coming_soon at yahoo.com Thu Jun 15 06:08:48 2006 From: coming_soon at yahoo.com (veritas) Date: Thu, 15 Jun 2006 20:08:48 +1000 Subject: Python in Windows ng Message-ID: <449131ab$0$10456$afc38c87@news.optusnet.com.au> Can anyone tell me of a good newsgroup for running/programming Python on Windows OS ? Thanks in advance . From faulkner612 at comcast.net Sun Jun 25 11:20:03 2006 From: faulkner612 at comcast.net (faulkner) Date: 25 Jun 2006 08:20:03 -0700 Subject: Python taught in schools? In-Reply-To: <1151220913.406987.162420@u72g2000cwu.googlegroups.com> References: <1151220913.406987.162420@u72g2000cwu.googlegroups.com> Message-ID: <1151248803.267792.98120@m73g2000cwd.googlegroups.com> Franklin W. Olin College of Engineering I TAed a python class last semester, and am using it to build a webapp for the Arts and Humanities dept. http://www.olin.edu MilkmanDan wrote: > I'll be a college freshman this fall, attending Florida Institute of > Tech studying electrical engineering. > > I was considering taking some classes in programming and computer > science, and I happened to notice that everything taught is using C++. > After further research, it seems to me that C++ seems to be the > dominating language in universities. > > By comparison, our local community college teaches a few classes in VB, > Java, Javascript, C++, and for some reason, PASCAL. > > I'm certianly not against any of this, but out of curiousity does > anyone know of a school that teaches Python? From maxm at mxm.dk Tue Jun 20 10:58:29 2006 From: maxm at mxm.dk (Max M) Date: Tue, 20 Jun 2006 16:58:29 +0200 Subject: Python is fun (useless social thread) ;-) In-Reply-To: <4497e9b2$0$1602$636a55ce@news.free.fr> References: <449433b5$0$1344$626a54ce@news.free.fr> <44965e69$0$38632$edfadb0f@dread12.news.tele.dk> <4497e9b2$0$1602$636a55ce@news.free.fr> Message-ID: <44980c68$0$38718$edfadb0f@dread12.news.tele.dk> bruno at modulix wrote: > Max M wrote: >> bruno at modulix wrote: >> >>>> Or did you just like what you saw and decided to learn it for fun? >>> >>> Well, I haven't be really impressed the first time - note that it was at >>> the very end of the last century, with v1.5.2. >> >> >> 1.5.2 was an excellent version. Not really that different in use than >> current version. > > Nope, "not really that different" - we were just missing list-comps, > generators, new-style classes, classmethods, staticmethods, usable > metaclasses, descriptors, @decorators sugar, extended slices, and a few > other goodies coming in 2.5 like coroutines and with: statement... I wrote "different in use". Which is not the same as saying it has not changed. The general feel of coding in Python is exactly the same to me. I believe that most of those changes you mention are rarely used by most programmers. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science Phone: +45 66 11 84 94 Mobile: +45 29 93 42 96 From jo at durchholz.org Fri Jun 16 05:22:08 2006 From: jo at durchholz.org (Joachim Durchholz) Date: Fri, 16 Jun 2006 11:22:08 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: <2006061501423327544-raffaelcavallaro@pasdespamsilvousplaitmaccom> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <2006061410510511272-raffaelcavallaro@pasdespamsilvousplaitmaccom> <2006061501423327544-raffaelcavallaro@pasdespamsilvousplaitmaccom> Message-ID: Raffael Cavallaro schrieb: > On 2006-06-14 15:04:34 -0400, Joachim Durchholz said: > >> Um... heterogenous lists are not necessarily a sign of expressiveness. >> The vast majority of cases can be transformed to homogenous lists >> (though these might then contain closures or OO objects). >> >> As to references to nonexistent functions - heck, I never missed >> these, not even in languages without type inference :-) >> >> [[snipped - doesn't seem to relate to your answer]] > > This is a typical static type advocate's response when told that users > of dynamically typed languages don't want their hands tied by a type > checking compiler: > > "*I* don't find those features expressive so *you* shouldn't want them." And this is a typical dynamic type advocate's response when told that static typing has different needs: "*I* don't see the usefulness of static typing so *you* shouldn't want it, either." No ad hominem arguments, please. If you find my position undefendable, give counterexamples. Give a heterogenous list that would to too awkward to live in a statically-typed language. Give a case of calling nonexistent functions that's useful. You'll get your point across far better that way. Regards, Jo From Shani718 at gmail.com Thu Jun 8 10:38:19 2006 From: Shani718 at gmail.com (Shani) Date: 8 Jun 2006 07:38:19 -0700 Subject: Instead of saving text files i need as html Message-ID: <1149777499.506986.292830@j55g2000cwa.googlegroups.com> I have the following code which takes a list of urls "http://google.com", without the quotes ofcourse, and then saves there source code as a text file. I wan to alter the code so that for the list of URLs an html file is saved. -----begin----- import urllib urlfile = open(r'c:\temp\url.txt', 'r') for lines in urlfile: try: outfilename = lines.replace('/', '-') urllib.urlretrieve(lines.strip('/n'), 'c:\\temp\\' \ + outfilename.strip('\n')[7:] + '.txt') except: pass -----end----- From tactics40 at gmail.com Tue Jun 13 10:06:20 2006 From: tactics40 at gmail.com (tactics40 at gmail.com) Date: 13 Jun 2006 07:06:20 -0700 Subject: .py and running in Windows: In-Reply-To: References: <1150203354.861658.181110@h76g2000cwa.googlegroups.com> Message-ID: <1150207580.324952.177500@f6g2000cwb.googlegroups.com> The only problem I know of for changing PY files to open up in an editor is that it could screw up Python as a CGI with Apache under Windows. To change file associations, right click and go to "Open With." Choose your text editor and click "always open with this problem" at the bottom. And easy way to run your scripts is to open a console (Start->Run->type "cmd.exe" and hit OK). Type "python" and drag&drop your .py file into the console. It will copy the path name ("C:\programming\python stuff\myproject\mypython.py"). Michael Yanowitz wrote: > Hello: > > Presently in my Windows 2000 system, when I double-click on a > .py file (open it) it automatically runs it in Python. I would > like to change that behavour. That is fine for .pyc file, but > for .py files, I would either like to have it run in Python but > return to the Python shell prompt when finished rather than > exit the shell. How do I do that? > Or would it cause a problem (so that Python no longer works) if > I change the default .py extension to open in an editor rather > than execute it if I open it? > > Thanks: > Michael Yanowitz From sekhon.hari at googlemail.com Wed Jun 21 09:02:18 2006 From: sekhon.hari at googlemail.com (Hari Sekhon) Date: Wed, 21 Jun 2006 14:02:18 +0100 Subject: What's the best way to wrap a whole script in try..except? In-Reply-To: <44993148.8000003@gmail.com> References: <44993148.8000003@gmail.com> Message-ID: <4499435A.9040800@gmail.com> Hari Sekhon wrote: > Jon Ribbens wrote: >> In article , Hari Sekhon wrote: >> >>> I want to wrap a whole script in try ... except. What is the best way of >>> doing this? >>> >> >> You could do this maybe: >> >> import sys >> >> def excepthook(exc_type, exc_value, tb): >> import modules_needed_to_notify_exception >> ... >> >> sys.excepthook = excepthook >> >> import modules_needed_by_script >> ... >> > having tested this more, I was worried about a recursive call to > exception should an exception be raised inside the function but > luckily python deals and give you a double traceback. > > batteries included indeed. > > Thanks again > > Hari I see that the exceptionhook is handed 3 things, the name of the error, the explanation, and the traceback object. Does anybody know how I can get the linenumber of the error the way it does normally, since this is very useful info when debugging. I think I need the traceback module but I can't see how to extract the extra info from the traceback object passed to excepthook. -------------- next part -------------- An HTML attachment was scrubbed... URL: From onurb at xiludom.gro Wed Jun 28 06:23:57 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Wed, 28 Jun 2006 12:23:57 +0200 Subject: global name is not defined - error In-Reply-To: <1151469851.975668.262090@d56g2000cwd.googlegroups.com> References: <1151469851.975668.262090@d56g2000cwd.googlegroups.com> Message-ID: <44a258be$0$1363$626a54ce@news.free.fr> a wrote: > What I want > --------------- > I want to create a list of items from a function operating on an array > of strings def func(s): return s.upper() arrayOfStrings = ['bicycle', 'repair', 'man'] print "solution 1: with map()" print map(func, arrayOfStrings) print "solution 2: with list comprehension" print [func(s) for s in arrayOfStrings] -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From tactics40 at gmail.com Fri Jun 23 11:54:42 2006 From: tactics40 at gmail.com (tactics40 at gmail.com) Date: 23 Jun 2006 08:54:42 -0700 Subject: Python in HTML References: <1151077239.840572.175120@y41g2000cwy.googlegroups.com> <449c0c43$0$11196$636a55ce@news.free.fr> Message-ID: <1151078082.229271.85480@m73g2000cwd.googlegroups.com> Bruno Desthuilliers wrote: > brochu121 at gmail.com wrote: > > Does anyone know of a way to embed python scripts into html, much like > > you would javascript or php? > > I think you'd better learn the profound difference between client-side > and server-side scripting. Indeed. You really should Google this before continuing. Python, like it's (evil?) cousin Perl, can be used as a CGI. If you don't have one already, go download Apache server to play with on your own machine and Google "Python CGI" and "Python module cgi". Basically, (after setting up your server correctly), you can do "http://localhost/index.py" and your webserver will _execute_ your script. The server then returns the output of your script (everything from the print statements) to the web browser. From dingbat at codesmiths.com Mon Jun 12 10:26:55 2006 From: dingbat at codesmiths.com (dingbat at codesmiths.com) Date: 12 Jun 2006 07:26:55 -0700 Subject: Python or Ajax? In-Reply-To: References: Message-ID: <1150122415.913983.150600@g10g2000cwb.googlegroups.com> Redefined Horizons wrote: > How does a web application that uses Python compare with one that uses AJAX? Mauve has the most RAM From bussieremaillist at gmail.com Fri Jun 2 10:57:30 2006 From: bussieremaillist at gmail.com (bussiere maillist) Date: Fri, 2 Jun 2006 16:57:30 +0200 Subject: gadfly error gadfly instance has no attribute 'execute' Message-ID: <8a8f62c80606020757g328bb37dlbdbf3d63bf379e69@mail.gmail.com> here is the error i've get : Traceback (most recent call last): File "D:\Programmation\pitney\pitney.py", line 13, in ? connection.execute('create table personne(nom varchar)') AttributeError: gadfly instance has no attribute 'execute' i'am under windows and i still haven't found the error here is my code : import csv,gadfly,fileinput,glob, string, sys, os,unicodedata print "que voulez vous faire ?\n" fichA=raw_input("Entrez le nom du fichier a importer : ") cr = csv.reader(open(fichA),delimiter=";") connection = gadfly.gadfly() connection.startup('pitney','D:\Programmation\pitney\') cursor = connection.cursor() connection.execute('create table personne(nom varchar)') cursor.execute("insert into personne(nom) values('bussiere')") connection.commit() cursor.execute('select * from personne') print cursor.fetchall() compteur = 0 for row in cr: print row[0],row[1] compteur += 1 print "Dead Parrot" regards Bussiere -------------- next part -------------- An HTML attachment was scrubbed... URL: From paddy3118 at netscape.net Thu Jun 15 17:18:42 2006 From: paddy3118 at netscape.net (Paddy) Date: 15 Jun 2006 14:18:42 -0700 Subject: Regular expression for not-group In-Reply-To: <1150405899.027971.256160@r2g2000cwb.googlegroups.com> References: <1150405899.027971.256160@r2g2000cwb.googlegroups.com> Message-ID: <1150406322.094263.239930@g10g2000cwb.googlegroups.com> Chris Lasher wrote: > Is it possible to write a regular expression such that a "match" is > found provided the string does not match a group in the regex? Let me > give a concrete example. > > Suppose I want to find a match to any filename that does not end in > .py, (ignoring the obvious use of the .endswith('.py') string method). > I tried the things that were obvious to me, none of which worked. > > \.^(py) > \.(^py) > \.[^p][^y] > > The last one deceived me at first because it will match "spam.spam", > but not "spam.parrot". I'm a bit stumped at this point. If this can be > done with a regular expression, I'd love to know how, and even if it > can't be, that would be very helpful to know, too. > The re module documentation has this snippet: (?!...) Matches if ... doesn't match next. This is a negative lookahead assertion. For example, Isaac (?!Asimov) will match 'Isaac ' only if it's not followed by 'Asimov'. - Paddy. From eric.pederson at gmail.com Wed Jun 21 03:09:39 2006 From: eric.pederson at gmail.com (EP) Date: 21 Jun 2006 00:09:39 -0700 Subject: Python SHA-1 as a method for unique file identification ? [help!] Message-ID: <1150873779.832601.154920@b68g2000cwa.googlegroups.com> This inquiry may either turn out to be about the suitability of the SHA-1 (160 bit digest) for file identification, the sha function in Python ... or about some error in my script. Any insight appreciated in advance. I am trying to reduce duplicate files in storage at home - I have a large number files (e.g. MP3s) which have been stored on disk multiple times under different names or on different paths. The using applications will search down from the top path and find the files - so I do not need to worry about keeping track of paths. All seemed to be working until I examined my log files and found files with the same SHA digest had different sizes according to os.stat(fpath).st_size . This is on Windows XP. - Am I expecting too much of SHA-1? - Is it that the os.stat data on Windows cannot be trusted? - Or perhaps there is a silly error in my code I should have seen? Thanks - Eric - - - - - - - - - - - - - - - - - - Log file extract: Dup: no Path: F:\music\mp3s\01125.mp3 Hash: 00b3acb529aae11df186ced8424cb189f062fa48 Name: 01125.mp3 Size: 63006 Dup: YES Path: F:\music\mp3s\0791.mp3 Hash: 00b3acb529aae11df186ced8424cb189f062fa48 Name: 0791.mp3 Size: 50068 Dup: YES Path: F:\music\mp3s\12136.mp3 Hash: 00b3acb529aae11df186ced8424cb189f062fa48 Name: 12136.mp3 Size: 51827 Dup: YES Path: F:\music\mp3s\11137.mp3 Hash: 00b3acb529aae11df186ced8424cb189f062fa48 Name: 11137.mp3 Size: 56417 Dup: YES Path: F:\music\mp3s\0991.mp3 Hash: 00b3acb529aae11df186ced8424cb189f062fa48 Name: 0991.mp3 Size: 59043 Dup: YES Path: F:\music\mp3s\0591.mp3 Hash: 00b3acb529aae11df186ced8424cb189f062fa48 Name: 0591.mp3 Size: 59162 Dup: YES Path: F:\music\mp3s\10140.mp3 Hash: 00b3acb529aae11df186ced8424cb189f062fa48 Name: 10140.mp3 Size: 59545 Dup: YES Path: F:\music\mp3s\0491.mp3 Hash: 00b3acb529aae11df186ced8424cb189f062fa48 Name: 0491.mp3 Size: 63101 Dup: YES Path: F:\music\mp3s\0392.mp3 Hash: 00b3acb529aae11df186ced8424cb189f062fa48 Name: 0392.mp3 Size: 63252 Dup: YES Path: F:\music\mp3s\0891.mp3 Hash: 00b3acb529aae11df186ced8424cb189f062fa48 Name: 0891.mp3 Size: 65808 Dup: YES Path: F:\music\mp3s\0691.mp3 Hash: 00b3acb529aae11df186ced8424cb189f062fa48 Name: 0691.mp3 Size: 67050 Dup: YES Path: F:\music\mp3s\0294.mp3 Hash: 00b3acb529aae11df186ced8424cb189f062fa48 Name: 0294.mp3 Size: 67710 Code: # Dedup_inplace.py # vers .02 # Python 2.4.1 # Create a dictionary consisting of hash:path # Look for 2nd same hash and delete path testpath=r"F:\music\mp3s" logpath=r"C:\testlog6.txt" import os, sha def hashit(pth): """Takes a file path and returns a SHA hash of its string""" fs=open(pth,'r').read() sh=sha.new(fs).hexdigest() return sh def logData(d={}, logfile="c://filename999.txt", separator="\n"): """Takes a dictionary of values and writes them to the provided file path""" logstring=separator.join([str(key)+": "+d[key] for key in d.keys()])+"\n" f=open(logfile,'a') f.write(logstring) f.close() return def walker(topPath): fDict={} logDict={} limit=1000 freed_space=0 for root, dirs, files in os.walk(topPath): for name in files: fpath=os.path.join(root,name) fsize=os.stat(fpath).st_size fkey=hashit(fpath) logDict["Name"]=name logDict["Path"]=fpath logDict["Hash"]=fkey logDict["Size"]=str(fsize) if fkey not in fDict.keys(): fDict[fkey]=fpath logDict["Dup"]="no" else: #os.remove(fpath) --uncomment only when script proven logDict["Dup"]="YES" freed_space+=fsize logData(logDict, logpath, "\t") items=len(fDict.keys()) print "Dict entry: ",items, print "Cum freed space: ",freed_space if items > limit: break if items > limit: break def emptyNests(topPath): """Walks downward from the given path and deletes any empty directories""" for root, dirs, files in os.walk(topPath): for d in dirs: dpath=os.path.join(root,d) if len(os.listdir(dpath))==0: print "deleting: ", dpath os.rmdir(dpath) walker(testpath) emptyNests(testpath) From chowychow at gmail.com Tue Jun 27 12:26:35 2006 From: chowychow at gmail.com (chowychow at gmail.com) Date: 27 Jun 2006 09:26:35 -0700 Subject: new python icons for windows In-Reply-To: <1150944756.720958.78670@u72g2000cwu.googlegroups.com> References: <1150811271.282850.321510@p79g2000cwp.googlegroups.com> <1150901231.837272.129040@g10g2000cwb.googlegroups.com> <1150944756.720958.78670@u72g2000cwu.googlegroups.com> Message-ID: <1151425595.797400.238090@y41g2000cwy.googlegroups.com> Istvan Albert wrote: > and-google at doxdesk.com wrote: > > > > For example it resembles the icon for text files. > > > > This is intentional: to make it obvious that .py files are the > > readable, editable scripts, contrasting with .pyc's binary gunk - > > I think this is a mistake, it does not seem obious, all it does is just > blends in and does not separate the python files from regular text > files. > > Also the black icons for pyc files are far more visible and > stand out much more than the white ones. If anything I wish the pyc had > no icons at all or was invisible, I mean how often do you need to do > any work with pyc files... I agree with those points after trying out the icons. Something about the icons seems blurry (perhaps it's the yellow snake with the poorly visible white eye. Or it could be the paper that doesn't seem to have enough contrast on the top (I have white background behind them.) To my eyes, the pyc stick out also. I almost want to swap the two since the pyc files look so striking. I do like the egg icons very much. Good work! -Kevin Deenanauth From akameswaran at gmail.com Sun Jun 11 00:16:49 2006 From: akameswaran at gmail.com (akameswaran at gmail.com) Date: 10 Jun 2006 21:16:49 -0700 Subject: "parent" in a class __init__ def? In-Reply-To: References: Message-ID: <1149999409.650251.251240@g10g2000cwb.googlegroups.com> I'm not sure how it's a comparison to class variables. So I wouldn't worry about that. I think there are some advantages to having the parent as an instance member. Intuitively, the name lookup on self.parent.foo would be faster than if you passed in the object in question - although I haven't tested this. In short, there's nothin wrong with doin it - and it helps in many situations. Ray Schumacher wrote: > What is the feeling on using "parent" in a class definition that > class methods can refer to, vs. some other organization ? > Should all relevant objects/vars just be passed into the method as needed? > It seems like including "parent" in the class def is just like a > class variable, which most do not recommend. > > An example: > class LXSerial: > def __init__(self, parent, debug=False): > ... > def connect(self, port, baud=9600, ptimeout=10): > if self.debug: > self.connectedPort = StringIO.StringIO(':A#') > else: > if self.parent.model=='LX200GPS': ptimeout = 240 > ... > > Ray From ptmcg at austin.rr._bogus_.com Mon Jun 5 22:32:32 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Tue, 06 Jun 2006 02:32:32 GMT Subject: Is there a way to pass a python function ptr to a c++ method from a python script? References: <1149555886.251441.188180@i39g2000cwa.googlegroups.com> Message-ID: <4P5hg.15944$0v4.2485@tornado.texas.rr.com> "liam_herron" wrote in message news:1149555886.251441.188180 at i39g2000cwa.googlegroups.com... > > I have a core c++ library that is exposed to python through the > boost_python framework. > I would like to write the core of a Newton's method solver in C++ and > be able to write the > functions that are evaluated to be in python. Does anyone have any > ideas on this? > My suggestion would be to prototype in all-Python first. This will let you work out the kinks of your call/callback interfaces. Then see if the Newton's method part is a bottleneck worth converting to C++. My suspicion is that the performance (for all but trivial functions) will be in the function you are solving for, not in the Newton's metod. So be sure to test with a function that you feel is representative of those you want to solve for, not just a simple parabola. Then, stop thinking in C++. "Function pointer"? A function in Python is an object, a callable. You should be able to just treat it like one. -- Paul From sturnfie at gmail.com Mon Jun 5 17:08:50 2006 From: sturnfie at gmail.com (sturnfie at gmail.com) Date: 5 Jun 2006 14:08:50 -0700 Subject: xml.sax problem: getting parse() to read a string References: <1149525288.546237.78700@u72g2000cwu.googlegroups.com> <1149536174.891894.13760@h76g2000cwa.googlegroups.com> Message-ID: <1149541730.549545.208880@h76g2000cwa.googlegroups.com> Fredrik Lundh wrote: > as mentioned in the documentation, and implied by my answer, parseString > is a helper function in the xml.sax module, not a parser method. try doing > > xml.sax.parseString(string, handler) > > instead of that make_parser/setContentHandler/parse dance. > > Thanks a ton for all your help! I have successfully moved past this obstacle, with much appreciated thanks to your postings here (and other postings of yours I found via google). -- lucas From defcon8 at gmail.com Mon Jun 26 10:14:25 2006 From: defcon8 at gmail.com (defcon8) Date: 26 Jun 2006 07:14:25 -0700 Subject: A game idea. Message-ID: <1151331265.902998.75620@r2g2000cwb.googlegroups.com> I have had what I think is quite a nice game idea, but I don't really have the experience or knowledge to go about it. Would anyone be willing to start a game project? The game I am thinking about is a virtual IRC stock exchange. There will be a bot in the channel which gets the live stock quotes and also adds any effects of buying or selling of the players. Everyone will have their own portfolio, which they will be able to view on the web, and will be able to issue commands from the irc channel. They'll be able to trade between eachother, and also to the stock exchange. I know this sounds like quite a big project, but I think this would be a highly fun game and maybe it would become quite popular. I would be willing to help of course with what I can, but obviously, an experienced developer would be needed. From padraigkitterick at gmail.com Mon Jun 19 12:03:43 2006 From: padraigkitterick at gmail.com (Padraig) Date: 19 Jun 2006 09:03:43 -0700 Subject: Installing Python on Windows Vista In-Reply-To: <1150732391.956521.125310@r2g2000cwb.googlegroups.com> References: <1150731053.741522.190010@p79g2000cwp.googlegroups.com> <1150732391.956521.125310@r2g2000cwb.googlegroups.com> Message-ID: <1150733023.763040.51080@p79g2000cwp.googlegroups.com> dakman at gmail.com wrote: > Padraig wrote: > > Hi all, > > > > Just a quick question... when I try to install Python on Windows Vista > > Beta 2 the installer seems to hang after I select the destination > > folder, saying that it will "return when it has finished calculating > > disk space requirements". I just can't seem to get past that step. I've > > also tried installing both 2.4.3 and 2.4.2 with no luck. > > > > Any help would be very much appreciated. > > > > Many thanks > > > > P > > I've heard that Windows Vista has many restrictions on reading/writing > to the disk, perhaps you do not have an admin account? I don't think there is such a thing as an admin account under vista but I'm sure that the account I'm using is the Vista-equivalent of an admin account. Perhaps running it in compatibility mode might help. Will try that this evening... Thanks From johnjsal at NOSPAMgmail.com Thu Jun 15 12:46:40 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 15 Jun 2006 16:46:40 GMT Subject: code folding, a unique problem to python? In-Reply-To: <4fdgh7F1hbtteU1@uni-berlin.de> References: <4fdgh7F1hbtteU1@uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > Eric3, the Qt-based and in python written IDE can do that. So I'd say > it's an UE-problem - nad it has to be: to perform folding, one has to > find out what constitutes a block. Obviously this CAN be done with > python-code - do it CAN be done in editor code. ::lowers head in embarassment:: I wanted to try out Eric3, but I couldn't figure out how to install it! Is there a binary file? All I found was a zipped file with a bunch of stuff I didn't recognize in it. There was even a file called eric3.py which I thought might be it, but running it did nothing. From xivulon at gmail.com Wed Jun 7 11:30:35 2006 From: xivulon at gmail.com (ago) Date: 7 Jun 2006 08:30:35 -0700 Subject: Very nice python IDE (windows only) Message-ID: <1149694235.741274.325200@u72g2000cwu.googlegroups.com> I have just discovered Python Scripter by Kiriakos Vlahos and it was a pleasant surprise. I thought that it deserved to be signalled. It is slim and fairly fast, with embedded graphical debugger, class browser, file browser... If you are into graphical IDEs you are probably going to enjoy it. Windows only unfortunately. http://mmm-experts.com/Products.aspx?ProductId=4 From dnew at san.rr.com Wed Jun 21 11:42:05 2006 From: dnew at san.rr.com (Darren New) Date: Wed, 21 Jun 2006 15:42:05 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: <44992e6c$0$664$bed64819@news.gradwell.net> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <0%Wlg.3521$MF6.947@tornado.socal.rr.com> <44992e6c$0$664$bed64819@news.gradwell.net> Message-ID: Chris Uppal wrote: > doesn't fit with my intuitions very well -- most noticeably in that the sets > are generally unbounded Errr, not in Ada. Indeed, not in any machine I know of with a limited address space. Andreas Rossberg wrote: > Indeed, this view is much too narrow. In particular, it cannot explain > abstract types, which is *the* central aspect of decent type systems. Well, it's Ada's view. I didn't say it was right for theoretical languages or anything like that. As far as I know, LOTOS is the only language that *actually* uses abstract data types - you have to use the equivalent of #include to bring in the integers, for example. Everything else uses informal rules to say how types work. But Ada's definition gives you a very nice way of talking about things like whether integers that overflow are the same type as integers that don't overflow, or whether an assignment of an integer to a positive is legal, or adding a CountOfApples to a CountOfOranges is legal, or whether passing a "Dog" object to an "Animal" function parameter makes sense in a particular context. Indeed, the ability to declare a new type that has the exact same underlying representation and isomorphically identical operations but not be the same type is something I find myself often missing in languages. It's nice to be able to say "this integer represents vertical pixel count, and that represents horizontal pixel count, and you don't get to add them together." -- Darren New / San Diego, CA, USA (PST) My Bath Fu is strong, as I have studied under the Showerin' Monks. From paddy3118 at netscape.net Thu Jun 1 18:36:56 2006 From: paddy3118 at netscape.net (Paddy) Date: 1 Jun 2006 15:36:56 -0700 Subject: grouping a flat list of number by range References: <1149196642.001466.53990@c74g2000cwc.googlegroups.com> Message-ID: <1149201416.196975.123370@c74g2000cwc.googlegroups.com> joh12005 at yahoo.fr wrote: > hello, > > i'm looking for a way to have a list of number grouped by consecutive > interval, after a search, for example : > > [3, 6, 7, 8, 12, 13, 15] > > => > > [[3, 4], [6,9], [12, 14], [15, 16]] > > (6, not following 3, so 3 => [3:4] ; 7, 8 following 6 so 6, 7, 8 => > [6:9], and so on) > > i was able to to it without generators/yield but i think it could be > better with them, may be do you an idea? > > best regards, > > J. I did a proceedural version, then re-read your post and did a generator based version ;-) === interv1 === >>> inlist = [3, 6, 7, 8, 12, 13, 15] >>> tmp = [] >>> for i,val in enumerate(inlist): ... if i==0: ... tmp.append(val) ... elif val != valinc: ... tmp += [valinc, val] ... valinc = val+1 ... >>> tmp.append(valinc) >>> tmp [3, 4, 6, 9, 12, 14, 15, 16] >>> tmp[0::2] [3, 6, 12, 15] >>> tmp[1::2] [4, 9, 14, 16] >>> zip(tmp[0::2], tmp[1::2]) [(3, 4), (6, 9), (12, 14), (15, 16)] >>> === END interv1 === === interv2 === >>> def interv2(inlist): ... for i,val in enumerate(inlist): ... if i==0: ... tmp = val ... elif val != valinc: ... yield [tmp, valinc] ... tmp = val ... valinc = val+1 ... yield [tmp, valinc] ... >>> list(interv2(inlist)) [[3, 4], [6, 9], [12, 14], [15, 16]] === END interv2 === - Paddy. From sjmachin at lexicon.net Tue Jun 13 03:21:19 2006 From: sjmachin at lexicon.net (John Machin) Date: Tue, 13 Jun 2006 17:21:19 +1000 Subject: Getting "TypeError:list indices must be integers" In-Reply-To: <448E6466.10908@lexicon.net> References: <448E6466.10908@lexicon.net> Message-ID: <448E676F.9020602@lexicon.net> On 13/06/2006 5:08 PM, John Machin wrote: > On 13/06/2006 4:11 PM, Girish Sahani wrote: > [snip] >> instance = ti2(k) >> tiNew = ti1.append(instance) > > ti2 is quacking "function" but ti1 is quacking "list". > > Possibilities: > (1) You meant to type ti2[k] ... and this section of code has not yet > been executed, and would have featured as episode N+1 had morbid > curiosity not led me to read further. > (2) You have the weirdest system of choosing names that I have seen for > decades. > (3) Both of the above. > Episode N+2: tiNew = ti1.append(instance) doesn't do what you think it does: >>> foo = [9, 8, 7] >>> bar = 'xyz' >>> bar = foo.append(42) >>> foo [9, 8, 7, 42] >>> repr(bar) 'None' >>> Cheers, John From aleax at mac.com Mon Jun 5 10:24:57 2006 From: aleax at mac.com (Alex Martelli) Date: Mon, 5 Jun 2006 07:24:57 -0700 Subject: An oddity in list comparison and element assignment References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> <1hg9nl6.xivwcd7n0j5N%aleax@mac.com> <1149277242.199765.213600@g10g2000cwb.googlegroups.com> <1hgbjx1.1gn7haipx7x5N%aleax@mac.com> <1hgd7ry.1lrs9rqnn77ayN%aleax@mac.com> Message-ID: <1hgg5o4.rfx6dk1tmcn6rN%aleax@mac.com> Slawomir Nowaczyk wrote: > On Sat, 03 Jun 2006 17:03:00 -0700 > aleax at mac.com (Alex Martelli) wrote: > > #> Terry Reedy wrote: > #> > #> > Depends what one means by 'copy'. See below for your alternate wording. > #> > #> Please give me a reasonable definition of the unadorned word "copy" > #> which would make this statement false. (And, just to forestall one > #> possible attempt: no, I cannot agree that a ``deepcopy'' is a reasonable > #> definition of the _unadorned_ word "copy"). > > Actually, when *I* think about the word "copy", I have in mind what > happens with files... Sure! In particular, to reproduce the concept of an object containing references to other objects, imagine that the file is a .tar, .dmg (on MacOSX), or other kind of "container"/"archive" kind of file, and one of the items in its contents is a symbolic link. When you copy the archive file, both the original and the copy now contain symbolic links to the SAME target. > and I to me semantics of []*3 is more like > symbolic linking, not copying. ??? an _assignment_ in Python can be said to be "like symbolic linking, not copying" -- and that's a crucial part of Python's semantics, of course. But the Sequence*N operation has nothing to do with creating symbolic links; it may (of course) _copy_ such links, if they're present in the sequence, just like copying a container file copies symbolic links it may contain -- in each case one can end up with symbolic links to the same target. The analogy between files and Python objects is of course not exact (partly because filesystems normally distinguish between directories, which only contain references to files, and "ordinary" files, that don't -- the Composite Design Pattern proceeds, often fruitfully, by abstracting away this distinction), but in as far as it holds, it points roughly in the right direction. (GNU's cp offers a -R switch to explicitly perform a "recursive copy", with other switches such as -H, -L, -P to affect what happens in that case to symlinks -- this -R is more akin to "deep copying", except that Python's deepcopy is simpler, and always "recurses to the hilt"). > While I, personally, understand the > sentence in question "The result of S*n or n*S is the concatenation of > n copies of S" correctly, I *do* see how it might be misunderstood by > others. > > Not that I know how to express it better :-( I do find it interesting that the concept of "copy" causes such trouble, even when the analogies used (filecopying and symlinks) would tend to point in the right direction. The "real-life" analogy of copying a list also points in the right direction: if I have a list of the writings I hold on my library's top shelf, when I copy the list, both the original and the copy point to _exactly the same_ writings -- not to separate copies of each. If I asked an employee to "please copy this list" I would be astonished if he or she by default also copied each other writing that is an _item_ on the list -- surely I would expect such huge amounts of work to happen only when explicitly requested, and the default meaning of "copy" to be therefore ``shallow'' (wherever applicable, that is, when copying something that references other things). It would be interesting to study the root of the confusion in more detail (although it's unlikely, as you indicate, that such study would yield a different definition, concise and simple enough to be used in a concise reference work, it would still help authors of tutorials). Alex From shejo284 at gmail.com Wed Jun 28 12:03:35 2006 From: shejo284 at gmail.com (Sheldon) Date: 28 Jun 2006 09:03:35 -0700 Subject: Numeric help! Message-ID: <1151510615.139278.167520@j72g2000cwa.googlegroups.com> Hi, I have the following loop that I think can be written to run faster in Numeric. I am currently using Numeric. range_va = [60,61,62,63,64,65,66,67,68,69,70,71,72] main.xsize= 600 main.ysize= 600 #msgva is an (600x600) Numeric array with mutiple occurrences of the values in range_va #sat_id is an (600x600) Numeric array with values ranging from -2 to 2 for z in range_va: count = 0 mbias = 0 for i in range(main.xsize): for j in range(main.ysize): if msgva[i,j] == z: mbias += sat_id[i,j] # take the sum of the values count += 1 # count the occurrences tmp_array[0,index] = round(mbias/count,1) # store the mean tmp_array[1,index] = z index += 1 Any help would be greatly appreciated! Sincerely, Sheldon From sjmachin at lexicon.net Thu Jun 1 08:03:28 2006 From: sjmachin at lexicon.net (John Machin) Date: Thu, 01 Jun 2006 22:03:28 +1000 Subject: Function mistaken for a method In-Reply-To: References: Message-ID: <447ED790.20101@lexicon.net> On 1/06/2006 9:46 PM, Maric Michaud wrote: > Le Jeudi 01 Juin 2006 13:34, Peter Otten a ?crit : >> A python-coded function has a __get__ attribute, a C-function doesn't. >> Therefore C1.f performs just the normal attribute lookup while C2.f also >> triggers the f.__get__(C2(), C2) call via the descriptor protocol which >> happens to return a bound method. > I don't think it's about c-coded versus python-coded stuff, C1.f is a type, > C2.f is a method. > Try putting f = chr (a C function); it behaves like int, not like a 1-arg Python function. See below. Cheers, John C:\junk>type func_meth.py class C: f = None def __init__(self): if self.f is not None: self.x = self.f(0) else: self.x = 99 # differs from int(0) :-) class C1(C): f = int class C2(C): def f(self, arg): return arg != 0 class C3(C): pass class C4(C): f = chr for cls in (C1, C2, C3, C4): o = cls() print "callable: %r; result: %r" % (o.f, o.x) C:\junk>func_meth.py callable: ; result: 0 callable: >; result: False callable: None; result: 99 callable: ; result: '\x00' C:\junk> From ptmcg at austin.rr._bogus_.com Fri Jun 30 10:46:34 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 30 Jun 2006 14:46:34 GMT Subject: Regular Expression - old regex module vs. re module References: <1151607229.548737.145800@d56g2000cwd.googlegroups.com> Message-ID: "Steve" wrote in message news:1151607229.548737.145800 at d56g2000cwd.googlegroups.com... > Hi All, > > I'm having a tough time converting the following regex.compile patterns > into the new re.compile format. There is also a differences in the > regsub.sub() vs. re.sub() > > Could anyone lend a hand? > > Not an re solution, but pyparsing makes for an easy-to-follow program. TransformString only needs to scan through the string once - the "reals-before-ints" testing is factored into the definition of the formatters variable. Pyparsing's project wiki is at http://pyparsing.wikispaces.com. -- Paul ------------------- from pyparsing import * """ read Perl-style formatting placeholders and replace with proper Python %x string interp formatters ###### -> %6d ##.### -> %6.3f <<<<< -> %-5s >>>>> -> %5s """ # set up patterns to be matched - Word objects match character groups # made up of characters in the Word constructor; Combine forces # elements to be adjacent with no intervening whitespace # (note use of results name in realFormat, for easy access to # decimal places substring) intFormat = Word("#") realFormat = Combine(Word("#")+"."+ Word("#").setResultsName("decPlaces")) leftString = Word("<") rightString = Word(">") # define parse actions for each - the matched tokens are the third # arg to parse actions; parse actions will replace the incoming tokens with # value returned from the parse action intFormat.setParseAction( lambda s,l,toks: "%%%dd" % len(toks[0]) ) realFormat.setParseAction( lambda s,l,toks: "%%%d.%df" % (len(toks[0]),len(toks.decPlaces)) ) leftString.setParseAction( lambda s,l,toks: "%%-%ds" % len(toks[0]) ) rightString.setParseAction( lambda s,l,toks: "%%%ds" % len(toks[0]) ) # collect all formatters into a single "grammar" # - note reals are checked before ints formatters = rightString | leftString | realFormat | intFormat # set up our test string, and use transform string to invoke parse actions # on any matched tokens testString = """ This is a string with ints: #### # ############### floats: #####.# ###.###### #.# left-justified strings: <<<<<<<< << < right-justified strings: >>>>>>>>>> >> > int at end of sentence: ####. """ print formatters.transformString( testString ) ------------------- Prints: This is a string with ints: %4d %1d %15d floats: %7.1f %10.6f %3.1f left-justified strings: %-8s %-2s %-1s right-justified strings: %10s %2s %1s int at end of sentence: %4d. From kent at kentsjohnson.com Sun Jun 4 08:14:19 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Sun, 04 Jun 2006 08:14:19 -0400 Subject: ANN: PQRC - Python Quick Reference Card - v 0.55 In-Reply-To: <4481b8ff$0$19687$ba4acef3@news.orange.fr> References: <4481b8ff$0$19687$ba4acef3@news.orange.fr> Message-ID: <4482cd93$1_2@newspeer2.tds.net> Laurent Pointal wrote: > And I'll maintain a fixed URL at > > http://laurent.pointal.org/python/pqrc/ Broken at the moment. Kent From luis_lupe2XXX at netvisaoXXX.pt Fri Jun 16 13:11:25 2006 From: luis_lupe2XXX at netvisaoXXX.pt (Luis P. Mendes) Date: Fri, 16 Jun 2006 18:11:25 +0100 Subject: download file from intranet linux server to windows clients Message-ID: <4492e5c1$0$15782$14726298@news.sunsite.dk> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi, I'm building an intranet web server in Linux for around 40 windows clients with Django. The problem is that I want to build an excel file based on criteria entered by the client, that the client must be able do download to his personal work space. I use pyExcelerator to create the Excel files. How can I do it? Do I need another excel generator? Client's information about its working directory should be read, but how? I could only find the way to read the server environment variables, where data is processed. Luis P. Mendes -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.1 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFEkuY9Hn4UHCY8rB8RAvjYAJ9RSp1llMo6GPJIYAicm8gRSQJ/AwCgrN5Y 3EzU+SGn3Uk/1j1gwl4uBik= =3330 -----END PGP SIGNATURE----- From faisjobs at yahoo.co.in Sat Jun 10 14:39:00 2006 From: faisjobs at yahoo.co.in (faisjobs) Date: 10 Jun 2006 11:39:00 -0700 Subject: USA UK CANADA AUSTRALIA Jobs With VISA Sponsorship Message-ID: <1149964739.973593.137690@c74g2000cwc.googlegroups.com> USA UK CANADA AUSTRALIA Jobs IT Jobs, Medical Jobs, Marketing Jobs, Engineering Jobs, Call Center Jobs, HRM Jobs, Administrative Jobs, Customer-related Jobs, Non Customer-related Jobs, and many more. Career Opportunities, Vacancies, Hiring, Job Fairs, Recruitment Agency, Employer, Manpower Pooling, etc. ACCEPTED LANGUAGE: ENGLISH ONLY. Members will receive emails everyday. Update your Resume NOW! click here http://vibajobs4u.50webs.com/ http://www.freewebs.com/viba International Jobs includes the Countries around Asia: Afghanistan Jobs, Armenia Jobs, Azerbaijan Jobs, Bahrain Jobs, Bangladesh Jobs, Bhutan Jobs, Brunei Jobs, Burma (Myanmar) Jobs, Cambodia Jobs, China Jobs, Georgia Jobs, Hong Kong Jobs, India Jobs, Indonesia Jobs, Iran Jobs, Iraq Jobs, Israel Jobs, Japan Jobs, Jordan Jobs, Kazakstan Jobs, (North and South) Korea Jobs, Kuwait Jobs, Kyrgyzstan Jobs, Laos Jobs, Lebanon Jobs, Malaysia Jobs, Maldives Jobs, Mongolia Jobs, Myanmar Jobs, Nepal Jobs, Oman Jobs, Pakistan Jobs, Philippines Jobs, Qatar Jobs, Russia Jobs, Saudi Arabia Jobs, Singapore Jobs, Sri Lanka Jobs, Syria Jobs, Taiwan Jobs, Tajikistan Jobs, Thailand Jobs, Turkey Jobs, Turkmenistan Jobs, United Arab Emirates Jobs, Uzbekistan Jobs, Vietnam Jobs, and Yemen Jobs. You send your reesume and details, Your details will be stored on my jobs data base, your resume match any jobs position we will inform you, lot of jobs with VISA sponsorship available. You send your resume here click here http://vibajobs4u.50webs.com/ From joncle at googlemail.com Tue Jun 20 15:06:09 2006 From: joncle at googlemail.com (Jon Clements) Date: 20 Jun 2006 12:06:09 -0700 Subject: Iteration over recursion? In-Reply-To: <1150829446.122164.295070@h76g2000cwa.googlegroups.com> References: <1150808045.539887.291180@i40g2000cwc.googlegroups.com> <1150816827.826028.114740@h76g2000cwa.googlegroups.com> <1150829446.122164.295070@h76g2000cwa.googlegroups.com> Message-ID: <1150830369.178114.307490@g10g2000cwb.googlegroups.com> Kay Schluehr wrote: > Nick Maclaren wrote: > > > Tail recursion removal can often eliminate the memory drain, but the > > code has to be written so that will work - and I don't know offhand > > whether Python does it. > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691 > > Regards, > Kay Interesting..... Thanks Kay. Jon. From flaus.a at wanadoo.fr Wed Jun 14 16:41:18 2006 From: flaus.a at wanadoo.fr (flaus.a at wanadoo.fr) Date: 14 Jun 2006 13:41:18 -0700 Subject: How to select a folder with native windows dialog box? References: <1150237380.370088.29270@p79g2000cwp.googlegroups.com> <1150252926_60371@sp6iad.superfeed.net> Message-ID: <1150317678.028483.49080@i40g2000cwc.googlegroups.com> Thanks for your answer, it's working fine! For information, the function to use to get the pathName is shell.SHGetPathFromIDList It returns an error if you select a special folder (!?!?) but otherwise it's working fine... And I was unable to fix this issue. From nun at example.com Tue Jun 13 12:13:48 2006 From: nun at example.com (Mitja Trampus) Date: Tue, 13 Jun 2006 18:13:48 +0200 Subject: a string problem In-Reply-To: References: <1150206140.912224.113420@p79g2000cwp.googlegroups.com> Message-ID: <4vBjg.3738$oj5.1228864@news.siol.net> John Salerno wrote: > micklee74 at hotmail.com wrote: >> hi >> >> if i have a some lines like this >> a ) "here is first string" >> b ) "here is string2" >> c ) "here is string3" >> >> When i specify i only want to print the lines that contains "string" ie > ... > And I'm actually ashamed to admit that I know the RE way, but not the > regular string manipulation way, if there is one! This seems like > something easy enough to do without REs though. I'd just split it on whitespace, just like with the RE: if "string" in "here is first string".split(): ... From fabiofz at gmail.com Mon Jun 19 14:44:08 2006 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Mon, 19 Jun 2006 15:44:08 -0300 Subject: Python with Eclipse In-Reply-To: <9OBlg.6681$FR1.4810@dukeread05> References: <449679c3@news.uni-ulm.de> <9OBlg.6681$FR1.4810@dukeread05> Message-ID: On 6/19/06, Philippe Martin wrote: > > Dennis Benzinger wrote: > > > Stan Cook wrote: > >> I've been trying to use Eclipse with Python on Linux for a while and > >> have noticed something odd. After running the code or debugging a few > >> times, its responsiveness gets really bad. Upon checking the > equivalent > >> of the task manager, I find several instances of Python running. When > I > >> kill these instances, the responsiveness comes back. I'm not sure if > >> there is a better place to post this, but it is Python related. Is > this > >> just an issue with Eclipse or is there something else I should inspect? > >> > >> Any help would be appreciated. > >> > >> Regards, > >> > >> S Cook > > > > Which Python plugin are you using? PyDev? > > > > > > Bye, > > Dennis > > Hi, > > What other plugins are there ? > Well, there is the colorer... so, it would color things, but that would be all ;-) -------------- next part -------------- An HTML attachment was scrubbed... URL: From sonja.coussell at gmail.com Thu Jun 15 12:45:19 2006 From: sonja.coussell at gmail.com (sonjaa) Date: 15 Jun 2006 09:45:19 -0700 Subject: memory leak problem with arrays In-Reply-To: <1150374727.103552.200120@p79g2000cwp.googlegroups.com> References: <1150317325.614389.14770@i40g2000cwc.googlegroups.com> <1150374727.103552.200120@p79g2000cwp.googlegroups.com> Message-ID: <1150389919.477862.146950@g10g2000cwb.googlegroups.com> Carl Banks wrote: > sonjaa wrote: > > I've created a cellular automata program in python with the numpy array > > extensions. After each cycle/iteration the memory used to examine and > > change the array as determined by the transition rules is never freed. > > Are you aware that slicing shares memory? For example, say you defined > a grid to do the automata calculations on, like this: > > grid = numpy.zeros([1000,1000]) > > And then, after running it, you took a tiny slice as a region of > interest, for example: > > roi = grid[10:20,10:20] > > Then deleted grid: > > del grid > > Then stored roi somewhere, for example: > > run_results.append(roi) > > If you do this, the memory for the original grid won't get freed. > Although grid was deleted, roi still contains a reference to the whole > 1000x1000 array, even though it's only a tiny slice of it. Your poorly > worded description--no offense--of what you did suggests that this is a > possibility in your case. I recommend you try to create a new array > out of any slices you make, like this (but ONLY if the slice doesn't > depend on the memory being shared): > > roi = numpy.array(grid[10:20,10:20]) > > This time, when you del grid, there is no object left referencing the > array data, so it'll be freed. > > This might not be your problem. Details are important when asking > questions, and so far you've only given us enough to speculate with. > > Carl Banks I believe I understand your post. I don't think I was slicing the array, I was only changing the values of the array. I will try your suggestion and let you know how it goes thanks Sonja From meng.yan at gmail.com Mon Jun 5 19:57:55 2006 From: meng.yan at gmail.com (Mike Meng) Date: 5 Jun 2006 16:57:55 -0700 Subject: PyOpenSSL and PyCrypto are outdated! In-Reply-To: References: <1149524697.220261.73510@c74g2000cwc.googlegroups.com> Message-ID: <1149551875.067080.49750@f6g2000cwb.googlegroups.com> Thank you Terry. I searched but didn't get useful information. In fact, I've built pycrypto 2.0.1 successfully. However, the source of pyOpenSSL seemed to be incompatible with lastest OpenSSL 0.98b. I tried to build it and got dozens of compile errors which complain about syntax error in x509v3.h. My C++ compiler is Visual C++ 7.1. Should I use older OpenSSL release? Terry Reedy ??? > "Mike Meng" wrote in message > news:1149524697.220261.73510 at c74g2000cwc.googlegroups.com... > > > I'm learning Twisted and downloaded pyOpenSSL and pycrypto win32 > > installer on http://twisted.sourceforge.net/contrib/ . But I find the > > lastest version are for Python 2.3. I try to rebuild pyOpenSSL from > > source, but get lots of compile errors. Are these two packages > > obsolated? Where can I find updated version? > > Did you try Google? This question has been asked before. From jeff_barish at earthlink.net Sat Jun 17 13:46:29 2006 From: jeff_barish at earthlink.net (Jeffrey Barish) Date: Sat, 17 Jun 2006 11:46:29 -0600 Subject: Popen3 on Windows Message-ID: I have an application that has been working fine on Linux, but now I need to port it to Windows XP. The program uses Popen3 to run another program. I use Popen3 so that I can access the pid attribute, which I use to kill the auxiliary program when necessary. Popen3 does not exist on Windows. I see os.popen2 and os.popen3, but they provide only file objects for stdin, stdout, and stderr so I don't see a way to kill the auxiliary program that I start. Is there a way to do this on Windows? -- Jeffrey Barish From jo at durchholz.org Sun Jun 25 08:40:29 2006 From: jo at durchholz.org (Joachim Durchholz) Date: Sun, 25 Jun 2006 14:40:29 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150892256.591282.43880@u72g2000cwu.googlegroups.com> Message-ID: Darren New schrieb: > John W. Kennedy wrote: >> 360-family assembler, yes. 8086-family assembler, not so much. > > And Burroughs B-series, not at all. There was one "ADD" instruction, and > it looked at the data in the addresses to determine whether to add ints > or floats. :-) I heard that the Telefunken TR series had a tagged architecture. This seems roughly equivalent to what the B-series did (does?). Regards, Jo From gotletter at gmail.com Sat Jun 10 04:30:54 2006 From: gotletter at gmail.com (gotletter at gmail.com) Date: 10 Jun 2006 01:30:54 -0700 Subject: __getattr__ question In-Reply-To: References: Message-ID: <1149928254.153476.184030@f6g2000cwb.googlegroups.com> Hello! > How can I determine if an attribute can be found in the usual places? print "item1" in dir(root) # False print "item3" in dir(root) # True Is it the behavior you wanted? From joncle at googlemail.com Sun Jun 25 10:29:38 2006 From: joncle at googlemail.com (Jon Clements) Date: 25 Jun 2006 07:29:38 -0700 Subject: error with string (beginner) In-Reply-To: <1151240297.725336.305960@i40g2000cwc.googlegroups.com> References: <1151240297.725336.305960@i40g2000cwc.googlegroups.com> Message-ID: <1151245778.725997.146880@m73g2000cwd.googlegroups.com> Alex Pavluck wrote: > Hello. I get the following error with the following code. Is there > something wrong with my Python installation? > > code: > import types > something = input("Enter something and I will tell you the type: ") > > if type(something) is types.IntType: > print "you entered an integer" > elif type(something) is types.StringType: > print "you entered a string" > > error: > String: Source for exec/eval is unavailable >From the docs: """ input( [prompt]) Equivalent to eval(raw_input(prompt)). Warning: This function is not safe from user errors! It expects a valid Python expression as input; if the input is not syntactically valid, a SyntaxError will be raised. Other exceptions may be raised if there is an error during evaluation. (On the other hand, sometimes this is exactly what you need when writing a quick script for expert use.) If the readline module was loaded, then input() will use it to provide elaborate line editing and history features. Consider using the raw_input() function for general input from users. """" So you want be using raw_input() for starters... Cheers, Jon. From sjmachin at lexicon.net Mon Jun 5 21:10:06 2006 From: sjmachin at lexicon.net (John Machin) Date: Tue, 06 Jun 2006 11:10:06 +1000 Subject: check for dictionary keys In-Reply-To: <4483f80a$0$27349$626a54ce@news.free.fr> References: <1149298230.864123.8320@u72g2000cwu.googlegroups.com> <4483f80a$0$27349$626a54ce@news.free.fr> Message-ID: <4484d5ee$1@news.eftel.com> On 5/06/2006 10:46 PM, Bruno Desthuilliers wrote: > micklee74 at hotmail.com a ?crit : >> hi >> in my code, i use dict(a) to make to "a" into a dictionary , "a" comes >> from user input, so my program does not know in the first place. Then >> say , it becomes >> >> a = { '-A' : 'value1' , '-B' : "value2" , "-C" : "value3" , '-D' : >> 'value4' } >> >> somewhere next in my code, i will check for these..: >> >> 1) -A and -B cannot exist together >> 2) -A and -C cannot exist together >> 3) -A and -B and -D cannot exist together >> 4) and lots of other combinations to check for.... > > Looks like an option parser... If so, there's all you need in the > standard lib (look for the optparse module). > >> >> how can i efficiently check for the above? At first as i do simple >> checks , i use if and else. >> But as i began to check for more combinatoiuns, it gets messy.... > > First : use boolean logic (truth table, Kernaugh diagram, etc) to > simplify things. As an example, rule #3 is useless - it's a subset of > rule #1 (-A and -B and -D implies -A and -B). This should greatly reduce > the number of needed tests. Good idea, but doesn't scale well. Simple code can weed out redundant rules, including any accidental duplicates that may creep into a long list. See code listing at end. > > Then, write a simple rule system describing either valid inputs or > invalid inputs (preferably the smallest set !-). FWIW, it can be as > simple as a list of lambdas/error messages pairs, with lambdas being > predicate taking dict keys as params: > > > _RULES = [ > (lambda keys : '-A' in keys and '-B' in keys, > "can't have both options -A and -B"), > (lambda keys : '-A' in keys and '-C' in keys, > "can't have both options -A and -C"), > # etc... > ] > The evil HR director won't let the PHB pay me on a per LOC basis, so I've had to come up with a compact table-driven approach :-) > def validate(options, rules): > keys = options.keys() > for predicate, message in rules: > if not predicate(keys): > raise ValueError(message) Cheers, John C:\junk>type option_combos.py bad_combos = ['ABD', 'AC', 'AB', 'CA'] def rule_compaction(bc_list, verbose=False): # The next few lines are admittedly oldfashioned :-) bc_sets = [set(x) for x in bc_list] deco = [(len(y), y) for y in bc_sets] deco.sort() bc_sets = [z[1] for z in deco] del deco if verbose: print "bc_sets #1:", bc_sets for k in xrange(len(bc_sets)-1, 0, -1): candidate = bc_sets[k] for ko in bc_sets[:k]: if ko <= candidate: if verbose: print candidate, "knocked out by", ko del bc_sets[k] break if verbose: print "bc_sets #2:", bc_sets return bc_sets option_rules = rule_compaction(bad_combos, verbose=True) def combo_disallowed_by(opt_set, rules): for rule in rules: if opt_set >= rule: return rule return None # redundantly, for emphasis if __name__ == "__main__": import sys for opt_string in sys.argv[1:]: failer = combo_disallowed_by(set(opt_string), option_rules) if failer: print repr(opt_string), "disallowed by", failer else: print repr(opt_string), "is OK" === a test === C:\junk>option_combos.py A AB AC AD BC ABD ABX XBA BX bc_sets #1: [set(['A', 'C']), set(['A', 'B']), set(['A', 'C']), set(['A', 'B', 'D'])] set(['A', 'B', 'D']) knocked out by set(['A', 'B']) set(['A', 'C']) knocked out by set(['A', 'C']) bc_sets #2: [set(['A', 'C']), set(['A', 'B'])] 'A' is OK 'AB' disallowed by set(['A', 'B']) 'AC' disallowed by set(['A', 'C']) 'AD' is OK 'BC' is OK 'ABD' disallowed by set(['A', 'B']) 'ABX' disallowed by set(['A', 'B']) 'XBA' disallowed by set(['A', 'B']) 'BX' is OK === the end === From fredrik at pythonware.com Mon Jun 26 10:00:58 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 26 Jun 2006 16:00:58 +0200 Subject: DictProxy? What is this? References: <1151328077.677523.57820@b68g2000cwa.googlegroups.com> Message-ID: digitalorganics at gmail.com wrote: > When I tried to update a class's __dict__, I got an error saying that > there is no 'update' attribute for dictproxy object. What is a > dictproxy object? a CPython implementation detail, used to protect an internal data structure used by new-style objects from unexpected modifications. From scott.daniels at acm.org Thu Jun 1 12:45:09 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Thu, 01 Jun 2006 09:45:09 -0700 Subject: An oddity in list comparison and element assignment In-Reply-To: <1149177617.985251.74560@c74g2000cwc.googlegroups.com> References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> Message-ID: <447f152f@nntp0.pdx.net> michael.f.ellis at gmail.com wrote: > As to containers, would you say that envelope containing five $100 > bills is the same as an envelope containing a single $100 bill and 4 > xerox copies of it? If so, I'd like to engage in some envelope > exchanges with you :-) Would you say that envelope containing five $100 bills is equal to an envelope containing five $100 bills with different serial numbers? --Scott David Daniels scott.daniels at acm.org From fredrik at pythonware.com Tue Jun 27 09:59:06 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 27 Jun 2006 15:59:06 +0200 Subject: Having problems with strings in HTML References: Message-ID: Sion Arrowsmith wrote: >>By the way, you _do_ realize that your "&" characters should be escaped >>as "&", don't you? > > No they shouldn't. They part of the url, which is (IIRC) a CDATA > attribute of the A element, not PCDATA. Yes they should. CDATA sections can contain character entities; it's elements that are ignored, not character/entity references. From msrainess at comcast.net Thu Jun 8 01:46:41 2006 From: msrainess at comcast.net (Mark rainess) Date: Thu, 08 Jun 2006 01:46:41 -0400 Subject: Download .jpg from web In-Reply-To: References: Message-ID: GMane Python wrote: > Hello All. > Using a network camera with built-in webserver, I'd like to have a python > program download .jpg files on a local lan. the location is > http:///jpg/image.jpg. > > Currently, I'm importing urllib and using urlopen to the address, then > read()-ing it, saving it to a binary file. All that is working great, but > maybe a bit slowly. I'm getting ~2.3 frames per second, and would like > between 5-10 frames per second. > > Am I approaching this incorrectly? I have to do a urlopen, then .read() > for each image. Is there any way to 'persist' the urlopen so I just have to > keep read()-ing or maybe is there a type of streaming read? I have many > cameras, so there are many threads simultaneously reading and dropping them > in a central Queue for saving later. > > I appreciate it! > -Dave > > WebImage = urllib.urlopen("http:///jpg/image.jpg").read() > QueuePacket = [] > QueuePacket.append(WebImage) > > > > What your doing, downloading images one at a time, is not the most efficient method. What you want to do is to enable the mjpeg (motion jpeg) mode of the camera. I am using a Trendnet camera. To get the mjpeg stream out of this camera, I use: "camera-url/VIDEO.CGI". If you put this address into the Firefox address bar, and then press refresh (for some reason it doesn't start unless you press refresh) it will start. The camera will hold the connection open and send jpeg images as a multipart mime message. The camera will respond with the header: -------------------------------- Server: Camera Web Server/1.0 Auther: Steven Wu MIME-version: 1.0 Cache-Control: no-cache Content-Type:multipart/x-mixed-replace;boundary=--video boundary-- -------------------------------- Then it will repeatedly send send: ------------------------------- --video boundary-- Content-length: 27577 Content-type: image/jpeg --video boundary-- ------------------------------- I had a url with a good explanation of this but I can't find it now. If I find it I will post it. Here is a simplified version of my current thinking. I took out the error handeling stuff to make the logic clear. -------------------------------------------- Thread that reads from the camera -------------------------------------------- h=httplib.HTTP(camera url) h.putrequest('GET','VIDEO.CGI') h.putheader('Accept','text/html') h.putheader('Accept','image/jpeg') # Trendnet camera works without this h.endheaders() errcode,errmsg,headers=h.getreply() f=h.getfile() while 1: data=f.readline() if data[0:15]=='Content-length:': count=int(data[16:]) n=f.readline() # skip over Content-type: image/jpeg\n' n=f.readline() # skip over \n' s = f.read(count) p=file(tempfile,'wb') p.write(s) p.close() -------------------------------------------- The first part sets it up and the while loop gets the jpeg data as fast is the camera will send it. Mark Rainess From huwjeffries at gmail.com Wed Jun 21 11:50:19 2006 From: huwjeffries at gmail.com (huwjeffries at gmail.com) Date: 21 Jun 2006 08:50:19 -0700 Subject: 'import site' failed; use -v for traceback Message-ID: <1150905019.706161.288510@y41g2000cwy.googlegroups.com> Hi There, I've installed python2.4-dev on Unbuntu linux. When I run it, it gives an error: 'import site' failed; use -v for traceback (Get the same result if I uninstall it and install regular python2.4). Using -v traceback gives: 'import site' failed; traceback: ImportError: No module named site Python is installed in: /usr/bin/python /usr/lib/python2.4 File listing of /usr/lib/python2.4: aifc.py htmlentitydefs.py rlcompleter.py anydbm.py htmllib.py robotparser.py asynchat.py HTMLParser.py sched.py asyncore.py httplib.py sets.py atexit.py ihooks.py sgmllib.py audiodev.py imaplib.py shelve.py base64.py imghdr.py shlex.py BaseHTTPServer.py imputil.py shutil.py Bastion.py keyword.py SimpleHTTPServer.py bdb.py lib-dynload SimpleXMLRPCServer.py binhex.py lib-old site-packages bisect.py LICENSE.txt smtpd.py bsddb locale.py smtplib.py calendar.py logging sndhdr.py CGIHTTPServer.py _LWPCookieJar.py SocketServer.py cgi.py macpath.py statcache.py cgitb.py macurl2path.py statvfs.py chunk.py mailbox.py stringold.py cmd.py mailcap.py stringprep.py codecs.py markupbase.py _strptime.py codeop.py mhlib.py sunaudio.py code.py mimetools.py sunau.py colorsys.py mimetypes.py symbol.py commands.py MimeWriter.py symtable.py compiler mimify.py tabnanny.py config modulefinder.py tarfile.py cookielib.py _MozillaCookieJar.py telnetlib.py Cookie.py multifile.py test csv.py mutex.py this.py curses netrc.py _threading_local.py dbhash.py new.py threading.py decimal.py nntplib.py timeit.py difflib.py ntpath.py toaiff.py dircache.py nturl2path.py trace.py distutils os2emxpath.py tty.py doc pdb.doc tzparse.py doctest.py pdb.py unittest.py DocXMLRPCServer.py __phello__.foo.py urllib2.py dumbdbm.py pickletools.py urllib.py dummy_threading.py pipes.py urlparse.py dummy_thread.py pkgutil.py UserList.py email plat-linux2 user.py encodings poplib.py UserString.py filecmp.py posixfile.py uu.py fileinput.py pprint.py wave.py formatter.py pty.py weakref.py fpformat.py pyclbr.py webbrowser.py ftplib.py pydoc.py whichdb.py getpass.py Queue.py whrandom.py gettext.py quopri.py xdrlib.py gopherlib.py reconvert.py xml gzip.py regex_syntax.py xmllib.py heapq.py regsub.py xmlrpclib.py hmac.py rexec.py zipfile.py hotshot rfc822.py Have noticed that python-minimal is installed with Unbuntu and can't be easily removed, but running "which python" shows it's running the proper version (python2.4). Any ideas? Many Thanks, Huw From jo at durchholz.org Fri Jun 16 17:57:10 2006 From: jo at durchholz.org (Joachim Durchholz) Date: Fri, 16 Jun 2006 23:57:10 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <2006061410510511272-raffaelcavallaro@pasdespamsilvousplaitmaccom> <2006061501423327544-raffaelcavallaro@pasdespamsilvousplaitmaccom> Message-ID: Sacha schrieb: > > Many lists are heterogenous, even in statically typed languages. > For instance lisp code are lists, with several kinds of atoms and > sub-lists.. Lisp isn't exactly a statically-typed language :-) > A car dealer will sell cars, trucks and equipment.. > In a statically typed language you would need to type the list on a common > ancestor... Where's the problem with that? BTW the OO way isn't the only way to set up a list from heterogenous data. In statically-typed FPL land, lists require homogenous data types all right, but the list elements aren't restricted to data - they can be functions as well. Now the other specialty of FPLs is that you can construct functions at run-time - you take a function, fill some of its parameters and leave others open - the result is another function. And since you'll iterate over the list and will do homogenous processing over it, you construct the function so that it will do all the processing that you'll later need. The advantage of the FPL way over the OO way is that you can use ad-hoc functions. You don't need precognition to know which kinds of data should be lumped under a common supertype - you simply write and/or construct functions of a common type that will go into the list. > What would then be the point of statical typing , as you stilll need to type > check each element in order to process that list ? Both OO and FPL construction allow static type checks. > Sure you can do this in a > statically-typed > language, you just need to make sure some relevant ancestor exists. In my > experience > you'll end up with the base object-class more often than not, and that's > what i call dynamic typing. Not quite - the common supertype is more often than not actually useful. However, getting the type hierarchy right requires a *lot* of experimentation and fine-tuning. You can easily spend a year or more (sometimes *much* more) with that (been there, done that). Even worse, once the better hierarchy is available, you typically have to adapt all the client code that uses it (been there, done that, too). That's the problems in OO land. FPL land doesn't have these problems - if the list type is just a function mapping two integers to another integer, reworking the data types that went into the functions of the list don't require those global changes. >> Give a case of calling nonexistent functions that's useful. > > I might want to test some other parts of my program before writing this > function. That's unrelated to dynamic typing. All that's needed is an environment that throws an exception once such an undefined function is called, instead of aborting the compilation. I'll readily admit that very few static languages offer such an environment. (Though, actually, C interpreters do exist.) > Or maybe will my program compile that function depending on user input. Hmm... do I really want this kind of power at the user's hand in the age of malware? > As long as i get a warning for calling a non-existing function, everything > is fine. That depends. For software that's written to run once (or very few times), and where somebody who's able to correct problems is always nearby, that's a perfectly viable strategy. For safety-critical software where problems must be handled within seconds (or an even shorter period of time), you want to statically ensure as many properties as you can. You'll take not just static typing, you also want to ascertain value ranges and dozens of other properties. (In Spark, an Ada subset, this is indeed done.) Between those extremes, there's a broad spectrum. From mensanator at aol.com Tue Jun 6 13:52:57 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 6 Jun 2006 10:52:57 -0700 Subject: what are you using python language for? In-Reply-To: References: Message-ID: <1149616377.628393.19890@g10g2000cwb.googlegroups.com> hacker1017 wrote: > im just asking out of curiosity. Math research on the Collatz Conjecture. From mjp at pilcrow.madison.wi.us Sat Jun 10 21:25:50 2006 From: mjp at pilcrow.madison.wi.us (mjp at pilcrow.madison.wi.us) Date: 10 Jun 2006 18:25:50 -0700 Subject: how not to run out of memory in cursor.execute References: <1149447895.037396.81550@j55g2000cwa.googlegroups.com> Message-ID: <1149989150.806313.130590@j55g2000cwa.googlegroups.com> johnlichtenstein at gmail.com wrote: > I am using cx_Oracle and MySQLdb to pull a lot of data from some tables > and I find that the cursor.execute method uses a lot of memory that > never gets garbage collected. Using fetchmany instead of fetchall does > not seem to make any difference, since it's the execute that uses > memory. [...] For MySQLdb, the SSCursor class ("Server Side Cursor"), rather than the default cursor class, may do what you want: retrieve the result set row-by-row on demand, rather than all at once at the time of .execute(). You'll need to remember to .fetch...() every row and call .close(), however. See the docstrings for CursorUseResultMixIn and CursorStoreResultMixIn classes in MySQLdb.cursors for more information. > [...] Breaking the query down to build lots of small tables doesn't > help, since execute doesn't give its memory back, after reading enough > small tables execute returns a memory error. What is the trick to get > memory back from execute in cx_Oracle and MySQLdb? Generally, the trick is to avoid consuming the memory in the first place. :) Regards, Mike From neuruss at gmail.com Thu Jun 1 23:05:47 2006 From: neuruss at gmail.com (Neuruss) Date: 1 Jun 2006 20:05:47 -0700 Subject: C# equivalent to range() References: <1149214153.359809.288610@i39g2000cwa.googlegroups.com> <1149214491.034665.29030@j55g2000cwa.googlegroups.com> Message-ID: <1149217547.618703.209770@i39g2000cwa.googlegroups.com> John Machin wrote: > Neuruss wrote: > > I'm sorry for asking about another language here, but since I only know > > Python and I'm trying to write something in C#, I guess this is the > > best place... > > > > Bad guess. Ask questions about language X on comp.lang.X Well, perhaps I should. And I should also explain how range and extend work in python, which is almost the same thing... I thougt that maybe some python programmer could have experience here with c# and give me a little hint. But unfortunately, there are people here who are not willing to waste their time helping, but enjoy to waste their time niggling... Thanks anyway! Neuruss From rogue_pedro at yahoo.com Wed Jun 28 18:13:42 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 28 Jun 2006 15:13:42 -0700 Subject: Building Web Site Using Python In-Reply-To: <1151529459.322632.261870@b68g2000cwa.googlegroups.com> References: <1151529459.322632.261870@b68g2000cwa.googlegroups.com> Message-ID: <1151532822.003629.213580@m73g2000cwd.googlegroups.com> Roman wrote: > I am new to python. > > I am looking to read in a 12mb csv file, parse it, generate web pages, > summarize on a column and make drop down bottons. > > Where would I be able to find sample code that does something similar > to this? > > Also, I know that microsoft has put out .net beta version of it. If I > am using windows server, I am confined to use iron python? or are there > alternatives? Perhaps, there are python web packages that have their > own web server engine? > > Thanks in advance, Google. From frank at chagford.com Tue Jun 13 02:29:11 2006 From: frank at chagford.com (Frank Millman) Date: 12 Jun 2006 23:29:11 -0700 Subject: "groupby" is brilliant! Message-ID: <1150180151.643245.148210@y43g2000cwc.googlegroups.com> Hi all This is probably old hat to most of you, but for me it was a revelation, so I thought I would share it in case someone has a similar requirement. I had to convert an old program that does a traditional pass through a sorted data file, breaking on a change of certain fields, processing each row, accumulating various totals, and doing additional processing at each break. I am not using a database for this one, as the file sizes are not large - a few thousand rows at most. I am using csv files, and using the csv module so that each row is nicely formatted into a list. The traditional approach is quite fiddly, saving the values of the various break fields, comparing the values on each row with the saved values, and taking action if the values differ. The more break fields there are, the fiddlier it gets. I was going to do the same in python, but then I vaguely remembered reading about 'groupby'. It took a little while to figure it out, but once I had cracked it, it transformed the task into one of utter simplicity. Here is an example. Imagine a transaction file sorted by branch, account number, and date, and you want to break on all three. ----------------------------- import csv from itertools import groupby from operator import itemgetter BRN = 0 ACC = 1 DATE = 2 reader = csv.reader(open('trans.csv', 'rb')) rows = [] for row in reader: rows.append(row) for brn,brnList in groupby(rows,itemgetter(BRN)): for acc,accList in groupby(brnList,itemgetter(ACC)): for date,dateList in groupby(accList,itemgetter(DATE)): for row in dateList: [do something with row] [do something on change of date] [do something on change of acc] [do something on change of brn] ----------------------------- Hope someone finds this of interest. Frank Millman From austuff at gmail.com Fri Jun 16 06:44:04 2006 From: austuff at gmail.com (janama) Date: 16 Jun 2006 03:44:04 -0700 Subject: Newbie wxpython staticbitmap help please References: <1150325882.038508.122780@g10g2000cwb.googlegroups.com> <4490f8b6$0$7766$7a628cd7@news.club-internet.fr> <1150376832.271801.19920@f6g2000cwb.googlegroups.com> <44925ab7$0$7761$7a628cd7@news.club-internet.fr> Message-ID: <1150454644.420240.253310@f6g2000cwb.googlegroups.com> Thanks Jean this now makes sense, really appreciate your time and effort mate. def __init__(self, parent): self._init_ctrls(parent) self.t1 = wx.Timer(self) self.t1.Start(2000) # 2 seconds self.Bind(wx.EVT_TIMER, self.OnTest1Timer) self.OnTest1Timer(self) def OnTest1Timer(self, evt): if os.path.isfile('images/page1.txt'): print "ok file present" i = wx.Image('images/pageGreen.png',wx.BITMAP_TYPE_PNG) b1 = wx.BitmapFromImage(i) self.staticBitmap1.SetBitmap(b1) else: print "ok file present" i = wx.Image('images/pageGrey.png',wx.BITMAP_TYPE_PNG) b1 = wx.BitmapFromImage(i) self.staticBitmap1.SetBitmap(b1) The above works a treat, thanks again Jean janama From nick at craig-wood.com Thu Jun 8 11:30:04 2006 From: nick at craig-wood.com (Nick Craig-Wood) Date: Thu, 08 Jun 2006 10:30:04 -0500 Subject: how to switch from os.tmpnam to os.tmpfile References: <1149773439.534989.54450@i40g2000cwc.googlegroups.com> Message-ID: Harold Fellermann wrote: > I need to create a temporary file and I need to retrieve the path > of that file. os.tmpnam() would do the job quite well if it wasn't > for the RuntimeWarning "tmpnam is a potential security risk to your > program". I would like to switch to os.tmpfile() which is supposed > to be safer, but I do not know how to get the path information from > the file object returned by tmpfile(). any clues? You can't. The file opened doesn't have a name tmpfile(...) tmpfile() -> file object Create a temporary file with no directory entries. Have a look at the functions in the tempfile module, mkstemp() in particular (the posix way), or NamedTemporaryFile() http://docs.python.org/lib/module-tempfile.html -- Nick Craig-Wood -- http://www.craig-wood.com/nick From sreeram at tachyontech.net Tue Jun 6 00:49:09 2006 From: sreeram at tachyontech.net (K.S.Sreeram) Date: Tue, 06 Jun 2006 10:19:09 +0530 Subject: the most efficient method of adding elements to the list In-Reply-To: References: Message-ID: <44850945.4050207@tachyontech.net> alf wrote: > Would it be .append()? Does it reallocate te list with each apend? No append does NOT reallocate for every call. Whenever a reallocation happens, the newsize is proportional to the older size. So you should essentially get amortized constant time for every append call. If you want to add a bunch of items in one call.. you should use the 'extend' method. Regards Sreeram -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 260 bytes Desc: OpenPGP digital signature URL: From bnblazer at gmail.com Fri Jun 2 11:35:05 2006 From: bnblazer at gmail.com (Brian) Date: 2 Jun 2006 08:35:05 -0700 Subject: Are there something like "Effective Python"? In-Reply-To: <1149236138.364915.189890@i40g2000cwc.googlegroups.com> References: <1149224468.481470.74580@i39g2000cwa.googlegroups.com> <1149229055.088793.89010@i39g2000cwa.googlegroups.com> <1149236138.364915.189890@i40g2000cwc.googlegroups.com> Message-ID: <1149262505.634173.126610@h76g2000cwa.googlegroups.com> You might want to give this site a look: http://www.livewires.org.uk/python/ From uval at rz.uni-karlsruhe.de Thu Jun 1 15:28:58 2006 From: uval at rz.uni-karlsruhe.de (=?ISO-8859-1?Q?Sch=FCle_Daniel?=) Date: Thu, 01 Jun 2006 21:28:58 +0200 Subject: integer to binary... In-Reply-To: <1149189570.376091.319890@j55g2000cwa.googlegroups.com> References: <1149189570.376091.319890@j55g2000cwa.googlegroups.com> Message-ID: nicolasg at gmail.com schrieb: > does anyone know a module or something to convert numbers like integer > to binary format ? unfortunately there is no builtin function for this >>> int("111",2) 7 >>> str(7) '7' >>> str(7,2) Traceback (most recent call last): File "", line 1, in ? TypeError: str() takes at most 1 argument (2 given) >>> int, str are not symmetrical I hope this will change in future you can use Ruby's 7.to_s(2) for this irb(main):001:0> 7.to_s(2) => "111" irb(main):002:0> 7.to_s(3) => "21" irb(main):003:0> > for example I want to convert number 7 to 0111 so I can make some > bitwise operations... you can use bitwise operations on int's anyway 7 & 3 == 3 (1 << 20) | (1 << 10) == 2**20+2**10 and so on From martin at v.loewis.de Wed Jun 28 09:34:19 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 28 Jun 2006 15:34:19 +0200 Subject: documentation for the change of Python 2.5 In-Reply-To: References: Message-ID: <44A2855B.8080504@v.loewis.de> bussiere wrote: > I've read thsi documentation n: > http://docs.python.org/dev/whatsnew/whatsnew25.html > is there a way to have it in a more printable form ? Yes. Download http://www.python.org/ftp/python/doc/2.5b1/pdf-a4-2.5b1.tar.bz2 and extract whatsnew25.pdf. Regards, Martin From slawomir.nowaczyk.847 at student.lu.se Thu Jun 8 15:30:11 2006 From: slawomir.nowaczyk.847 at student.lu.se (Slawomir Nowaczyk) Date: Thu, 08 Jun 2006 21:30:11 +0200 Subject: CONSTRUCT - Python's way of Ruby's "alias_method" In-Reply-To: References: Message-ID: <20060608210744.FC8A.SLAWOMIR.NOWACZYK.847@student.lu.se> On Thu, 08 Jun 2006 15:28:39 +0300 Ilias Lazaridis wrote: #> *IMPORT* #> #> I would like to know, if this construct is valid, or if it can #> result in problems (that I do not see as a newcomer): The intricacies of import are far beyond me, but FWIW I do not see anything wrong in this code. #> Is there any way (beside a patch) to alter the behaviour to an #> existing function. You can just assign new function to the old name. There are a few loops to hop through if you want to alter the behaviour of an existing *method*... There is an example -- I do not know if a good one -- here: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52192 -- Best wishes, Slawomir Nowaczyk ( Slawomir.Nowaczyk at cs.lth.se ) Strange how people who don't even know their neighbors are extremely curious to know if there's extra-terrestrial life. From a at tempinbox.com Fri Jun 23 15:28:24 2006 From: a at tempinbox.com (a) Date: 23 Jun 2006 12:28:24 -0700 Subject: templating languages for webdev Message-ID: <1151090904.496637.75220@u72g2000cwu.googlegroups.com> cheetah vs django vs kid Any of you have experience using kid templates please let us know what you feel about it thanks sincerely jason From girish at cse.iitb.ac.in Mon Jun 12 07:10:00 2006 From: girish at cse.iitb.ac.in (Girish Sahani) Date: Mon, 12 Jun 2006 16:40:00 +0530 (IST) Subject: Function to remove elements from a list working, but Python Hangs :(( In-Reply-To: <200606121237.04032.maric@aristote.info> References: <49543.10.209.4.1.1150100717.squirrel@10.105.1.3><200606121041.01792.maric@aristote.info><36394.10.209.4.1.1150103178.squirrel@10.105.1.3> <200606121237.04032.maric@aristote.info> Message-ID: <49961.10.209.4.1.1150110600.squirrel@10.105.1.3> > I guess it's already the case with lst = [ e for e in lst if e in pairs ] > > > In [1]: lst = (1,2,3,4) > > In [2]: pairs=(5,) > > In [3]: lst=[e for e in lst if e in pairs] > > In [4]: lst > Out[4]: [] Yes its working. I realized that i was giving an input which didnt satisfy the condition. Now if you could please check out this new problem i'm facing,related to this.In my code,l4 is a list of lists, and these lists contain such pairs. e.g. l4 = [[[4,2],[4,7],[4,10],[4,12],[9,2],[9,7],[9,10],[9,12],[11,2],[11,10]],[[1,2],[3,5],[7,8]]] which is a list of 2 lists (having 13 pairs) Now when l4 has 50 pairs, and i run the code, python just hangs, and i'm quite sure its because of this. Is there any way to rectify this??? > > > > -- > _____________ > > Maric Michaud > _____________ > > Aristote - www.aristote.info > 3 place des tapis > 69004 Lyon > Tel: +33 426 880 097 > -- > http://mail.python.org/mailman/listinfo/python-list > From digitalorganics at gmail.com Sun Jun 11 23:18:07 2006 From: digitalorganics at gmail.com (digitalorganics at gmail.com) Date: 11 Jun 2006 20:18:07 -0700 Subject: direct initialization of class attributes vs. declarations w/in __init__ In-Reply-To: <4f3it1F1gptbcU1@uni-berlin.de> References: <1150041510.139609.171120@f6g2000cwb.googlegroups.com> <4f2thrF1fd4r4U1@uni-berlin.de> <1150043792.136250.99770@u72g2000cwu.googlegroups.com> <1150047314.025241.260750@c74g2000cwc.googlegroups.com> <1150061669.491796.95700@g10g2000cwb.googlegroups.com> <4f3it1F1gptbcU1@uni-berlin.de> Message-ID: <1150082287.401522.164950@h76g2000cwa.googlegroups.com> Diez B. Roggisch wrote: > > No need to be obnoxious. I do appreciate your efforts to help, but you > > must admit, your last statement is a bit snide and certainly not > > useful. > > I'm telling you that the code runs differently on my laptop. > > It certainly doesn't. There is absolutely no imaginable way how this > behavior could be different, even if the python versions would differ > considerably. Apart from quantum-fluctuations. Or other SciFi voodoo. Hmmm > > > Why this is, I don't know any more /or/ less than you do apparently. > > Frederik (as one of the most profiled python developers out there) might > not be the most amicable of posters, Although he dropped what I perceived to be a snide and unhelpful comment, two things. One, I understand what's behind it in the sense that the behavior I was describing goes against the semantic fundamentals of python, and should therefore be impossible. Two, Fredrik is no doubt a sweetheart and he showed it by continuing to put his efforts toward helping me despite my criticism of him. I can't thank him enough. Honestly, I believe newsgroups need more people like him . . . > ... > > It is NOT identical code, otherwise you won't see different > results. It might be code from which you _believe_ it is identical, and > the difference might be subtle to see. But if you'd store it in a file, > execute on your laptop, use an usb-stick and then transfer it to > whatever the other machine of yours is, it will yield the exact same > results. > > Diez Read my other post. The code was/is definitely identical. In any event, I don't really care. It's working properly now, and if I have similarly weird problems in future, I'll deal with them at that time. I don't know what was up, but I understand it doesn't make sense from any visible standpoint of logic. Thank you for your efforts Diez... From antroy at gmail.com Thu Jun 15 14:01:03 2006 From: antroy at gmail.com (Ant) Date: 15 Jun 2006 11:01:03 -0700 Subject: a good programming text editor (not IDE) In-Reply-To: References: <_xgkg.2317$No6.48542@news.tufts.edu> <1150393919.514359.55580@h76g2000cwa.googlegroups.com> Message-ID: <1150394463.501086.211540@i40g2000cwc.googlegroups.com> John Salerno wrote: > Ant wrote: > > > jEdit is for me still the best text editor available. Very extensible > > with macros (which can be written in Jython with the appropriate plugin > > installed). > > I like the idea of being extensible, but of course I can only write in > Python. Are there any editors that support that? Jython is python (running on the Java platform) - just not a very recent version (2.1 currently IIRC). From onurb at xiludom.gro Tue Jun 6 06:38:36 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 06 Jun 2006 12:38:36 +0200 Subject: check for dictionary keys In-Reply-To: <4484d5ee$1@news.eftel.com> References: <1149298230.864123.8320@u72g2000cwu.googlegroups.com> <4483f80a$0$27349$626a54ce@news.free.fr> <4484d5ee$1@news.eftel.com> Message-ID: <44855b2c$0$10988$626a54ce@news.free.fr> John Machin wrote: > On 5/06/2006 10:46 PM, Bruno Desthuilliers wrote: > >> micklee74 at hotmail.com a ?crit : >> >>> hi >>> in my code, i use dict(a) to make to "a" into a dictionary , "a" comes >>> from user input, so my program does not know in the first place. Then >>> say , it becomes >>> >>> a = { '-A' : 'value1' , '-B' : "value2" , "-C" : "value3" , '-D' : >>> 'value4' } >>> >>> somewhere next in my code, i will check for these..: >>> >>> 1) -A and -B cannot exist together >>> 2) -A and -C cannot exist together >>> 3) -A and -B and -D cannot exist together >>> 4) and lots of other combinations to check for.... >> >> >> Looks like an option parser... If so, there's all you need in the >> standard lib (look for the optparse module). >> >>> >>> how can i efficiently check for the above? At first as i do simple >>> checks , i use if and else. >>> But as i began to check for more combinatoiuns, it gets messy.... >> >> >> First : use boolean logic (truth table, Kernaugh diagram, etc) to >> simplify things. As an example, rule #3 is useless - it's a subset of >> rule #1 (-A and -B and -D implies -A and -B). This should greatly >> reduce the number of needed tests. > > > Good idea, but doesn't scale well. Does it need to scale ? If there are lot of rules and frequently changing, yes, automating the process will be a good idea - but if it's about a program options, just using one's brain might be enough. At least it forces one to think about what's going on... > Simple code can weed out redundant > rules, Simple code can weed out redundant *simple* rules !-) (snip) >> Then, write a simple rule system describing either valid inputs or >> invalid inputs (preferably the smallest set !-). FWIW, it can be as >> simple as a list of lambdas/error messages pairs, with lambdas being >> predicate taking dict keys as params: >> >> >> _RULES = [ >> (lambda keys : '-A' in keys and '-B' in keys, >> "can't have both options -A and -B"), >> (lambda keys : '-A' in keys and '-C' in keys, >> "can't have both options -A and -C"), >> # etc... >> ] >> > > The evil HR director won't let the PHB pay me on a per LOC basis, so > I've had to come up with a compact table-driven approach :-) I'm my own evil HR director and PHB !-) Don't like table-driven programming, John ? This solution takes very few lines, and while it's surely not a full-blown rule engine, it's at least reasonably flexible. (Not to say it's better than yours - it's of course a matter of effective use case). >> def validate(options, rules): >> keys = options.keys() >> for predicate, message in rules: >> if not predicate(keys): >> raise ValueError(message) > > > > C:\junk>type option_combos.py > bad_combos = ['ABD', 'AC', 'AB', 'CA'] > > def rule_compaction(bc_list, verbose=False): > # The next few lines are admittedly oldfashioned :-) > bc_sets = [set(x) for x in bc_list] > deco = [(len(y), y) for y in bc_sets] > deco.sort() > bc_sets = [z[1] for z in deco] > del deco > if verbose: > print "bc_sets #1:", bc_sets > for k in xrange(len(bc_sets)-1, 0, -1): > candidate = bc_sets[k] > for ko in bc_sets[:k]: > if ko <= candidate: > if verbose: > print candidate, "knocked out by", ko > del bc_sets[k] > break > if verbose: > print "bc_sets #2:", bc_sets > return bc_sets > Nice code - but how does it handle more complex predicates ? Seems you can only deal with 'and' rules here. "Doesn't scale well", you said ?-) (snip) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From wegein at gmail.com Fri Jun 23 21:35:18 2006 From: wegein at gmail.com (damacy) Date: 23 Jun 2006 18:35:18 -0700 Subject: python + postgres psql + os.popen In-Reply-To: <1150992464.012824.295810@r2g2000cwb.googlegroups.com> References: <1150946077.931411.170930@u72g2000cwu.googlegroups.com> <1150992464.012824.295810@r2g2000cwb.googlegroups.com> Message-ID: <1151112918.188723.48680@b68g2000cwa.googlegroups.com> hi, there. thanks for the help. now i have a different problem now. i decided to use 'subprocess' and 'Popen' objects instead of 'os.popen()' function, which i believe do not make much difference. my code is like the following... [1] link = subprocess.Popen(command, stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE, shell = True) [2] link.communicate(password) [3] link.wait() [4] err = link.communicate()[1] [5] if err != None: print str(err) i have read several threads about 'subprocess' posted on this group and still i have way too much confusion regarding the above section of code. 1. i'm currently using MS Windows. i remember some have said that communicate() function is not usable on this OS. could anyone confirm this? 2. i'm expecting an error message, as i am trying to create a table which does already exist in the database. but if i try to print out the error message as [5], it is just an EMPTY string. and, if i try the SAME THING using command-line, i get a correct error message this time ('psql:createstudent.sql:12: ERROR: relation "student" already exists'). HOWEVER, if i comment out [2] link.communicate(password), meaning i do not supply a password, it shows an error message, 'psql: fe_sendauth: no password supplied', which is correct as expected. my question is... why does it work (i.e. showing a correct error message) when no password supplied but NOT when creating a table which already exists in the database? it should work for both cases. thank you very much. Simon Forman wrote: > damacy wrote: > > hello, everyone. > ... > > this works well. however, it does not show me any warning nor error > > messages if there is one. for example, i am trying to create a table > > which already exists in the database, it should show me a warning/error > > message saying there already is one present in the database, or > > something like that. > > > > can anyone help me? > > I recently needed to use psql from python on a computer that I couldn't > install psycopg on and I used something similar to this to do it (I > edited the code slightly to make it clearer): > > from subprocess import Popen, PIPE > > # Pass the password through an environment > # variable to prevent psql asking for it. > psql_env = dict(PGPASSWORD='********') > > # Create the subprocess. > proc = Popen(cmd, shell=True, env=psql_env, stdout=PIPE, stderr=PIPE) > > # Try reading it's data. > data = proc.stdout.read() > > # Check for errors. > err = proc.stderr.read() > if err: raise Exception(err) > > > It worked nicely for me, YMMV. > > > Hope that helps, > > ~Simon From anton at appsolutions.com Fri Jun 23 02:32:49 2006 From: anton at appsolutions.com (Anton van Straaten) Date: Fri, 23 Jun 2006 06:32:49 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> Message-ID: Chris Smith wrote: > I don't recall who said what at this > point, but earlier today someone else posted -- in this same thread -- > the idea that static type "advocates" want to classify some languages as > untyped in order to put them in the same category as assembly language > programming. That's something I've never seen, and I think it's far > from the goal of pretty much anyone; but clearly, *someone* was > concerned about it. I don't know if much can be done to clarify this > rhetorical problem, but it does exist. For the record, I'm not concerned about that problem as such. However, I do think that characterizations of dynamically typed languages from a static type perspective tend to oversimplify, usually because they ignore the informal aspects which static type systems don't capture. Terminology is a big part of this, so there are valid reasons to be careful about how static type terminology and concepts are applied to languages which lack formally defined static type systems. > The *other* bit that's been brought up in this thread is that the word > "type" is just familiar and comfortable for programmers working in > dynamically typed languages, and that they don't want to change their > vocabulary. What I'm suggesting is actually a kind of bridge between the two positions. The dynamically typed programmer tends to think in terms of values having types, rather than variables. What I'm pointing out is that even those programmers reason about something much more like static types than they might realize; and that there's a connection between that reasoning and static types, and also a connection to the tags associated with values. If you wanted to take the word "type" and have it mean something reasonably consistent between the static and dynamic camps, what I'm suggesting at least points in that direction. Obviously, nothing in the dynamic camp is perfectly isomorphic to a real static type, which is why I'm qualifying the term as "latent type", and attempting to connect it to both static types and to tags. > The *third* thing that's brought up is that there is a (to me, somewhat > vague) conception going around that the two really ARE varieties of the > same thing. I'd like to pin this down more, and I hope we get there, > but for the time being I believe that this impression is incorrect. At > the very least, I haven't seen a good way to state any kind of common > definition that withstands scrutiny. There is always an intuitive word > involved somewhere which serves as an escape hatch for the author to > retain some ability to make a judgement call, and that of course > sabotages the definition. So far, that word has varied through all of > "type", "type error", "verify", and perhaps others... but I've never > seen anything that allows someone to identify some universal concept of > typing (or even the phrase "dynamic typing" in the first place) in a way > that doesn't appeal to intuition. It's obviously going to be difficult to formally pin down something that is fundamentally informal. It's fundamentally informal because if reasoning about the static properties of terms in DT languages were formalized, it would essentially be something like a formal type system. However, there are some pretty concrete things we can look at. One of them, which as I've mentioned elsewhere is part of what led me to my position, is to look at what a soft type inferencer does. It takes a program in a dynamically typed language, and infers a static type scheme for it (obviously, it also defines an appropriate type system for the language.) This has been done in both Scheme and Erlang, for example. How do you account for such a feat in the absence of something like latent types? If there's no static type-like information already present in the program, how is it possible to assign a static type scheme to a program without dramatically modifying its source? I think it's reasonable to look at a situation like that and conclude that even DT programs contain information that corresponds to types. Sure, it's informal, and sure, it's usually messy compared to an explicitly defined equivalent. But the point is that there is "something" there that looks so much like static types that it can be identified and formalized. > Undoubtedly, some programmers sometimes perform reasoning about their > programs which could also be performed by a static type system. I think that's a severe understatement. Programmers always reason about things like the types of arguments, the types of variables, the return types of functions, and the types of expressions. They may not do whole-program inference and proof in the way that a static type system does, but they do it locally, all the time, every time. BTW, I notice you didn't answer any of the significant questions which I posed to Vesa. So let me pose one directly to you: how should I rewrite the first sentence in the preceding paragraph to avoid appealing to an admittedly informal notion of type? Note, also, that I'm using the word in the sense of static properties, not in the sense of tagged values. >>There are reasons to connect >>it to type theory, and if you can't see those reasons, you need to be >>more explicit about why. > > > Let me pipe up, then, as saying that I can't see those reasons; or at > least, if I am indeed seeing the same reasons that everyone else is, > then I am unconvinced by them that there's any kind of rigorous > connection at all. For now, I'll stand on what I've written above. When I see if or how that doesn't convince you, I can go further. > It is, nevertheless, quite appropriate to call the language "untyped" if > I am considering static type systems. I agree that in the narrow context of considering to what extent a dynamically typed language has a formal static type system, you can call it untyped. However, what that essentially says is that formal type theory doesn't have the tools to deal with that language, and you can't go much further than that. As long as that's what you mean by untyped, I'm OK with it. > I seriously doubt that this usage > in any way misleads anyone into assuming the absence of any mental > processes on the part of the programmer. I hope you agree. I didn't suggest otherwise (or didn't mean to). However, the term "untyped" does tend to lead to confusion, to a lack of recognition of the significance of all the static information in a DT program that is outside the bounds of a formal type system, and the way that runtime tag checks relate to that static information. One misconception that occurs is the assumption that all or most of the static type information in a statically-typed program is essentially nonexistent in a dynamically-typed program, or at least is no longer statically present. That can easily be demonstrated to be false, of course, and I'm not arguing that experts usually make this mistake. > If not, > then I think you significantly underestimate a large category of people. If you think there's no issue here, I think you significantly overestimate a large category of people. Let's declare that line of argument a draw. >>The first point I was making is that *automated* checking has very >>little to do with anything, and conflating static types with automated >>checking tends to lead to a lot of confusion on both sides of the >>static/dynamic fence. > > > I couldn't disagree more. Rather, when you're talking about static > types (or just "types" in most research literature that I've seen), then > the realm of discussion is specifically defined to be the very set of > errors that are automatically caught and flagged by the language > translator. I suppose that it is possible to have an unimplemented type > system, but it would be unimplemented only because someone hasn't felt > the need nor gotten around to it. Being implementABLE is a crucial part > of the definition of a static type system. I agree with the latter sentence. However, it's nevertheless the case that it's common to confuse "type system" with "compile-time checking". This doesn't help reasoning in debates like this, where the existence of type systems in languages that don't have automated static checking is being examined. > I am beginning to suspect that you're make the converse of the error I > made earlier in the thread. That is, you may be saying things regarding > the psychological processes of programmers and such that make sense when > discussing dynamic types, and in any case I haven't seen any kind of > definition of dynamic types that is more acceptable yet; but it's > completely irrelevant to static types. Static types are not fuzzy -- if > they were fuzzy, they would cease to be static types -- and they are not > a phenomenon of psychology. To try to redefine static types in this way > not only ignores the very widely accepted basis of entire field of > existing literature, but also leads to false ideas such as that there is > some specific definable set of problems that type systems are meant to > solve. I'm not trying to redefine static types. I'm observing that there's a connection between the static properties of untyped programs, and static types; and attempting to characterize that connection. You need to be careful about being overly formalist, considering that in real programming languages, the type system does have a purpose which has a connection to informal, fuzzy things in the real world. If you were a pure mathematician, you might get away with claiming that type systems are just a self-contained symbolic game which doesn't need any connections beyond its formal ruleset. Think of it like this: the more ambitious a language's type system is, the fewer uncaptured static properties remain in the code of programs in that language. However, there are plenty of languages with rather weak static type systems. In those cases, code has more static properties that aren't captured by the type system. I'm pointing out that in many of these cases, those properties resemble types, to the point that it can make sense to think of them and reason about them as such, applying the same sort of reasoning that an automated type inferencer applies. If you disagree, then I'd be interested to hear your answers to the two questions I posed to Vesa, and the related one I posed to you above, about what else to call these things. >>I agree, to make the comparison perfect, you'd need to define a type >>system. But that's been done in various cases. > > > I don't think that has been done, in the case of dynamic types. I was thinking of the type systems designed for soft type inferencers; as well as those cases where e.g. a statically-typed subset of an untyped language is defined, as in the case of PreScheme. But in such cases, you end up where a program in these systems, while in some sense statically typed, is also a valid untyped program. There's also nothing to stop someone familiar with such things programming in a type-aware style - in fact, books like Felleisen et al's "How to Design Programs" encourage that, recommending that functions be annotated with comments expressing their type. Examples: ;; product : (listof number) -> number ;; copy : N X -> (listof X) You also see something similar in e.g. many Erlang programs. In these cases, reasoning about types is done explicitly by the programmer, and documented. What would you call the descriptions in those comments? Once you tell me what I should call them other than "type" (or some qualified variant such as "latent type"), then we can compare terminology and decide which is more appropriate. > It has > been done for static types, but much of what you're saying here is in > contradiction to the definition of a type system in that sense of the > word. Which is why I'm using a qualified version of the term. >>The problem we're dealing with in this case is that anything that's not >>formally defined is essentially claimed to not exist. > > > I see it as quite reasonable when there's an effort by several > participants in this thread to either imply or say outright that static > type systems and dynamic type systems are variations of something > generally called a "type system", and given that static type systems are > quite formally defined, that we'd want to see a formal definition for a > dynamic type system before accepting the proposition that they are of a > kind with each other. A complete formal definition of what I'm talking about may be impossible in principle, because if you could completely formally define it, you'd have a static type system. If that makes you throw up your hands, then all you're saying is that you're unwilling to deal with a very real phenomenon that has obvious connections to type theory, examples of which I've given above. That's your choice, but at the same time, you have to give up exclusive claim to any variation of the word "type". Terms are used in a context, and it's perfectly reasonable to call something a "latent type" or even a "dynamic type" in a certain context and point out connections between those terms and their cousins (or if you insist, their completely unrelated namesakes) static types. > So far, all the attempts I've seen to define a > dynamic type system seem to reduce to just saying that there is a well- > defined semantics for the language. That's a pretty strong claim, considering you have so far ducked the most important questions I raised in the post you replied to. > I believe that's unacceptable for several reasons, but the most > significant of them is this. It's not reasonable to ask anyone to > accept that static type systems gain their essential "type system-ness" > from the idea of having well-defined semantics. The definition of static type system is not in question. However, realistically, as I pointed out above, you have to acknowledge that type systems exist in, and are inextricably connected to, a larger, less formal context. (At least, you have to acknowledge that if you're interested in programs that do anything related to the real world.) And outside the formally defined borders of static type systems, there are static properties that bear a pretty clear relationship to types. Closing your eyes to this and refusing to acknowledge any connection doesn't achieve anything. In the absence of some other account of the phenomena in question, (an informal version of) types turn out to be a pretty convenient way to deal with the situation. > From the perspective of > a statically typed language, this looks like a group of people getting > together and deciding that the real "essence" of what it means to be a > type system is... There's a sense in which one can say that yes, the informal types I'm referring to have an interesting degree of overlap with static types; and also that static types do, loosely speaking, have the "purpose" of formalizing the informal properties I'm talking about. But I hardly see why such an informal characterization should bother you. It doesn't affect the definition of static type. It's not being held up as a foundation for type theory. It's simply a way of dealing with the realities of programming in a dynamically-checked language. There are some interesting philophical issues there, to be sure (although only if you're willing to stray outside the formal), but you don't have to worry about those unless you want to. > and then naming something that's so completely non- > essential that we don't generally even mention it in lists of the > benefits of static types, because we have already assumed that it's true > of all languages except C, C++, and assembly language. This is based on the assumption that all we're talking about is "well-defined semantics". However, there's much more to it than that. I need to hear your characterization of the properties I've described before I can respond. Anton From deets at nospam.web.de Thu Jun 15 12:34:50 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 15 Jun 2006 18:34:50 +0200 Subject: code folding, a unique problem to python? In-Reply-To: References: Message-ID: <4fdgh7F1hbtteU1@uni-berlin.de> John Salerno schrieb: > Specifically, I'm using UltraEdit and perhaps there's no way perfect way > to implement code folding with it, given how it uses its syntax > highlighting file to do so (i.e., you have to specify an "Opening" and > "Closing" character in which to enfold code, such as braces). > > But my question is more general: is it possible to implement code > folding with Python given that it has no real block delimiters? Or is > this still a matter of which particular editor/IDE you use? For my part > I've tried (as was suggested elsewhere) to use 'def' as an opening and > closing keyword, but this of course will enfold everything between two > defs, even if you have more code between your function definitons (such > as a new class definition). > > So maybe I'm stuck in UE, but I'm curious if there is some general way > to do this, or is Python just too simple and concise for its own good? :) Eric3, the Qt-based and in python written IDE can do that. So I'd say it's an UE-problem - nad it has to be: to perform folding, one has to find out what constitutes a block. Obviously this CAN be done with python-code - do it CAN be done in editor code. Diez From ilias at lazaridis.com Wed Jun 7 11:45:38 2006 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Wed, 07 Jun 2006 18:45:38 +0300 Subject: PUDGE - Project Status, Alternative Solutions In-Reply-To: <4482DD82.6010003@lazaridis.com> References: <447786E9.9010208@lazaridis.com> <4482DD82.6010003@lazaridis.com> Message-ID: <4486F4A2.1000906@lazaridis.com> Ilias Lazaridis wrote: > Ilias Lazaridis wrote: >> What is going on with the pudge project? > > Any chance to get an comment on this? After a little bit off-list discussion, I understand that many python documentation projects stop at some point, and that efforts are in general not very synchronized. Small overview here (work in progress): http://case.lazaridis.com/wiki/Docgen - btw: Still, the pudge.general list needs to be activated!!! >> Mr. Patrik O'Brien (Orbtech LLC) had told me that there is no similar >> tool available within the python domain, thus I have invested some >> effort to create a Website template, and to enable pudge to generate >> colored code: >> >> http://audit.lazaridis.com/schevo/wiki/SchevoWebsiteReview >> >> I like to reuse the results for personal projects, but I am wondering >> that the pudge email-list is death (since the server update) - and >> that no one of the project reacts to personal and public postings. >> >> Additionally, the schevo project removes the pudge stuff, mscott, the >> developer which has introduced pudge removes it again (although this >> was done with several other tools in the past, too): >> >> http://schevo.org/trac/changeset/2127 >> >> - >> >> Is there a similar tool available, with which I can generate python >> documentation / websites or both based on templates and reST? >> >> Or an overview of such tools? >> >> I mean such an organized tool is essential for developmente with python. >> >> . >> > > -- http://lazaridis.com From fredrik at pythonware.com Thu Jun 1 09:41:10 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 1 Jun 2006 15:41:10 +0200 Subject: PythonDoc Ant Task References: <1149165032.870017.254980@i40g2000cwc.googlegroups.com> <1149167403.532618.22370@y43g2000cwc.googlegroups.com> Message-ID: "abcd" wrote: > class Bar: > global javax.swing > import javax.swing > [/code] > > ....so it seems that pydoc cant giggity-giggit! "global javax.swing" is not valid Python syntax. what is that global/import combo supposed to do, and what environment do you run this under ? From rossberg at ps.uni-sb.de Fri Jun 23 06:02:36 2006 From: rossberg at ps.uni-sb.de (Andreas Rossberg) Date: Fri, 23 Jun 2006 12:02:36 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <7zpshbsvjy.fsf@app-1.diku.dk><4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <0%Wlg.3521$MF6.947@tornado.socal.rr.com> <44992e6c$0$664$bed64819@news.gradwell.net> <1150916327.332627.124400@g10g2000cwb.googlegroups.com> <1150987852.784870.7610@y41g2000cwy.googlegroups.com> Message-ID: David Hopwood wrote: >> >>"Values" refers to the concrete values existent in the semantics of a >>programming language. This set is usually infinite, but basically fixed. >>To describe the set of "values" of an abstract type you would need >>"fresh" values that did not exist before (otherwise the abstract type >>would be equivalent to some already existent type). So you'd need at >>least a theory for name generation or something similar to describe >>abstract types in a types-as-sets metaphor. > > Set theory has no difficulty with this. It's common, for example, to see > "the set of strings representing propositions" used in treatments of > formal systems. Oh, I was not saying that this particular aspect cannot be described in set theory (that was a different argument, about different issues). Just that you cannot naively equate types with a set of underlying values, which is what is usually meant by the types-are-sets metaphor - to capture something like type abstraction you need to do more. (Even then it might be arguable if it really describes the same thing.) - Andreas From gneuner2/ at comcast.net Wed Jun 21 19:22:49 2006 From: gneuner2/ at comcast.net (George Neuner) Date: Wed, 21 Jun 2006 19:22:49 -0400 Subject: What is Expressiveness in a Computer Language References: <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <34aj92h0g7tqi9amhh7k3ieq5n568t0e6f@4ax.com> <1150927463.340542.65690@g10g2000cwb.googlegroups.com> Message-ID: <7pij925jg29ddfvfrn0b98crrkfm4daaef@4ax.com> On 21 Jun 2006 15:04:23 -0700, "Greg Buchholz" wrote: > I haven't been following this thread too closely, but I thought the >following article might be of interest... > >Eliminating Array Bound Checking through Non-dependent types. >http://okmij.org/ftp/Haskell/types.html#branding That was interesting, but the authors' method still involves runtime checking of the array bounds. IMO, all they really succeeded in doing was turning the original recursion into CPS and making the code a little bit clearer. George -- for email reply remove "/" from address From yairchu at gmail.com Thu Jun 1 04:16:14 2006 From: yairchu at gmail.com (yairchu at gmail.com) Date: 1 Jun 2006 01:16:14 -0700 Subject: Best Python Editor References: Message-ID: <1149149773.999940.13500@i40g2000cwc.googlegroups.com> > Can anyone tell me a good python editor/IDE? > It would be great if you can provide the download link also. WingIDE is very good. It gives very nice completions and has a nice thing called "source assistant" that shows the help of the function you're standing on and etc. But I don't think it's open-source and freei if that bothers you http://www.wingware.com/ Another good one is idlespoon. this one is open-source and freei http://idlespoon.python-hosting.com/ From cdsmith at twu.net Thu Jun 22 22:46:10 2006 From: cdsmith at twu.net (Chris Smith) Date: Thu, 22 Jun 2006 20:46:10 -0600 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> Message-ID: Chris Smith wrote: > I see it as quite reasonable when there's an effort by several > participants in this thread to either imply or say outright that static > type systems and dynamic type systems are variations of something > generally called a "type system" [...] I didn't say that right. Obviously, no one is making all that great an EFFORT to say anything. Typing is not too difficult, after all. What I meant is that there's an argument being made to that effect. -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation From maxerickson at gmail.com Thu Jun 1 11:29:46 2006 From: maxerickson at gmail.com (Max Erickson) Date: Thu, 1 Jun 2006 15:29:46 +0000 (UTC) Subject: argmax References: Message-ID: "David Isaac" wrote: > 1. Why is there no argmax built-in? > (This would return the index of the largest element in a > sequence.) > > 2. Is this a good argmax (as long as I know the iterable is > finite)? def argmax(iterable): return max(izip( iterable, count() > ))[1] > use len: len(iterable)-1 max From digitalorganics at gmail.com Mon Jun 12 12:27:41 2006 From: digitalorganics at gmail.com (digitalorganics at gmail.com) Date: 12 Jun 2006 09:27:41 -0700 Subject: Bridge: Ruby to Python communication In-Reply-To: References: <1150126134.802843.122890@h76g2000cwa.googlegroups.com> Message-ID: <1150129661.338531.289510@j55g2000cwa.googlegroups.com> Wait wait, what do I do exactly? Thanks Michel. Michel Claveau wrote: > Hi! > > For me, like PHP (message of 11h.35) : > > Only in Windows, I can call Ruby (more exactly Ruby-script) from > Python. > I can, also, call, from Python, Ruby-defined-functions, like a method > of a Python-class. > > It's a combination of Active-scripting & dynamic method add to a class. > > It's run OK with : Ruby-script, Perl-script, PHPscript, VBscript, > Jscript. > > -- > @-salutations > > Michel Claveau > > -- > @-salutations > > Michel Claveau From lucaberto at libero.it Fri Jun 16 09:24:20 2006 From: lucaberto at libero.it (luca72) Date: 16 Jun 2006 06:24:20 -0700 Subject: Pycrypto In-Reply-To: <1150462237.224431.213020@c74g2000cwc.googlegroups.com> References: <1150446904.527285.255170@g10g2000cwb.googlegroups.com> <1150458752.342042.189650@h76g2000cwa.googlegroups.com> <1150462237.224431.213020@c74g2000cwc.googlegroups.com> Message-ID: <1150464260.227630.263210@p79g2000cwp.googlegroups.com> Thanks Luca From tim.golden at viacom-outdoor.co.uk Fri Jun 9 03:51:47 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Fri, 9 Jun 2006 08:51:47 +0100 Subject: better Python IDE? Mimics Maya's script editor? Message-ID: [Steve Holden] | warpcat wrote: | > In Maya's mel script editor window, it's split into two sections. | > Bottom window you can enter commands (where your script lives), top | > window gives results. The thing I'm really used to is | highlighting X# | > of lines in the bottom window (little snippits from my script), and | > executing that selection, with instant feedback of the | results on top. | > This really speeds my workflow. | I don't know of anything that exhibits the exact behaviour | you describe, | but then again you might like to consider that i found your | request very | odd. I'm sure that way of testing code seems entirely natural to you, | but I can honestly say that in almost ten years using Python it's not | something I have ever wished for. I may have misread, but it sounds just like what Lightning does: https://sourceforge.net/project/showfiles.php?group_id=125834 Except that you enter snippets in the top window and the results appear in the bottom window. (Or, I think, even side-by-side according to some preference setting). Try it and see, perhaps. 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 ________________________________________________________________________ From bdesth.quelquechose at free.quelquepart.fr Wed Jun 28 22:21:14 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 29 Jun 2006 04:21:14 +0200 Subject: Immutability In-Reply-To: References: Message-ID: <44a308c8$0$23554$626a54ce@news.free.fr> Georg Brandl a ?crit : > Steve Holden wrote: > > >>>>Thanks very much. And, what's more, I have even found its documentation! >>>>Whatsnew2.2. The 2.4.2 reference is, er, unhelpful. >>> >>> >>>Is it? >>> >>>http://docs.python.org/lib/built-in-funcs.html >>> >>>documents "property" quite well. >>> >> >>I can't really agree that "quite good" documentation doesn't refer to >>the use of property as a decorator. It's obvious that a ncessary upgrade >>to the docs didn't happen (and we can all understand why, I am sure). > > > In my opinion property isn't really meant to be used as a decorator since > it's impossible to create a read-write property. The decorator pattern > doesn't really fit here. Making an attribute read-only is a common use case for properties, so using property as a decorator in this case seems quite ok. From fredrik at pythonware.com Tue Jun 27 22:58:21 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 28 Jun 2006 04:58:21 +0200 Subject: xml.sax.xmlreader and expat In-Reply-To: <2006062717023716807-garyrob@goombahcom> References: <2006062717023716807-garyrob@goombahcom> Message-ID: Gary Robinson wrote: > We're using xml.sax.xmlreader in our app (http://www.goombah.com, which > is written in Python). > > In Python 2.3.x, does that use the C-language expat under the hood? yes. > The reason I'm asking is because we're wondering if we can speed up the > parsing significantly. if you want speed, you don't really want any of the xml.sax or xml.dom stuff. I'm a bit biased, but I'd recommend the iterparse interface to cElementTree: http://effbot.org/zone/celementtree.htm http://effbot.org/zone/element-iterparse.htm From levi.r.self at gmail.com Tue Jun 6 23:46:48 2006 From: levi.r.self at gmail.com (Levi Self) Date: Tue, 6 Jun 2006 22:46:48 -0500 Subject: A more elegant way to do this list comprehension? Message-ID: <12428afb0606062046nda97570j2b5eb7cab5518352@mail.gmail.com> This probably seems very trivial, maybe even a bit silly, but I was wondering if someone has a better list comprehension that does the same thing as this one: >>> print [[[i]*i for i in range(1,9)][j][k] for j in range(8) for k in range(j+1)] [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8] Thanks, Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: From vesa.karvonen at cs.helsinki.fi Tue Jun 20 01:05:14 2006 From: vesa.karvonen at cs.helsinki.fi (Vesa Karvonen) Date: 20 Jun 2006 05:05:14 GMT Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> Message-ID: In comp.lang.functional Chris Smith wrote: [...] > Knowing that it'll cause a lot of strenuous objection, I'll nevertheless > interject my plea not to abuse the word "type" with a phrase like > "dynamically typed". If anyone considers "untyped" to be perjorative, > as some people apparently do, then I'll note that another common term is > "type-free," which is marketing-approved but doesn't carry the > misleading connotations of "dynamically typed." We are quickly losing > any rational meaning whatsoever to the word "type," and that's quite a > shame. [...] FWIW, I agree and have argued similarly on many occasions (both on the net (e.g. http://groups.google.fi/group/comp.programming/msg/ba3ccfde4734313a?hl=fi&) and person-to-person). The widely used terminology (statically / dynamically typed, weakly / strongly typed) is extremely confusing to beginners and even to many with considerable practical experience. -Vesa Karvonen From imcsee at gmail.com Wed Jun 14 01:06:25 2006 From: imcsee at gmail.com (imcs ee) Date: Wed, 14 Jun 2006 13:06:25 +0800 Subject: daily python url - gmane links dead? In-Reply-To: <448F0856.4090303@tachyontech.net> References: <448F0856.4090303@tachyontech.net> Message-ID: same error here. On 6/14/06, K.S.Sreeram wrote: > Is it just me.. or are all the gmane links on daily-python dead? > All the c.l.py.announce entries point to gmane, and none of them seem to > be working. This is the error i get on gmane: > > Warning: fsockopen(): unable to connect to hugh:8010 in > /home/httpd/gmane/php/lib.php on line 18 > Couldn't contact hugh:8010 > The web interface is down for maintenance. > > How about using google groups or the python.org archives instead of gmane? > > Regards > Sreeram > > > > -- > http://mail.python.org/mailman/listinfo/python-list > > > From rossberg at ps.uni-sb.de Fri Jun 23 16:02:19 2006 From: rossberg at ps.uni-sb.de (rossberg at ps.uni-sb.de) Date: 23 Jun 2006 13:02:19 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: <1151086320.564736.272500@y41g2000cwy.googlegroups.com> References: <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150908952.804184.218990@r2g2000cwb.googlegroups.com> <1150991074.705803.211570@m73g2000cwd.googlegroups.com> <1151083239.829296.33030@i40g2000cwc.googlegroups.com> <1151083931.162325.268050@g10g2000cwb.googlegroups.com> <1151086320.564736.272500@y41g2000cwy.googlegroups.com> Message-ID: <1151092939.711328.280740@p79g2000cwp.googlegroups.com> Rob Thorpe write: > > > > Take one of these languages. You have a variable that is supposed to > > store functions from int to int. Can you test that a given function > > meets this requirement? > > The answer is no for python and perl AFAIK. Also no for lisp _aux > naturelle_ (you can do it by modifying lisp though of-course, I believe > you can make it entirely statically typed if you want). > > But the analogous criticism could be made of statically typed > languages. > Can I make a type in C that can only have values between 1 and 10? > How about a variable that can only hold odd numbers, or, to make it > more difficult, say fibonacci numbers? Fair point. However, there are in fact static type systems powerful enough to express all of this and more (whether they are convenient enough in practice is a different matter). On the other hand, AFAICS, it is principally impossible to express the above property on functions with tags or any other purely dynamic mechanism. > The cases can be far from trivial. In lisp a type specifier can mean > something like "argument must be a 10x10 matrix with top corner element > larger than 35" You can also, for example, easily make predicates that > tell if a value is odd, or a fibonacci number. Now, these are yet another beast. They are not tags, they are user-defined predicates. I would not call them types either, but that's an equally pointless battle. :-) - Andreas From rpdooling at gmail.com Tue Jun 20 09:25:50 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 20 Jun 2006 06:25:50 -0700 Subject: Newbie Question References: <1150750938.973049.114780@y41g2000cwy.googlegroups.com> <129e55eahc35f00@corp.supernews.com> <1150753085.332654.283270@f6g2000cwb.googlegroups.com> <1150767309.831092.188530@h76g2000cwa.googlegroups.com> <1150767801.754519.165440@y41g2000cwy.googlegroups.com> <1150770698.928563.55530@y41g2000cwy.googlegroups.com> Message-ID: <1150809950.179455.171880@g10g2000cwb.googlegroups.com> >>> FWIW, I'm pretty sure the example of BartleByScrivener >>> didn't entail a new read each time but that it was written >>> for readabilityt purposes only of the "print what you want" idea... ;-) Yes, but now it's becoming one of those "Guess what I'm thinking. Or guess what I'm trying to do." I leave the op in your generous, capable hands. rd From dickey at saltmine.radix.net Thu Jun 22 08:41:51 2006 From: dickey at saltmine.radix.net (Thomas Dickey) Date: Thu, 22 Jun 2006 12:41:51 -0000 Subject: need all python dialog equivalent References: <1150872252.418400.13070@i40g2000cwc.googlegroups.com> Message-ID: <129l40ffu3fsn8a@corp.supernews.com> Eric S. Johansson wrote: > hdante at gmail.com wrote: >> dialog binary is 110 KB. Won't it fit ? > missing library. I have ncurses and newt and dialog seems to require > something called ncursesw. I've been trying to find the Python newt "seems to require" if you're installing some package. dialog builds/works against either ncurses/ncursesw -- Thomas E. Dickey http://invisible-island.net ftp://invisible-island.net From a at tempinbox.com Fri Jun 30 20:29:57 2006 From: a at tempinbox.com (a) Date: 30 Jun 2006 17:29:57 -0700 Subject: list comprehension In-Reply-To: <1151602493.629010.269360@i40g2000cwc.googlegroups.com> References: <1151600332.552024.119990@y41g2000cwy.googlegroups.com> <1151602493.629010.269360@i40g2000cwc.googlegroups.com> Message-ID: <1151713797.748621.294120@i40g2000cwc.googlegroups.com> hi simon thanks for your reply what if i want to do this feed_list=[] feed_id=[] for ix in feeds_list_select: global feeds_list global feeds_id feeds_list.append(ix.url) feeds_id.append(ix.id) ie not one variable but more variables thanks Simon Forman wrote: > a wrote: > > can someone tell me how to use them > > thanks > > basically, a list comprehension is just like a for loop, if you wrote > it out the "long way" it would be something like this: > > results = [] > for var in some_iterable: > if some condition: > results.append(some expression) > > > The list comprehension version: > > results = [some expression for var in some_iterable if some condition] > > > There's more to it, but that's the basic idea. > > Hope this helps, > ~Simon From duncan.booth at invalid.invalid Fri Jun 9 13:42:09 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 9 Jun 2006 17:42:09 GMT Subject: CONSTRUCT - Python's way of Ruby's "alias_method" References: Message-ID: Ilias Lazaridis wrote: >> #patch_service.py >> from toto import service >> >> def my_impl(self, *args) : >> old_result = self._old_method(*args) >> # ... >> return new_result >> >> if not hasattr(service, '_old_method') : >> service._old_method = service.method >> service.method = my_impl >> >> once this file is imported, all future calls to "method" of service >> instances will use my_impl. > > Ok, just a small problem when a _function_ is to be hooked. > > Looking a the code in the debugger shows that the function "syncdb" is > correctly overridden. But when the code returns, "syncdb" has again > it's original value. > > Can I import "syncdb" by reference instead by value, thus the change > 'survives'? The difference is that Maric imported the module. To make the change affect the original model you have to access the function as an attribute of its module, not by importing the function from the module. > > #---------------------------------------------------------------------- > -------- > > #syncdb_hook.py > > from django.rework.evolve import evolvedb > from django.core.management import syncdb from django.core import management > > def syncdb_new(*args) : > evolvedb() > syncdb_result = syncdb_old(*args) > return syncdb_result > > if syncdb != syncdb_new: > syncdb_old = syncdb > syncdb = syncdb_new > if management.syncdb != syncdb_new: syncdb_old = management.syncdb management.syncdb = syncdb_new From alikakakhel at yahoo.com Sat Jun 3 20:46:49 2006 From: alikakakhel at yahoo.com (greenflame) Date: 3 Jun 2006 17:46:49 -0700 Subject: reordering elements of a list Message-ID: <1149382009.640607.217470@y43g2000cwc.googlegroups.com> I am trying to reorder elements of a list and I am stuck as to what might be the best way to approach this. I have a (main) list of elements and another (ordering) list (which is may shorter, but not longer than the main list) which contains the order in which I want the elements of the main list but only as far along as the length of the ordering list. This may be confusing so I will try to give an example. Suppose the main list is: mainlist = list('qwertyuiop') Suppose the ordering list is: orderinglist = [3, 4, 2, 1] Then I am looking for a function that will take mainlist and orderinglist as arguments and return the following list: ['e', 'r', 'w', 'q', 't', 'y', 'u', 'i', 'o', 'p'] Also by the way the main list is always going to be a list of strings and the ordering list will be a list of numbers. Also the largest number in orderinglist will always be equal to the length of orderinglist. I hope this makes any sense. Thanks for your help. From marc.t.davies at gmail.com Mon Jun 12 09:21:17 2006 From: marc.t.davies at gmail.com (MTD) Date: 12 Jun 2006 06:21:17 -0700 Subject: Searching and manipulating lists of tuples In-Reply-To: <1150118110.412882.159240@f14g2000cwb.googlegroups.com> References: <1150117632.693617.45310@c74g2000cwc.googlegroups.com> <1150118110.412882.159240@f14g2000cwb.googlegroups.com> Message-ID: <1150118477.447521.234830@u72g2000cwu.googlegroups.com> > Yes, use the proper tool for the job. Tuples are immutable (they are > read-only once created). Instead use a dictionary. They key would be > your string, the value would be the count. Wow, I really should have thought of that! Thanks. From runlevelten at gmail.com Thu Jun 22 13:18:19 2006 From: runlevelten at gmail.com (Ten) Date: Thu, 22 Jun 2006 18:18:19 +0100 Subject: better Python IDE? Mimics Maya's script editor? In-Reply-To: <1149810048.765664.107820@i40g2000cwc.googlegroups.com> References: <1149810048.765664.107820@i40g2000cwc.googlegroups.com> Message-ID: <200606221818.20164.runlevelten@gmail.com> On Friday 09 June 2006 00:40, warpcat wrote: > I've been scripting in Maya, via mel for years now. Recently learning > to Python, love it. Thing that's driving me nuts it the IDE. I'm > using PythonWin right now and trying to find something better, mainly > with this functionality: > > In Maya's mel script editor window, it's split into two sections. > Bottom window you can enter commands (where your script lives), top > window gives results. The thing I'm really used to is highlighting X# > of lines in the bottom window (little snippits from my script), and > executing that selection, with instant feedback of the results on top. > This really speeds my workflow. > It seems completely missing (so far) in Python's IDE. I have to copy > and paste from a script to the ide window to execute and see the > results, or I have to make a bunch of "buffer scripts" with just the > code snippetsI want to test in. Seems *really* clunky. > > Does anyone know of a scripting enviroment for Python that mimics what > Maya's script editor has? Much appreciated. It may not be much of an answer as many people don't want to learn emacs (or vi for that matter), but emacs does this, specifically the separate buffers and the ability to highlight and execute parts of your code to test it. If you get into emacs, it's worth the time invested. The learning curve's alleged to be steep, but it isn't that bad, I use it and I'm as dumb as a stump. It's a very good IDE for everyday use. :-) Good luck, Ten -- There are 10 types of people in this world, those who understand binary, and those who don't. From luismgz at gmail.com Mon Jun 19 10:49:35 2006 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 19 Jun 2006 07:49:35 -0700 Subject: wxPython GUI designer In-Reply-To: <1150661348.837969.46870@r2g2000cwb.googlegroups.com> References: <1150661348.837969.46870@r2g2000cwb.googlegroups.com> Message-ID: <1150728575.495207.53590@f6g2000cwb.googlegroups.com> diffuser78 at gmail.com wrote: > I am newbie learning wxPython. I tried using GUI designer called > wxGlade. When it generated code I couldnt get the same level of > flexibility as writing the code by oneself. > > Any view on what you think about using GUI designer tools. > > Every help is appreciated. Try PythonCard. It's based on wxPython, and it's more higher level than Boa. Very simple and very easy to learn and use. From aleax at mac.com Sun Jun 18 01:33:00 2006 From: aleax at mac.com (Alex Martelli) Date: Sat, 17 Jun 2006 22:33:00 -0700 Subject: any subway experiences References: <1150533811.911621.112430@y41g2000cwy.googlegroups.com> Message-ID: <1hh3l96.1b3bcp3kpts70N%aleax@mac.com> a wrote: > thanks for reading Yah, I got a sandwich there once, it was very large but not all that good... Alex From fredrik at pythonware.com Thu Jun 8 15:47:56 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 08 Jun 2006 21:47:56 +0200 Subject: follow-up to FieldStorage In-Reply-To: <44886462$0$10267$636a55ce@news.free.fr> References: <4484b428$0$29635$636a55ce@news.free.fr> <44886462$0$10267$636a55ce@news.free.fr> Message-ID: bruno at modulix wrote: > FWIW, reading the source is not even needed to know this: >>>> import cgi >>>> dir(cgi.FieldStorage) not to mention: >>> help(cgi.FieldStorage) Help on class FieldStorage in module cgi: class FieldStorage | Store a sequence of fields, reading multipart/form-data. | | This class provides naming, typing, files stored on disk, and | more. At the top level, it is accessible like a dictionary, whose | keys are the field names. (Note: None can occur as a field name.) (followed by a detailed description of the field objects, and descriptions of all methods on the dictionary-list object). From danmcleran at yahoo.com Wed Jun 21 10:07:48 2006 From: danmcleran at yahoo.com (danmcleran at yahoo.com) Date: 21 Jun 2006 07:07:48 -0700 Subject: Psyco performance In-Reply-To: References: <1150819763.818687.114360@y41g2000cwy.googlegroups.com> <44981e4c$0$29812$626a54ce@news.free.fr> <1150839749.939196.142440@r2g2000cwb.googlegroups.com> Message-ID: <1150898868.763472.234840@b68g2000cwa.googlegroups.com> > > > Place all the code in a function. Even without psyco you might get > > > somewhat better performances then. And I doubt psyco can optimise code > > > that isn't in a function anyway. Another thing I wasn't considering is that the first call with psyco enabled might be slower. The 2nd time the psyco-compiled function is called is where the speed improvement may be present. With the code at the bottom, I get these results: without psyco = 0.000421282593179 first call with psyco = 0.000902349320933 with psyco = 5.30793718196e-005 first call with psyco = 114.190981432 % slower 2nd call with psyco = 87.400530504 % faster import time import psyco def test(l): result = 0 for item in l: result += item return result l = list(range(0, 1000)) t1 = time.clock() l2 = test(l) t2 = time.clock() no_psyco = t2 - t1 psyco.log() psyco.bind(test) t1 = time.clock() l2 = test(l) t2 = time.clock() first_call_with_psyco = t2 - t1 t1 = time.clock() l2 = test(l) t2 = time.clock() with_psyco = t2 - t1 print 'without psyco = ',no_psyco print 'first call with psyco = ',first_call_with_psyco print 'with psyco = ',with_psyco first_delta = ((no_psyco - first_call_with_psyco)/no_psyco) * 100 delta = ((no_psyco - with_psyco)/no_psyco) * 100 if(first_delta > 0): result = 'faster' else: result = 'slower' print 'first call with psyco = ',abs(first_delta),'% ',result if(delta > 0): result = 'faster' else: result = 'slower' print '2nd call with psyco = ',abs(delta),'% ',result From pipedreamergrey at gmail.com Tue Jun 6 08:18:05 2006 From: pipedreamergrey at gmail.com (PipedreamerGrey) Date: 6 Jun 2006 05:18:05 -0700 Subject: Expanding Search to Subfolders In-Reply-To: References: <1149526866.681348.273590@c74g2000cwc.googlegroups.com> Message-ID: <1149596285.027303.160510@u72g2000cwu.googlegroups.com> Thanks, that was a big help. It worked fine once I removed > os.chdir("C:\\Python23\\programs\\Magazine\\SamplesE") and changed "for file, st in DirectoryWalker("."):" to "for file in DirectoryWalker("."):" (removing the "st") From rpw3 at rpw3.org Wed Jun 21 23:03:16 2006 From: rpw3 at rpw3.org (Rob Warnock) Date: Wed, 21 Jun 2006 22:03:16 -0500 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150892256.591282.43880@u72g2000cwu.googlegroups.com> Message-ID: Rob Thorpe wrote: +--------------- | > So, will y'all just switch from using "dynamically typed" to "latently | > typed", and stop talking about any real programs in real programming | > languages as being "untyped" or "type-free", unless you really are | > talking about situations in which human reasoning doesn't come into play? | | I agree with most of what you say except regarding "untyped". | | In machine language or most assembly the type of a variable is | something held only in the mind of the programmer writing it, and | nowhere else. In latently typed languages though the programmer can | ask what they type of a particular value is. There is a vast | difference to writing code in the latter kind of language to writing | code in assembly. | | I would suggest that at least assembly should be referred to as | "untyped". +--------------- Another language which has *neither* latent ("dynamic") nor manifest ("static") types is (was?) BLISS[1], in which, like assembler, variables are "just" addresses[2], and values are "just" a machine word of bits. However, while in BLISS neither variable nor values are typed, operators *are* "typed"; that is, each operator specifies how it will treat its input machine word(s) and how the machine word(s) of bits it produces should be interpreted. So "+" is (mod 2^wordsize) [unsigned?] integer addition, and "FADR" is floating-point addition with rounding (as opposed to "FADD", which truncates), and so on. So this (legal but non-sensical!) BLISS: x := .y FMPR (.x - 13); would, in C, have to be written roughly like this: ((void*)x) = (void*)((float)(*(void*)y) * (float)((int)(*(void*)x) - 13)); On the PDP-10, at least, both of them would generate this assembler code: move t1, x subi t1, 13 fmpr t1, y movem t1, x So is BLISS "typed" or not? And if so, what is that kind of typing called? -Rob [1] "Basic Language for the Implementation of Systems Software", see . Created at CMU, added-to by DEC, used by CMU, DEC, and a few others for in the 70's-80's. [2] Well, approximately. A BLISS variable is, conceptually at least, really a "byte-pointer" -- a triple of a word address, a byte-size, and a byte-position-within-word -- even on target architectures other than the DEC PDP-10 [which had hardware byte-pointer types]. The compiler (even on the PDP-10) optimizes away LDB/DPB accesses into natively-addressible load/store sizes, when possible. ----- Rob Warnock 627 26th Avenue San Mateo, CA 94403 (650)572-2607 From find at my.address.elsewhere Tue Jun 20 14:28:24 2006 From: find at my.address.elsewhere (Matthias Blume) Date: Tue, 20 Jun 2006 13:28:24 -0500 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <1150809118.677124.142230@u72g2000cwu.googlegroups.com> <1150815461.210286.53120@r2g2000cwb.googlegroups.com> <1150822150.701434.296460@u72g2000cwu.googlegroups.com> Message-ID: "Rob Thorpe" writes: > I think we're discussing this at cross-purposes. In a language like C > or another statically typed language there is no information passed > with values indicating their type. You seem to be confusing "does not have a type" with "no type information is passed at runtime". > Have a look in a C compiler if you don't believe me. Believe me, I have. > No it doesn't. Casting reinterprets a value of one type as a value of > another type. > There is a difference. If I cast an unsigned integer 2000000000 to a > signed integer in C on the machine I'm using then the result I will get > will not make any sense. Which result are you getting? What does it mean to "make sense"? From cbfalconer at yahoo.com Tue Jun 13 14:03:57 2006 From: cbfalconer at yahoo.com (CBFalconer) Date: Tue, 13 Jun 2006 14:03:57 -0400 Subject: Earthquake and Tornado Forecasting Programs June 13, 2006 References: <448eef76$0$30713$ec3e2dad@news.usenetmonster.com> Message-ID: <448EFE0D.3B2D968B@yahoo.com> Frank Silvermann wrote: > > [snip] > I look forward to a day when meteorology has more to do with precise > models than models, although I'm all for Russian-style delivery of such > data. I forecast that a lot of people will be surprised by the weather > today, as they are categorical idiots, as is the OP. frank Oh for a newsreader that can eliminate all such ugly excessively cross-posted articles lacking follow-ups. PLONK thread is the only remaining answer. -- Some informative links: news:news.announce.newusers http://www.geocities.com/nnqweb/ http://www.catb.org/~esr/faqs/smart-questions.html http://www.caliburn.nl/topposting.html http://www.netmeister.org/news/learn2quote.html From pc at p-cos.net Tue Jun 27 17:02:11 2006 From: pc at p-cos.net (Pascal Costanza) Date: Tue, 27 Jun 2006 23:02:11 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <7zy7vt1mz2.fsf@app-3.diku.dk> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <1151384511.223582.305760@m73g2000cwd.googlegroups.com> Message-ID: <4gdkmiF1ldalhU3@individual.net> David Hopwood wrote: > Marshall wrote: >> The real question is, are there some programs that we >> can't write *at all* in a statically typed language, because >> they'll *never* be typable? > > In a statically typed language that has a "dynamic" type, all > dynamically typed programs are straightforwardly expressible. What about programs where the types change at runtime? Pascal -- 3rd European Lisp Workshop July 3 - Nantes, France - co-located with ECOOP 2006 http://lisp-ecoop06.bknr.net/ From antroy at gmail.com Thu Jun 15 13:58:02 2006 From: antroy at gmail.com (Ant) Date: 15 Jun 2006 10:58:02 -0700 Subject: urllib2 problem with ports. Message-ID: <1150394282.406329.177960@c74g2000cwc.googlegroups.com> Hi all, I have just moved to a new machine, and so have installed the latest version of Python (2.4.3 - previously I believe I was running 2.4.2). Unfortunately this seems to have broken urllib2... An app I wrote for testing our web application makes heavy use of urllib2 against the localhost, and I am getting the following problem (minimal code sample): #/usr/bin/python import urllib2 urllib2.urlopen("http://localhost:8080/") This gives the output (Stack trace snipped - can post if required): urllib2.HTTPError: HTTP Error 502: Proxy Error ( The Uniform Resource Locator (U RL) does not use a recognized protocol. Either the protocol is not supported or the request was not typed correctly. Confirm that a valid protocol is in use (fo r example, HTTP for a Web request). ) This I believe is a problem with the addition of a non-default port. Replace the url with "http://google.com" for example, and all is well. Any ideas for workarounds? Or do I roll back to 2.4.2? From diffuser78 at gmail.com Tue Jun 20 01:30:29 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 19 Jun 2006 22:30:29 -0700 Subject: OS specific command in Python Message-ID: <1150781429.090359.148560@c74g2000cwc.googlegroups.com> I want to write a python program and call OS specific commands in it. So basically, instead of typing in on the command line argument I want to have it in a python program and let it do the action. for example. in my program I would want to call the ssh feature like one does on the command line ssh Admin at 192.168.2.10 .....etc How can I do this easily ? Every help is appreciated. Thanks From eoinrogers at gmail.com Mon Jun 5 15:39:56 2006 From: eoinrogers at gmail.com (Byte) Date: 5 Jun 2006 12:39:56 -0700 Subject: GUI Program Error Message-ID: <1149536396.375285.319390@y43g2000cwc.googlegroups.com> Hi, I'm using the "Learning to Program" GUI tutorial on http://www.freenetpages.co.uk/hp/alan.gauld/ and am trying to write my first GUI. However, the code the tutorial gives for starting by making a window: import Tkinter top = Tkinter.Tk() dir(top) Does not work. The Python interpreter does not complain about anything, but the window the tutorial promises will apperar will not. I'm using Python 2.4.2 and the Eric 3.7.0 IDE on Ubuntu 5.10. Anybody know what to do? -- /usr/bin/byte From python.list at tim.thechases.com Thu Jun 1 13:08:27 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 01 Jun 2006 12:08:27 -0500 Subject: Finding web host headers In-Reply-To: <1149179050.315297.79470@j55g2000cwa.googlegroups.com> References: <1149179050.315297.79470@j55g2000cwa.googlegroups.com> Message-ID: <447F1F0B.6000600@tim.thechases.com> > Is there any way to fetch a website's host/version headers using > Python? >>> import httplib >>> conn = httplib.HTTPConnection("docs.python.org") >>> conn.connect() >>> conn.request("HEAD", "/") >>> response = dict([(k.lower(), v) for k,v in conn.getresponse()]) >>> conn.close() >>> server = response["server"] >>> print server Apache/2.0.54 (Debian GNU/Linux) DAV/2 SVN/1.1.4 mod_python/3.1.3 Python/2.3.5 mod_ssl/2.0.54 OpenSSL/0.9.7e I've found a bit of discrepancy with regards to the case of the "server" portion, so the above code just normalizes it to lowercase and then shoves it in a dictionary. You can then do as you please with the contents of the "server" variable. It's theoretically possible that the server can return differing headers based on the URL you request or its method. You'll have to adjust the request() call for the method (GET/HEAD/POST, etc) and for the resource you want (in this case, just "/") -tkc From scott.daniels at acm.org Thu Jun 8 14:59:04 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Thu, 08 Jun 2006 11:59:04 -0700 Subject: Newbie question about updating multiple objects ... In-Reply-To: <1149753137.498806.314640@c74g2000cwc.googlegroups.com> References: <1149753137.498806.314640@c74g2000cwc.googlegroups.com> Message-ID: <44886edf$1@nntp0.pdx.net> fivenastydisco at hotmail.com wrote: > > Any ideas? I've run out of options. Any help would be very *gratefully* > appreciatedd!! Your time-step is too small. Simply try: dt = .5, and you should see (slow) motion. Note, I'd update the position, then wrap it, rather than wrapping and then updating. -- --Scott David Daniels scott.daniels at acm.org From robert.thorpe at antenova.com Fri Jun 23 05:08:50 2006 From: robert.thorpe at antenova.com (Rob Thorpe) Date: 23 Jun 2006 02:08:50 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150908952.804184.218990@r2g2000cwb.googlegroups.com> <1150991074.705803.211570@m73g2000cwd.googlegroups.com> Message-ID: <1151053730.887911.256200@u72g2000cwu.googlegroups.com> David Hopwood wrote: > Rob Thorpe wrote: > > David Hopwood wrote: > > > >>As far as I can tell, the people who advocate using "typed" and "untyped" > >>in this way are people who just want to be able to discuss all languages in > >>a unified terminological framework, and many of them are specifically not > >>advocates of statically typed languages. > > > > Its easy to create a reasonable framework. My earlier posts show simple > > ways of looking at it that could be further refined, I'm sure there are > > others who have already done this. > > > > The real objection to this was that latently/dynamically typed > > languages have a place in it. > > You seem to very keen to attribute motives to people that are not apparent > from what they have said. The term "dynamically typed" is well used and understood. The term untyped is generally associated with languages that as you put it "have no memory safety", it is a pejorative term. "Latently typed" is not well used unfortunately, but more descriptive. Most of the arguments above describe a static type system then follow by saying that this is what "type system" should mean, and finishing by saying everything else should be considered untyped. This seems to me to be an effort to associate dynamically typed languages with this perjorative term. > > But some of the advocates of statically > > typed languages wish to lump these languages together with assembly > > language a "untyped" in an attempt to label them as unsafe. > > A common term for languages which have defined behaviour at run-time is > "memory safe". For example, "Smalltalk is untyped and memory safe." > That's not too objectionable, is it? Memory safety isn't the whole point, it's only half of it. Typing itself is the point. Regardless of memory safety if you do a calculation in a latently typed langauge, you can find the type of the resulting object. From tommy04 at gmail.com Tue Jun 6 02:41:12 2006 From: tommy04 at gmail.com (Tommy B) Date: 5 Jun 2006 23:41:12 -0700 Subject: Writing to a certain line? Message-ID: <1149576072.168354.14470@f6g2000cwb.googlegroups.com> I was wondering if there was a way to take a txt file and, while keeping most of it, replace only one line. See, I'd have a file like: Tommy 555 Bob 62 Joe 529 And I'd want to set it to be: Tommy 555 Bob 66 Joe 529 Is there any easy way to do this? From ilias at lazaridis.com Wed Jun 7 08:33:15 2006 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Wed, 07 Jun 2006 15:33:15 +0300 Subject: CENSORSHIP - Django Project (Schema Evolution Support) In-Reply-To: <1149681320.550163.277030@i40g2000cwc.googlegroups.com> References: <4486B9FB.9030804@lazaridis.com> <1149681320.550163.277030@i40g2000cwc.googlegroups.com> Message-ID: Simon Willison wrote: > Ilias Lazaridis wrote: >> [posted publicly to comp.lang.python, with email notification to 6 >> recipients relevant to the topic] >> >> I have implemented a simple schema evolution support for django, due to >> a need for a personal project. Additionally, I've provided an Audit: >> >> http://case.lazaridis.com/wiki/DjangoAudit >> >> As a result, I was censored ('banned' from the development list) > > Please see this message for background: > > http://groups.google.com/group/django-users/msg/5a96eabf75f2b9c7 what 'background'? > To summarise, it was felt that Ilias was deliberately trolling the > mailing list. It was 'felt', by whom? If anoyone has 'deliberately trolled', that it was the team/community/leadership. This is simply unbelievable that I am attacked on a _personal_ level, and additionally _removed_ from the discussions groups. > No further explanation seems necessary. Please do yourself a favour and read the provided thread fully: http://groups.google.com/group/django-users/msg/5a96eabf75f2b9c7 If you are honest, than you have to admit that it is not me who's 'trolling'. . -- http://lazaridis.com From gh at gregor-horvath.com Tue Jun 6 09:15:18 2006 From: gh at gregor-horvath.com (Gregor Horvath) Date: Tue, 06 Jun 2006 15:15:18 +0200 Subject: Interpretation of UnhandledException.rpt Message-ID: Hi, in a windows server python application I receive once a week suddenly and not reproducible the following error. UnhandledException.rpt file: //=========================================================================================================== Exception code: C0000090 FLT_INVALID_OPERATION Program: C:\Python24\python.exe Date: 6/ 6/2006 14:36:13 (MM/DD/YYYY HH:MM:SS) Fault address: 00E9ADF0 01:00019DF0 C:\in4\inforCOM\Prod\InforDbCOM_Server.dll Registers: EAX:012BDAA0 EBX:012ADF50 ECX:0000B0D6 EDX:012BDAA0 ESI:012ADF50 EDI:0096A8C0 CS:EIP:001B:00DC4DC7 SS:ESP:0023:0021EF4C EBP:02E91EF0 DS:0023 ES:0023 FS:003B GS:0000 Flags:00010212 Call stack: Address Frame 00DC4DC7 02E91EF0 0001:00003DC7 C:\Python24\DLLs\psycopg.pyd 2D36302D 36303032 *** Exception while writing report! *** Do I read this correct, that the problem is in the InforDbCOM_Server.dll? The call stack mentions the psycopg.pyd, can it be related to this problem? How can I track down this problem? -- Servus, Gregor From sigzero at gmail.com Sat Jun 24 09:03:12 2006 From: sigzero at gmail.com (Robert Hicks) Date: 24 Jun 2006 06:03:12 -0700 Subject: sum fonction in gadfly In-Reply-To: <449d253d$1@nntp0.pdx.net> References: <1151137825.177814.217180@u72g2000cwu.googlegroups.com> <449d253d$1@nntp0.pdx.net> Message-ID: <1151154192.030596.223840@r2g2000cwb.googlegroups.com> I haven't been keeping up. Is Gadfly still in development? From martin.wiechert at gmx.de Wed Jun 14 09:41:05 2006 From: martin.wiechert at gmx.de (Martin Wiechert) Date: Wed, 14 Jun 2006 15:41:05 +0200 Subject: Where is documentation for += In-Reply-To: <1150292372.337690.25290@y41g2000cwy.googlegroups.com> References: <1150292372.337690.25290@y41g2000cwy.googlegroups.com> Message-ID: <200606141541.05401.martin.wiechert@gmx.de> http://docs.python.org/ref/augassign.html On Wednesday 14 June 2006 15:39, Marco Wahl wrote: > Hello, > > by accident I found that += exists in python. > E.g. > > >>> a = 0 > >>> a += 42 > >>> a > > 42 > > >>> a += 0.42 > >>> a > > 42.420000000000002 > > > But I can't find any documentation for +=. > Any hints? > > > Best wishes From David.Squire at no.spam.from.here.au Tue Jun 20 11:51:43 2006 From: David.Squire at no.spam.from.here.au (David Squire) Date: Tue, 20 Jun 2006 16:51:43 +0100 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <1150809118.677124.142230@u72g2000cwu.googlegroups.com> Message-ID: Matthias Blume wrote: > David Squire writes: > >> Andreas Rossberg wrote: >>> Rob Thorpe wrote: >>>>>> No, that isn't what I said. What I said was: >>>>>> "A language is latently typed if a value has a property - called it's >>>>>> type - attached to it, and given it's type it can only represent values >>>>>> defined by a certain class." >>>>> "it [= a value] [...] can [...] represent values"? >>>> ??? >>> I just quoted, in condensed form, what you said above: namely, that >>> a value represents values - which I find a strange and circular >>> definition. >>> >> But you left out the most significant part: "given it's type it can >> only represent values *defined by a certain class*" (my emphasis). In >> C-ish notation: >> >> unsigned int x; >> >> means that x can only represent elements that are integers elements of >> the set (class) of values [0, MAX_INT]. Negative numbers and >> non-integer numbers are excluded, as are all sorts of other things. > > This x is not a value. It is a name of a memory location. > >> You over-condensed. > > Andreas condensed correctly. I should have stayed out of this. I had not realised that it had degenerated to point-scoring off someone typing "value" when it is clear from context that he meant "variable". Bye. DS From find at my.address.elsewhere Mon Jun 19 14:24:47 2006 From: find at my.address.elsewhere (Matthias Blume) Date: Mon, 19 Jun 2006 13:24:47 -0500 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> Message-ID: "Rob Thorpe" writes: > I don't think dynamic typing is that nebulous. I remember this being > discussed elsewhere some time ago, I'll post the same reply I did then > .. > > > A language is statically typed if a variable has a property - called > it's type - attached to it, and given it's type it can only represent > values defined by a certain class. By this definition, all languages are statically typed (by making that "certain class" the set of all values). Moreover, this "definition", when read the way you probably wanted it to be read, requires some considerable stretch to accommodate existing static type systems such as F_\omega. Perhaps better: A language is statically typed if its definition includes (or ever better: is based on) a static type system, i.e., a static semantics with typing judgments derivable by typing rules. Usually typing judgmets associate program phrases ("expressions") with types given a typing environment. > A language is latently typed if a value has a property - called it's > type - attached to it, and given it's type it can only represent values > defined by a certain class. This "definition" makes little sense. Any given value can obviously only represent one value: itself. "Dynamic types" are nothing more than sets of values, often given by computable predicates. > Untyped and type-free mean something else: they mean no type checking > is done. Look up "untyped lambda calculus". From fredrik at pythonware.com Thu Jun 8 07:51:31 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 08 Jun 2006 13:51:31 +0200 Subject: language-x-isms In-Reply-To: <1149764092.806419.322130@i39g2000cwa.googlegroups.com> References: <1149753206.451066.120960@h76g2000cwa.googlegroups.com> <1149759486.695563.110640@g10g2000cwb.googlegroups.com> <1149760633.796809.166430@h76g2000cwa.googlegroups.com> <1149762625.346302.135220@y43g2000cwc.googlegroups.com> <1149764092.806419.322130@i39g2000cwa.googlegroups.com> Message-ID: Alan Kennedy wrote: > We still don't get anything that sheds light on how the code I posted > is deficient. who said that? > Why can't you just say "I made a mistake, I thought your code replaced > the builtin enumerate, but it doesnt"? I can read python code quite well, thank you. the point here (which was made in the context of this thread) is that the "unpythonic" solution isn't all that bad, especially if you prefer writing code that runs well on more than just the latest platforms. your fallback solution doesn't do that; it punishes old platforms, and doesn't even perform as well as an "unpythonic" solution on recent ones. that's not much of a problem for use cases where performance isn't all that important, but it's something that should be kept in mind. From andre.roberge at gmail.com Fri Jun 16 08:58:49 2006 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: 16 Jun 2006 05:58:49 -0700 Subject: Python is fun (useless social thread) ;-) In-Reply-To: References: Message-ID: <1150462729.906226.38230@u72g2000cwu.googlegroups.com> John Salerno wrote: > So out of curiosity, I'm just wondering how everyone else came to learn > it. If you feel like responding, I'll ask my questions for easy quoting: > > Did you have to learn it for a job? No. My job is purely administrative; I have absolutely no need to do any programming. I had done a *small* amount of programming (fortran, C) while studying Physics and wrote a few simple Java applets while teaching Physics. > > Or did you just like what you saw and decided to learn it for fun? More or less. In the summer of 2004 I felt I needed a hobby. I also thought I should introduce my kids to something useful about computers. I decided to combine both goals. I started writing an html tutorial for my kids and, while surfing the net for helpful resources, saw a few independent references to Python. Curious, I downloaded it just to see what it was like and, after trying a few things, I decided to forget about the html tutorial and proceeded to write one on Python for my kids, following more or less a traditional (boring) approach. > Also, how did you go about learning it? (i.e., like I described above, I > started with the main stuff then moved on to the different available > frameworks) Having taught Physics for a number of years, I realised that the best way to learn something is try to prepare to teach it to someone else. This is what I was trying to do for my kids. But, after spending a little over a month with Python, I stumbled upon Guido van Robot which inspired me to change course again and I started working on RUR-PLE. I had some ideas as to what RUR-PLE should look like, and just started building from scratch, first implementing the logic (no GUI) and then learning what I needed (like wxPython) as I went along. Being a newbie sometimes made it difficult to make things work the way I thought they should. I'm sure professional programmers/experts would be horrified if they were to look at the details of the code I wrote. My excuse: it works ... why break it? ;-) > Was there any necessity in the specifics you learned, or did you just > dabble in something (e.g. wxPython) for fun? Driven by the final goal in mind... The whole adventure has been for fun! > Are there still some things you feel you need to learn or improve? *Lots*. At the moment, it is webserver stuff for another project (Crunchy Frog), again designed to make teaching/learning Python more fun. > Additional comments/complains here: :) Programming in Python is fantastic as a hobby... when I can find the time. Since I started 2 years ago, I have gone for a few weeks (and once for 4 months) at a time without doing any programming. However, it is always easy to get back at it. I don't think I'd be able to say that with other languages. I have found members of the Python community to be generally extremely helpful and generous of their time, in answering my silly questions. I sometimes wish I had a different job, one which required me to do programming using Python. Andr? From duncan.booth at invalid.invalid Fri Jun 23 07:46:54 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 23 Jun 2006 11:46:54 GMT Subject: * in Python References: <1151061836.557835.295820@p79g2000cwp.googlegroups.com> Message-ID: placid wrote: > Hi all, > > Can someone tell me what * in the following code means/does a Google > search didnt turn up anything as i dont know what the * is called > (related to Python and i dont think Python has pointers) > * is for variable number of positional arguments, ** is for variable keyword arguments. The syntax is symmetrical when defining functions and when calling them. See http://docs.python.org/ref/calls.html and http://docs.python.org/ref/function.html From dnew at san.rr.com Fri Jun 23 13:06:20 2006 From: dnew at san.rr.com (Darren New) Date: Fri, 23 Jun 2006 17:06:20 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: <1151081129.290382.297530@r2g2000cwb.googlegroups.com> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150902275.129780.50260@p79g2000cwp.googlegroups.com> <1150918629.818145.143220@y41g2000cwy.googlegroups.com> <4fv081F1jh4ifU1@individual.net> <1150967543.947096.72840@g10g2000cwb.googlegroups.com> <4fv84rF1kp06kU1@individual.net> <1150988625.527780.148710@c74g2000cwc.googlegroups.com> <4g22l7F1j8p4mU1@individual.net> <1151081129.290382.297530@r2g2000cwb.googlegroups.com> Message-ID: Marshall wrote: > I can't see how you'd call + on a and b if you think they might > not be numbers. Now substitute "<" for "+" and see if you can make the same argument. :-) -- Darren New / San Diego, CA, USA (PST) Native Americans used every part of the buffalo, including the wings. From diffuser78 at gmail.com Sun Jun 25 13:15:24 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 25 Jun 2006 10:15:24 -0700 Subject: Python taught in schools? In-Reply-To: <1151220913.406987.162420@u72g2000cwu.googlegroups.com> References: <1151220913.406987.162420@u72g2000cwu.googlegroups.com> Message-ID: <1151255724.452079.109330@y41g2000cwy.googlegroups.com> I replied to a wrong post. My bad.....I know for sure that there is some kinda Python Club at UCF Orlando. There is Prof called Michael Johnson who teaches Physics gives you an intro to Python. http://www.physics.ucf.edu/~mdj/MinimalPython.html Good Luck From ilias at lazaridis.com Wed Jun 7 08:18:47 2006 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Wed, 07 Jun 2006 15:18:47 +0300 Subject: CENSORSHIP - Django Project (Schema Evolution Support) In-Reply-To: <4ent10F1f9d3gU1@uni-berlin.de> References: <4486B9FB.9030804@lazaridis.com> <4ent10F1f9d3gU1@uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > http://en.wikipedia.org/wiki/Ilias_Lazaridis What has this "wikipedia" entry to do with the topic here? What is the credibility and value of the provided "wikipedia" entry? Let's review the editor's list: http://en.wikipedia.org/w/index.php?title=Ilias_Lazaridis&action=history "Ubernostrum" "Howdy. I'm James Bennett, a web developer[...]and then moved to Lawrence, Kansas where I now work for World Online, the online division of the Lawrence Journal-World and home of the Django web framework." http://en.wikipedia.org/wiki/User:Ubernostrum "Gldnspud" - no profile available - http://en.wikipedia.org/wiki/User:Gldnspud - Note to readers: Further links and explanations about my past evaluation work are publicized on my website: http://lazaridis.com/core/eval/index.html http://lazaridis.com/core/index.html Those evaluations are now closed, and I try to focus on personal projects, whilst contribution results back to other users in the open source way. - I try now to apply such "Requirements Compliancy Audits" in a more decent way: http://case.lazaridis.com/wiki For some reason, the Django Project Community and leadership has reacted extremely against my findings, writings and even code-level contributions. At this point I don't know why. But possibly I will do so shortly. - -- http://lazaridis.com From grante at visi.com Sat Jun 17 13:07:10 2006 From: grante at visi.com (Grant Edwards) Date: Sat, 17 Jun 2006 17:07:10 -0000 Subject: any subway experiences References: <1150533811.911621.112430@y41g2000cwy.googlegroups.com> <1150562110.126305.21830@h76g2000cwa.googlegroups.com> Message-ID: <1298dlus7hsc14a@corp.supernews.com> On 2006-06-17, mensanator at aol.com wrote: > > a wrote: >> thanks for reading > > Their bread is awful. At least they actually slice it now. Around here they used to just cut a shallow V-shaped notch in the top. -- Grant Edwards grante Yow! ... this must be what at it's like to be a COLLEGE visi.com GRADUATE!! From avelldiroll at yahoo.fr Wed Jun 21 17:48:14 2006 From: avelldiroll at yahoo.fr (Avell Diroll) Date: Wed, 21 Jun 2006 23:48:14 +0200 Subject: OS specific command in Python In-Reply-To: <1150899193.321218.235760@i40g2000cwc.googlegroups.com> References: <1150781429.090359.148560@c74g2000cwc.googlegroups.com> <44979b35$0$8390$626a54ce@news.free.fr> <1150823140.295590.307390@i40g2000cwc.googlegroups.com> <4498d973$0$25496$626a54ce@news.free.fr> <1150899193.321218.235760@i40g2000cwc.googlegroups.com> Message-ID: <4499BE9E.80408@yahoo.fr> diffuser78 at gmail.com wrote: (snip) > I have a linux box, from where I remotely execute all the commands. The > remote machine is windows machine. I installed an OpenSSH server for > windows to send the shutdown command. I setup the public keys in such a > way that I could login to SSH server without using password. > (snip : script that fits your first need) > > I was wondering how can I interact with an application . Since you > mentioned about subprocess module, I want a ability that my PYthon > script can actually interact with the windows box and launch and close > application there remotely. (snip) To clear up things a little, you _interact_ with the ssh process launched on your local machine from your python script. this ssh process _connect_ to an ssh server on your remote winbox. the ssh server then execute the requested shell command. So you are limited by what a windows shell script can do. I must warn you that I never used windows much and never thought about running a ssh server or even a serious shell session (can you even call that a shell ?) on a windows box, so I won't be of much help for the _interacting_ with windows process from the windows shell. The only suggestion I could make would be to write a python script to be executed on the remote machine that would be executed by the ssh server ... ####local_machine_script.py import os os.system('ssh Admin at IP_ADDRESS python remote_machine_script.py') ###remote_machine_script.py from subprocess import * p = Popen(['A_WIN32_COMMAND'], stdout=PIPE) (output, error) = p.communicate('INPUT_FOR_THE_WIN32_CMD') This is really a _bad_ way to proceed but it gives you a little more interaction. A better way to interact with the remote shell is to keep the ssh session interactive in the first place. To do that os.system is a 'no go' and using the subprocess module all the way won't be easy (if even possible). For an interactive ssh session you will need some non standard library modules. I know 2 modules that would help : pexpect and paramiko. Both may help but you will have to choose one or the other. pexpect pexpect gives you some control over a child process easing the way to pass argument, to get and test the output in order to choose the next input to send to the child process. you can find it here : http://pexpect.sourceforge.net/ The demo files contain some _great_ examples of how to use it with ssh paramiko paramiko implements the ssh2 protocol in python, that way you don't have to use a child process to connect to the remote ssh server. After establishing the connection you may open an ssh session or whatever you need from your local script. you can find it here : http://www.lag.net/paramiko/ Again the demo files contain some _great_ examples I would advise you to download both and to play with the demo files in order to choose which one you prefer using. If you are in a hurry, you should check pexpect first as one of the demo files is implementing nearly everything you want. Hope this helps -Avell From onurb at xiludom.gro Mon Jun 12 05:31:22 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Mon, 12 Jun 2006 11:31:22 +0200 Subject: Function to remove elements from a list not working In-Reply-To: References: Message-ID: <448d346b$0$20350$636a55ce@news.free.fr> Girish Sahani wrote: > Hi, > I am trying to convert a list of pairs (l4) to list l5 by removing those > pairs from l4 which are not present in a third list called pairList. > The following is a simplified part of the routine i have written. However > it does not give the correct output. Please help! > Its possible i have made a trivial mistke since i am a newbie. > > def getl5(): Please avoid this kind of names : it's both meaningless (what the ... is 'l5', I wonder ???) and confusing (is it 'l5' or '15' ?) FWIW, read this: http://mindprod.com/jgloss/unmain.html > l5 = [] > pairList = [[1,2],[3,4],[3,5],[3,6],[9,7],[8,9],[8,7],[7,9],[11,10]] >From a semantic POV, you should use tuples for pairs - not lists. > l4 = [[4,2],[4,7],[4,10],[4,12],[9,2],[9,7],[9,10],[9,12],[11,2],[11,7]] > for pair in l4: > if pair not in pairList: err... see below... > element.remove(l4) > l5.append(element) This is outside the for loop, so this would be executed only once (if the rest of the code was correct, of course...) > print "l5 is",l5 > You did not test this code, did you ? >>> getl5() Traceback (most recent call last): File "", line 1, in ? File "/usr/tmp/python-961l_S.py", line 7, in getl5 NameError: global name 'element' is not defined >>> The SimpleStupid(tm) way to do this is far more simple - at least if I understood your specifications: pairList = [(1,2),(3,4),(3,5),(3,6),(9,7),(8,9),(8,7),(7,9),(11,10)] l4 = [(4,2),(4,7),(4,10),(4,12),(9,2),(9,7),(9,10),(9,12),(11,2),(11,7)] l5 = [pair for pair in l4 if pair in pairList] print "l5 is : ", l5 Now this is not necessarily the most efficient solution... -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From zeusherm at gmail.com Sun Jun 25 18:50:45 2006 From: zeusherm at gmail.com (Harry) Date: 25 Jun 2006 15:50:45 -0700 Subject: Python question Message-ID: <1151275845.423382.294260@u72g2000cwu.googlegroups.com> Hi All, It is nice to join the python group. Can someone please help me with a python question? I have the following object which is like a list of tuples What command do I use to get the value corresponding to 'min'? This object seems to be non-indexable row= [('name', 'x1'), ('min', 15.449041129349528), ('max', 991.6337818245629), ('range', 976.18474069521335), ('mean', 496.82174193958127), ('stddev', 304.78275004920454), ('variance', 92892.524727555894), ('mode', '46.5818482111'), ('unique_count', '99'), ('count', 99.0), ('count_missing', 0.0), ('sum_weight', 99.0)] Thanks, Harry From grflanagan at yahoo.co.uk Thu Jun 1 06:37:10 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 1 Jun 2006 03:37:10 -0700 Subject: shuffling elements of a list References: <1149045499.212967.13120@f6g2000cwb.googlegroups.com> <1149147164.012044.66960@u72g2000cwu.googlegroups.com> Message-ID: <1149158230.815685.167850@i39g2000cwa.googlegroups.com> Peter Otten wrote: > Gerard Flanagan wrote: > > > Ben Finney wrote: > > >> pile_index = 0 > >> for card in deck: > >> piles[pile_index].append(card) > >> pile_index = (pile_index + 1) % numpiles > >> > > > > no need to maintain an index ;-) > > > > piles = [ list() for _ in range(n) ] > > for i, card in enumerate(deck): > > piles[i % numpiles].append(card) > > No need to maintain an index ;-) > > piles = [deck[start::numpiles] for start in range(numpiles)] I am humbled :-) Gerard From timothy.williams at nvl.army.mil Tue Jun 27 09:33:05 2006 From: timothy.williams at nvl.army.mil (timw.google) Date: 27 Jun 2006 06:33:05 -0700 Subject: using pydoc in an application Message-ID: <1151415185.842258.27440@c74g2000cwc.googlegroups.com> Hi all, I'm discovering pydoc, and it seems to me that this is a great way to have online documentation for my application. Are there any examples of using this in some kind of help menu in an application? I've tried to just bind pydoc.gui() to a menu item, but this just brings up the GUI for pydoc, and the user still needs to search for the module before the browser comes up, and when I quit serving pydoc.gui(), my application dies along with it. Also, I need to get out of python to use pydoc.gui again, or I get error: (98, 'Address already in use') I'm sure there's a better way to take advantage of this module and my docstrings to get some online help. I'm using Tkinter and Pmw, but maybe it's time to convert all this to wxWidgets? Thanks for any help. From girodt at gmail.com Thu Jun 22 14:15:55 2006 From: girodt at gmail.com (TG) Date: 22 Jun 2006 11:15:55 -0700 Subject: Numeric N-dimensional array initialization In-Reply-To: <1150999204.839644.179940@g10g2000cwb.googlegroups.com> References: <1150999204.839644.179940@g10g2000cwb.googlegroups.com> Message-ID: <1151000155.059823.256350@b68g2000cwa.googlegroups.com> I tried to use Numeric.fromfunction, but there seems to be a problem : the function called must have the right number of args (hint : the number of dimensions, which I don't know). So i tried to use a function like : def myfunc(*args, **kw): return 0 and then i get : >> Numeric.fromfunction(myfunc,(5,5)) 0 I'm a bit puzzled here From george.sakkis at gmail.com Tue Jun 20 17:41:44 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 20 Jun 2006 14:41:44 -0700 Subject: TEST IGNORE References: Message-ID: <1150839704.374556.88470@b68g2000cwa.googlegroups.com> David Hirschfield wrote: > Having email trouble... > Having bathroom trouble... can I help myself at your house entrance ? Didn't think so... From aleax at mac.com Thu Jun 29 11:37:08 2006 From: aleax at mac.com (Alex Martelli) Date: Thu, 29 Jun 2006 08:37:08 -0700 Subject: Python in a nutshell - new edition ? References: <44A2C52A.6040807@skynet.be> <1hhnpen.1bkiv8l1d0r6puN%aleax@mac.com> <1151551938.499099.162520@75g2000cwc.googlegroups.com> <1hhnvof.1apknoe1v7zz8aN%aleax@mac.com> Message-ID: <1hhoqjk.z9msqs1opi16zN%aleax@mac.com> John Salerno wrote: > Alex Martelli wrote: > > BartlebyScrivener wrote: > > > >>>> Yep, we're still aiming for OSCON '06 (Portland, end of July). > >> Amazon says July 1st. > > > > Let me assure you that it _won't_ be on paper this coming Saturday (two > > days from now). > > > > > > Alex > > Doh! I had just noticed this yesterday on Amazon and was all set to head > to the bookstore and get it this weekend! :) Glad to have saved you a trip;-). End of July is our aggressive but still-achievable target: everything was scheduled from the start to hit OSCON '06 (and the release of Python 2.5 -- whether 2.5 final will be out at OSCON is still uncertain, though). Alex From gh at ghaering.de Tue Jun 13 15:40:17 2006 From: gh at ghaering.de (=?UTF-8?B?R2VyaGFyZCBIw6RyaW5n?=) Date: Tue, 13 Jun 2006 21:40:17 +0200 Subject: [pysqlite] [ANN] pysqlite 2.3.0 In-Reply-To: <448F1178.7060407@gmail.com> References: <448F0982.70906@ghaering.de> <448F1178.7060407@gmail.com> Message-ID: <448F14A1.7020503@ghaering.de> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Dawid Gajownik wrote: > Dnia 06/13/2006 08:52 PM, U?ytkownik Gerhard H?ring napisa?: > >> pysqlite 2.3.0 released > > Great :) I have one more problem, though. It does not compile: [...] > src/connection.c:31:26: error: sqlitecompat.h: No such file or directory > [...] > I had to manually download this file [sqlitecompat.h] > Why it's not included in the tarball? python setup.py sdist didn't recreate the MANIFEST file, so it was omitted. I've uploaded a fixed source tarball now. It's my fault, I should have tried to build from the source tarball, like I normally do before a release ... - -- Gerhard -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2.2 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFEjxShdIO4ozGCH14RAuodAJ9N5bbR5lBtdWjzk2xMMivATIi63wCgoHNP y77XMzv1kmP9kIMFc3yQCSI= =VdBx -----END PGP SIGNATURE----- From alikakakhel at yahoo.com Fri Jun 2 17:03:04 2006 From: alikakakhel at yahoo.com (greenflame) Date: 2 Jun 2006 14:03:04 -0700 Subject: Making a second window with Tkinter Message-ID: <1149282184.587252.59160@y43g2000cwc.googlegroups.com> I have a script that will make a window that shows the text I want using Tkinter. What I need to do is to make another window popup above the current window showing other text. I tryed: ----------- from Tkinter imprt * root = Tk() L = Label(root, text="Blah") L.grid(row=0, column=0) # Other labels are also here but their inclusion is not so relavent. root.mainloop() sub = Tk() subL = Label(root, text="Blah") subL.grid(row=0, column=0) sub.mainloop() ---------- However, when I ran the script it only showed the second window after I closed the first one. After looking at the code I guess I can see why. The problem is that I do not know how to fix the issue. Thank you for you help. From da404lewzer at gmail.com Thu Jun 22 19:40:55 2006 From: da404lewzer at gmail.com (da404LewZer) Date: 22 Jun 2006 16:40:55 -0700 Subject: coderwiki.com is starting and needs you! Message-ID: <1151019655.327087.15310@g10g2000cwb.googlegroups.com> i'm starting a wiki on coding, keeping everything seperate. anyone who wants to help check out the site. i want to document every function for every language ever www.coderwiki.com From steve at holdenweb.com Fri Jun 9 03:44:26 2006 From: steve at holdenweb.com (Steve Holden) Date: Fri, 09 Jun 2006 08:44:26 +0100 Subject: Exeucte a system command in python script In-Reply-To: <1149820817.793432.38530@i39g2000cwa.googlegroups.com> References: <1149815748.856808.200140@j55g2000cwa.googlegroups.com> <1149820344.244437.120220@g10g2000cwb.googlegroups.com> <1149820817.793432.38530@i39g2000cwa.googlegroups.com> Message-ID: ken.carlino at gmail.com wrote: > I am using python 2.4, so I don' t need to insteall that module > separately. > > ken.carlino at gmail.com wrote: > >>Thanks I get this error 'NameError: global name 'call' is not defined" >> >>I already import 'subprocess'. >> >>Can you pleaes tell me what am I missing? Among other things you are missing the traceback that the Python interpreter provides with its error messages. This will point you to a particular line of the source. If you include a few lines of the source around that point, as well as a pasted copy of the traceback, we have some chance to determine the error without overtaxing our psychic powers. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From antroy at gmail.com Thu Jun 8 04:34:32 2006 From: antroy at gmail.com (Ant) Date: 8 Jun 2006 01:34:32 -0700 Subject: XML, JSON, or what? References: <1149749530.734275.181300@j55g2000cwa.googlegroups.com> Message-ID: <1149755672.088330.42610@h76g2000cwa.googlegroups.com> > to use? I could go back to XML, or I could switch to JSON - I have read I'd favour JSON if the data structures are simple personally. XML is comparatively speaking a pain to deal with, where with JSON you can simply eval() the data and you have a Python dictionary at your disposal. I recently used JSON as a way of passing data from a Java backend to a web page for Javascript to deal with, with the added side effect that my Python testing scripts could also easily read the same data. From no-spam at no-spam-no-spam.com Sat Jun 3 13:38:44 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Sat, 03 Jun 2006 19:38:44 +0200 Subject: __builtins__.loglog - logging more pythonic, decent & scalable ? - Re: "No handlers could be found for logger xxx" Message-ID: As more and more python packages are starting to use the bloomy (Java-ish) 'logging' module in a mood of responsibility and as I am not overly happy with the current "thickener" style of usage, I want to put this comment and a alternative most simple default framework for discussion. Maybe there are more Python users which like to see that imported (managed) logging issue more down-to-earth and flexible ? ... Vinay Sajip wrote: > robert wrote: > >>some packages like paramiko use the logging. I get this messages: >>"No handlers could be found for logger xxx" on stderr >> >>Why is un-initialized logging allowed to chatter at all? > > You could invoke logging.basicConfig with a level of CRITICAL. This > will generally filter out logging messages. Meanwhile i looked on logging and its doc: The doc of for example basicConfig (promising to be quite simple/silent): "basicConfig( ) Does basic configuration for the logging system by creating a StreamHandler with a default Formatter and adding it to the root logger. The functions debug(), info(), warning(), error() and critical() will call basicConfig() automatically if no handlers are defined for the root logger. " => So far I don't get any idea what will happen after doing this. What is a StreamHandler? a "default Formatter"? CRITICAL? what is this default magic behavior? even if silent behavior is installed log(), debug() consume still a lot of execution time => I have to read the logging code anyway => for my needs i rendered dead the Logger() in app-init / dead the line in logging which chatters within my standard set of Python patches. I looked around a little more and think, that logging it is really a _FRAMEWORK_ - non-pythonic . a declarative monster. Meaning: too big the interface and too big its basic footprint. without a decent scaling. too loud. it takes lots of time until one understands the basics. even the simplest setup example has not less than 8 lines - strange "filehandlers" and "formatters" are going on - and it is a framework which does a lot of obscure things, its class collection reads more like an magic application only understandable by its immediate programmers - rather than a stdlib part. Its almost a Java-ish ego class bunch. Some wide spread packages like paramiko use it already - inside stdlib only cookielib so far. Yet, just for providing the option they are costly pre-importing almost the whole framework functionality (in memory, frozen apps etc.) and have considerable costs during execution (regarding my step-in debugging sessions: seems to do very very late dispatching). Python is still not an OS on its own but a programming language/library which should fit into OS'es. ( though they meanwhile put the CJK codecs etc. into the python core !? :-) ) Yes, one could use such functionality - but one does only in rarest cases. I did and do logging a lot, but always had quite simple paths. I'd usually still not go though that framework in almost all cases, because it would require many hours until I really know whats going magically in all kinds of cases. 99% of my app logging needs were and are fulfilled by a simple direct module function as simple as: def doLog(text,level,**kwattrs): # in case write to file or whatever ... and so I simply know really what will happen. Collecting all logs is also so easy with Python, that it could be _enabled_ by a much much simpler and pythonic one-function-framework: a empty log-hook function in the python __builtins__: ========================================================= def loglog(text, channel='default', level=0, **kwattrs): pass ========================================================= yet there could go any complex hierarchical channel names through that like channel="mypackage.mymodule.subtheme" or even multi-hierarchical channel classes/objects similar to exception-class-catching in addition to string-catching. Example: ========================================================= class MyLogChannelAA(MyLogChannelA, MyLogAspectXY) loglog(text, MyLogChannelAA, __debug__, lcls=locals() ) ========================================================= If that simple would be the recommended standard logging interface in Python, I think, really a significant fraction of Python programmers would first understand and than use ( call and consume ) it - and (decent) modules would not blow up the machine unconditionally just for a mere specialized option. For massive usage apps could shortcut THEMSELVES with bloomy names and level-constants like logdebug() logerror() .... (Recommendations at best - no more framework.) Still this would be flexible enough and a super-hierarchical obscure logger and handler collection as exposed by "logging" or any other alternative could still be hooked in, while no module which does logging has to PRE-IMPORT SUCH A FAT SPECIAL LOGGING FRAMEWORK. > Un-initialized logging chatters because in development environments, > it's useful to be able to spot misconfigured loggers. For production > use, set logging.raiseExceptions to 0 and logging should then be quiet. Think a potentially "misconfigured logger" is not a reason to chatter. If there is an error in setup you'd 99.99% get an exception. If you really totally forget to setup - you simply have forgotten as you can forget many things. If you really want log's you'll have 1000 chances as developer to see that there are no logs - and add the setup. My opinion: _By default_ logging should really * be totally silent * not import all the logging code and handler classes etc. (but only a minimal stub or do ** (see below)) * consume only minimum execution time: Consider a typical complex program: Hundreds and thousands of things have to be be set up and configured which are much more important than a debug logger. Yet not every imported library and every class yells because it was not used or not basicConfig'ed :-). The logging is not the center of the world. In 99% only the developer of a module uses/wants the log output. I see there were already other complaints about this chattering - and other people also wondered how to make it silent. -- In cookielib recently the logging initialization has been **virtualized => its not imported / necessary (in frozen apps) until the cookielib debugging was not really requested. Think thats a better/acceptable style of use and such guidline should be put at the top of the logging docs to complete/alternate the above 3 issues. That all maybe could be healed most easily by the proposed __builtin__.loglog in Python : not unconditional wiring to such a specific and fat package. -robert From bayerj at in.tum.de Sun Jun 11 07:51:04 2006 From: bayerj at in.tum.de (bayerj) Date: 11 Jun 2006 04:51:04 -0700 Subject: learning python idioms In-Reply-To: <1150018807.945016.3100@y43g2000cwc.googlegroups.com> References: <1149998884.261678.299860@u72g2000cwu.googlegroups.com> <1150006411.269862.117680@j55g2000cwa.googlegroups.com> <1150016172.064188.264790@m38g2000cwc.googlegroups.com> <1150018807.945016.3100@y43g2000cwc.googlegroups.com> Message-ID: <1150026664.358254.67150@m38g2000cwc.googlegroups.com> > yup, you could spend weeks reading the Language Wars: Actually, that link is not about language wars. It's about making the switch from java to python. Nothing more, nothing less. From studi4 at fe-design.de Fri Jun 30 08:43:11 2006 From: studi4 at fe-design.de (Petr Man) Date: Fri, 30 Jun 2006 14:43:11 +0200 Subject: finding the last file created in a directory Message-ID: <200606301443.11201.> Hello everyone, I have a repeatedly running process, which always creates a new logfile with an ending n+1. What I need is to find the last file, the one with highest number at the end. The problem is, that the max() method gives me a wrong answer. I tried to convert the items in my list into integers using int(), but that ends up with an error ValueError: invalid literal for int(): My code currently looks like this: def get_logfile(dir, file_name): new_file_name = file_name[:-3] + 'log' listing = glob.glob(dir + new_file_name + '*') numbers = [] for i in range(len(listing)): item = listing[i] numbers.append(item[len(dir) + len(new_file_name) + 1:]) return new_file_name + '.' + max(numbers) cheers Petr From email at christoph-haas.de Tue Jun 13 18:20:03 2006 From: email at christoph-haas.de (Christoph Haas) Date: Wed, 14 Jun 2006 00:20:03 +0200 Subject: Correctly reading stdout/stderr from subprocess Message-ID: <20060613222002.GB5153@workaround.org> Evening, I'm having trouble with running a process through Python 2.4's subprocess module. Example code: ======================================================== def run(command): run = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # Wait for the process to return returncode = run.wait() stdout = run.stdout.readlines() stderr = run.stderr.readlines() # Strip newlines at the end of each line stdout = [line.rstrip('\n') for line in stdout] stderr = [line.rstrip('\n') for line in stderr] return returncode,stdout,stderr ======================================================== Unfortunately this def fails when it runs programs that do a lot of output. I believe this problem has also been described in Bug #1162428. It says: "You must read away the data before wait() on the process." Easier said than done. If I put the readlines() call before the run.wait() then the process hangs, too, waiting for further lines. Then I read about the communicate() call which handles both stdout/stderr reading and also waiting for the process to end. Unfortunately it returned the output char-wise instead of line-wise. I could certainly re-join the lines. But somehow I feel I'm missing something simple. Any ideas? Kindly Christoph From johnjsal at NOSPAMgmail.com Tue Jun 13 09:59:17 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 13 Jun 2006 13:59:17 GMT Subject: a string problem In-Reply-To: <1150206140.912224.113420@p79g2000cwp.googlegroups.com> References: <1150206140.912224.113420@p79g2000cwp.googlegroups.com> Message-ID: micklee74 at hotmail.com wrote: > hi > > if i have a some lines like this > a ) "here is first string" > b ) "here is string2" > c ) "here is string3" > > When i specify i only want to print the lines that contains "string" ie > the first line and not the others. If i use re module, how to compile > the expression to do this? I tried the re module and using simple > search() and everytime it gives me all the 3 lines that have "string" > in it, whereas i only need line 1. > If re module is not needed, how can i use string manipulation to do > this? thanks > As far as re goes, you can search for the pattern '\bstring\b', which will find just the word 'string' itself. Not sure if there's a better way to do it with REs. And I'm actually ashamed to admit that I know the RE way, but not the regular string manipulation way, if there is one! This seems like something easy enough to do without REs though. From pc at p-cos.net Fri Jun 23 11:00:58 2006 From: pc at p-cos.net (Pascal Costanza) Date: Fri, 23 Jun 2006 17:00:58 +0200 Subject: Saying "latently-typed language" is making a category mistake In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <86Qmg.10725$o4.1907@newsread2.news.pas.earthlink.net> <4g251pF1knc6tU1@individual.net> <4g28s6F1k9npnU1@individual.net> Message-ID: <4g2e1bF1kmiteU1@individual.net> Patricia Shanahan wrote: > Pascal Costanza wrote: >> Matthias Blume wrote: >>> Pascal Costanza writes: >>> >>>> Patricia Shanahan wrote: >>>>> Vesa Karvonen wrote: >>>>> ... >>>>>> An example of a form of informal reasoning that (practically) every >>>>>> programmer does daily is termination analysis. There are type >>>>>> systems >>>>>> that guarantee termination, but I think that is fair to say that it >>>>>> is not >>>>>> yet understood how to make a practical general purpose language, >>>>>> whose >>>>>> type system would guarantee termination (or at least I'm not aware >>>>>> of such >>>>>> a language). It should also be clear that termination analysis >>>>>> need not >>>>>> be done informally. Given a program, it may be possible to >>>>>> formally prove >>>>>> that it terminates. >>>>> To make the halting problem decidable one would have to do one of >>>>> two >>>>> things: Depend on memory size limits, or have a language that >>>>> really is >>>>> less expressive, at a very deep level, than any of the languages >>>>> mentioned in the newsgroups header for this message. >>>> Not quite. See http://en.wikipedia.org/wiki/ACL2 >>> >>> What do you mean "not quite"? Of course, Patricia is absolutely >>> right. Termination-guaranteeing languages are fundamentally less >>> expressive than Turing-complete languages. ACL2 was not mentioned in >>> the newsgroup header. >> >> ACL2 is a subset of Common Lisp, and programs written in ACL2 are >> executable in Common Lisp. comp.lang.lisp is not only about Common >> Lisp, but even if it were, ACL2 would fit. > > To prove Turing-completeness of ACL2 from Turing-completeness of Common > Lisp you would need to run the reduction the other way round, showing > that any Common Lisp program can be converted to, or emulated by, an > ACL2 program. Sorry, obviously I was far from being clear. ACL2 is not Turing-complete. All iterations must be expressed in terms of well-founded recursion. Pascal -- 3rd European Lisp Workshop July 3 - Nantes, France - co-located with ECOOP 2006 http://lisp-ecoop06.bknr.net/ From rganesan at myrealbox.com Tue Jun 13 06:33:17 2006 From: rganesan at myrealbox.com (Ganesan Rajagopal) Date: Tue, 13 Jun 2006 16:03:17 +0530 Subject: Python 411. References: <1150152755.474292.39010@j55g2000cwa.googlegroups.com> <1150188399.809316.172840@f14g2000cwb.googlegroups.com> Message-ID: >>>>> Mike T writes: > What exactly is 411 in this context? A reference to higher education > perhaps? Or perhaps part of the American constitution? What exactly? > Also for that matter what is 101? It's a directory assistance number in the US. The site is a directory of URLs. Ganesan -- Ganesan Rajagopal From Thaqalainnaqvi at gmail.com Tue Jun 13 07:08:16 2006 From: Thaqalainnaqvi at gmail.com (Thaqalainnaqvi at gmail.com) Date: 13 Jun 2006 04:08:16 -0700 Subject: What's wrong in this HTML Source file of a Bank Message-ID: <1150196896.819711.154640@c74g2000cwc.googlegroups.com> Several times I logged-in successfully but after log-in I can't use features/services which were shown prior to my login. Can anyone exoert from this forum check , is it technical fault of Bank Web Site or this problem pertaining to the user(me). hPLUS Login

Service with Security
(Incorporated in Switzerland 1967)Jun 13 2006, 11:18:49 AM GMT
  
Home Register Online


HBZ Web Login





Your request has been accepted








HBZ Web Login
From fzhenglee23 at yahoo.com.cn Wed Jun 7 18:29:10 2006 From: fzhenglee23 at yahoo.com.cn (=?gb2312?q?=C0=EE=D5=FE?=) Date: Thu, 8 Jun 2006 06:29:10 +0800 (CST) Subject: Regular Expression question In-Reply-To: Message-ID: <20060607222910.73292.qmail@web15808.mail.cnb.yahoo.com> I'm sorry! I mean pattern is an argument of the function, in this case, how I process special charactors. patter = 'www.' # not this if re.compile(pattern).match(string) is not None: ...... but not: if re.compile(r'www.').match(string) is not None: or if re.compile('www\.').match(string) is not None: , how you process special characters, like dot. Fredrik Lundh wrote? ken.carlino at gmail.com wrote: > I am new to python regular _expression, I would like to use it to get an > attribute of an html element from an html file? if you want to parse HTML, use an HTML parser. if you want to parse sloppy HTML, use a tolerant HTML parser: http://www.crummy.com/software/BeautifulSoup/ -- http://mail.python.org/mailman/listinfo/python-list __________________________________________________ ??????????????? http://cn.mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From claird at lairds.us Thu Jun 22 06:42:07 2006 From: claird at lairds.us (Cameron Laird) Date: Thu, 22 Jun 2006 10:42:07 +0000 Subject: How to generate all permutations of a string? References: Message-ID: In article , Girish Sahani wrote: >Hi guys, > I want to generate all permutations of a string. I've managed to >generate all cyclic permutations. Please help :) > >def permute(string): > l= [] > l.append(string) > string1 = '' > for i in range(0,len(string)-1,1): > string1 = string[1:len(string)] + string[:1] > l.append(string1) > string = string1 > return l > Those so passionate about enumerations as to consider *everything* known about them, and not just a specific Python function, will want to be aware of the referent of and related materials. and its referents. From anton at appsolutions.com Sat Jun 24 13:19:16 2006 From: anton at appsolutions.com (Anton van Straaten) Date: Sat, 24 Jun 2006 17:19:16 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150904134.520639.71070@b68g2000cwa.googlegroups.com> <4padnQn3SOWhkQfZnZ2dnUVZ_rqdnZ2d@speakeasy.net> Message-ID: David Hopwood wrote: > Anton van Straaten wrote: ... >>When you get to more complex cases, though, most type inferencers for >>Scheme assign traditional static-style types to terms. If you think >>about this in conjunction with the term "latent types", it's an obvious >>connection to make that what the inferencer is doing is recovering types >>that are latent in the source. > > > But these types are not part of the Scheme language. If you combine Scheme > with a type inferencer, you get a new language that is not R*RS Scheme, > and *that* language is typed. Sure. So one obvious question, as I've just observed in another reply to you, is which language programmers actually program in. I'd say that they certainly don't program in the completely untyped language as defined by RnRS. > Note that different inferencers will give different type assignments. > They may be similar, but they may also be quite dissimilar in some cases. > This casts considerable doubt on the assertion that the inferencer is > "recovering types latent in the source". I mentioned this earlier, in a reply to Marshall where I gave an informal definition of latent typing, which read in part: "Terms in the program may be considered as having static types, and it is possible to infer those types, but it isn't necessarily easy to do so automatically, and there are usually many possible static type schemes that can be assigned to a given program." As far as the term "recovering" goes, that perhaps shouldn't be taken too literally. It's clearly not the case that a latently-typed program has a single formalizable type scheme which was put there deliberately by the programmer. But programmers do reason about things like the types of functions and expressions, and the goal of soft type inferencers is to find an approximation to what the programmer intended. Anton From sashang at gmail.com Thu Jun 22 19:24:29 2006 From: sashang at gmail.com (sashang at gmail.com) Date: 22 Jun 2006 16:24:29 -0700 Subject: Using metaclassed to dynamically generate a class based on a parameter to the objects init function. Message-ID: <1151018669.849641.265990@g10g2000cwb.googlegroups.com> Hi I'd like to use metaclasses to dynamically generate a class based on a parameter to the objects init function. For example: class MetaThing(type): def __init__(cls, name, bases, dict, extra_information): super(MetaThing, cls).__init__(name, bases, dict) #setup the class based on the parameter extra_information class Thing: __metaclass__ = MetaThing def __init__(self, extra_information): #Somehow pass extra_information to the MetaThing extra_information = 1 t = Thing(extra_information) The above sample won't work but I hope it demonstrates what I'm trying to do. From torbenm at app-1.diku.dk Fri Jun 16 05:07:57 2006 From: torbenm at app-1.diku.dk (=?iso-8859-1?q?Torben_=C6gidius_Mogensen?=) Date: 16 Jun 2006 11:07:57 +0200 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> Message-ID: <7zu06lqxhu.fsf@app-1.diku.dk> Pascal Costanza writes: > Torben ?gidius Mogensen wrote: > > > On a similar note, is a statically typed langauge more or less > > expressive than a dynamically typed language? Some would say less, as > > you can write programs in a dynamically typed language that you can't > > compile in a statically typed language (without a lot of encoding), > > whereas the converse isn't true. > > It's important to get the levels right here: A programming language > with a rich static type system is more expressive at the type level, > but less expressive at the base level (for some useful notion of > expressiveness ;). > > > However, I think this is misleading, > > as it ignores the feedback issue: It takes longer for the average > > programmer to get the program working in the dynamically typed > > language. > > This doesn't seem to capture what I hear from Haskell programmers who > say that it typically takes quite a while to convince the Haskell > compiler to accept their programs. (They perceive this to be > worthwhile because of some benefits wrt correctness they claim to get > in return.) That's the point: Bugs that in dynamically typed languages would require testing to find are found by the compiler in a statically typed language. So whil eit may take onger to get a program thatgets past the compiler, it takes less time to get a program that works. Torben From nogradi at gmail.com Sun Jun 4 18:24:18 2006 From: nogradi at gmail.com (Daniel Nogradi) Date: Mon, 5 Jun 2006 00:24:18 +0200 Subject: ideas for programs? In-Reply-To: <20060604000919.7E06.0.NOFFLE@dieschf.news.arcor.de> References: <20060604000919.7E06.0.NOFFLE@dieschf.news.arcor.de> Message-ID: <5f56302b0606041524l67090e7bk903eb0a087e09a68@mail.gmail.com> > I've been learning python for the past couple of months and writing > misc scripts here and there, along with some web apps. > I'm wondering if anyone has ideas of programs I might try my hand at > making? You could put together a handy CSS generator library that could be used from a python webapp to generate CSS stylesheets on the fly. I'm sure many webdevelopers would find this helpful. From rcs at bgoark.no Thu Jun 8 20:01:37 2006 From: rcs at bgoark.no (baalbek) Date: Fri, 09 Jun 2006 02:01:37 +0200 Subject: what are you using python language for? In-Reply-To: References: Message-ID: <4488ba3c$0$22970$c83e3ef6@nn1-read.tele2.net> To score with the chicks! A Python script roams the nightclubs for beautiful women, finds an appropriate woman based on my preferances, charms her with its sleek Pythonic manners, calls for a cab and brings the lady to my recidency. Works like a charm! Baalbek From mariano.difelice at gmail.com Wed Jun 7 13:53:38 2006 From: mariano.difelice at gmail.com (mardif) Date: 7 Jun 2006 10:53:38 -0700 Subject: SpinCtrl events problem Message-ID: <1149702818.058705.80270@u72g2000cwu.googlegroups.com> Hi, I've a problem with wx.SpinCtrl Here we go with my source code: import wx import traceback class TextPage(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, -1, "") box = wx.BoxSizer(wx.VERTICAL) self.spin = wx.SpinCtrl(self, -1) box.Add(self.spin) self.SetSizer(box) wx.EVT_SPINCTRL(self, self.spin.GetId(), self.spinCtrlEvent ) self.CenterOnScreen() def spinCtrlEvent(self, evt): pass print "ALL RIGHT" if __name__ == "__main__": app = wx.PySimpleApp(0) p = TextPage() p.Show() app.MainLoop() Now, my problem is the increment/decrement of self.spin value. The SpinCtrl object increment/decrement 1 unit at time. I must increment/decrement "n" unit at time, ex: 5,10,15,20.... I've tried: def __init__(self): ........ ........ self.old_quantity = 0 def spinCtrlEvent(self, evt): if ( evt.GetInt() > self.old_quantity ): qta = self.old_quantity + 5 else: qta = self.old_quantity - 5 self.old_quantity = qta self.spin.SetValue( qta ) But here the process it goes in loop, because the SetValue SpinCtrl method regenerates the EVT_SPINCTRL event Any idea? Thanks very much From steve at holdenweb.com Wed Jun 14 05:22:36 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 14 Jun 2006 10:22:36 +0100 Subject: Tuple Syntax and () In-Reply-To: <1150226796.616272.223320@i40g2000cwc.googlegroups.com> References: <1150226796.616272.223320@i40g2000cwc.googlegroups.com> Message-ID: tactics40 at gmail.com wrote: > I keep accidently trying to declare t-tuples as mytuple = (myitem) > > I know this doesn't work and that you need the trailing comma, but > reading something online, I just came to realize.... the parenthesises > don't have any special meaning in relation to tuples at all, do they? > Give that (?)man a cigar! The only time the parentheses are necessary is when you need to disambiguate - the most frequent needs are: () for an empty tuple: there's no other way to express that without using tuple(), and f((a, b, ...)) to provide a single tuple argument to a function. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From richard at nospam.com Tue Jun 13 14:13:38 2006 From: richard at nospam.com (Richard Townsend) Date: Tue, 13 Jun 2006 19:13:38 +0100 Subject: USB support References: <1150222139.721785.268830@f14g2000cwb.googlegroups.com> Message-ID: <1pnp8g07uat4w.117hod7ouvbpg.dlg@40tude.net> On 13 Jun 2006 11:08:59 -0700, rodmc wrote: > Hi, > > I need to write a program which can access the USB ports on Mac and > Linux, is there a library available for Python? > > Thanks in advance. > > Best, > > rod Not tried it, but: http://pyusb.berlios.de/ -- Richard From fabiofz at gmail.com Thu Jun 1 06:46:51 2006 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Thu, 1 Jun 2006 07:46:51 -0300 Subject: Best Python Editor In-Reply-To: <1149149668.113003.142940@j55g2000cwa.googlegroups.com> References: <1149149668.113003.142940@j55g2000cwa.googlegroups.com> Message-ID: On 1 Jun 2006 01:14:28 -0700, andyrsmith at googlemail.com < andyrsmith at googlemail.com> wrote: > > If we could go back to emacs again for a second... > > I'm still using emacs but have been playing with a few other ide's > (wing, komodo + pydev) are the ones i've given a go recently. > > However I still end up coming back to emacs for what I consider to be > emacs mode's piece of 'killer functionality', (well, killer for me > anyway :-) ) which is the C-c C-c shortcut to send the contents of the > current buffer to a running interpreter. (i.e. one long-running > interpreter that behaves as if the entire buffer had been retyped). > Have you checked pydev extensions? It has an 'interactive console' which can do what you just said (but different keybinding, as it would require you to select all you want: Ctrl+A and then send it to the buffer: Ctrl+Enter, but on the other hand, it can do much more too) You can check details at http://www.fabioz.com/pydev/manual_adv_interactive_console.html If there's something missing there, you can submit a feature-request... Cheers, Fabio -------------- next part -------------- An HTML attachment was scrubbed... URL: From cga2000 at optonline.net Sat Jun 3 18:00:32 2006 From: cga2000 at optonline.net (cga2000) Date: Sat, 03 Jun 2006 18:00:32 -0400 Subject: Python & ncurses Message-ID: <20060603220032.GA18469@turki.gavron.org> Can anyone recommend a nice sample application that demonstrates the capabilities of python+ncurses and a clean/elegant UI? Thanks, cga From david.huard at gmail.com Wed Jun 21 12:04:15 2006 From: david.huard at gmail.com (David Huard) Date: Wed, 21 Jun 2006 12:04:15 -0400 Subject: How to override the doc of an object instance. References: <200606211539.02663.maric@aristote.info> Message-ID: Paul, Although your solution works for the class itself, it doesn't for class attributes, since they point to built-ins whose attributes are read-only. >>> w.x.__doc__ = widget.x.__doc__ AttributeError: 'int' object attribute '__doc__' is read-only Would the solution be to build a new type and change its dict ? David From theller at python.net Mon Jun 12 12:22:37 2006 From: theller at python.net (Thomas Heller) Date: Mon, 12 Jun 2006 18:22:37 +0200 Subject: VC++ types to ctypes In-Reply-To: <1150125909.402633.63250@i40g2000cwc.googlegroups.com> References: <1150125909.402633.63250@i40g2000cwc.googlegroups.com> Message-ID: lux wrote: > Hi to all, > i need to traslate this struct in python using ctypes > > struct Soptions > { > char chVolumeLabel[128]; > __int32 nSessionToImport; > BS_BOOL bJolietFileSystem; > BS_BOOL bBootable; > TCHAR chBootImage[_MAX_PATH]; > BS_BOOL bFinalize; > BS_BOOL bTestBurn; > BS_BOOL bPerformOPC; > BS_BOOL bVerifyAfterBurn; > __int32 nCacheSize; > BS_BOOL bUnderrunProtection; > BS_BOOL bEjectAfterBurn; > __int32 nCopies; > } > > I try to convert: > > char xxx[128] -> c_char*128 > __int32 -> c_int > BS_BOOL -> c_byte > > TCHAR chBootImage[_MAX_PATH]; -> ??? > > But not work... > how to solve it? > > Thank's, Luca > _MAX_PATH is 260. TCHAR is normally a unicode (wide) or a ascii (ansi) character, depending on if _UNICODE is defined by the compiler. Assuming ascii, TCHAR chBootImage[_MAX_PATH] -> c_char * 260 Thomas From norbert at akumakun.de Fri Jun 2 04:53:51 2006 From: norbert at akumakun.de (Norbert Kaufmann) Date: Fri, 02 Jun 2006 10:53:51 +0200 Subject: How do you practice Python? In-Reply-To: <1149152214.215907.31800@i39g2000cwa.googlegroups.com> References: <1149150517.034409.292530@g10g2000cwb.googlegroups.com> <447eaae0$0$20867$636a55ce@news.free.fr> <1149152214.215907.31800@i39g2000cwa.googlegroups.com> Message-ID: Ray wrote: [...] > Um, I mean, what if you have to use something other than > Python/Jython/IronPython? :) How do you keep your Python skill sharp? > You could use IPython as your primary shell. Than you have the opportunity to do all these nasty automation tasks -- create test data, deploy configuration files, search in logfiles for errors, etc. -- for your project in Python. Convince your project manager to develop prototypes. No one in your company is better and faster in prototyping than the Python expert Ray. HTH Norbert -- It is easier to get forgiveness than permission. From python at hope.cz Fri Jun 23 01:53:42 2006 From: python at hope.cz (Lad) Date: 22 Jun 2006 22:53:42 -0700 Subject: Blog source code in Python In-Reply-To: References: <1150989366.242671.254300@g10g2000cwb.googlegroups.com> Message-ID: <1151042022.048547.183030@y41g2000cwy.googlegroups.com> Frederic and Klaus, Thank you for the reply L. Klaus Alexander Seistrup wrote: > Lazy Lad wrote: > > > Is there a blog application source available in Python? > > Several. Did you try Google before you posted your question? The search > term "python blog" has > within the first 10 hits. > > Cheers, > > -- > Klaus Alexander Seistrup > Copenhagen, Denmark > http://surdej.dk/ From bignose+hates-spam at benfinney.id.au Thu Jun 15 10:01:30 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 16 Jun 2006 00:01:30 +1000 Subject: Python and databases (was: Re: how you get Python files on websites?) References: <1150373046.038502.307850@i40g2000cwc.googlegroups.com> Message-ID: <87lkryldqd.fsf@benfinney.id.au> azadi232 at gmail.com writes: > 1. Can Python work with databases like MySql,Oracle? (i think it > sounds silly) Not silly: -- \ "Money is always to be found when men are to be sent to the | `\ frontiers to be destroyed: when the object is to preserve them, | _o__) it is no longer so." -- Voltaire, _Dictionnaire Philosophique_ | Ben Finney From jmdeschamps at gmail.com Mon Jun 19 22:09:09 2006 From: jmdeschamps at gmail.com (jmdeschamps at gmail.com) Date: 19 Jun 2006 19:09:09 -0700 Subject: Active Python versions In-Reply-To: References: <2hElg.41514$mF2.19600@bgtnsc04-news.ops.worldnet.att.net> Message-ID: <1150769349.111390.280450@y41g2000cwy.googlegroups.com> Trent Mick wrote: > Tom Del Rosso wrote: > > Can I ask you about alternative environments? How do Active Python and IDLE > > from python.org compare? > > Both ActivePython and the Python installers from python.org install > IDLE. They should not differ at all (AFAIK). > > Trent > > -- > Trent Mick > trentm at activestate.com Maybe the OP is refering to PythonWin editor (as compared to IDLE) which is in ActiveState's release but not in the Python.org release... makes for a very different subject, and hopefully for very different answer direction. jean-marc From onurb at xiludom.gro Sat Jun 17 12:54:12 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Sat, 17 Jun 2006 18:54:12 +0200 Subject: Python is fun (useless social thread) ;-) In-Reply-To: References: Message-ID: <449433b5$0$1344$626a54ce@news.free.fr> John Salerno wrote: (snip) > So out of curiosity, I'm just wondering how everyone else came to learn > it. If you feel like responding, I'll ask my questions for easy quoting: > > Did you have to learn it for a job? It has never been an official requirement for any of the jobs I got since I'm a programmer, if that's what you mean. I discovered it while learning C++ / wxWidgets (someone talked me about Python as being pretty good for rapid prototyping). > Or did you just like what you saw and decided to learn it for fun? Well, I haven't be really impressed the first time - note that it was at the very end of the last century, with v1.5.2. But still I found the language suprisingly simple to get up and running with - seemed like the language was almost always reading my mind about how I would have named a librairy, function or whatever !-) So I ended up using it more and more when wanting to play with an idea or write a quick script... Until I realised than it was not the toy language I first thought it was (my, no access restrictors, not static typing, this just could not be a serious language, could it ?-), but a fantastic application programming language - far better than anything I had seen before (mostly 'modern' basics, C, C++, Pascal and Java...). > Also, how did you go about learning it? (i.e., like I described above, I > started with the main stuff then moved on to the different available > frameworks) Just used it, played with it, and lurked here. > Was there any necessity in the specifics you learned, or did you just > dabble in something (e.g. wxPython) for fun? I first used it for scripts, then turned to web programming (job opportunity), so I never really went very far in GUI programming with Python. > Are there still some things you feel you need to learn or improve? Yes - all and everything... -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From td_01 at att.net.invalid Sun Jun 18 04:39:59 2006 From: td_01 at att.net.invalid (Tom Del Rosso) Date: Sun, 18 Jun 2006 08:39:59 GMT Subject: Active Python versions Message-ID: Why is the Windows msi install file for ActivePython-2.4.3.12 only 15MB whereas the older msi file for ActivePython-2.4.2.10 was 19MB? BTW, is that the prefered Python environment? -- Reply in group, but if emailing add another zero, and remove the last word. From jdhunter at ace.bsd.uchicago.edu Wed Jun 7 08:38:31 2006 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 07 Jun 2006 07:38:31 -0500 Subject: curses event handling Message-ID: <8764jdta2g.fsf@peds-pc311.bsd.uchicago.edu> I have a curses app that is displaying real time data. I would like to bind certain keys to certain functions, but do not want to block waiting for c = screen.getch() Is it possible to register callbacks with curses, something like screen.register('keypress', myfunc) Thanks, JDH From kay.schluehr at gmx.net Tue Jun 20 01:00:08 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 19 Jun 2006 22:00:08 -0700 Subject: code is data In-Reply-To: <1150772934.314520.165200@p79g2000cwp.googlegroups.com> References: <1150574111.415068.255900@p79g2000cwp.googlegroups.com> <1150606118.456390.262620@y41g2000cwy.googlegroups.com> <1150626424.563673.175060@c74g2000cwc.googlegroups.com> <1150650852.275956.249340@p79g2000cwp.googlegroups.com> <1150658597.272001.171840@r2g2000cwb.googlegroups.com> <1150772934.314520.165200@p79g2000cwp.googlegroups.com> Message-ID: <1150779608.479611.44120@g10g2000cwb.googlegroups.com> Ian Bicking wrote: > > I don't use Django and I made this up quickly, so please don't pick on > > subtleties. > > > > @Poll: > > question: char length 200 > > pub_date('date published'): date > > > > @Choice: > > poll -> Poll > > choice: char length 200 > > votes: int > > That doesn't look that much better. How do you create it > programmatically? I know how to pass a variable to > CharField(maxlength=200); can I pass a variable to "char length 200" > just as easily? Can I use **kw? Can I read it from a CSV file and > construct the class that way? Maybe, but only by recreating all the > native patterns that I can infer easily looking at the Django class. If it is just a different kind of representation of common data structures as in YAML the answer might be a translation of these declarative blocks into dicts/lists ( or derivatives of those ) at compile time. The underlying semantics would be that of an "implicitely embedded DSL" ( there are quite a lot in Python ). Enabling code generation would just make them more explicit. For example XML syntax could be considered as an alternate surface syntax for elementrees. XML elements in Python code might be translated to aequivalent elementree annotation syntax at compile time. Under this considerations "choice: char length 200" and "CharField(maxlength = 200 )" are essentially the same thing. I guess @Choice.choice would finally represented by a property. Regards, Kay From digitalorganics at gmail.com Sun Jun 11 17:34:29 2006 From: digitalorganics at gmail.com (digitalorganics at gmail.com) Date: 11 Jun 2006 14:34:29 -0700 Subject: direct initialization of class attributes vs. declarations w/in __init__ In-Reply-To: References: <1150041510.139609.171120@f6g2000cwb.googlegroups.com> <4f2thrF1fd4r4U1@uni-berlin.de> <1150043792.136250.99770@u72g2000cwu.googlegroups.com> <1150047314.025241.260750@c74g2000cwc.googlegroups.com> Message-ID: <1150061669.491796.95700@g10g2000cwb.googlegroups.com> Fredrik Lundh wrote: > digitalorganics at gmail.com wrote: > > > At first, I thought that self.jerk was resolving to the class attribute > > instead of creating a new variable (w/ a differing scope). > > When you access an instance attribute, Python first looks in the > instance object, and then in the class object. > > When you assign to an instance attribute, it's *always* assigned to the > instance object, whether there's a class attribute with the same name or > not. > > If there's already a class attribute with the same name, that attribute > will be shadowed (but can still be accessed via the class object, of > course). > > > It doesn't work this way on my laptop... > > Python's always worked that way, so I find that a bit hard to believe. > No need to be obnoxious. I do appreciate your efforts to help, but you must admit, your last statement is a bit snide and certainly not useful. I'm telling you that the code runs differently on my laptop. Why this is, I don't know any more /or/ less than you do apparently. Now, it is of course possible that I'm interpreting the results incorrectly, but that doesn't change the fact that I'm getting different results per computer with identical code. From foster at home.nl Wed Jun 7 08:54:41 2006 From: foster at home.nl (Maarten van Veen) Date: Wed, 07 Jun 2006 14:54:41 +0200 Subject: cgi and popen Message-ID: A long story made short, I've build a python/cgi website consisting of two pages. Page1 has a html form in which you can input a series of queries. Then via Popen it starts a pythons search script, which stores the results in a python shelve. As the Popen command is given it should redirect to page2, which will check if the shelve is ready (search finished) and if not displays a search page, refreshing itself after 10 seconds. The Popen command works nice when tried out in the console. The script isueing the Popen quits, and the other process keeps on running till finished. But when embedded in page1.cgi, page 1 waits till the search is finished, resulting in a browser timeout when big queries are done. It was this problem in the first place why I split up the page in two and added Popen. Does anybody know how to get the page not waiting on Popen to finish? thnx Maarten From ripleyfu at gmail.com Wed Jun 7 07:37:54 2006 From: ripleyfu at gmail.com (ripley) Date: 7 Jun 2006 04:37:54 -0700 Subject: Python language problem In-Reply-To: References: <1149678146.681370.5130@c74g2000cwc.googlegroups.com> Message-ID: <1149680274.133008.167140@c74g2000cwc.googlegroups.com> Laszlo Nagy wrote: > You must undestand that 'a' and 'b' are names. You can only delete > names, not objects. Objects are freed by the garbage collector, > automatically. Probably you used to write programs in C or Pascal or > other languages with pointers. In Python, there are no pointers, just > references and you cannot free an object. You can only delete the > references to it. The good question is: why would you like to free an > object manually? The garbage collector will do it for you automatically, > when the object has no more references. (Well, cyclic references are > also garbage collected but not immediately.) > > If you need to handle resources, you can still use the try-finally > statement. Like in: > > f = file('example.txt','r') > try: > s = f.read() > finally: > f.close() # The resource is freed. But the object that was used to > access the resource, may not be freed here.... > > Regards, > > Laszlo Thanks for your so detailed explain, I think I know you, But my Engish is not enough to explain. I create same object in Tree, I want to update Tree, when I need to delete subtree. If where no references, I can't do that. some thing like blow: for i in list: del i >From that code, I can't update list anymore. From malvert at telenet.be Sat Jun 10 15:48:42 2006 From: malvert at telenet.be (malv) Date: 10 Jun 2006 12:48:42 -0700 Subject: Questions about extending Python... References: Message-ID: <1149968921.972194.153430@c74g2000cwc.googlegroups.com> Redefined Horizons wrote: > I've got a third-part application that exposes a C API. I'd like to > wrap it in Python. Is there a specific forum that covers extending and > embedding Python, or are those type of questions O.K. on this list? > > Scott Huey Over the years, many posts (and questions) have come up on dynamically importing and reloading modules and the inadequacy of the now available import and reload() features. This should enable one to modify or add code at runtime without having to restart the application. Unfortunately, few respondents understand the implications of this possibility. Regrettably also some display their ignorance by swinging their self perceived weight around. James Coplien, a Bell Laboratories Scientist, published "Advanced C++ Programming Styles and Idioms". Although now 15 years old, this book still has today quite some impact. Of particular interest for the problem at hand is Chapter 9 which presents idioms supporting incremental run-time update. Further Coplien illustrates in this chapter the major advantage gained by languages like Smalltalk and Lisp in this matter by having incremental run-time update as a built-in feature. Reading Coplien may further the cause of this very basic missing requirement in Python, From aleax at mac.com Sat Jun 3 20:03:01 2006 From: aleax at mac.com (Alex Martelli) Date: Sat, 3 Jun 2006 17:03:01 -0700 Subject: Using print instead of file.write(str) References: <2Iq*Jzbir@news.chiark.greenend.org.uk> <44809e93$0$13657$636a55ce@news.free.fr> <1d5482dibl4b4or8d4fkd90pd17ml3st2p@4ax.com> Message-ID: <1hgd8io.infymkfhpuerN%aleax@mac.com> Tim Roberts wrote: > Bruno Desthuilliers wrote: > > >Sion Arrowsmith a ?crit : > >> A.M wrote: > >> > >>>I found print much more flexible that write method. > >> > >> "more flexible"? More convenient, yes. More powerful, maybe. But I > >> don't see more flexible. Everything print can to stdout.write() can > >> do. The reverse isn't true. eg (this appears to be a FAQ on this > >> group, although I can't find it in the FAQ): > >> > >> for x in range(10): > >> sys.stdout.write(str(x)) > >> > >> to print: > >> > >> 0123456789 > > > >The reverse isn't true ??? > > > > print "".join(str(x) for x in range(10)) > > What he meant it that it is impossible to produce "0123456789" using 10 > separate print statements, while it IS possible with 10 separate writes. it's not quite impossible, just cumbersome: >>> for x in range(10): ... print x, ... sys.stdout.softspace=0 ... 0123456789>>> Yes, you do need the softspace assignments -- but then, in the write version you need the explicit str calls, so it's not as if in either case you're using "just" the print or write-call. The differences in terms of convenience are surely there (in different circumstances they will favor one or the other of the two approaches), but I don't see such differences in either flexibility or power (if one ignores the issue of convenience, the same tasks can be performed with either approach). Alex From steve at holdenweb.com Thu Jun 8 14:18:05 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 08 Jun 2006 19:18:05 +0100 Subject: Select hangs after some reads In-Reply-To: References: <1149737234.816833.177710@j55g2000cwa.googlegroups.com> <1149764138.868847.326250@i39g2000cwa.googlegroups.com> <128g8uvi6aj4240@corp.supernews.com> <1149779056.498540.46620@f6g2000cwb.googlegroups.com> Message-ID: Jon Ribbens wrote: > In article , Steve Holden wrote: > >>Of course, if the client forces the TCP PSH flag true then the receiver >>is guaranteed to debuffer the stream up to that point - this is how FTP >>clients work, for example. > > > I don't think that's right. You are confusing the PSH flag (which is > basically unused in Unix networking I think) and the URG flag (which > is extremely rarely used, but is indeed used by FTP to get abort > requests to 'jump the queue' as it were). Nope. The URG flag indicates that a packet contains out-of-band data, whihc is what you describe above. The PSH flag indicates that the data stream must be flushed right through to the other end. This is essential for interactive protocols such as FTP: without it the server has no way to know that the client has sent a complete command, and vice versa. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From kent at kentsjohnson.com Fri Jun 9 14:33:55 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Fri, 09 Jun 2006 14:33:55 -0400 Subject: regexp questoin In-Reply-To: <1149868825.331142.280180@f6g2000cwb.googlegroups.com> References: <1149868825.331142.280180@f6g2000cwb.googlegroups.com> Message-ID: <4489bdef$1_1@newspeer2.tds.net> micklee74 at hotmail.com wrote: > hi > > i created a script to ask user for an input that can be a pattern > right now, i use re to compile that pattern > pat = re.compile(r"%s" %(userinput) ) #userinput is passed from > command line argument > if the user key in a pattern , eg [-] , and my script will search some > lines that contains [-] > > pat.findall(lines) > > but the script produce some error: sre_constants.error: unexpected end > of regular expression > > how can i successful catch patterns such as "[-]" in my regexp > compilation where input is unknown...? Maybe you want pat = re.compile(re.escape(userinput)) Kent From eval.apply at gmail.com Wed Jun 28 15:08:09 2006 From: eval.apply at gmail.com (Joe Marshall) Date: 28 Jun 2006 12:08:09 -0700 Subject: What is Expressiveness in a Computer Language [correction] In-Reply-To: References: <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <1151384511.223582.305760@m73g2000cwd.googlegroups.com> <1151425350.679754.278820@i40g2000cwc.googlegroups.com> <7bjog.229500$8W1.29971@fe1.news.blueyonder.co.uk> Message-ID: <1151521689.654605.261320@p79g2000cwp.googlegroups.com> Andreas Rossberg wrote: > > ~/> ocaml -rectypes > Objective Caml version 3.08.3 > > # let rec blackhole x = blackhole;; > val blackhole : 'b -> 'a as 'a = > > The problem is, though, that almost everything can be typed once you > have unrestricted recursive types (e.g. missing arguments etc), and > consequently many actual errors remain unflagged (which clearly shows > that typing is not only about potential value class mismatches). > Moreover, there are very few practical uses of such a feature, and they > can always be coded easily with recursive datatypes. > > It is a pragmatic decision born from experience that you simply do *not > want* to have this, even though you easily could. E.g. for OCaml, > unrestricted recursive typing was removed as default because of frequent > user complaints. > > Which is why this actually is a very bad example to chose for dynamic > typing advocacy... ;-) Actually, this seems a *good* example. The problem seems to be that you end up throwing the baby out with the bathwater: your static type system stops catching the errors you want once you make it powerful enough to express certain programs. So now it seems to come down to a matter of taste: use a restricted language and catch certain errors early or use an unrestricted language and miss certain errors. It is interesting that the PLT people have made this tradeoff as well. In the DrScheme system, there are different `language levels' that provide a restricted subset of Scheme. At the beginner level, first-class procedures are not allowed. This is obviously restrictive, but it has the advantage that extraneous parenthesis (a common beginner mistake) cannot be misinterpreted as the intent to invoke a first-class procedure. From robert.thorpe at antenova.com Wed Jun 21 08:17:36 2006 From: robert.thorpe at antenova.com (Rob Thorpe) Date: 21 Jun 2006 05:17:36 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> Message-ID: <1150892256.591282.43880@u72g2000cwu.googlegroups.com> > So, will y'all just switch from using "dynamically typed" to "latently > typed", and stop talking about any real programs in real programming > languages as being "untyped" or "type-free", unless you really are > talking about situations in which human reasoning doesn't come into > play? I think you'll find it'll help to reason more clearly about this > whole issue. I agree with most of what you say except regarding "untyped". In machine language or most assembly the type of a variable is something held only in the mind of the programmer writing it, and nowhere else. In latently typed languages though the programmer can ask what they type of a particular value is. There is a vast difference to writing code in the latter kind of language to writing code in assembly. I would suggest that at least assembly should be referred to as "untyped". From jo at durchholz.org Sun Jun 4 10:10:01 2006 From: jo at durchholz.org (Joachim Durchholz) Date: Sun, 04 Jun 2006 16:10:01 +0200 Subject: HOST - dreamhost.com / Liberality (Hosting, Basic Requirement) In-Reply-To: <4482CDDA.9060905@lazaridis.com> References: <4482CDDA.9060905@lazaridis.com> Message-ID: Ilias Lazaridis schrieb: > crossposted to 5 groups, which are affected by this case. > > followup not applicable. Actually, in this case, yes. > It _seems_ that Mr. Xah Les's account was terminated by dreamhost.com > because of > > a) the inability of several people to detect the interconnections within > writings which lead to perfectly valid cross-posts within the usenet. Actually, his posts are mostly off-topic. > b) the non-liberal and essentially non-professional way of how > dreamhost.com deals with abuse complaints. Unless you give some concrete facts, this is simply slander. URLs don't count. > To dreamhost.com: > > You should install an autoresponder to your abuse email, which reminds > people that it is > > * nearly inpossible to rate the content posted to usenet > * neally inpossible to detect validity of cross-posts > especially within complex analytical/philosophical writings > * other important facts Why are you wasting our mental bandwidth with that? Besides, it's utter nonsense. There's an infinity of invalid reasons, so you can't rule them out with an autoresponder. > People can then decide if they still wish to send the abuse complain > (e.g. can follow a link within the autoresponder). Nope. Finding out the provider is enough of a barrier. Additional barriers are not really necessary. Xah Lee has been irritating people for months. I do share your concerns. Complaint handling often is unprofessional. However, in Xah Lee's case, he's indeed been irritating too many people for a too long time that *some* sanction is in fact appropriate. I routinely kill his threads, but I'm reading a specific newsgroup for a purpose, and Xah Lee requires me to kill his. He's essentially doing semantic spam - analytical and philosophical writings may be well and fine, but they aren't appropriate on the newsgroups that I frequent (or only in very specific ways that Xah Lee doesn't address). > To anyone: > > Any form of censorship and "suppression of freedom of expression" should > be kept out of from open-source projects and from usenet. > > It is the within the responsibility of every entity (including > commercial companies) to act against it. > > http://dev.lazaridis.com/base/wiki/LiberalProjectDefinition There are many important goals. Free speech is indeed very high on the list. On the other hand, I'm pretty sure that Xah Lee will find another provider. From tomerfiliba at gmail.com Fri Jun 23 07:51:23 2006 From: tomerfiliba at gmail.com (gangesmaster) Date: 23 Jun 2006 04:51:23 -0700 Subject: windows and socket.dup Message-ID: <1151063477.718109.76890@b68g2000cwa.googlegroups.com> what uses do you have to socket.dup? on *nixes it makes, to dup() the socket before forking, but how can that be useful on windows? -tomer From paddy3118 at netscape.net Fri Jun 2 03:12:38 2006 From: paddy3118 at netscape.net (Paddy) Date: 2 Jun 2006 00:12:38 -0700 Subject: grouping a flat list of number by range In-Reply-To: <447F79C9.6080407@lexicon.net> References: <1149196642.001466.53990@c74g2000cwc.googlegroups.com> <1149201416.196975.123370@c74g2000cwc.googlegroups.com> <447F79C9.6080407@lexicon.net> Message-ID: <1149232358.817706.92680@j55g2000cwa.googlegroups.com> John Machin wrote: > On 2/06/2006 8:36 AM, Paddy wrote: > > Oh the siren call of every new feature in the language! > enumerate() just to get a first-time test, and then botch it?? > > Read the following; the replacement version uses a simple old-fashioned > inelegant flag, works with an empty sequence, and doesn't depend on the > input being sliceable or indexable. > > HTH, > John > Thanks, un-botchable John. What if the poster doesn't send a null list? What if the correct result for a null list is "spam"; or an exception? What if.... ... we toned down the language? Cheers, Pad. :-) From jzgoda at o2.usun.pl Thu Jun 1 16:23:43 2006 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Thu, 01 Jun 2006 22:23:43 +0200 Subject: Best Python Editor In-Reply-To: References: Message-ID: Fredrik Lundh napisa?(a): >>Can anyone tell me a good python editor/IDE? > > vim! jEdit! >>It would be great if you can provide the download link also. > > google it! google it! :D (I love these Vim <-> Emacs disputes) -- Jarek Zgoda http://jpa.berlios.de/ From maric at aristote.info Wed Jun 21 09:08:01 2006 From: maric at aristote.info (Maric Michaud) Date: Wed, 21 Jun 2006 15:08:01 +0200 Subject: Search substring in a string and get index of all occurances In-Reply-To: <200606211345.52243.maric@aristote.info> References: <4499034A.9040306@gmail.com> <200606211345.52243.maric@aristote.info> Message-ID: <200606211508.02191.maric@aristote.info> Le Mercredi 21 Juin 2006 14:01, Fredrik Lundh a ?crit : > > Another variant, I feel this one more natural as it doesn't contain a > > C-looking infinite loop > > doing things in a convoluted way because you think that non-infinite while- > loops are not natural? you can get help for that, you know ;-) Hehe, I was looking for a more pythonic solution (one like Tim gave), but not convinced. Sure these loops are common and natural. They're so natural I wonder why I avoid this kind of code : for i in lst : ... if continue_condition : continue ... if break_condition : break ... Maybe I'll vote for a goto statment for Python3000... Really I prefer code like this, when it's possible : for i in [ e for e in lst[:first_breaking_elt] if not e in continue_condition ] : .... > and a potentially large number of new strings. there's a lot of string > copying going on in there... Oh, yes, you're right, a xsplit operator would be of minor help as it will copy all the string piece by piece. Le Mercredi 21 Juin 2006 14:27, K.S.Sreeram a ?crit : > > Actually it's even more efficient than Lundh's > > effbot's solution finds overlapping occurrences, whereas your solution > finds non-overlapping occurrences. Missed that. > So efficiency comparisons are not valid. Right, but anyway, the problem is more about memory usage. Regards, -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From g.brandl-nospam at gmx.net Fri Jun 30 16:04:51 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Fri, 30 Jun 2006 22:04:51 +0200 Subject: Immutability In-Reply-To: References: <4Qj*cEjkr@news.chiark.greenend.org.uk> Message-ID: Georg Brandl wrote: > Steve Holden wrote: >> Georg Brandl wrote: >>> Steve Holden wrote: >> [...] >>> >>>>Would it make sense, in the single argument case, to default the doc >>>>value to fget.__doc__ to support that use case, or should we just not >>>>create read-only properties by using property as a decorator? >>> >>> >>> This is actually already the case in 2.5. >>> >> Sorry, haven't had much time for python-checkins lately. > > I didn't want to offend you, I must know since I implemented it myself ;) > >> But this would >> certainly argue that the decorator form for read-only properties is >> accepted at some level. > > Yes, one could argue in this direction. I will ask on python-dev whether > an official hint should be added to the documentation. Okay, this is now documented in the trunk. Georg From rogerb at rogerbinns.com Fri Jun 9 23:24:05 2006 From: rogerb at rogerbinns.com (Roger Binns) Date: Fri, 9 Jun 2006 20:24:05 -0700 Subject: Adding extra frames to traceback in C module Message-ID: One thing I would like to do in my extension module is add extra frames to the traceback when an extension occurs. At the moment C code is invisible to tracebacks. This is relevant when the C code makes a Python callback. For example if the following code sequence happens (time going down) Python C A B C D E F G H If there is an exception in H then the traceback seen from A will be "B C G H". I want to get D, E and F into there as well. This is because "G H" could be called for several different reasons in the C code and adding the extra information will establish why. I couldn't find anything on the web or in the documentation to explain how to do it. I did find snippets of code doing things like PyTraceback_Here but they use a real Python frame which I don't have and don't know how to synthesize. Roger From antroy at gmail.com Fri Jun 30 11:15:03 2006 From: antroy at gmail.com (Ant) Date: 30 Jun 2006 08:15:03 -0700 Subject: Chapter 9 Tutorial for Classes Not Working In-Reply-To: References: Message-ID: <1151680503.208437.265260@75g2000cwc.googlegroups.com> > class MyClass: > "A simple example class" > i = 12345 > def f(self): > return 'hello world' Nothing wrong with this. > From here I run: > x = MyClass Here's your problem - x is a class, *not* an instance of a class (i.e. an object). Methods operate on objects, not classes. Try x = MyClass() instead to get an instance of the class. > xf = x.f > while True: > print xf() Why not try something simpler - it doesn't look like you really know what you are doing here. The while True is going to print your "hello world" until the end of time, and there is no value in assigning the function to a variable at this stage - its adding complexity which you don't seem to need at the moment... Try: x = MyClass() x.f() From andrew.arobert at gmail.com Fri Jun 9 21:24:27 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Fri, 09 Jun 2006 21:24:27 -0400 Subject: __getattr__ question In-Reply-To: References: <4489AE08.2080407@designaproduct.biz> Message-ID: <128k7qtra9ku72f@corp.supernews.com> If I remember correctly, this behavior depends on how the class is created (classic mode versus modern). Modern class foo(object): pass Classic ( pre python 2.2 I believe ) class foo(): pass The modern method of specifying object in the class definition gets all of the class attributes cleanly. The classic method does not have this so the behavior is simulated. Ben Finney wrote: > Laszlo Nagy writes: > >> This is from the Python documentation (fragment): >> >> __getattr__( self, name) >> Called when an attribute lookup has not found the attribute in the >> usual places (i.e. it is not an instance attribute nor is it found in >> the class tree for self). name is the attribute name. This method should >> return the (computed) attribute value or raise an AttributeError exception. >> >> >> How can I determine if an attribute can be found in the usual places? > > When the attribute is not found in the usual places, the object's > __getattr__ method (if it has one) is called. Thus, when you write > your __getattr__ method, you should assume that the attribute has not > been found in the usual places. > From writetoalok at googlemail.com Thu Jun 29 20:38:44 2006 From: writetoalok at googlemail.com (Alok) Date: 29 Jun 2006 17:38:44 -0700 Subject: Reddit broke - should have remained on Lisp? In-Reply-To: <1151627462.297352.205150@i40g2000cwc.googlegroups.com> References: <1151626961.232761.255550@d56g2000cwd.googlegroups.com> <1151627462.297352.205150@i40g2000cwc.googlegroups.com> Message-ID: <1151627924.322764.6040@y41g2000cwy.googlegroups.com> Luis M. Gonz?lez wrote: > Alok wrote: > > While posting a comment on http://www.reddit.com I got an error page > > with the following curious statement on it. > > > > "reddit broke (sorry)" > > "looks like we shouldn't have stopped using lisp..." > > > > See screenshot at > > http://photos1.blogger.com/blogger/1773/1980/1600/reddit-broke.jpg > > > > Whether they truly repent not using lisp or otherwise, their site > > appears to be 3 times slower ... > > > > Alok > > > I don't know if this is true or not, but blaming a language for a poor > development is a little bit ridiculous... I was merely describing my experience and inviting others' response about theirs. Please don't misconstrue that as a blame on any language. And of course, I disagree with your comments about ridicule etc. From danmcleran at yahoo.com Tue Jun 20 12:09:23 2006 From: danmcleran at yahoo.com (danmcleran at yahoo.com) Date: 20 Jun 2006 09:09:23 -0700 Subject: Psyco performance Message-ID: <1150819763.818687.114360@y41g2000cwy.googlegroups.com> I'm not seeing much benefit from psyco (only 5-10% faster). Maybe this example is too trivial? Can someone give me some pointers as to what kind of code would see a dramatic benefit? Here's the code: import time import psyco n = 100000 t1 = time.clock() l = list(range(0,n)) l2 = [x**2 for x in l] t2 = time.clock() no_psyco = t2 - t1 psyco.log() psyco.full() t1 = time.clock() l = list(range(0,n)) l2 = [x**2 for x in l] t2 = time.clock() with_psyco = t2 - t1 print 'without psyco = ',no_psyco print 'with psyco = ',with_psyco print 'delta = ',(((no_psyco - with_psyco)/no_psyco) * 100),'%' From france.macchi at tele2.it Thu Jun 29 14:26:53 2006 From: france.macchi at tele2.it (Heavy) Date: 29 Jun 2006 11:26:53 -0700 Subject: XMLLIB Message-ID: <1151605613.912057.130510@x69g2000cwx.googlegroups.com> hi, I need to know if the 'xmllib' module have some method able to transform a data structure in a xml file and viceversa, thanks From scott.daniels at acm.org Fri Jun 30 22:11:34 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Fri, 30 Jun 2006 19:11:34 -0700 Subject: efficiency question In-Reply-To: References: Message-ID: <44a5d49d$1@nntp0.pdx.net> David Harvey wrote: > if x in ("abc", "def", "xyz"): > doStuff() > elif x in ("pqr", "tuv", "123"): > doOtherStuff() > elif ... If the code really looks like this: # one-time-only code big_dispatch_table = {} for function, keys in [ (doStuff, ["abc", "def", "xyz"]), (doOtherStuff, ["pqr", "tuv", "123"]), ... ]: for key in keys: big_dispatch_table[key] = function Then your actual code goes something like: big_dispatch_table[x]() --Scott David Daniels scott.daniels at acm.org From johnjsal at NOSPAMgmail.com Mon Jun 5 11:23:25 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 05 Jun 2006 15:23:25 GMT Subject: follow-up to FieldStorage Message-ID: If I want to get all the values that are entered into an HTML form and write them to a file, is there some way to handle them all at the same time, or must FieldStorage be indexed by each specific field name? From deets at nospam.web.de Sun Jun 11 12:09:31 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 11 Jun 2006 18:09:31 +0200 Subject: direct initialization of class attributes vs. declarations w/in __init__ In-Reply-To: <1150041510.139609.171120@f6g2000cwb.googlegroups.com> References: <1150041510.139609.171120@f6g2000cwb.googlegroups.com> Message-ID: <4f2thrF1fd4r4U1@uni-berlin.de> digitalorganics at gmail.com schrieb: > What's the difference between initializing class variables within the > class definition directly versus initializing them within the class's > __init__ method? Is there a reason, perhaps in certain situations, to > choose one over the other? You are confusing class variables with instance variables. The former are what you can initialize inside the class-statement. However, they are shared amongst _all_ instances. Consider this little example: class Foo(object): FOO = 1 BAR = [] def __init__(self, FOO): self.FOO = FOO self.BAR.append(FOO) def __repr__(self): return "FOO: %r\nBAR: %r\n" % (self.FOO, self.BAR) f1 = Foo(1) print f1 f2 = Foo(2) print f2 print f1 ------ meskal:~/Projects/CameraCalibrator deets$ python2.4 /tmp/test.py FOO: 1 BAR: [1] FOO: 2 BAR: [1, 2] FOO: 1 BAR: [1, 2] ----- As you can see, the list BAR is shared. And you can also see that _assigning_ to something like this: self.FOO will create an instance-variable. Even if a variable of the same name existed on the class before! Which is precisely the difference between using variable initialization in __init__ and inside the class-statement. BTW, self.__class__.FOO = value will set class-variables inside a method. Just if you wondered. Diez From LittlePython at lost.com Wed Jun 7 13:34:48 2006 From: LittlePython at lost.com (LittlePython) Date: Wed, 07 Jun 2006 17:34:48 GMT Subject: Converting binary sid's to a hex string Message-ID: I am trying to create a hexstring of a NT4 user account sid which I can in turn use to query an exchange 55 database. I believe I need to convert a binary sid to a hex string. ADsSID com object will do this for me however it is a little slow. Can anybody point me in the right direction to converting a PySID to a hexstring. Thx import win32netcon import win32net import win32security def report(): resume = 0 while 1: filter = win32netcon.FILTER_NORMAL_ACCOUNT data, total, resume = win32net.NetUserEnum('nt4pridc1', 20, filter, resume) for user in data: MySid, string, int = win32security.LookupAccountName('nt4pridc1', user['name']) sString = win32security.ConvertSidToStringSid(MySid) print MySid print sString if resume ==0: break report() ## sString prints = S-1-5-21-357043131-537017027-1947940980-1289 ## MySid prints = PySID:S-1-5-21-357043131-537017027-1947940980-1289 ## I need this , I believe this is a hex string of the SID ## 010500000000000515000000BB0B4815C33A022074381B7409050000 From python at hope.cz Tue Jun 13 08:54:06 2006 From: python at hope.cz (Lad) Date: 13 Jun 2006 05:54:06 -0700 Subject: PIL problem after installation In-Reply-To: References: <1149954516.785869.160700@i40g2000cwc.googlegroups.com> <1150093465.553355.50410@f14g2000cwb.googlegroups.com> Message-ID: <1150203246.500164.177860@y43g2000cwc.googlegroups.com> Fredrik Lundh wrote: > Lad wrote: > > > I downloaded jpeg (from ftp://ftp.uu.net/graphics/jpeg/ ) source > > libraries( file jpegsrc.v6b.tar.gz) and installed them. Now in > > /usr/local/lib I have the following files: cjpeg > > ,djpeg,jpegtran,rdjpgcom and wrjpgcom > > cjpeg, djpeg etc are executables, not libraries. if you have them under > /usr/local/lib, something's not quite right. > > to save some time, I suggest looking for a jpeg-dev or jpeg-devel > package in the package repository for your platform. > > Hello Fredrik, Thank you for your reply. I installed jpeg-devel package and now selftest.py worked! But I want to use PIL in my Python program( Django) running under Apache. What permissions must I use for which files? Thank you very much for your help. regards, L, From sjmachin at lexicon.net Tue Jun 13 03:08:22 2006 From: sjmachin at lexicon.net (John Machin) Date: Tue, 13 Jun 2006 17:08:22 +1000 Subject: Getting "TypeError:list indices must be integers" In-Reply-To: References: Message-ID: <448E6466.10908@lexicon.net> On 13/06/2006 4:11 PM, Girish Sahani wrote: [snip] > instance = ti2(k) > tiNew = ti1.append(instance) ti2 is quacking "function" but ti1 is quacking "list". Possibilities: (1) You meant to type ti2[k] ... and this section of code has not yet been executed, and would have featured as episode N+1 had morbid curiosity not led me to read further. (2) You have the weirdest system of choosing names that I have seen for decades. (3) Both of the above. Cheers, John From duncan.booth at invalid.invalid Fri Jun 23 10:29:42 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 23 Jun 2006 14:29:42 GMT Subject: * in Python References: <1151061836.557835.295820@p79g2000cwp.googlegroups.com> <1151065046.668902.23010@g10g2000cwb.googlegroups.com> <449beca5$0$13891$626a54ce@news.free.fr> <1151072320.621378.218520@r2g2000cwb.googlegroups.com> Message-ID: placid wrote: > i did try it in a Python shell after i learnt what it was. Like i said > *args will be a list, but when i try **args with the following code it > doesnt work > > def test(**args): > keys = args.keys() > for key in keys: > print key+"="+args(key) > When you post here, it helps if instead of saying 'it doesnt work' you say what you expected to happen and what actually happened (and quote exact error messages, dont paraphrase them). If I try your code it works fine: it defines a function. If I try to call your function, even though you didn't include a call in what 'doesnt work', then I get the exception I would expect, namely that you are trying to call args as though it were a function 'args(key)' instead of subscripting it as a dictionary 'args[key]'. Fixing that will then generate a different error, but I'm sure you'll be able to figure it out. From girish at cse.iitb.ac.in Tue Jun 6 00:38:21 2006 From: girish at cse.iitb.ac.in (Girish Sahani) Date: Tue, 6 Jun 2006 10:08:21 +0530 (IST) Subject: the most efficient method of adding elements to the list In-Reply-To: References: Message-ID: <33618.10.209.4.1.1149568701.squirrel@10.105.1.3> > Hi, > > Would it be .append()? Does it reallocate te list with each apend? Yes it does. If order of the new element being added doesnt matter you can use append. If it does, you can use insert(). > > l=[] > for i in xrange(n): > l.append(i) > > > Thx, A. > -- > http://mail.python.org/mailman/listinfo/python-list > From mdudley at king-cart.com Mon Jun 5 14:23:28 2006 From: mdudley at king-cart.com (Marshall Dudley) Date: Mon, 05 Jun 2006 14:23:28 -0400 Subject: Installation Problem References: <44830900.155C7297@king-cart.com> <44831694.A022913A@king-cart.com> <44836E91.7F640B4@king-cart.com> <448458CA.E867E532@king-cart.com> Message-ID: <4484769F.7900FD19@king-cart.com> Fredrik Lundh wrote: > Marshall Dudley wrote: > > > That is what I did originally, downloaded the latest version from the main > > python site. I compiled by the README file instructions, and I compiled by the > > instructions on the python url which are different, but both gave identical > > results, compiles fine, runs fine from the directory I compiled in, but will > > error out when I move the executible code to and run it from the /usr/local/bin > > or the /usr/local directory. > > deep sigh. alright, one more attempt: > > DO NOT copy any binaries yourself, DO NOT use any bogus FreeBSD source > distribution, DO NOT download 2.2.2 if you need Python 2.3 or newer, DO > NOT type random commands into the shell when logged in as root. etc. > > just follow these instructions: > > 1) go fetch a the latest source code kit from python.org. I recommend > getting Python-2.4.3.tgz: > > $ wget http://www.python.org/ftp/python/2.4.3/Python-2.4.3.tgz OK, did that again. > > > 2) unpack the file to a local temporary directory > > $ tar xvfz Python-2.4.3.tar.gz > $ cd Python-2.4.3 did that again. > > 3) in that directory, type the following commands: > > $ ./configure > $ make > $ ./python > OK, did that, got: Python 2.4.3 (#2, Jun 5 2006, 11:15:03) [GCC 2.95.4 20020320 [FreeBSD]] on freebsd4 Type "help", "copyright", "credits" or "license" for more information. >>> > > 4) verify that the ./python command prints the following: > > Python 2.4.3 [followed by some number, and today's date] > Type "help", "copyright", "credits" or "license" ... > >>> > > 5) press control-D to leave the interpreter Ok, did that. > > > 6) login as root, and type > > # make install OK, did that again. > > (or use sudo, or whatever mechanism you usually do to run a command as root) > > 7) log out from root. that's it. python is now installed as > "/usr/local/bin/python", *and* as "/usr/local/bin/python2.4". support > libraries and other files are installed under /usr/local/lib/python2.4 > and /usr/local/include/python2.4. > > OK, that is exactly what I had done previously, but this time there IS a copy of python in the /usr/local/bin directory, and this time it DOES work. Don't know why the previous times it put in the /usr/local/bin/pydoc, /usr/local/bin/idle and /usr/local/bin/smtpd.py files, but not the python executable one. Thanks, Marshall -------------- next part -------------- An HTML attachment was scrubbed... URL: From Serge.Orlov at gmail.com Mon Jun 12 12:38:51 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 12 Jun 2006 09:38:51 -0700 Subject: Intermittent Failure on Serial Port (Trace Result) References: Message-ID: <1150130330.843537.305310@f14g2000cwb.googlegroups.com> H J van Rooyen wrote: > Note that the point of failure is not the same place in the python file, but it > is according to the traceback, again at a flush call... Yes, traceback is bogus. Maybe the error is raised during garbage collection, although the strace you've got doesn't show that. The main reason of the failure seems to be a workaround in python's function new_buffersize, it doesn't clear errno after lseek and then this errno pops up somewhere else. There are two places I can clearly see that don't clear errno: file_dealloc and get_line. Obviously this stuff needs to be fixed, so you'd better file a bug report. I'm not sure how to work around this bug in the meantime, since it is still not clear where this error is coming from. Try to pin point it. For example, if your code relies on garbage collection to call file.close, try to close all files in your program explicitly. It seems like a good idea anyway, since your program is long running, errors during close are not that significant. Instead of standard close I'd call something like this: def soft_close(f): try: f.close() except IOError, e: print >>stderr, "Hmm, close of file failed. Error was: %s" % e.errno > The "close failed" is explicable - it seems to happen during closedown, with the > port already broken.., It is not clear who calls lseek right before close. lseek is called by new_buffersize that is called by file.read. But who calls file.read during closedown? From jo at durchholz.org Sun Jun 25 08:59:33 2006 From: jo at durchholz.org (Joachim Durchholz) Date: Sun, 25 Jun 2006 14:59:33 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: <1151030140.202720.245140@y41g2000cwy.googlegroups.com> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150904134.520639.71070@b68g2000cwa.googlegroups.com> <1151030140.202720.245140@y41g2000cwy.googlegroups.com> Message-ID: Marshall schrieb: > It seems we have languages: > with or without static analysis > with or without runtime type information (RTTI or "tags") > with or without (runtime) safety > with or without explicit type annotations > with or without type inference > > Wow. And I don't think that's a complete list, either. > > I would be happy to abandon "strong/weak" as terminology > because I can't pin those terms down. (It's not clear what > they would add anyway.) Indeed. >> Programmers infer and reason about these latent types while they're >> writing or reading programs. Latent types become manifest when a >> programmer reasons about them, or documents them e.g. in comments. > > Uh, oh, a new term, "manifest." Should I worry about that? I think that was OED usage of the term. > Well, darn. It strikes me that that's just a decision the language > designers > made, *not* to record complete RTTI. (Is it going to be claimed that > there is an *advantage* to having only incomplete RTTI? It is a > serious question.) In most cases, it's probably "we don't have to invent or look up efficient algorithms that we can't think of right now". One could consider this a sorry excuse or a wise decision to stick with available resources, both views have their merits IMHO ;-) >> But "function" is not a useful type. Why not? Because if all you know >> is that timestwo is a function, then you have no idea what an expression >> like "timestwo(foo)" means. You couldn't write working programs, or >> read them, if all you knew about functions was that they were functions. >> As a type, "function" is incomplete. > > Yes, function is a parameterized type, and they've left out the > parameter values. Well, in JavaScript, the explicit type system as laid down in the run-time type information is unparameterized. You can criticize this as unsound, or inadequate, or whatever you wish, and I'd like agree with that ;-), but the type of timestwo is indeed just "function". *Your mental model* is far more detailed, of course. > Question: if a language *does* record complete RTTI, and the > languages does *not* have subtyping, could we then say that > the runtime type information *is* the same as the static type? Only if the two actually use the same type system. In practice, I'd say that this is what most designers intend but what implementors may not have gotten right ;-p Regards, Jo From gh at ghaering.de Mon Jun 19 17:38:09 2006 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 19 Jun 2006 23:38:09 +0200 Subject: any subway web dev experiences In-Reply-To: References: <1150533811.911621.112430@y41g2000cwy.googlegroups.com> <1150664491.533947.61090@p79g2000cwp.googlegroups.com> <44965c1f$0$22857$626a54ce@news.free.fr> Message-ID: <44971941.2060504@ghaering.de> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Fredrik Lundh wrote: > bruno at modulix wrote: > >> Nope - it's a Python MVC web framework. Like Django, Pylons and >> Turborgears. And FWIW, there have been recently some discussions about >> merging Subway and Turbogears. > > recently? was that before or after the developer picked up his marbles > and went home to complain to his mother? So it was not only me that found this behaviour especially childish ... > (according to the subway wiki, only porn sites use the framework these > days. hint to developers: if you're shutting down a project, make sure > you lock down the project site). Unfortunately, this not only applies to shut down projects, but also to alive projects using Trac. It's a failure of Trac, because their developers don't see spam as such a big problem to warrant implement basic antispam support now instead of in a future release. Instead of diving deeper into Trac or installing the antispam version of it that is developed as a branch in their sandbox or otherwise wasting a lot of time, I tried to solve the problem the pragmatic way by installing a cron job that periodically runs the following commands on the SQLite database: gh at maya:~$ cat delspam.sql delete from wiki where text like '%cialis%'; delete from wiki where text like '%plumper%'; No spam was seen since then on the pysqlite wiki ... - -- Gerhard -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2.2 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFElxlBdIO4ozGCH14RAtMPAJ45eFuVwV+EMVWITDulxuex0R9gtgCgjKfn 5L1NQjaBOgZEJARVq6Y+2mU= =eZkz -----END PGP SIGNATURE----- From girish at cse.iitb.ac.in Thu Jun 22 05:35:39 2006 From: girish at cse.iitb.ac.in (Girish Sahani) Date: Thu, 22 Jun 2006 15:05:39 +0530 (IST) Subject: How to generate all permutations of a string? In-Reply-To: References: Message-ID: <50192.10.209.4.1.1150968939.squirrel@10.105.1.3> > In article , > "Girish Sahani" wrote: > >> I want to generate all permutations of a string. > > def permute(Seq) : > """generator which yields successive permutations of the elements > of Seq.""" > if len(Seq) == 0 : > yield () > else : > for i in range(0, len(Seq)) : > for rest in permute(Seq[:i] + Seq[i + 1:]) : > yield (Seq[i],) + rest > #end for > #end for > #end if > #end permute thanks lawrence...however this func doesnt return the permuted strings, so i added some code as follows to generate a list of all the permutations: def permute(seq): l = [] if len(seq) == 0: yield [] else: for i in range(0,len(seq)): for rest in permute(seq[:i] + seq[i+1:]): yield (seq[i],) + rest for t in permute(seq): l.append(''.join(t)) return l This gives me a syntax error! I need to output a list that has all the permutations of the input string. > -- > http://mail.python.org/mailman/listinfo/python-list > From martin at pythonic.de Fri Jun 30 00:44:35 2006 From: martin at pythonic.de (=?iso-8859-1?q?Martin_J=FCrgens?=) Date: Fri, 30 Jun 2006 06:44:35 +0200 Subject: logging module question References: <1151637748.098340.21010@75g2000cwc.googlegroups.com> Message-ID: Am Thu, 29 Jun 2006 20:22:28 -0700 schrieb s99999999s2003: > hi > i have defined a function > def logger(logfile,msg): > import logging > > logging.basicConfig(level=logging.DEBUG, > format='%(asctime)s %(levelname)-8s > %(message)s', > datefmt='%a, %d %b %Y %H:%M:%S', > filename='%s' % (logfile), > filemode='a') > logging.critical(msg) > logging.error(msg) > logging.warning(msg) > logging.info(msg) Why log the same message with different severity ? > logging.shutdown() > > In my main code: > > ----- some python code here--- > logger("test.log","error") > ..... > ..... > logger("test.log","another error") > ... > logger("test.log","yet another error") > ... > sys.exit(0) > > When i do the above, i get : > self.stream.write(fs % msg) > ValueError: I/O operation on closed file > > If i removed logging.shutdown(), it workds..what is wrong with my > function ? > thanks Why exactly do you call logging.shutdown() when you use the logging system again with further calls to logger(). As far as I see it logging.shutdown() should only be called when you're done with logging alltogether. However in your case you probably don't need to call it at all since it's invoked automatically when yout program exits. Regards, Martin From find at my.address.elsewhere Fri Jun 16 14:10:34 2006 From: find at my.address.elsewhere (Matthias Blume) Date: Fri, 16 Jun 2006 13:10:34 -0500 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <2006061410510511272-raffaelcavallaro@pasdespamsilvousplaitmaccom> <2006061501423327544-raffaelcavallaro@pasdespamsilvousplaitmaccom> <_eBkg.14895$uy3.4988@tornado.socal.rr.com> <1sBkg.14897$uy3.4884@tornado.socal.rr.com> Message-ID: Darren New writes: > Joachim Durchholz wrote: >> Give a heterogenous list that would to too awkward to live in a >> statically-typed language. > > Printf()? Very good statically typed versions of printf exist. See, e.g., Danvy's unparsing combinators. From onurb at xiludom.gro Fri Jun 16 10:35:47 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 16 Jun 2006 16:35:47 +0200 Subject: Python is fun (useless social thread) ;-) In-Reply-To: <44917776$1@nntp0.pdx.net> References: <1150381872.958342.180420@p79g2000cwp.googlegroups.com> <44917776$1@nntp0.pdx.net> Message-ID: <4492c1c6$0$11008$626a54ce@news.free.fr> Scott David Daniels wrote: > BartlebyScrivener wrote: > >> .... I am not touching OO, classes, or GUIs until I understand >> EVERYTHING else. Could take a few years. ;) > > > You know how modules separate globals, right? That is, what you > write in one module doesn't affect the names in another module. > What classes (and hence OO) give you is a way of saying, "I'd > like something a bit like a module, but I'd like to make several > of them, and not have them interfere with each other." That is > the big intuition about objects, the rest is just details. Another way to put it: You know what are dicts, right ? That is, containers with keyword-access to values ? Then you probably have dicts with a known, defined structure, and functions working on it. What classes (and hence 00) gives you is a way to associate these functions with the dicts themselves. That is the big intuition about objects, the rest is just details. !-) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From jim.lewis at miclog.com Sun Jun 4 07:02:31 2006 From: jim.lewis at miclog.com (Jim Lewis) Date: 4 Jun 2006 04:02:31 -0700 Subject: Pyrex list/array In-Reply-To: References: <1149360983.373137.200740@i39g2000cwa.googlegroups.com> <448239EB.6010706@lexicon.net> <1149415140.458073.65310@c74g2000cwc.googlegroups.com> Message-ID: <1149418950.943306.262510@h76g2000cwa.googlegroups.com> > Is it substantially faster with psyco than without? If psyco is performing > its magic on the critical section of code already, you are going to lose > that when switching to Pyrex. Yes but from what I read Pyrex can be a lot faster than psyco under the right circumstances. From fredrik at pythonware.com Thu Jun 15 11:15:37 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 15 Jun 2006 17:15:37 +0200 Subject: Python is fun (useless social thread) ;-) In-Reply-To: References: Message-ID: Sybren Stuvel wrote: >> Are there still some things you feel you need to learn or improve? > > I'd love to be able to calll functions from Windows DLLs on x86 Linux. call functions *in* DLLs, you mean? http://docs.python.org/dev/lib/module-ctypes.html http://starship.python.net/crew/theller/ctypes/ From Bulkan at gmail.com Fri Jun 23 07:23:56 2006 From: Bulkan at gmail.com (placid) Date: 23 Jun 2006 04:23:56 -0700 Subject: * in Python Message-ID: <1151061836.557835.295820@p79g2000cwp.googlegroups.com> Hi all, Can someone tell me what * in the following code means/does a Google search didnt turn up anything as i dont know what the * is called (related to Python and i dont think Python has pointers) def test(*args): pass and sometimes its; def test(**args): pass Cheers From bborcic at gmail.com Mon Jun 12 09:41:34 2006 From: bborcic at gmail.com (Boris Borcic) Date: Mon, 12 Jun 2006 15:41:34 +0200 Subject: Function to remove elements from a list not working (corrected) In-Reply-To: References: Message-ID: <448d6efc$1_6@news.bluewin.ch> Girish Sahani wrote: > Hi, > I am trying to modify a list of pairs (l4) by removing those > pairs which are not present in a third list called pairList. > The following is a simplified part of the routine i have written. However > it does not give the correct output. Please help! > Its possible i have made a trivial mistke since i am a newbie. > > def getl5(): > l5 = [] > pairList = [[1,2],[3,4],[3,5],[3,6],[9,7],[8,9],[8,7],[7,9],[11,10]] > l4 = [[4,2],[4,7],[4,10],[4,12],[9,2],[9,7],[9,10],[9,12],[11,2],[11,7]] > for pair in l4: > if pair not in pairList: > l4.remove(pair) > print "l4 is",l4 > > The output given is: > l4 is [[4, 7], [4, 12], [9, 7], [9, 12], [11, 7]] use sets def gets5() : pairSet = set([(1,2),(3,4),(3,5),(3,6),(9,7),(8,9),(8,7),(7,9),(11,10)]) s4= set([(4,2),(4,7),(4,10),(4,12),(9,2),(9,7),(9,10),(9,12),(11,2),(11,7)]) s4 &= pairSet print "s4 is",s4 the output is s4 is set([(9, 7)]) From fairwinds at eastlink.ca Fri Jun 2 17:47:43 2006 From: fairwinds at eastlink.ca (David Pratt) Date: Fri, 02 Jun 2006 18:47:43 -0300 Subject: Initializing an attribute that needs the object In-Reply-To: <4480B174.5090403@eastlink.ca> References: <4480AA70.2020804@eastlink.ca> <20060602212819.GA2688@localdomain> <4480B174.5090403@eastlink.ca> Message-ID: <4480B1FF.5020009@eastlink.ca> My apologies. What I meant to write was this class Factory def __init__(self, handler): David Pratt wrote: > Hi Marco. Thanks for your reply. I am providing the handler with the > factory instance as I have shown. This is how my code currently works. > What I am trying to figure out is how to possibly provide the handler in > the constructor when it needs the factory instance. This would give me > some better flexibility. > > ie. > > class Factory > > def __init__(self, factory): > > At this point I don't have self. Would super help me? > > Regards, > David > > > Marco Giusti wrote: >> On Fri, Jun 02, 2006 at 06:15:28PM -0300, David Pratt wrote: >>> Hi. I want to have different handlers to do perform logic. The problem >>> is the Handler requires an instance of the factory since it will use its >>> own methods in conjunction with methods of the factory. >>> >>> Once I have got a Factory instance I can give it a new handler (see >>> below). It would be more flexible if I could provide a handle in >>> constructor - but how to do this when it requires the object itself. >>> Would I use a super for this sort of thing? Many thanks >> when __init__ is called the object already exists. >> >>> class Factory: >>> >>> def __init__(self): >>> self.some_handler = Handler(self) >>> >>> f = Factory() >>> f.some_handler = AnotherHandler(f) >> try this, should works: >> >> class Factory: >> >> def __init__(self): >> self._some_handler = AnotherHandler(self) >> >> maybe a class hierarchy is good for you >> >> ciao >> m. >> From martin at v.loewis.de Sat Jun 17 16:21:13 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 17 Jun 2006 22:21:13 +0200 Subject: Which compiler will Python 2.5 / Windows (Intel) be built with? In-Reply-To: <1150557228.922848.259890@u72g2000cwu.googlegroups.com> References: <1150367139.495114.148550@g10g2000cwb.googlegroups.com> <44917535$1@nntp0.pdx.net> <1150391891.130185.4640@f6g2000cwb.googlegroups.com> <4492414C.10505@v.loewis.de> <1150444191.618761.22810@c74g2000cwc.googlegroups.com> <44933F17.7050500@v.loewis.de> <1150557228.922848.259890@u72g2000cwu.googlegroups.com> Message-ID: <44946439.9010309@v.loewis.de> meyer at mesw.de wrote: > Bottom Line: As I said before, I don't have a problem using VC2003 or > anything. It's by far the cheapest and easiest way just to buy VC2003 > and be done with it, than to fiddle around with GCC or anything. I just > think that Python should use the best technology available at the time > of release, which is VC2005 on Windows. But as I indicated before, of > course I do understand the argument that the release cycle has already > been planned and should not be changed, so we'll just live with it as > it is now. Thanks for the confirmation; that's good enough for me. Regards, Martin From michele.simionato at gmail.com Thu Jun 15 10:06:41 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 15 Jun 2006 07:06:41 -0700 Subject: Python is fun (useless social thread) ;-) In-Reply-To: References: Message-ID: <1150380401.422325.119360@h76g2000cwa.googlegroups.com> John Salerno wrote: > So out of curiosity, I'm just wondering how everyone else came to learn > it. I have already reported my first experiences with Python here: http://groups.google.com/group/comp.lang.python/browse_frm/thread/2afa89689e897039/3d77eba36a97751d?q=simionato+my+first+python&rnum=3#3d77eba36a97751d Michele Simionato From jstroud at ucla.edu Fri Jun 2 16:43:19 2006 From: jstroud at ucla.edu (James Stroud) Date: Fri, 02 Jun 2006 13:43:19 -0700 Subject: Reversible replacement of whitespace characters with visible characters In-Reply-To: <1149280203.974237.209080@y43g2000cwc.googlegroups.com> References: <1149280203.974237.209080@y43g2000cwc.googlegroups.com> Message-ID: Micah wrote: > Hi, > > I'm looking for a tool to do the following 2 things: > > 1) Given a string (ie. file, std input, whatever), replace all > whitespace characters with visible characters (like their Unicode value > or something). The end result will be one long unbroken line > > 2) Given a string altered as in step 1, "decode" it back to the > original string. > > Note: The original string (it will usually be source files) might > already contain Unicode values, and these must remain and not be > altered in step 2. > > Note 2: I'm working in a Windows XP environment, but I have access to > cygwin if that makes a difference. > > Can anyone think of a tool that already does this? I could probably > whip something up, but if there's already something that does it I'd > rather just use it. > > Micah > Try urllib. py> import urllib py> astr = 'faf\tfasf dsf\ndsfds dsf dsaf \t\r' py> urllib.quote(astr) 'faf%09fasf%20dsf%0Adsfds%20dsf%20dsaf%20%09%0D' py> print astr faf fasf dsf dsfds dsf dsaf James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From petr.jakes at tpc.cz Fri Jun 30 09:25:03 2006 From: petr.jakes at tpc.cz (=?windows-1250?Q?Petr_Jake=9A?=) Date: Fri, 30 Jun 2006 15:25:03 +0200 Subject: delete first line in a file In-Reply-To: <44a52219$0$12934$91cee783@newsreader02.highway.telekom.at> References: <44a4f854$0$12942$91cee783@newsreader02.highway.telekom.at><44a50151$0$12935$91cee783@newsreader02.highway.telekom.at> <44a50825$0$3888$91cee783@newsreader01.highway.telekom.at> <44a52219$0$12934$91cee783@newsreader02.highway.telekom.at> Message-ID: <43255099.20060630152503@tpc.cz> JH> this helps me! JH> thank you very much!!!!! JH> greetings, juergen I am happy to see my postings (which I sent by accident to you only, not to the list, see below) helped. But....: Its a pity we can not see your solution (your code) here :( It helps to others as well to see, how to solve some "problems" Petr Jakes JH>> that documentation i have already read, but it wouldn`t help me for my JH>> problem! JH>> i know, how i can read the first line an print them on the screen! JH>> but...how can i say python, delete the first line?! JH>> thats my problem! PJ> as Fredrik told you, you can not delete the first line directly!!! JH>> in the entry of my posting i wrote, that i am a newbie and so please JH>> understand me, that i ask so questions?! :-) PJ> We are trying to understand that, but it is expected some effort on PJ> your side as well :) PJ> You didn't read the documentation properly! PJ> try to experiment with the code by yourself as well! PJ> Try: PJ> 1) open your file PJ> 2) use readlines() method PJ> which returns the list of ALL rows from the file and store them to some PJ> variable. PJ> it can be done for example like: PJ> all_lines = f.readlines() PJ> (if you do not know, what the list is, start here: PJ> http://docs.python.org/tut/node5.html#SECTION005140000000000000000) PJ> 4) save the list members without its first member to the file PJ> for example: PJ> for line in all_lines[1:]: PJ> f.write(line) PJ> 5) close the file JH> Good luck JH> Petr Jakes JH>> thanks for your help! From maxilys at SPAMCOP_tele2.fr Tue Jun 13 17:43:55 2006 From: maxilys at SPAMCOP_tele2.fr (Remi Villatel) Date: Tue, 13 Jun 2006 23:43:55 +0200 Subject: What's wrong in this HTML Source file of a Bank In-Reply-To: <1150196896.819711.154640@c74g2000cwc.googlegroups.com> References: <1150196896.819711.154640@c74g2000cwc.googlegroups.com> Message-ID: Thaqalainnaqvi at gmail.com wrote: > Several times I logged-in successfully but after log-in I can't use > features/services which were shown prior to my login. Can anyone exoert > from this forum check , is it technical fault of Bank Web Site or this > problem pertaining to the user(me). This is definitively not the right newsgroup for HTML issues. Go to: http://validator.w3.org/ And I'm already too nice... -- ================== Remi Villatel maxilys_ at _tele2.fr ================== From davidh at ilm.com Tue Jun 20 19:48:34 2006 From: davidh at ilm.com (David Hirschfield) Date: Tue, 20 Jun 2006 16:48:34 -0700 Subject: Deprecation wrapper Message-ID: <44988952.4090205@ilm.com> I have a "deprecation" wrapper that allows me to do this: def oldFunc(x,y): ... def newFunc(x,y): ... oldFunc = deprecated(oldFunc, newFunc) It basically wraps the definition of "oldFunc" with a DeprecationWarning and some extra messages for code maintainers, and also prompts them to look at "newFunc" as the replacement. This way, anyone who calls oldFunc() will get the warning and messages automatically. I'd like to expand this concept to classes and values defined in my modules as well. So, I'd like a deprecatedClass that would somehow take: class OldClass: ... class NewClass: ... OldClass = deprecatedClass(OldClass, NewClass) and would similarly give the warning and other messages when someone tried to instantiate an OldClass object. And, for general values, I'd like: OLD_CONSTANT = "old" NEW_CONSTANT = "new" OLD_CONSTANT = deprecatedValue(OLD_CONSTANT, NEW_CONSTANT) so any attempt to use OLD_CONSTANT (or just the first attempt) would also output the warning and associated messages. I think that setting it up for classes would just mean making a wrapper class that generates the warning in its __init__ and then wraps the instantiation of the old class. But how can I do something similar for plain values like those constants? Is there a better way to do this whole thing, in general? Anyone already have a similar system set up? Thanks in advance, -David -- Presenting: mediocre nebula. From steve at holdenweb.com Thu Jun 15 12:40:52 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 15 Jun 2006 17:40:52 +0100 Subject: Which compiler will Python 2.5 / Windows (Intel) be built with? In-Reply-To: <1150367139.495114.148550@g10g2000cwb.googlegroups.com> References: <1150367139.495114.148550@g10g2000cwb.googlegroups.com> Message-ID: meyer at mesw.de wrote: > Hi everyone, > > which compiler will Python 2.5 on Windows (Intel) be built with? The default build will be the VC 2003 compiler as for 2.4, but there will also be VC 2005 project support files in a PCBuild8 subdirectory, if current efforts by CCP succeed. I am certainly compiling the 2.5 trunk with VC 2005 (VC++ 8.0, IIRC). It would be great if Tim Peters got more support for his efforts in that area, so it's good to see people besides Tim, Mark Hammond and Martin von Loewis doing significant work on that platform. Eventually someone may contribute (say) mingw support, but I'm not aware that anyone has yet stood up for the challenge of getting that into the distributions (and anyway I suspect that VC 200X will remain the default). regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From fc14301589 at icqmail.com Tue Jun 13 10:06:42 2006 From: fc14301589 at icqmail.com (TheSaint) Date: Tue, 13 Jun 2006 22:06:42 +0800 Subject: Linux info Message-ID: <448ec675_1@news.tm.net.my> Hello there, I still learning, but I couldn't find anything which tells me where a symlink is pointing to. A part of os.system('ls -l ' + path) and cutting down to the need, I haven't got any specialized function. F From bengtfrost at gmail.com Sat Jun 10 07:06:44 2006 From: bengtfrost at gmail.com (bfrost) Date: 10 Jun 2006 04:06:44 -0700 Subject: Class browser Message-ID: <1149937604.660123.259750@g10g2000cwb.googlegroups.com> Hi, Is there a easy way to start a standalone IDLE class-path- browser or 'else' recommended standalone classbrowser. Thanks. From geoffschmidt at gmail.com Tue Jun 20 19:12:54 2006 From: geoffschmidt at gmail.com (geoffschmidt at gmail.com) Date: 20 Jun 2006 16:12:54 -0700 Subject: Bus error in PyGILState_Release (callbacks from other threads) References: <1150788204.188239.55450@g10g2000cwb.googlegroups.com> Message-ID: <1150845174.931094.281230@r2g2000cwb.googlegroups.com> geoffschmidt at gmail.com wrote: > I'm trying to write an extension in C that delivers callbacks to > Python. The C code starts several threads, and I'd like one of the new > threads that is started to be able to deliver callbacks to Python. I > thought I could do this by wrapping the callback function in > PyGILState_Ensure / PyGILState_Release. When I do this, the Python code > in the callback in between those two calls certainly works, but when > PyGILState_Release is called, the process dies with a bus error! The fine folks on the Pyrex list figured out the problem: PyEval_InitThreads() needs to be called somewhere before any of the threading calls are made. For a fixed version of my test program, please see the Pyrex list archives. thanks, Geoff Schmidt gschmidt [[a t]] gschmidt [[d o t]] org (send correspondence here, not the address in the header) From onurb at xiludom.gro Fri Jun 16 09:13:15 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 16 Jun 2006 15:13:15 +0200 Subject: a good programming text editor (not IDE) In-Reply-To: <1150402733.116243.9680@y41g2000cwy.googlegroups.com> References: <_xgkg.2317$No6.48542@news.tufts.edu> <1150402733.116243.9680@y41g2000cwy.googlegroups.com> Message-ID: <4492ae6c$0$19179$626a54ce@news.free.fr> BartlebyScrivener wrote: > Emacs must be dying if this thread could get all the way to 20 with > nobody arguing with the vi folks. No need to argue. I started with vim, and finally switched to emacs less than one year later. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From rossberg at ps.uni-sb.de Thu Jun 22 12:05:55 2006 From: rossberg at ps.uni-sb.de (Andreas Rossberg) Date: Thu, 22 Jun 2006 18:05:55 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: <1150991074.705803.211570@m73g2000cwd.googlegroups.com> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150908952.804184.218990@r2g2000cwb.googlegroups.com> <1150991074.705803.211570@m73g2000cwd.googlegroups.com> Message-ID: Rob Thorpe wrote: > > Its easy to create a reasonable framework. Luca Cardelli has given the most convincing one in his seminal tutorial "Type Systems", where he identifies "typed" and "safe" as two orthogonal dimensions and gives the following matrix: | typed | untyped -------+-------+---------- safe | ML | Lisp unsafe | C | Assembler Now, jargon "dynamically typed" is simply untyped safe, while "weakly typed" is typed unsafe. > The real objection to this was that latently/dynamically typed > languages have a place in it. But some of the advocates of statically > typed languages wish to lump these languages together with assembly > language a "untyped" in an attempt to label them as unsafe. No, see above. And I would assume that that is how most proponents of the typed/untyped dichotomy understand it. - Andreas From rossberg at ps.uni-sb.de Wed Jun 21 05:53:13 2006 From: rossberg at ps.uni-sb.de (Andreas Rossberg) Date: Wed, 21 Jun 2006 11:53:13 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: <1150823297.816352.75370@u72g2000cwu.googlegroups.com> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <1150809118.677124.142230@u72g2000cwu.googlegroups.com> <1150815461.210286.53120@r2g2000cwb.googlegroups.com> <1150823297.816352.75370@u72g2000cwu.googlegroups.com> Message-ID: Rob Thorpe wrote: > > I think this should make it clear. If I have a "xyz" in lisp I know it > is a string. > If I have "xyz" in an untyped language like assembler it may be > anything, two pointers in binary, an integer, a bitfield. There is no > data at compile time or runtime to tell what it is, the programmer has > to remember. You have to distinguish between values (at the level of language semantics) and their low-level representation (at the implementation level). In a high-level language, the latter should be completely immaterial to the semantics, and hence not interesting for the discussion. >>No, variables are insignificant in this context. You can consider a >>language without variables at all (such languages exist, and they can >>even be Turing-complete) and still have evaluation, values, and a >>non-trivial type system. > > Hmm. You're right, ML is no-where in my definition since it has no > variables. Um, it has. Mind you, it has no /mutable/ variables, but that was not even what I was talking about. >>>But the value itself has no type >> >>You mean that the type of the value is not represented at runtime? True, >>but that's simply because the type system is static. It's not the same >>as saying it has no type. > > Well, is it even represented at compile time? > The compiler doesn't know in general what values will exist at runtime, > it knows only what types variables have. Sometimes it only has partial > knowledge and sometimes the programmer deliberately overrides it. From > what knowledge it you could say it know what types values will have. Again, variables are insignificant. From the structure of an expression the type system derives the type of the resulting value. An expression may contain variables, and then the type system generally must know (or be able to derive) their types too, but that's a separate issue. Most values are anonymous. Nevertheless their types are known. > Unfortunately it's often necessary to break static type systems. Your definitely using the wrong static language then. ;-) - Andreas From gandalf at designaproduct.biz Fri Jun 30 05:45:22 2006 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Fri, 30 Jun 2006 11:45:22 +0200 Subject: No error while sending via TCP Socket In-Reply-To: References: Message-ID: <44A4F2B2.3070103@designaproduct.biz> Martin B?rkle ?rta: > Hi NG, > > I have writen a programm using TCP sockets. After i get the connection > to another socket I cut the Ethernet cable. Then I send a message. > The program doesnt raise any exception. Can somebody tell me why and > give me a hint how to get an exception > Okay, let's suppose you do not cut the ethernet cable and your message arrives on the other side, but the receiver program has a problem (not enough memory, bug in the handling code etc.) so your message is not processed on the other side. Most of the time, you do not only want to check if your message was transferred - you also need to check if that is actually processed. The TCP protocol cannot do this for you.Your clients needs to send back another message that notifies the sender about successful processing. Your sender program can wait for this notification, and then raise an exception after some timeout. In other words, you need to develop your own communication protocol over TCP/IP. You should try to minimize the number of send-receive-notification cycles, because the answer time can be high, compared to the transfer speed of the communication channel. And also because notifications are usually small, and they a buffered for a while... I have seen a paper about designing protocols over TCP/IP, but I do not remember now. Others will help you for sure. Please also consider UDP (if possible), which can be much more efficient. Best, Laszlo From tactics40 at gmail.com Thu Jun 22 15:45:42 2006 From: tactics40 at gmail.com (tactics40 at gmail.com) Date: 22 Jun 2006 12:45:42 -0700 Subject: Network Programming in Python In-Reply-To: <1151002934.586359.174540@m73g2000cwd.googlegroups.com> References: <1151002934.586359.174540@m73g2000cwd.googlegroups.com> Message-ID: <1151005542.852613.115870@r2g2000cwb.googlegroups.com> diffuser78 at gmail.com wrote: > I am a newbie in python. I want to learn and implement a small > networking concept. Please help me. Every help is appreciated. (hums the Batman Theme song replacing the words Batman with Google)... http://www.amk.ca/python/howto/sockets/ http://www.devshed.com/c/a/Python/Sockets-in-Python/ Really, was that so hard? Python makes sockets a total breeze. You can write an 80's style HTTP server in less than a page of code. From steven.bethard at gmail.com Thu Jun 22 10:38:27 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 22 Jun 2006 08:38:27 -0600 Subject: Registry of Methods via Decorators In-Reply-To: <1150983145.387222.5600@c74g2000cwc.googlegroups.com> References: <1150983145.387222.5600@c74g2000cwc.googlegroups.com> Message-ID: bayerj wrote: > I want to make a registry of methods of a class during creation. I think you're going to need a metaclass for this, e.g.:: >>> import inspect >>> def registered(func): ... func.registered = True ... return func ... >>> class RegisterFuncs(type): ... def __init__(cls, name, bases, classdict): ... cls.methods = [] ... for name, value in classdict.iteritems(): ... if inspect.isfunction(value): ... if hasattr(value, 'registered'): ... cls.methods.append(name) ... >>> class C(object): ... __metaclass__ = RegisterFuncs ... @registered ... def first_func(self): ... pass ... @registered ... def second_func(self): ... pass ... >>> C.methods ['first_func', 'second_func'] If you just want to store *all* method names, you can dispense with the @registered decorator and the hasattr() check. STeVe From dananrg at yahoo.com Thu Jun 29 16:52:22 2006 From: dananrg at yahoo.com (dananrg at yahoo.com) Date: 29 Jun 2006 13:52:22 -0700 Subject: pyGoogle - restrict by country doesn't seem to work Message-ID: <1151614342.293952.294630@75g2000cwc.googlegroups.com> If I want to restrict search results by country, what precisely do I need to include in searchTerm variable below? I've tried: searchTerm = 'restrict:countryUS blah blah' searchTerm = ' countryUS blah blah' Neither work. What am I doing wrong? import google data = google.doGoogleSearch(searchTerm) Thanks From jhnsmth at gmail.com Mon Jun 12 11:14:05 2006 From: jhnsmth at gmail.com (jhnsmth at gmail.com) Date: 12 Jun 2006 08:14:05 -0700 Subject: Thread specific singleton In-Reply-To: <448991d2$0$18298$4fafbaef@reader1.news.tin.it> References: <448991d2$0$18298$4fafbaef@reader1.news.tin.it> Message-ID: <1150125245.800085.75390@c74g2000cwc.googlegroups.com> Gabriele Farina wrote: > Hi, > > I'm tring to implement a Singleton object that should be specific for > every thread who create it, not global. > I tried a solution that seems to work, but I have a very poor knowledge > of concurrent programming, so I'd like someone to help me find some > problems in my implementation. > > Here is the code: > > ------------------------------------------------------------- > > import thread > > class ThreadLock(object): > > locks = {} > > def __new__(cls): > id = thread.get_ident() > try: > lock = cls.locks[id] > except KeyError: > lock = thread.allocate_lock() > cls.locks[id] = lock > > return lock > > @classmethod > def clear(cls, id=None): > """ Clear the lock associated with a given id. > > If the id is None, thread.get_ident() is used. > """ > > if id is None: > id = thread.get_ident() > try: > del cls.locks[id] > except KeyError: > pass > > class ThreadedSingleton(object): > > pool = {} > > def __new__(cls, *args, **kw): > lock = ThreadLock() > lock.acquire() > > id = thread.get_ident() > try: > obj = cls.pool[id] > except KeyError: > obj = object.__new__(cls, *args, **kw) > if hasattr(obj, '__init_singleton__'): > obj.__init_singleton__(*args, **kw) > cls.pool[id] = obj > > lock.release() > > return obj > > def __del__(self): > id = thread.get_ident() > ThreadLock.clear(id) > try: > del cls.pool[id] > except KeyError: > pass > > if __name__ == '__main__': > > import time > import random > > class Specific(ThreadedSingleton): > > def __init_singleton__(self): > print "Init singleton" > self.a = None > > def test(a): > s = Specific() > s.a = a > print "%d: %s" %(thread.get_ident(), Specific().a) > time.sleep(1) > print "%d: %s" %(thread.get_ident(), Specific().a) > time.sleep(random.randint(1, 5)) > print "%d: %s" %(thread.get_ident(), Specific().a) > time.sleep(2) > print "%d: %s" %(thread.get_ident(), Specific().a) > > for x in range(4): > thread.start_new_thread(test, (x, )) > > time.sleep(10) > > ------------------------------------------------------------- > > using the thread module should be fine even if threads are created > trought the threading module, right ? > > Thanks, > Gabriele import thread class Singleton: pass singletons = {} def get_singleton(): ident = thread.get_ident() try: singleton = singletons[ident] except KeyError: singleton = Singleton() singletons[ident] = singleton return singleton From stever at cruzio.com Thu Jun 29 14:53:49 2006 From: stever at cruzio.com (Steve) Date: 29 Jun 2006 11:53:49 -0700 Subject: Regular Expression - old regex module vs. re module Message-ID: <1151607229.548737.145800@d56g2000cwd.googlegroups.com> Hi All, I'm having a tough time converting the following regex.compile patterns into the new re.compile format. There is also a differences in the regsub.sub() vs. re.sub() Could anyone lend a hand? import regsub import regex import re # << need conversion to this module .... """Convert perl style format symbology to printf tokens. Take a string and substitute computed printf tokens for perl style format symbology. For example: ###.## yields %6.2f ######## yields %8d <<<<< yields %-5s """ exponentPattern = regex.compile('\(^\|[^\\#]\)\(#+\.#+\*\*\*\*\)') floatPattern = regex.compile('\(^\|[^\\#]\)\(#+\.#+\)') integerPattern = regex.compile('\(^\|[^\\#]\)\(##+\)') leftJustifiedStringPattern = regex.compile('\(^\|[^\\<]\)\(<<+\)') rightJustifiedStringPattern = regex.compile('\(^\|[^\\>]\)\(>>+\)') while 1: # process all integer fields print("Testing Integer") if integerPattern.search(s) < 0: break print("Integer Match : ", integerPattern.search(s).span() ) # i1 , i2 = integerPattern.regs[2] i1 , i2 = integerPattern.search(s).span() width_total = i2 - i1 f = '%'+`width_total`+'d' # s = regsub.sub(integerPattern, '\\1'+f, s) s = integerPattern.sub(f, s) Thanks in advance! Steve From alanalan at newsgroup.nospam Thu Jun 1 14:55:28 2006 From: alanalan at newsgroup.nospam (A.M) Date: Thu, 1 Jun 2006 14:55:28 -0400 Subject: How to format datetime values Message-ID: Hi, I have a datetime value and want to format it to "June 1, 2006" shape. How can I do that? Thank you, Alan From rossberg at ps.uni-sb.de Tue Jun 20 11:39:28 2006 From: rossberg at ps.uni-sb.de (Andreas Rossberg) Date: Tue, 20 Jun 2006 17:39:28 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: <1150815461.210286.53120@r2g2000cwb.googlegroups.com> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <1150809118.677124.142230@u72g2000cwu.googlegroups.com> <1150815461.210286.53120@r2g2000cwb.googlegroups.com> Message-ID: Rob Thorpe wrote: >Andreas Rossberg wrote: >>Rob Thorpe wrote: >> >>>>>"A language is latently typed if a value has a property - called it's >>>>>type - attached to it, and given it's type it can only represent values >>>>>defined by a certain class." >>>> >>>>"it [= a value] [...] can [...] represent values"? >>> >>>??? >> >>I just quoted, in condensed form, what you said above: namely, that a >>value represents values - which I find a strange and circular definition. > > Yes, but the point is, as the other poster mentioned: values defined by > a class. I'm sorry, but I still think that the definition makes little sense. Obviously, a value simply *is* a value, it does not "represent" one, or several ones, regardless how you qualify that statement. >>>Well I haven't programmed in any statically typed language where values >>>have types themselves. >> >>They all have - the whole purpose of a type system is to ensure that any >>expression of type T always evaluates to a value of type T. > > But it only gaurantees this because the variables themselves have a > type, No, variables are insignificant in this context. You can consider a language without variables at all (such languages exist, and they can even be Turing-complete) and still have evaluation, values, and a non-trivial type system. > But the value itself has no type You mean that the type of the value is not represented at runtime? True, but that's simply because the type system is static. It's not the same as saying it has no type. > in a C program for example I can take > the value from some variable and recast it in any way I feel and the > language cannot correct any errors I make because their is no > information in the variable to indicate what type it is. Nothing in the C spec precludes an implementation from doing just that. The problem with C rather is that its semantics is totally underspecified. In any case, C is about the worst example to use when discussing type systems. For starters, it is totally unsound - which is what your example exploits. - Andreas From duncan.booth at invalid.invalid Thu Jun 8 09:15:52 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 8 Jun 2006 13:15:52 GMT Subject: CONSTRUCT - Python's way of Ruby's "alias_method" References: Message-ID: Ilias Lazaridis wrote: > I would like to know, if this construct is valid, or if it can result in > problems (that I do not see as a newcomer): > > 1082 try: > 1083 from django.rework.evolve import evolvedb > 1084 except ImportError: > 1085 def evolvedb(): > 1086 "Evolve Command Dummy" > 1087 print 'Command evolvedb not imported' > 1088 evolvedb.args ='' The only real problem here is that if django.rework.evolve imports something else which doesn't exist you get your fallback code instead of reporting the error. In other words there is a chance that you could mask a deeper problem. If this worries you then you could do: try: from django.rework.evolve import evolvedb except ImportError, e: if str(e).rsplit(' ')[-1] != 'django.rework.evolve': raise ... rest of code here ... From wassipaul at gmx.at Fri Jun 30 10:46:32 2006 From: wassipaul at gmx.at (Stephan Wassipaul) Date: Fri, 30 Jun 2006 16:46:32 +0200 Subject: XMLLIB In-Reply-To: <1151605613.912057.130510@x69g2000cwx.googlegroups.com> References: <1151605613.912057.130510@x69g2000cwx.googlegroups.com> Message-ID: <44a5392a$0$3882$91cee783@newsreader01.highway.telekom.at> Gnosis (http://gnosis.cx/download/) is able to do this if you mean something like pickling, but with an XML-like ouput. From claird at lairds.us Tue Jun 20 08:37:42 2006 From: claird at lairds.us (Cameron Laird) Date: Tue, 20 Jun 2006 12:37:42 +0000 Subject: OS specific command in Python References: <1150781429.090359.148560@c74g2000cwc.googlegroups.com> <1150783324.258644.65770@u72g2000cwu.googlegroups.com> Message-ID: In article <1150783324.258644.65770 at u72g2000cwu.googlegroups.com>, wrote: >diffuser78 at gmail.com a ?crit : > >> So basically, instead of typing in on the command line argument I want >> to have it in a python program and let it do the action. > >Try exec() and execfile() from the standard library (IIRC) > >> >> for example. in my program I would want to call the ssh feature like >> one does on the command line >> >> ssh Admin at 192.168.2.10 .....etc >> > >When you connect (via ssh or telnet) to a remote machine, you need to >type (manually) >your username and your password. Programming that is never easy. > >If what you need is simulating console interaction, you will need to >get Expect. >Expect allows you to program/emulate user interaction in a text >console, based on the Tool Command Language (a.k.a. Tcl). > >But there are alternatives : start a SSH daemon written as a shell >script. (you just have to enter your login/pass once, then call the >daemon to execute some commands) > >IMHO, Expect is by far the cleanest way. . . . While Tcl-based Expect is indeed a remarkable achievement, please be aware, as Avell Diroll mentions elsewhere in this thread, that there is a Python-based pexpect with all the basic functionality of its predecessor. For most programming requirements you're likely to encounter, pexpect will serve you as well as Expect, and, of course, the former is easier to use for Pythoneers. From robert.thorpe at antenova.com Wed Jun 21 10:17:09 2006 From: robert.thorpe at antenova.com (Rob Thorpe) Date: 21 Jun 2006 07:17:09 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <7zpshbsvjy.fsf@app-1.diku.dk><4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <1150809118.677124.142230@u72g2000cwu.googlegroups.com> <1150815461.210286.53120@r2g2000cwb.googlegroups.com> <1150822150.701434.296460@u72g2000cwu.googlegroups.com> <1150883442.498308.226730@b68g2000cwa.googlegroups.com> Message-ID: <1150899429.801658.16120@r2g2000cwb.googlegroups.com> Matthias Blume wrote: > "Rob Thorpe" writes: > > Matthias Blume wrote: > >> "Rob Thorpe" writes: > >> > >> > I think we're discussing this at cross-purposes. In a language like C > >> > or another statically typed language there is no information passed > >> > with values indicating their type. > >> > >> You seem to be confusing "does not have a type" with "no type > >> information is passed at runtime". > >> > >> > Have a look in a C compiler if you don't believe me. > >> > >> Believe me, I have. > > > > In a C compiler the compiler has no idea what the values are in the > > program. > > It is no different from any other compiler, really. If the compiler > sees the literal 1 in a context that demands type int, then it knows > perfectly well what value that is. Well, with a literal yes. But with the value of some variable x at runtime it only know the type because it knows the type of the variable. Similarly the type of values generated by an expression are only known because the type the expression generates is known. > > It knows only their type in that it knows the type of the variable they > > are contained within. > > Would you agree with that? Would you? > >> > No it doesn't. Casting reinterprets a value of one type as a value of > >> > another type. > >> > There is a difference. If I cast an unsigned integer 2000000000 to a > >> > signed integer in C on the machine I'm using then the result I will get > >> > will not make any sense. > >> > >> Which result are you getting? What does it mean to "make sense"? > > > > Well the right one actually, bad example. > > > > But, if I cast an unsigned int 2500000000 to signed I get -1794967296. > > So, why do you think this "does not make sense"? Well, it makes sense in terms of the C spec certainly. It does not make sense in that it does not emit an error. >And, as this example > illustrates, casting in C maps values to values. Depending on the > types of the source and the target, a cast might change the underlying > representation, or it might leave it the same. But it does produce a > value, and the result value is usually not the same as the argument > value, even if the representation is the same. Yes. I'm not arguing with that. From riteshsarraf at gmail.com Fri Jun 30 06:33:43 2006 From: riteshsarraf at gmail.com (Ritesh Raj Sarraf) Date: 30 Jun 2006 03:33:43 -0700 Subject: FIXED: Re: optparse multiple arguments In-Reply-To: <1151661717.240109.47650@h44g2000cwa.googlegroups.com> References: <1151657119.837675.213700@p79g2000cwp.googlegroups.com> <1151657634.348133.291340@x69g2000cwx.googlegroups.com> <1151658092.273456.32260@75g2000cwc.googlegroups.com> <1151661717.240109.47650@h44g2000cwa.googlegroups.com> Message-ID: <1151663623.101732.264020@d56g2000cwd.googlegroups.com> Simon Percivall wrote: > > It might do you good to read the documentation instead of blindly > experimenting. > > Anyway, > > parser.add_option("", "--my-option", nargs=3) > > http://docs.python.org/lib/optparse-standard-option-actions.html That won't help because by design of my program, I can't limit the number of arguments a user can pass to it. Ritesh From pythor at gmail.com Fri Jun 23 12:45:54 2006 From: pythor at gmail.com (Pythor) Date: 23 Jun 2006 09:45:54 -0700 Subject: Getting Python scripts to execute in RedHat Message-ID: <1151081154.003234.299170@r2g2000cwb.googlegroups.com> I apologise if this is a stupid newbie error, but I've been googling "hash bang" and "shebang" all morning. I've added the shebang to my scripts: #!/usr/bin/python I've added execute permissions: chmod +rx shebang.py But I still can't execute my scripts by themselves shebang.py ## produces error python shebang.py ## runs correctly I found one site that mentioned adding "./" to the beginning, and that works. ./shebang.py ## runs correctly. I gather that there's a path problem then. My script is in ~/pyscripts/. How do I get my scripts to run without using "./"? From chris at kateandchris.net Fri Jun 2 10:33:06 2006 From: chris at kateandchris.net (Chris Lambacher) Date: Fri, 2 Jun 2006 10:33:06 -0400 Subject: Python for Visual Basic or C# programmers In-Reply-To: References: Message-ID: <20060602143305.GA7371@kateandchris.net> On Fri, Jun 02, 2006 at 10:26:28AM +0200, Laurent Pointal wrote: > A.M a ?crit : > > Hi, > > > > > > > > I am trying to find the equivalent functions such as vb's str or asc in > > Python. Is there any resource that help me to find these kinds of functions > > in Python faster? > > > > I've written the PQRC for that purpose: > http://www.limsi.fr/Individu/pointal/python/pqrc/ > > There is also the Python Quick reference series: http://rgruet.free.fr/#QuickRef > > A+ > > Laurent. > -- > http://mail.python.org/mailman/listinfo/python-list From bdesth.quelquechose at free.quelquepart.fr Tue Jun 27 00:16:56 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 27 Jun 2006 06:16:56 +0200 Subject: replace a method in class: how? In-Reply-To: References: <44a07037$0$1020$626a54ce@news.free.fr> Message-ID: <44a080f4$0$5277$636a55ce@news.free.fr> Maric Michaud a ?crit : > Le mardi 27 juin 2006 05:05, Bruno Desthuilliers a ?crit : > >>import types >>t.update = types.MethodType(another_update) > > > This works with : > > t.update = types.MethodType(another_update, t) oops ! too fast on the send button :( And thanks for the correction. From josiah.carlson at gmail.com Thu Jun 29 13:27:07 2006 From: josiah.carlson at gmail.com (josiah.carlson at gmail.com) Date: 29 Jun 2006 10:27:07 -0700 Subject: compiling python (or ironpython) to .exe or .dll for or not for .NET In-Reply-To: <1151531193.852307.223440@x69g2000cwx.googlegroups.com> References: <1151501398.664329.142920@d56g2000cwd.googlegroups.com> <1151531193.852307.223440@x69g2000cwx.googlegroups.com> Message-ID: <1151602027.886877.36790@p79g2000cwp.googlegroups.com> per9000 wrote: > Update: > > I have found a holy handgrenade. > > I found something that seems to work fine for me - I've only tried it > for 5 minutes but seems to work very smoothly. Open-source, Mozilla > license, you know the drill... > > http://www.py2exe.org/ > > py2exe (the name makes me fall in love) creates some dll's for me > containing python I guess. Your code exists as a .pyc file inside of the library.zip . People who still want access to it will be able to use the free or commercial versions of decompyle to get your code back. If you want to make it more difficult, you can always use pyrex, but that will require a compiler. - Josiah From fredrik at pythonware.com Wed Jun 21 11:51:21 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 21 Jun 2006 17:51:21 +0200 Subject: memory error with zipfile module In-Reply-To: <4499689D.1000206@gmail.com> References: <446e07ab$0$12795$636a55ce@news.free.fr> <1148072514.207383.26370@j55g2000cwa.googlegroups.com> <446e51e6$0$6831$636a55ce@news.free.fr> <4499689D.1000206@gmail.com> Message-ID: Hari Sekhon wrote: > I take it that it's still a work in progress to be able to pythonify > everything, and until then we're just gonna have to rely on shell and > those great C coded coreutils and stuff like that. Ok, I'm rather fond > of Bash+coreutils, highest ratio of code lines to work I've ever > seen.... it's the real strength of Linux. Shame about Windows... you make very little sense. From cfc at shell01.TheWorld.com Sun Jun 25 17:03:53 2006 From: cfc at shell01.TheWorld.com (Chris F Clark) Date: 25 Jun 2006 17:03:53 -0400 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> Message-ID: Chris F Clark (I) wrote: > Do you reject that there could be something more general than what a > type theorist discusses? Or do you reject calling such things a type? Chris Smith wrote: > I think that the correspondence partly in the wrong direction to > describe it that way. ... > What I can't agree to is that what you propose is actually more general. > It is more general in some ways, and more limited in others. As such, > the best you can say is that is analogous to formal types in some ways, > but certainly not that it's a generalization of them. Yes, I see your point. Me: > I'm particularly interested if something unsound (and perhaps > ambiguous) could be called a type system. Chris Smith: > Yes, although this is sort of a pedantic question in the first place, I > believe that an unsound type system would still generally be called a > type system in formal type theory. However, I have to qualify that with > a clarification of what is meant by unsound. We mean that it DOES > assign types to expressions, but that those types are either not > sufficient to prove what we want about program behavior, or they are not > consistent so that a program that was well typed may reduce to poorly > typed program during its execution. Obviously, such type systems don't > prove anything at all, but they probably still count as type systems. Yes, and you see mine. These informal systems, which may not prove what they claim to prove are my concept of a "type system". That's because at some point, there is a person reasoning informally about the program. (There may also people reasoning formally about the program, but I am going to neglect them.) It is to the people who are reasoning informally about the program we wish to communicate that there is a type error. That is, we want someone who is dealing with the program informally to realize that there is an error, and that this error is somehow related to some input not being kept within proper bounds (inside the domain set) and that as a result the program will compute an unexpected and incorrect result. I stressed the informal aspect, because the intended client of the program is almost universally *NOT* someone who is thinking rigorously about some mathematical model, but is dealing with some "real world" phenomena which they wish to model and may not have a completely formed concrete representation of. Even the author of the program is not likely to have a completely formed rigorous model in mind, only some approxiamtion to such a model. I also stress the informality, because beyond a certain nearly trivial level of complexity, people are not capable of dealing with truly formal systems. As a compiler person, I often have to read sections of language standards to try to discern what the standard is requiring the compiler to do. Many language standards attempt to describe some formal model. However, most are so imprecise and ambiguous when they attempt to do so that the result is only slightly better than not trying at all. Only when one understands the standard in the context of typical practice can one begin to fathom what the standard is trying to say and why they say it the way they do. A typical example of this is the grammars for most programming languages, they are expressed in a BNF variant. However, most of the BNF descriptions omit important details and gloss over certain inconsistencies. Moreover, most BNF descriptions are totally unsuitable to a formal translation (e.g. an LL or LR parser generator, or even an Earley or CYK one). Yet, when considered in context of typical implementations, the errors in the formal specification can easily be overlooked and resolved to produce what the standard authors intended. For example, a few years ago I wrote a Verilog parser by transliterating the grammar in the standard (IEEE 1364-1995) into the notation used by my parser generator, Yacc++. It took a couple of days to do so. The resulting parser essentially worked on the first try. However, the reason it did so, is that I had a lot of outside knowledge when I was making the transliteration. There were places where I knew that this part of the grammar was lexical for lexing and this part was for parsing and cut the grammar correctly into two parts, despite there being nothing in the standard which described that dichotomy. There were other parts, like the embedded preprocessor, that I knew were borrowed from C, so that I could use the reoultions of issues the way a C compiler would do so, to guide resolving the ambiguities in the Verilog standard. There were other parts, I could tell the standard was simply written wrong, that is where the grammar did not specify the correct BNF, because the BNF they had written did not specifiy something which would make sense--for example, the endif on an if-then-else-statement was bound to the else, so that one would write an if then without an endif, but and if then else with the endif--and I knew that was not the correct syntax. The point of the above paragraph is that the very knowledgable people writing the Verilog standard made mistakes in their formal specification, and in fact these mistakes made it passed several layers of review and had been formally ratified. Given the correct outside knowledge these mistakes are relatively trivial to ignore and correct. However, from a completely formal perspective, the standard is simply incorrect. More importantly, chip designers use knowledge of the standard to guide the way they write chip descriptions. Thus, at some level these formal erros, creep into chip designs. Fortunately, the chip designers also look past the inconsistencies and "program" (design) in a language which looks very like standard Verilog, but actually says what they mean. Moreover, not only is the grammar in the standard a place where Verilog is not properly formalized. There are several parts of the type model which suffer similar problems. Again, we have what the standard specifies, and what is a useful (and expected) description of the target model. There are very useful and informal models of how the Verilog language work and what types are involved. There is also an attempt in the standard to convey some of these aspects formally. Occassionally, the formal description is write and illuminating, at other times it is opaque and at still other times, it is inconsistent, saying contradictory things in different parts of the standard. Some of the more egregious errors were corrected in the 2001 revision. However, at the same time, new features were added which were (as far as I can tell) just as inconsistently specified. And, this is not the case of incompetence or unprofessionalism. The Verilog standard is not alone in these problems--it's just my most recent experience, and thus the one I am most familiar with at the moment. I would expect the Python, Scheme, Haskell, and ML standards to be more precise and less inconsistent, because of their communities. However, I would be surprised if they were entirely unambiguous and error-free. In general, I think most non-trivial attempts at formalization flounder on our inability. Therefore, I do not want to exlcude from type systems, things wich are informal and unsound. They are simply artifacts of human creation. -Chris From dnew at san.rr.com Sun Jun 25 16:22:46 2006 From: dnew at san.rr.com (Darren New) Date: Sun, 25 Jun 2006 20:22:46 GMT Subject: languages with full unicode support In-Reply-To: <1151251736.590910.36050@u72g2000cwu.googlegroups.com> References: <1151251736.590910.36050@u72g2000cwu.googlegroups.com> Message-ID: Xah Lee wrote: > If you know a lang that does full unicode support, please let me know. Tcl. You may have to modify the "source" command to get it to default to something other than the system encoding, but this is trivial in Tcl. -- Darren New / San Diego, CA, USA (PST) Native Americans used every part of the buffalo, including the wings. From cdsmith at twu.net Mon Jun 26 03:58:51 2006 From: cdsmith at twu.net (Chris Smith) Date: Mon, 26 Jun 2006 01:58:51 -0600 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <1151199196.870389.81960@p79g2000cwp.googlegroups.com> <_xrng.108673$H71.2451@newssvr13.news.prodigy.com> Message-ID: Anton van Straaten wrote: > I'm not trying to call programmer reasoning in general a type system. > I'd certainly agree that a programmer muddling his way through the > development of a program, perhaps using a debugger to find all his > problems empirically, may not be reasoning about anything that's > sufficiently close to types to call them that. Let me be clear, then. I am far less agreeable than you that this couldn't be called a type system. One of my goals here is to try to understand, if we are going to work out what can and can't be called a type system in human thought, how we can possible draw a boundary between kinds of logic and say that one of them is a type system while the other is not. I haven't seen much of a convincing way to do it. The only things that I can see rejecting out of hand are the empirical things; confidence gained through testing or observation of the program in a debugger. Everything else seems to qualify, and that's the problem. So let's go ahead and agree about everything up until... [...] > As an initial next step, we could simply rely on the good old universal > type everywhere else in the program - it ought to be possible to make > the program well-typed in that case, it would just mean that the > provable properties would be nowhere near as pervasive as with a > traditional statically-typed program. It would, in fact, mean that interesting provable properties would only be provable if data can't flow outside of those individual small bits where the programmer reasoned with types. Of course that's not true, or the programmer wouldn't have written the rest of the program in the first place. If we define the universal type as a variant type (basically, tagged or something like it, so that the type can be tested at runtime) then certain statements become provable, of the form "either X or some error condition is raised because a value is inappropriate". That is indeed a very useful property; but wouldn't it be easier to simply prove it by appealing to the language semantics that say that "if not X, the operation raises an exception," or to the existence of assertions within the function that verify X, or some other such thing (which must exist, or the statement wouldn't be true)? > But the point is we would now > have put our types into a formal context. Yes, but somewhat vacuously so... > The point about inherent informality is just that if you fully formalize > a static type system for a dynamic language, such that entire programs > can be statically typed, you're likely to end up with a static type > system with the same disadvantages that the dynamic language was trying > to avoid. Okay, so you've forced the admission that you have a static type system that isn't checked and doesn't prove anything interesting. If you extended the static type system to cover the whole program, then you'd have a statically typed language that lacks an implementation of the type checker. I don't see what we lose in generality by saying that the language lacks a static type system, since it isn't checked, and doesn't prove anything anyway. The remaining statement is that the programmer may use static types to reason about the code. But, once again, the problem here is that I don't see any meaning to that. It would basically mean the same thing as that the programmer may use logic to reason about code. That isn't particularly surprising to me. I suppose this is why I'm searching for what is meant by saying that programmers reason about types, and am having that conversation in several places throughout this thread... because otherwise, it doesn't make sense to point out that programmers reason with types. > Well, I'm trying to use the term "latent type", as a way to avoid the > ambiguity of "type" alone, to distinguish it from "static type", and to > get away from the obvious problems with "dynamic type". I replied to your saying something to Marshall about the "type systems (in the static sense) of dynamically-typed languages." That's what my comments are addressing. If you somehow meant something other than the static sense, then I suppose this was all a big misunderstanding. > But I'm much less interested in the term itself than in the issues > surrounding dealing with "real" types in dynamically-checked programs - > if someone had a better term, I'd be all in favor of it. I will only repeat again that in static type systems, the "type" becomes a degenerate concept when it is removed from the type system. It is only the type system that makes something a type. Therefore, if you want "real" types, then my first intuition is that you should avoid looking in the static types of programming languages. At best, they happen to coincide frequently with "real" types, but that's only a pragmatic issue if it means anything at all. > So when well-typed program fragments are considered as part of a larger > untyped program, you're suggesting that this so radically changes the > picture, that we can no longer distinguish the types we identified as > being anything beyond programmer reasoning in general? Is this so awfully surprising, when the type system itself is just programmer reasoning? When there ceases to be anything that's provable about the program, there also ceases to be anything meaningful about the type system. You still have the reasoning, and that's all you ever had. You haven't really lost anything, except a name for it. Since I doubt the name had much meaning at all (as explained above), I don't count that as a great loss. If you do, though, then this simple demonstrates that you didn't really mean "type systems (in the static sense)". > > Hopefully, this isn't perceived as too picky. I've already conceded > > that we can use "type" in a way that's incompatible with all existing > > research literature. > > Not *all* research literature. There's literature on various notions of > dynamic type. I haven't seen it, but I'll take your word that some of it exists. I wouldn't tend to read research literature on dynamic types, so that could explain the discrepancy. > > I would, however, like to retain some word with > > actually has that meaning. Otherwise, we are just going to be > > linguistically prevented from discussing it. > > For now, you're probably stuck with "static type". That's fine. I replied to your attempting to apply "static type" in a sense where it doesn't make sense. > In CS, we don't have the luxury > of using the classic mathematician's excuse when confronted with > inconvenient philosophical issues, of claiming that type theory is just > a formal symbolic game, with no meaning outside the formalism. As it turns out, my whole purpose here is to address the idea that type theory for programming languages is limited to some subset of problems which people happen to think of as type problems. If type theorists fourty years ago had limited themselves to considering what people thought of as types back then, we'd be in a considerably worse position today with regard to the expressive power of types in commonly used programming languages. Hence, your implication that insisting on a formal rather than intuitive definition is opposed to the real-world usefulness of the field is actually rather ironic. The danger lies in assuming that unsolved problems are unsolvable, and therefore defining them out of the discussion until the very idea that someone would solve that problem with these techniques starts to seem strange. -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation From maxm at mxm.dk Mon Jun 19 04:24:43 2006 From: maxm at mxm.dk (Max M) Date: Mon, 19 Jun 2006 10:24:43 +0200 Subject: Python is fun (useless social thread) ;-) In-Reply-To: <449433b5$0$1344$626a54ce@news.free.fr> References: <449433b5$0$1344$626a54ce@news.free.fr> Message-ID: <44965e69$0$38632$edfadb0f@dread12.news.tele.dk> bruno at modulix wrote: >> Or did you just like what you saw and decided to learn it for fun? > > Well, I haven't be really impressed the first time - note that it was at > the very end of the last century, with v1.5.2. 1.5.2 was an excellent version. Not really that different in use than current version. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science Phone: +45 66 11 84 94 Mobile: +45 29 93 42 96 From johnjsal at NOSPAMgmail.com Fri Jun 9 14:57:39 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 09 Jun 2006 18:57:39 GMT Subject: wxpython: another missing attribute In-Reply-To: <4489bbed$0$11610$3b214f66@aconews.univie.ac.at> References: <4489bbed$0$11610$3b214f66@aconews.univie.ac.at> Message-ID: Morpheus wrote: > This becomes a local var, i.e. local to __init__. To make it an instance var > write > > self.text = wx.StaticText(panel, -1, 'Click results') Ah, more namespace trickery! Thanks! :) From ve_sivakumar at yahoo.com Thu Jun 8 18:29:44 2006 From: ve_sivakumar at yahoo.com (V Sivakumar) Date: Thu, 08 Jun 2006 22:29:44 -0000 Subject: TKinter Message-ID: Dear Group!, I am new to Python. I have Eclipse with Python support , is there better IDE for free and with good support for GUI development. I need to develop a nice looking desktop application. Like we could do in VB, C# and Java Swing. Is there a drag drop support GUI toolkit for Python like the above languages do? Thanks Siva From grante at visi.com Thu Jun 29 19:26:02 2006 From: grante at visi.com (Grant Edwards) Date: Thu, 29 Jun 2006 23:26:02 -0000 Subject: Bug reporting impossible References: Message-ID: <12a8ocakvjedv7e@corp.supernews.com> On 2006-06-29, Fredrik Lundh wrote: > Nick Maclaren wrote: > >> It's definitely worth fixing, but not as a high priority. Invoking a >> file spuriously is potentially serious, with very low probability. > > the traceback printer is reading the file (using a very robust reader), > it's not "invoking" it. If you make a fifo and pipe something into it, it's sort of fun: $ mkfifo \ $ while true; do yow >\; done $ python Python 2.4.2 (#1, Feb 17 2006, 12:02:16) [GCC 3.4.4 (Gentoo 3.4.4-r1, ssp-3.4.4-1.0, pie-8.7.8)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> print a Traceback (most recent call last): File "", line 1, in ? Yow! Bo Derek ruined my life! NameError: name 'a' is not defined >>> print a Traceback (most recent call last): while File "", line 1, in ? Yow! YOU!! Give me the CUTEST, PINKEST, most charming little VICTORIAN DOLLHOUSE you can find!! An make it SNAPPY!! NameError: name 'a' is not defined >>> print a Traceback (most recent call last): File "", line 1, in ? Yow! I will establish the first SHOPPING MALL in NUTLEY, New Jersey... NameError: name 'a' is not defined >>> import foo Traceback (most recent call last): File "", line 1, in ? Yow! Is this where people are HOT and NICE and they give you TOAST for FREE?? File "foo.py", line 4, in ? p('set out') NameError: name 'p' is not defined OK, so not everybody finds things like that amusing... -- Grant Edwards grante Yow! My LIBRARY CARD at expired... visi.com From rpdooling at gmail.com Mon Jun 26 10:15:11 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 26 Jun 2006 07:15:11 -0700 Subject: Python database access References: <1151295558.067744.91470@b68g2000cwa.googlegroups.com> Message-ID: <1151331311.172035.178060@y41g2000cwy.googlegroups.com> > But I don't know how to make the connectivity or rather which module to > import. Try mxODBC http://www.egenix.com/files/python/mxODBC.html From rpdooling at gmail.com Thu Jun 1 14:21:28 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 1 Jun 2006 11:21:28 -0700 Subject: os.walk trouble References: <1149173920.903876.68370@c74g2000cwc.googlegroups.com> Message-ID: <1149186088.418824.247510@h76g2000cwa.googlegroups.com> > As my first Python script, I am trying to make a program that recurses > a directory searching for files whose names match a pattern. I have a > basic idea of what the regexp would look like You probably don't need regexp for this, just use the fnmatch module http://docs.python.org/lib/module-fnmatch.html There's a great recipe in the Python Cookbook 2ed for just what you're trying to do. In fact, I believe there's a recipe in there for just about anything anybody (at the beginner or intermediate level) wants to do with Python. The recipe, with some other unrelated problems: http://tinyurl.com/nvmzg Amazon Python Cookbook link: http://www.amazon.com/exec/obidos/asin/0596007973/inscape-20 good luck rick From python.list at tim.thechases.com Thu Jun 1 09:53:21 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 01 Jun 2006 08:53:21 -0500 Subject: default argument values qns In-Reply-To: <1149169482.717737.241410@g10g2000cwb.googlegroups.com> References: <1149169482.717737.241410@g10g2000cwb.googlegroups.com> Message-ID: <447EF151.2020309@tim.thechases.com> > i have declared a function like this: > > def aFunction ( arg1 , arg2 = 0): > .... > print type(arg2) > > when i try to print the type of arg2, it gives me 'str' > type..why is it not integer type, since i have declared > it as 0 ?? >>> def a(arg1, arg2=0): ... print type(arg2) ... >>> a("something") Looks like it's an int to me. You must be doing something spurious in your mysterious "...." that changes the data type. -tkc From rmuschall at tecont.de Wed Jun 7 14:10:48 2006 From: rmuschall at tecont.de (Ralf Muschall) Date: Wed, 07 Jun 2006 20:10:48 +0200 Subject: 10GB XML Blows out Memory, Suggestions? In-Reply-To: <2Qfhg.18186$0v4.787@tornado.texas.rr.com> References: <1149594519.098115.8980@u72g2000cwu.googlegroups.com> <2Qfhg.18186$0v4.787@tornado.texas.rr.com> Message-ID: <9ehjl3-4um.ln1@prcm.tecont.de> Paul McGuire schrieb: > meat of the data can be relatively small. Note also that this XML overhead > is directly related to the verbosity of the XML designer's choice of tag > names, and whether the designer was predisposed to using XML elements over > attributes. Imagine a record structure for a 3D coordinate point (described > here in no particular coding language): > struct ThreeDimPoint: > xValue : integer, > yValue : integer, > zValue : integer > Directly translated to XML gives: > > 4 > 5 > 6 > This is essentially true, but should not cause the OP's problem. After parsing, the overhead of XML is gone, and long tag names are nothing but pointers to a string which happens to be long (unless *all* tags in the XML are differently named, which would cause a huge DTD/XSD as well). > This expands 3 integers to a whopping 101 characters. Throw in namespaces > for good measure, and you inflate the data even more. In the DOM, it contracts to 3 integers and a few pointers - essentially the same as needed in a reasonably written data structure. > Try zipping your 10Gb file, and see what kind of compression you get - I'll > bet it's close to 30:1. If so, convert the data to a real data storage In this case, his DOM (or whatever equivalent data structure, i.e. that what he *must* process) would be 300 MB + pointers. I'd even go as far and say that the best thing that can happen to him is a huge overhead - this would mean he has a little data in a rather spongy file (which collapses on parsing). > medium. Even a SQLite database table should do better, and you can ship it > around just like a file (just can't open it up like a text file). A table helps only if the data is tabular (i.e. a single relation), i.e. probably never (otherwise the sending side would have shipped something like CSV). Ralf From rpdooling at gmail.com Thu Jun 15 18:52:49 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 15 Jun 2006 15:52:49 -0700 Subject: a good programming text editor (not IDE) References: <_xgkg.2317$No6.48542@news.tufts.edu> Message-ID: <1150411969.535331.43840@g10g2000cwb.googlegroups.com> >> Most IDEs are rather weak as text editors compared to emacsen. That's true, but even emacs and xemacs don't offer simple automatic word wrap (i.e. wrap a line without splitting words or putting an eol or hard carriage return at the end of every line). I don't know if vim allows this. It's something writers just take for granted in non-Unix text editors. rd From larry.bates at websafe.com Thu Jun 8 11:09:51 2006 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 08 Jun 2006 10:09:51 -0500 Subject: Instead of saving text files i need as html In-Reply-To: <1149777499.506986.292830@j55g2000cwa.googlegroups.com> References: <1149777499.506986.292830@j55g2000cwa.googlegroups.com> Message-ID: <2aqdnQwuYZIvoBXZnZ2dnUVZ_qadnZ2d@comcast.com> Then just write HTML around your list. I would guess you want them inside a table. Just write appropriate HTML tags before/after the urls. If you want the URLs to be clickable make them in into
url lines. -Larry Bates Shani wrote: > I have the following code which takes a list of urls > "http://google.com", without the quotes ofcourse, and then saves there > source code as a text file. I wan to alter the code so that for the > list of URLs an html file is saved. > > -----begin----- > import urllib > urlfile = open(r'c:\temp\url.txt', 'r') > for lines in urlfile: > try: > outfilename = lines.replace('/', '-') > urllib.urlretrieve(lines.strip('/n'), 'c:\\temp\\' \ > + outfilename.strip('\n')[7:] + '.txt') > except: > pass > -----end----- > From alikakakhel at yahoo.com Fri Jun 2 23:31:12 2006 From: alikakakhel at yahoo.com (greenflame) Date: 2 Jun 2006 20:31:12 -0700 Subject: Making a second window with Tkinter References: <1149282184.587252.59160@y43g2000cwc.googlegroups.com> Message-ID: <1149305472.893535.67770@h76g2000cwa.googlegroups.com> Ok so I played with your script. Here is a script that more closely mimics what I would like to do except that the way I make the variable deckstr will be different. The only thing I am confused about is that it opens the second window in the beginning and when I click on the button, it does nothing even after I have closed the other window. from Tkinter import * from string import join root = Tk() def showdeck(deck): deckwin = Toplevel() deckstr = join(deck, "\n") Label(deckwin, text=deckstr, justify=LEFT, anchor=W, font="Courier").pack(fill=X) L = Button(root, text="Show Deck", font="Courier", command=showdeck(list('zxcvbnm'))) L.pack() root.mainloop() From cm012b5105 at blueyonder.co.uk Thu Jun 15 08:26:52 2006 From: cm012b5105 at blueyonder.co.uk (carmel stanley) Date: Thu, 15 Jun 2006 13:26:52 +0100 Subject: interactive programme, using pyTTS References: Message-ID: <003501c69076$fc89ae60$984cfea9@aries> Hi i have been making an interactive programme,i have recently tried using "pyTTS" with it. This is a small ammount of it. import pyTTS tts = pyTTS.Create() tts.Rate = -3 tts.Speak('hi molly how old are you?.') s = raw_input ("how old are you?") if s=='3': print "thats great" else: print "tuttut" tts.speak('tututut') What i dont get is if i type in "4" it prints "tuttut" but it does not say it,am i overlooking something here. allso does any one here know if there is Linux support for such,i have searched about but cannot find anything. Thanks nige From sjmachin at lexicon.net Mon Jun 19 16:44:47 2006 From: sjmachin at lexicon.net (John Machin) Date: Tue, 20 Jun 2006 06:44:47 +1000 Subject: Calling every method of an object from __init__ In-Reply-To: <1150746953.156851.92820@r2g2000cwb.googlegroups.com> References: <1150746953.156851.92820@r2g2000cwb.googlegroups.com> Message-ID: <44970CBF.3020206@lexicon.net> On 20/06/2006 5:55 AM, Rob Cowie wrote: > Hi all, > > Is there a simple way to call every method of an object from its > __init__()? > > For example, given the following class, what would I replace the > comment line in __init__() with to result in both methods being called? > I understand that I could just call each method by name but I'm looking > for a mechanism to avoid this. > > class Foo(object): > def __init__(self): > #call all methods here > def test(self): > print 'The test method' > def hello(self): > print 'Hello user' > === question === Why? What is the use case for a class *all* of whose methods can be called blindly from the __init__()? === code === class Foo(object): def __init__(self): #call all methods here for x in dir(self): if not x.startswith("__"): method = getattr(self, x) if callable(method): print x, type(method), repr(method) method() def test(self): print 'The test method' def hello(self): print 'Hello user' def variablenumberofargsohbuggerbacktothedrawingboard(self, arg1, arg2): print 'The unseen message' obj = Foo() === output === hello > Hello user test > The test method variablenumberofargsohbuggerbacktothedrawingboard > Traceback (most recent call last): File "C:\junk\cowie.py", line 17, in ? obj = Foo() File "C:\junk\cowie.py", line 9, in __init__ method() TypeError: variablenumberofargsohbuggerbacktothedrawingboard() takes exactly 3 arguments (1 given) Cheers, John From fredrik at pythonware.com Thu Jun 8 03:19:31 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 08 Jun 2006 09:19:31 +0200 Subject: GUI Program Error In-Reply-To: References: <1149536396.375285.319390@y43g2000cwc.googlegroups.com> <920hg.2238$No6.47697@news.tufts.edu> <1149700099.634036.88090@f6g2000cwb.googlegroups.com> Message-ID: Eric Brunel wrote: > It may be a platform-specific issue: On Unix/Linux, a window *does* appear > when you instantiate Tk, at least with tcl/tk 8.3 and 8.4 (which is the > latest stable version AFAIK). same on Windows, but it often appears *beneath* the window you're typing into, so you have to look for it in the task bar. this also relies on Python being able to keep the Tkinter event loop going behind the scenes; different command-line implementations have different limitations. for example, on Windows, the event loop runs only when you're at an empty Python prompt; as soon as you start typing the next command, the interpreter switches over to "text input mode", and the event loop is paused until you press return. From eval.apply at gmail.com Tue Jun 27 19:21:53 2006 From: eval.apply at gmail.com (Joe Marshall) Date: 27 Jun 2006 16:21:53 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <1151384511.223582.305760@m73g2000cwd.googlegroups.com> <1151425350.679754.278820@i40g2000cwc.googlegroups.com> Message-ID: <1151450513.458623.139460@b68g2000cwa.googlegroups.com> David Hopwood wrote: > Joe Marshall wrote: > > > (defun blackhole (argument) > > (declare (ignore argument)) > > #'blackhole) > > This is typeable in any system with universally quantified types (including > most practical systems with parametric polymorphism); it has type > "forall a . a -> #'blackhole". The #' is just a namespace operator. The function accepts a single argument and returns the function itself. You need a type that is a fixed point (in addition to the universally quantified argument). > >>The real question is, are there some programs that we > >>can't write *at all* in a statically typed language, because > >>they'll *never* be typable? > > > > Certainly! As soon as you can reflect on the type system you can > > construct programs that type-check iff they fail to type-check. > > A program that causes the type checker not to terminate (which is the > effect of trying to construct such a thing in the type-reflective systems > I know about) is hardly useful. > > In any case, I think the question implied the condition: "and that you > can write in a language with no static type checking." Presumably the remainder of the program does something interesting! The point is that there exists (by construction) programs that can never be statically checked. The next question is whether such programs are `interesting'. Certainly a program that is simply designed to contradict the type checker is of limited entertainment value, but there should be programs that are independently non checkable against a sufficiently powerful type system. From ksheka at gmail.com Tue Jun 20 22:12:54 2006 From: ksheka at gmail.com (K P S) Date: 20 Jun 2006 19:12:54 -0700 Subject: Simple script to make .png thumbnails from .zip archive... In-Reply-To: <1150793966.121556.169590@g10g2000cwb.googlegroups.com> References: <1150660266.413889.217280@c74g2000cwc.googlegroups.com> <1150769193.295701.246330@g10g2000cwb.googlegroups.com> <1150793966.121556.169590@g10g2000cwb.googlegroups.com> Message-ID: <1150855973.968837.151730@r2g2000cwb.googlegroups.com> Thanks a lot! This is what I ended up with. (I would like to get rar archive support, but browsing the web it looks like rar support isn't in any python library (yet)) :-( Anyway, I was able to use the below code unchanged to create thumbnails in nautilus based on the first .jpg file in a .zip archive. Is there any rar support module in python? Thanks again. #!/usr/bin/python import zipfile import sys import gnomevfs import Image import StringIO inURL=gnomevfs.get_local_path_from_uri(sys.argv[1]) outURL=sys.argv[2] zip=zipfile.ZipFile(inURL,mode="r") jpeglist=[x for x in zip.namelist() if '.jp' in x] try: picture=zip.read(jpeglist[0]) except IndexError: print 'No jpeg found' zip.close() #close the file, since we no longer have need of it image = Image.open(StringIO.StringIO(picture)) # create image object from file-like object image.thumbnail((128,128),Image.ANTIALIAS) #create the thumbnail image.save (outURL, "PNG") #output the file in the proper format From bdesth.quelquechose at free.quelquepart.fr Sat Jun 3 13:02:58 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 03 Jun 2006 19:02:58 +0200 Subject: Initializing an attribute that needs the object In-Reply-To: References: <4480be5b$0$27367$626a54ce@news.free.fr> Message-ID: <4481912f$0$20730$636a55ce@news.free.fr> David Pratt a ?crit : David, please, don't top-post (fixed) > > Bruno Desthuilliers wrote: > (snip) >> >> Hint : Python classes are objects too. >> >> >> class Factory(object): >> def __init__(self, handler_class): >> self.handler = handler_class(self) >> >> class SomeHandler(object): >> def __init__(self, factory): >> self.factory = factory >> >> f = Factory(SomeHandler) > Hi Bruno. This is certainly what I was missing. Thank you. I am afraid I > am behind the times with use of object. Will I only use object when I am > not subclassing? If you subclass from a new-style class (almost all classes in the standard lib are...), you don't need to anything more.Else, yes, inherit from 'object', or set 'type' as the metaclass. Both classes defined below are 'new-style' classes: class Parrot: __metaclass__ = type class CheeseChop(object): pass And now: class DeadParrot(Parrot): pass is a new-style class too. > Where will I find a document that provides info on the > use of object in new style classes? In the Fine Manual(tm), of course. Googling python.org for "type unification" or "new-style" should give relevant answers. From rookswood at suburbian.com.au Fri Jun 9 02:08:51 2006 From: rookswood at suburbian.com.au (John Savage) Date: Fri, 09 Jun 2006 06:08:51 GMT Subject: Writing to a certain line? References: <1149576072.168354.14470@f6g2000cwb.googlegroups.com> Message-ID: <060609000112740.09Jun06$rookswood@suburbian.com> "Tommy B" writes: >I was wondering if there was a way to take a txt file and, while >keeping most of it, replace only one line. See, I'd have a file like: .. >Is there any easy way to do this? An easy way? If you know how many bytes in from the start of the file your desired changes are to be positioned, the utility of choice is the strange but wonderful "dd" for Unix, MSwindows, MSDOS, etc. That's its name: dd. Are you planning to execute a call to dd from within a python program? Of course, you are constrained to substituting N bytes with another N bytes, exactly. -- John Savage (my news address is not valid for email) From ptmcg at austin.rr._bogus_.com Sun Jun 4 23:57:22 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Mon, 05 Jun 2006 03:57:22 GMT Subject: re beginner References: <44834d62$0$6192$626a54ce@news.free.fr> <4483665A.206@lexicon.net> <448399AF.9030001@lexicon.net> Message-ID: "John Machin" wrote in message news:448399AF.9030001 at lexicon.net... > On 5/06/2006 10:07 AM, Paul McGuire wrote: > > "John Machin" wrote in message > > news:4483665A.206 at lexicon.net... > >> Fantastic -- at least for the OP's carefully copied-and-pasted input. > >> Meanwhile back in the real world, there might be problems with multiple > >> tabs used for 'prettiness' instead of 1 tab, non-integer values, etc etc. > >> In that case a loop approach that validated as it went and was able to > >> report the position and contents of any invalid input might be better. > > > > Yeah, for that you'd need more like a real parser... hey, wait a minute! > > What about pyparsing?! > > > > Here's a pyparsing version. The definition of the parsing patterns takes > > little more than the re definition does - the bulk of the rest of the code > > is parsing/scanning the input and reporting the results. > > > > [big snip] > > I didn't see any evidence of error handling in there anywhere. > > Pyparsing has a certain amount of error reporting built in, raising a ParseException when a mismatch occurs. This particular "grammar" is actually pretty error-tolerant. To force an error, I replaced "One for the money" with "1 for the money", and here is the exception reported by pyparsing, along with a diagnostic method, markInputline: stuff = 'Yellow hat\t2\tBlue shirt\t1\nWhite socks\t4\tGreen pants\t1\nBlue bag\t4\tNice perfume\t3\nWrist watch\t7\tMobile phone\t4\nWireless cord!\t2\tBuilding tools\t3\nOne for the money\t7\tTwo for the show\t4' badstuff = 'Yellow hat\t2\tBlue shirt\t1\nWhite socks\t4\tGreen pants\t1\nBlue bag\t4\tNice perfume\t3\nWrist watch\t7\tMobile phone\t4\nWireless cord!\t2\tBuilding tools\t3\n1 for the money\t7\tTwo for the show\t4' pattern = dictOf( itemDesc, integer ) + stringEnd print pattern.parseString(stuff) print try: print pattern.parseString(badstuff) except ParseException, pe: print pe print pe.markInputline() Gives: [['Yellow hat', '2'], ['Blue shirt', '1'], ['White socks', '4'], ['Green pants', '1'], ['Blue bag', '4'], ['Nice perfume', '3'], ['Wrist watch', '7'], ['Mobile phone', '4'], ['Wireless cord!', '2'], ['Building tools', '3'], ['One for the money', '7'], ['Two for the show', '4']] Expected stringEnd (at char 210), (line:6, col:1) >!<1 for the money 7 Two for the show 4 -- Paul From scott.daniels at acm.org Fri Jun 2 17:51:23 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Fri, 02 Jun 2006 14:51:23 -0700 Subject: Open Source Charting Tool In-Reply-To: References: <1L0gg.1841$Su3.159041@news20.bellglobal.com> Message-ID: <4480ae6c$1@nntp0.pdx.net> Felipe Almeida Lessa wrote: > Em Sex, 2006-06-02 ?s 16:56 -0400, A.M escreveu: >> I can't browse to www.reporlab.org, but I found http://www.reportlab.com/ >> which has a commercial charting product. Is that what you referring to? > > ReportLab (the commercial bussiness thing on .com) is where the main > developers of ReportLab (a library freely available on www.reporlab.org) > work. So what you want really is .org, but apparently it's having > problems right now. > Or, you could look for: http://www.reportlab.org/ ------------------------^ --Scott David Daniels scott.daniels at acm.org From avelldiroll at yahoo.fr Wed Jun 21 01:30:32 2006 From: avelldiroll at yahoo.fr (Avell Diroll) Date: Wed, 21 Jun 2006 07:30:32 +0200 Subject: OS specific command in Python In-Reply-To: <1150823140.295590.307390@i40g2000cwc.googlegroups.com> References: <1150781429.090359.148560@c74g2000cwc.googlegroups.com> <44979b35$0$8390$626a54ce@news.free.fr> <1150823140.295590.307390@i40g2000cwc.googlegroups.com> Message-ID: <4498d973$0$25496$626a54ce@news.free.fr> diffuser78 at gmail.com wrote: > I tried the following and it seemed to work > > import os > os.system('') > > Any comments.... > This is an simple way to proceed if you don't need your python script to know what happens to the launched process ... When you need to : * send some input to the command from the python script after it is launched * get the output of the command in your python script * get the pid associated to your command * wait for your command to finish * pipe some shell commands * ... you should use the subprocess module. Here is a quick example from the Python Reference Library : http://docs.python.org/lib/node242.html ##Shell Script : output=`dmesg | grep hda` ##Python Script : from subprocess import Popen p1 = Popen(["dmesg"], stdout=PIPE) p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) output = p2.communicate()[0] From john at castleamber.com Thu Jun 1 14:59:53 2006 From: john at castleamber.com (John Bokma) Date: 1 Jun 2006 18:59:53 GMT Subject: how to print newline in xml? References: <1149023930.292203.152540@u72g2000cwu.googlegroups.com> <1149145466.190011.146250@i39g2000cwa.googlegroups.com> <1149186989.073062.230220@f6g2000cwb.googlegroups.com> Message-ID: "anatoli.barski at googlemail.com" wrote: > Thank you! I think description as an attribute is readable. But now I'm > thinking about the order of attributes cause I noticed that for > instance X="0" Y="0" Z="0" set in this order by my script is printed > like X="0" Z="0" Y="0" therefore it could be messy - I wouldn't like > the description to be somewhere between the other attributes. But I > have to test it. I don't know the library you are using, and also have way more experience in Perl. I guess that the attributes are stored in a dictionary, which has no order, and hence the original order of the attributes is lost. In Perl with some modules I use I can chose to use a list or a hash (= dictionary). With the former the original order is preserved. I am sure something like that is possible in Python as well. -- John MexIT: http://johnbokma.com/mexit/ personal page: http://johnbokma.com/ Experienced programmer available: http://castleamber.com/ Happy Customers: http://castleamber.com/testimonials.html From pc at p-cos.net Mon Jun 26 14:03:02 2006 From: pc at p-cos.net (Pascal Costanza) Date: Mon, 26 Jun 2006 20:03:02 +0200 Subject: What is a type error? In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <7i3mg.204167$8W1.155367@fe1.news.blueyonder.co.uk> <44992e6c$2$664$bed64819@news.gradwell.net> <%Igmg.464974$xt.353729@fe3.news.blueyonder.co.uk> <4fv0v3F1kipa6U1@individual.net> <4gakhiF1m698cU1@individual.net> Message-ID: <4galqlF1mae4qU1@individual.net> Chris Smith wrote: > Pascal Costanza wrote: >> Consider division by zero: appropriate arguments for division are >> numbers, including the zero. The dynamic type check will typically not >> check whether the second argument is zero, but will count on the fact >> that the processor will raise an exception one level deeper. > > Of course zero is not appropriate as a second argument to the division > operator! I can't possibly see how you could claim that it is. The > only reasonable statement worth making is that there doesn't exist a > type system in widespread use that is capable of checking this. ...and this is typically not even checked at the stage where type tags are checked in dynamically-typed languages. Hence, it is not a type error. (A type error is always what you define to be a type error within a given type system, right?) Note, this example was in response to David's reply that my definition turns every runtime error into a type error. That's not the case, and that's all I want to say. >> This is maybe better understandable in user-level code. Consider the >> following class definition: >> >> class Person { >> String name; >> int age; >> >> void buyPorn() { >> if (< this.age 18) throw new AgeRestrictionException(); >> ... >> } >> } >> >> The message p.buyPorn() is a perfectly valid message send and will pass >> both static and dynamic type tests (given p is of type Person in the >> static case). > > It appears you've written the code above to assume that the type system > can't cerify that age >= 18... otherwise, the if statement would not > make sense. Right. > It also looks like Java, in which the type system is indeed > not powerfule enough to do that check statically. Right. > However, it sounds as > if you're claiming that it wouldn't be possible for the type system to > do this? No. I only need an example where a certain error is not a type error in _some_ language. I don't need to make a universal claim here. > If so, that's not correct. If such a thing were checked at > compile-time by a static type check, then failing to actually provide > that guarantee would be a type error, and the compiler would tell you > so. That's fine, but not relevant in this specific subplot. Pascal -- 3rd European Lisp Workshop July 3 - Nantes, France - co-located with ECOOP 2006 http://lisp-ecoop06.bknr.net/ From timr at probo.com Wed Jun 14 03:09:45 2006 From: timr at probo.com (Tim Roberts) Date: Wed, 14 Jun 2006 07:09:45 GMT Subject: USB support References: <1150222139.721785.268830@f14g2000cwb.googlegroups.com> Message-ID: "rodmc" wrote: > >I need to write a program which can access the USB ports on Mac and >Linux, is there a library available for Python? The "stable" version of Libusb includes a Python binding. The version in development does not yet. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From jerry.levan at gmail.com Thu Jun 8 21:33:34 2006 From: jerry.levan at gmail.com (jerry.levan at gmail.com) Date: 8 Jun 2006 18:33:34 -0700 Subject: Tktable question? Message-ID: <1149816814.359618.183940@h76g2000cwa.googlegroups.com> Hi, I am using a Tktable in my python database browser program to hold the results of a query. I have declared an ArrayVar like (IntVar) to hold the table contents. In Tcl/Tk programs I have observed that the associated table variable does *not* get "smaller" as various results are displayed in the table. My Tcl/Tk solution to this problem is to "unset" the array variable prior to refilling the rascal. Tain't clear how to do this in Python...Any suggestions? Jerry From sonja.coussell at gmail.com Tue Jun 20 12:50:33 2006 From: sonja.coussell at gmail.com (sonjaa) Date: 20 Jun 2006 09:50:33 -0700 Subject: memory leak problem with arrays In-Reply-To: References: <1150317325.614389.14770@i40g2000cwc.googlegroups.com> <1150349112.780025.289480@i40g2000cwc.googlegroups.com> <1150389750.360090.123430@c74g2000cwc.googlegroups.com> Message-ID: <1150822233.801029.322410@y41g2000cwy.googlegroups.com> Hi Fredrik the array was created by reading in values from a ascii file. also, I've implemented the suggestions, but nothing has worked to date. And yes, I have enough memory for one iteration. The app usually runs out of memory around the 12th iteration. Also, I can send a working version of the app, and the two associated ascii files, if anyone is interested. -Sonja Fredrik Lundh wrote: > sonjaa wrote: > > > "y" is a 500x500 array. > > a 500x500 array of what ? how did you create the array ? > > From madpython at gmail.com Fri Jun 23 16:27:13 2006 From: madpython at gmail.com (madpython) Date: 23 Jun 2006 13:27:13 -0700 Subject: subprocess.Popen on Windows Message-ID: <1151094433.181414.164410@g10g2000cwb.googlegroups.com> playing with subprocess.Popen on Windows I stumbled into the following problem: Python 2.4.3 (#69, Mar 29 2006, 17:35:34) IDLE 1.1.3 >>> import subprocess >>> p1=subprocess.Popen("c:\\asd.bat") #works OK >>> p2=subprocess.Popen("c:\\asd.bat",stdout=subprocess.PIPE) Traceback (most recent call last): File "", line 1, in -toplevel- p2=subprocess.Popen("c:\\asd.bat",stdout=subprocess.PIPE) File "C:\Python24\lib\subprocess.py", line 533, in __init__ (p2cread, p2cwrite, File "C:\Python24\lib\subprocess.py", line 593, in _get_handles p2cread = self._make_inheritable(p2cread) File "C:\Python24\lib\subprocess.py", line 634, in _make_inheritable DUPLICATE_SAME_ACCESS) TypeError: an integer is required >>> What do I do wrongly? From sekhon.hari at googlemail.com Tue Jun 27 11:43:17 2006 From: sekhon.hari at googlemail.com (Hari Sekhon) Date: Tue, 27 Jun 2006 16:43:17 +0100 Subject: Unbound Local error? How? In-Reply-To: <44a14f72$0$16244$636a55ce@news.free.fr> References: <44a14f72$0$16244$636a55ce@news.free.fr> Message-ID: <44A15215.5060101@gmail.com> Bruno Desthuilliers wrote: > Hari Sekhon wrote: > >> I've got some code as follows: >> >> import re >> re_regexname = re.compile('abc') >> >> ..... >> ..... various function defs >> ..... >> >> def func1(): >> ... >> func2() >> ... >> >> def func2(): >> if re_regexname.match('abc'): >> >> >> if __name__ == '__main__': >> func1() >> >> >> but this returns the Traceback: >> >> UnboundLocalError: local variable 're_regexname' referenced before >> assignment >> > > this is *not* the traceback. This is only the error message. The > traceback contains all needed informations (or at least all possible > information at this point) to know what happened. But you did not post > the traceback. Nor did you post the minimal runnable code snippet > producing this error. > > >> How? >> > > How could we know ? > > > sorry, I know it looks like I was being stingy but the traceback was not that helpful, not without seeing more a huge amount more of the code. I was trying to abbreviate. Traceback (most recent call last): File "./backup.py", line 649, in ? backup(machine,share) File "./backup.py", line 364, in backup backupdir(source,destination) File "./backup.py", line 398, in backupdir (dirlist,filelist) = getdirlisting( source ) File "./backup.py", line 445, in getdirlisting if re_skip_dirs.match(x): UnboundLocalError: local variable 're_skip_dirs' referenced before assignment This doesn't really show that much, I figured the problem was the following: def getdirlisting(): re_skip_dirs = re_skip_top_dirs #Here's the culprit where both these regex compiled objects were declared at the top level, it seems that the assignment is trying to use the local variable re_skip_top_dirs which doesn't exist, that's why I'm getting a traceback, commenting out this line it runs fine. -h -------------- next part -------------- An HTML attachment was scrubbed... URL: From rasmussen.bryan at gmail.com Tue Jun 20 04:07:40 2006 From: rasmussen.bryan at gmail.com (bryan rasmussen) Date: Tue, 20 Jun 2006 10:07:40 +0200 Subject: crawlers in python with graphing? In-Reply-To: References: Message-ID: <3bb44c6e0606200107ua5e930fhd60ab266bac684cb@mail.gmail.com> Hi, Sorry, was imprecise, I meant not save the downloaded page locally. There probably isn't one though, so I should build one myself. Probably just need a good crawler that can be set to dump all links into dataset that I can analyse with R. Cheers, Bryan Rasmussen On 6/19/06, Marc 'BlackJack' Rintsch wrote: > In , bryan rasmussen > wrote: > > > It should hopefully be as high level as Wget, not download the pages > > but just follow the links, and output graphs. > > How do you get at the links without downloading the page!? > > Ciao, > Marc 'BlackJack' Rintsch > -- > http://mail.python.org/mailman/listinfo/python-list > From fredrik at pythonware.com Tue Jun 13 08:36:09 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 13 Jun 2006 14:36:09 +0200 Subject: Python Video processing. References: <1150201746.657059.228570@i40g2000cwc.googlegroups.com> Message-ID: "Ant" wrote: > In particular, does anyone know whether the data obtained from decoding > the video frame as in the following snippet from > http://pymedia.org/tut/src/dump_video.py.html: > > dd= d.convert( fmt ) > img= pygame.image.fromstring( dd.data, dd.size, "RGB" ) > > can be directly loaded into a PIL Image object (and back again?)? iirc, the pygame fromstring/tostring methods are designed to be data-compatible with PIL's corresponding methods, so you should be able to do im = Image.fromstring("RGB", dd.size, dd.data) instead of doing that pygame.image call (not that the argument order is different). for details, see the pygame tostring/fromstring docs, and the corresponding PIL methods: http://www.pygame.org/docs/ref/image.html http://www.pythonware.com/library/pil/handbook/image.htm hope this helps! From swillison at gmail.com Wed Jun 7 07:55:20 2006 From: swillison at gmail.com (Simon Willison) Date: 7 Jun 2006 04:55:20 -0700 Subject: CENSORSHIP - Django Project (Schema Evolution Support) References: <4486B9FB.9030804@lazaridis.com> Message-ID: <1149681320.550163.277030@i40g2000cwc.googlegroups.com> Ilias Lazaridis wrote: > [posted publicly to comp.lang.python, with email notification to 6 > recipients relevant to the topic] > > I have implemented a simple schema evolution support for django, due to > a need for a personal project. Additionally, I've provided an Audit: > > http://case.lazaridis.com/wiki/DjangoAudit > > As a result, I was censored ('banned' from the development list) Please see this message for background: http://groups.google.com/group/django-users/msg/5a96eabf75f2b9c7 To summarise, it was felt that Ilias was deliberately trolling the mailing list. No further explanation seems necessary. From iainking at gmail.com Thu Jun 22 10:59:48 2006 From: iainking at gmail.com (Iain King) Date: 22 Jun 2006 07:59:48 -0700 Subject: Feed wxComboBox with dictionary/hash In-Reply-To: <1150983925.131182.88670@i40g2000cwc.googlegroups.com> References: <1150983925.131182.88670@i40g2000cwc.googlegroups.com> Message-ID: <1150988388.287797.172890@b68g2000cwa.googlegroups.com> Roland Rickborn wrote: > Hi folks, > > I am relatively new to Python. Although I read a lot of howtos, > introductions and wikis, I am still having trouble ;-) > > My querstion: > As the subject says, I'd like to feed a wx.ComboBox with a > dictionary/hash. According to the posting of Stano Paska ("wxComboBox > <> combobox", 20 Jul. 2004), there seems to be a way to do this: > > > You must use something like > > combo.Append('aaa', 'a') > > combo.Append('bbb', 'b') > > ... > > My problem is: > my data has thousands of entries. Therefore, I'd like to feed the > combobox with a dictionary (which itself is fed by a database query). > > My first question: > how can a wx.ComboBox be fed by a dictionary? > > For further help, Stano says: > > > read manual for more details... > > Ok, I'd like to. But which one? > I was reading http://www.wxpython.org/docs/api/wx.ComboBox-class.html > and didn't even find the above mentioned append method :-( > > TIA, > Roland R. wxComboBox inherits from wxControlWithItems (as does wx.ListBox, and other controls which hold lists). See: http://wxwidgets.org/manuals/2.6.3/wx_wxcontrolwithitems.html#wxcontrolwithitems Iain From aleax at mac.com Sat Jun 10 13:51:42 2006 From: aleax at mac.com (Alex Martelli) Date: Sat, 10 Jun 2006 10:51:42 -0700 Subject: Get my airlines boarding pass References: <1hgotbh.1vd74fb1qhzdziN%aleax@mac.com> <1149954923.868806.87270@m38g2000cwc.googlegroups.com> Message-ID: <1hgponk.ojn7k0193tiamN%aleax@mac.com> KenAggie wrote: > Good idea - I just bought the 2nd edition of the book and it is very > good. Will check it out. I'm happy that you liked the book, but I meant the online site, sorry if that wasn't clear!-) Alex From micklee74 at hotmail.com Tue Jun 13 10:05:49 2006 From: micklee74 at hotmail.com (micklee74 at hotmail.com) Date: 13 Jun 2006 07:05:49 -0700 Subject: a string problem In-Reply-To: References: <1150206140.912224.113420@p79g2000cwp.googlegroups.com> Message-ID: <1150207549.429623.231830@f14g2000cwb.googlegroups.com> John Salerno wrote: > micklee74 at hotmail.com wrote: > > hi > > > > if i have a some lines like this > > a ) "here is first string" > > b ) "here is string2" > > c ) "here is string3" > > > > When i specify i only want to print the lines that contains "string" ie > > the first line and not the others. If i use re module, how to compile > > the expression to do this? I tried the re module and using simple > > search() and everytime it gives me all the 3 lines that have "string" > > in it, whereas i only need line 1. > > If re module is not needed, how can i use string manipulation to do > > this? thanks > > > > As far as re goes, you can search for the pattern '\bstring\b', which > will find just the word 'string' itself. Not sure if there's a better > way to do it with REs. > > And I'm actually ashamed to admit that I know the RE way, but not the > regular string manipulation way, if there is one! This seems like > something easy enough to do without REs though. just curious , if RE has the \b and it works, can we look into the source of re and see how its done for \b ? From bignose+hates-spam at benfinney.id.au Thu Jun 15 21:23:56 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 16 Jun 2006 11:23:56 +1000 Subject: Need Help comparing dates References: <1150419503.224684.320550@c74g2000cwc.googlegroups.com> Message-ID: <87hd2llwpf.fsf@benfinney.id.au> colincolehour at gmail.com writes: > I am new to Python and am working on my first program. I am trying > to compare a date I found on a website to todays date. The problem I > have is the website only shows 3 letter month name and the date. > Example: Jun 15 The 'datetime' module in the standard library will do the job of creating date objects that can be compared. Construct a date from arbitrary values with datetime.date(), get the current date with datetime.date.today(). The objects returned by those functions can be compared directly. As for how to get from a string representation to a date object, you're now talking about parsing strings to extract date/time information. This isn't provided in the standard library, largely because there's no "one obvious way to do it". An existing PEP proposing adding such functionality has since been withdrawn: Parsing datetime values from strings is fuzzy and prone to lots of assumptions and errors, so the programmer must choose their own set of assumptions. One popular implementation of a specific set of assumptions is the egenix 'mxDateTime' module. That module predates (and was largely an inspiration for) the standard library 'datetime' module; however, I don't know if the egenix module uses objects that can be used with those from the standard library. -- \ "There is no reason anyone would want a computer in their | `\ home." -- Ken Olson, president, chairman and founder of | _o__) Digital Equipment Corp., 1977 | Ben Finney From rtw at freenet.co.uk Fri Jun 2 05:28:25 2006 From: rtw at freenet.co.uk (Rob Williscroft) Date: Fri, 02 Jun 2006 04:28:25 -0500 Subject: how to define a static field of a given class References: <1149239221.045268.6170@g10g2000cwb.googlegroups.com> Message-ID: feel_energetic wrote in news:1149239221.045268.6170 @g10g2000cwb.googlegroups.com in comp.lang.python: > Hi, > > I already knew how to define a static method of a class( using > staticmethod() ),but I find there isn't a built-in func to build a > static field ( something like staticfield() ) > can anyone help me on this? > thanks very much for your help :) > What you possibly want is just a class attribute: class MyClass( object ): static_field = 10 myInstance = MyClass() print MyClass.static_field, myInstance.static_field Rob. -- http://www.victim-prime.dsl.pipex.com/ From jo at durchholz.org Sun Jun 25 07:48:04 2006 From: jo at durchholz.org (Joachim Durchholz) Date: Sun, 25 Jun 2006 13:48:04 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <34aj92h0g7tqi9amhh7k3ieq5n568t0e6f@4ax.com> Message-ID: Dimitri Maziuk schrieb: > That is the basic argument in favour of compile time error checking, > extended to runtime errors. I don't really care if it's the compiler > or runtime that tells the luser "your code is broken", as long as it > makes it clear it's *his* code that's broken, not mine. You can make runtime errors point to the appropriate code. Just apply "programming by contract": explicitly state what preconditions a function is requiring of the caller, have it check the preconditions on entry (and, ideally, throw the execption in a way that the error is reported in the caller's code - not a complicated thing but would require changes in the exception machinery of most languages). Any errors past that point are either a too liberal precondition (i.e. a bug in the precondition - but documenting wrong preconditions is still a massive bug, even if it's "just" a documentation bug), or a bug in the function's code. Regards, Jo From fredrik at pythonware.com Wed Jun 7 03:06:03 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 07 Jun 2006 09:06:03 +0200 Subject: 10GB XML Blows out Memory, Suggestions? In-Reply-To: <1149623638.736338.185320@h76g2000cwa.googlegroups.com> References: <1149594519.098115.8980@u72g2000cwu.googlegroups.com> <2Qfhg.18186$0v4.787@tornado.texas.rr.com> <1149623638.736338.185320@h76g2000cwa.googlegroups.com> Message-ID: axwack at gmail.com wrote: > Paul, > > This is interesting. Unfortunately, I have no control over the XML > output. The file is from Goldmine. However, you have given me an > idea... > > Is it possible to read an XML document in compressed format? sure. you can e.g. use gzip.open to create a file object that decompresses on the way in. file = gzip.open("data.xml.gz") for event, elem in ET.iterparse(file): if elem.tag == "item": elem.clear() I tried compressing my 1 GB example, but all 1000-byte records in that file are identical, so I got a 500x compression, which is a bit higher than you can reasonably expect ;-) however, with that example, I get a stable parsing time of 26 seconds, so it looks as if gzip can produce data about as fast as a preloaded disk cache... From onurb at xiludom.gro Mon Jun 26 13:02:37 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Mon, 26 Jun 2006 19:02:37 +0200 Subject: Replace Whole Object Through Object Method In-Reply-To: <1151337453.804750.293180@b68g2000cwa.googlegroups.com> References: <1151337453.804750.293180@b68g2000cwa.googlegroups.com> Message-ID: <44a0132d$0$21282$626a54ce@news.free.fr> digitalorganics at gmail.com wrote: > How can an object replace itself using its own method? AFAIK, It can't (but I can be wrong - some guru around ?). > See the > following code: > > class Mixin: > def mixin(object, *classes): > NewClass = type('Mixin', (object.__class__,) + classes, {}) > newobj = NewClass() > newobj.__dict__.update(object.__dict__) > return newobj > > def isClass(object): > if 'classobj' in str(type(object)): > return 1 > elif "'type'" in str(type(object)): > return 1 > else: > return 0 > def listClasses(): > classes = [] > for eachobj in globals().keys(): > if isClass(globals()[eachobj]): > classes.append(globals()[eachobj]) > print eachobj > return classes FWIW: Python 2.4.3 (#1, Jun 3 2006, 17:26:11) [GCC 3.4.6 (Gentoo 3.4.6-r1, ssp-3.4.5-1.0, pie-8.7.9)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> def dumbfactory(): ... class Dumb(object): pass ... class Dummy: pass ... return Dumb, Dummy ... >>> globals() {'__builtins__': , '__name__': '__main__', '__doc__': None, 'dumbfactory': } >>> def fun(): ... dumb, dummy = dumbfactory() ... return ... >>> fun() >>> globals() {'__builtins__': , '__name__': '__main__', 'fun': , '__doc__': None, 'dumbfactory': } >>> Looks like dumb and dummy won't get listed... And also: >>> class Mymeta(type): ... pass ... >>> class Foo(object): ... __metaclass__ = Mymeta ... >>> "'type'" in str(type(globals()['Mymeta'])) True Looks like this will list metaclasses too... May or may not be a problem... > def MixInto(Class, Mixin): You're aware that in this function's scope, the 'Mixin' arg name will shadow the Mixin class name ? (sorry for asking dumb question). > if Mixin not in Class.__bases__: > Class.__bases__ += (Mixin,) > ------------------------------------------------------------------------ > > Okay, so the mixin function becomes part of whatever class I choose and > hence its instances, but the problem is that the way I currently have > it setup mixin() returns a new object, instead of replacing whatever > class instance that calls it into that new object. I hope I'm making > sense here. > > Basically what I need is for the method to be able to find out the name > of the instance, then I can just go to the globals dictionary to do the > replacement. > > Advance thanks to all who can help... > Instead of exposing problems with your solution, you may want to expose the real use case ? -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From Bulkan at gmail.com Sat Jun 24 09:35:34 2006 From: Bulkan at gmail.com (placid) Date: 24 Jun 2006 06:35:34 -0700 Subject: search engine In-Reply-To: References: <1151151361.359777.269130@y41g2000cwy.googlegroups.com> <1151154081.787601.121110@i40g2000cwc.googlegroups.com> Message-ID: <1151156134.448196.319350@g10g2000cwb.googlegroups.com> Daniel Nogradi wrote: > > hai all, > > i am student of computer science dept. i have planned to > > design a search engine in python. i am seeking info about how to > > proceed further. > > i need to know what r the modules that can be used. > > There are these two guys Sacha or Sergey and Larry (if I remember > correctly) who already wrote a cute search engine in python, perhaps > you could ask them for some help. Sergey and Larry youre not talking about Google are you? *wink* ;) From aleax at mac.com Sun Jun 25 17:18:25 2006 From: aleax at mac.com (Alex Martelli) Date: Sun, 25 Jun 2006 14:18:25 -0700 Subject: array manipulation without for loops References: <1151251578.463273.24370@m73g2000cwd.googlegroups.com> <1151253182.496596.185420@r2g2000cwb.googlegroups.com> <1hhhes5.1hw0kbeniihqiN%aleax@mac.com> <1151254570.730665.298450@r2g2000cwb.googlegroups.com> <1hhhg1j.11oc03fuoikz8N%aleax@mac.com> <1151256882.568752.118970@b68g2000cwa.googlegroups.com> <1151261680.379790.185440@u72g2000cwu.googlegroups.com> Message-ID: <1hhhqa1.16suwwqysc1qeN%aleax@mac.com> Sheldon wrote: > The following script (using your function) raised no exception so it > worked! Elegant Alex, thanx. > > res = equalize_arrays(msgtmp,ppstmp,255) # class > (ppstmp,msgtmp) = res.equalize() # class method > for i in range(int(main.xsize)): > for j in range(int(main.ysize)): > if msgtmp[i,j] == 255 and ppstmp[i,j] != 255: > raise "equalize error!" > if ppstmp[i,j] == 255 and msgtmp[i,j] != 255: > raise "equalize error!" > I read up on the putmask function and I don't understand this part: > > >>> print x > [10 1 30 3 50] > >>> putmask(x, [1,0,1,0,1], [-1,-2]) > >>> print x > [-1 1 -1 3 -1] > > Can you explain why the -2 didn't factor in? Because it always happens in places where the mask is 0, of course -- the third argument gets conceptually "repeated" to get the length of the mask, giving [-1, -2, -1, -2, -1] -- and the "-2" always occur where the mask is 0, so they don't matter. Exactly as I would expect from: >>> print Numeric.putmask.__doc__ putmask(a, mask, v) results in a = v for all places mask is true. If v is shorter than mask it will be repeated as necessary. In particular v can be a scalar or length 1 array. and I just can't see where you might have formed any different expectations from this documentation. Use a different mask, say [1,0,0,1,1] -- and the -2 in 4th place will be set into x, just like the -1 ocurrences at the start and end. Similarly, say: >>> Numeric.compress([1,0,1,0,1], [-1, -2]*3) array([-1, -1, -1]) even though here we have to explicitly use the "*3" part for repetition since compress, differently from putmask, doesn't implicitly repeat the last argument, the idea is similar: pick only elements corresponding to a true value in the mask argument. If what you want is to put -1 where the first 1 in the mask occurs, -2 where the 2nd 1 in the mask occurs, and so forth, you need some auxiliary manipulation of the indices to prepare the proper "values" array, for example: import Numeric class SequenceRepeater(object): def __init__(self, seq, thelen): self.seq = seq self.len = thelen def __len__(self): return self.len def __getitem__(self, i): if i<0: i += self.len return self.seq[i % len(self.seq)] def strangeput(anarray, amask, somevalues): repeater = SequenceRepeater(somevalues, len(amask)) somevalues = Numeric.take(repeater, Numeric.cumsum(amask)-1) Numeric.putmask(anarray, amask, somevalues) if __name__ == '__main__': x = Numeric.zeros(5) strangeput(x, [1, 0, 1, 0, 1], [-1, -2]) print x brain:~/pynut alex$ python pr.py [-1 0 -2 0 -1] There may be simpler and faster approaches for this, of course, but I had this SequenceRepeater auxiliary class in my "mixed bag of useful stuff" so I just copied-and-pasted a solution based on it!-) Alex From dev at null.com Tue Jun 27 19:13:08 2006 From: dev at null.com (Mike Currie) Date: Tue, 27 Jun 2006 16:13:08 -0700 Subject: Python UTF-8 and codecs References: <5Hgog.627$Gv.173@fed1read09> Message-ID: Well, not really. It doesn't affect the result. I still get the error message. Did you get a different result? "Serge Orlov" wrote in message news:mailman.7522.1151446300.27775.python-list at python.org... > On 6/27/06, Mike Currie wrote: >> Okay, >> >> Here is a sample of what I'm doing: >> >> >> Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)] on >> win32 >> Type "help", "copyright", "credits" or "license" for more information. >> >>> filterMap = {} >> >>> for i in range(0,255): >> ... filterMap[chr(i)] = chr(i) >> ... >> >>> filterMap[chr(9)] = chr(136) >> >>> filterMap[chr(10)] = chr(133) >> >>> filterMap[chr(136)] = chr(9) >> >>> filterMap[chr(133)] = chr(10) > > This part is incorrect, it should be: > > filterMap = {} > for i in range(0,128): > filterMap[chr(i)] = chr(i) > > filterMap[chr(9)] = unichr(136) > filterMap[chr(10)] = unichr(133) > filterMap[unichr(136)] = chr(9) > filterMap[unichr(133)] = chr(10) From johnjsal at NOSPAMgmail.com Fri Jun 9 16:04:46 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 09 Jun 2006 20:04:46 GMT Subject: wxPython: Should you use a master sizer object? Message-ID: Sorry for posting here again. I tried the wxPython list but I'm not sure I'm sending to the right email address! It bounced back. Besides, your opinions are too good to pass up. ;) My question was: I was wondering, is it recommended to always have a top-level sizer in which you place all other sizers, or is it acceptable to have mulitple sizers that are not grouped together? From kent at kentsjohnson.com Tue Jun 13 16:38:21 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Tue, 13 Jun 2006 16:38:21 -0400 Subject: Is there a better way of accessing functions in a module? In-Reply-To: <1150218521.603365.306410@u72g2000cwu.googlegroups.com> References: <1150218398.443615.304880@p79g2000cwp.googlegroups.com> <1150218521.603365.306410@u72g2000cwu.googlegroups.com> Message-ID: <448f20ff_1@newspeer2.tds.net> Ant wrote: > Ant wrote: > ... >> But this feels like a hack... Is there a cleaner way for accessing the >> functions of the current module similar to the __dict__ attribute of >> classes? i.e. a way to access the local symbol table? > > Sorry - posted too soon. Found the globals() built-in... You can also import __main__ tests = [x for x in dir(__main__) if x.endswith("test")] for test in tests: getattr(__main__, test)() but I second the suggestion of looking in to unittest or one of the other test frameworks. Kent From dima at 127.0.0.1 Wed Jun 21 12:12:48 2006 From: dima at 127.0.0.1 (Dimitri Maziuk) Date: Wed, 21 Jun 2006 16:12:48 +0000 (UTC) Subject: What is Expressiveness in a Computer Language References: <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> Message-ID: George Neuner sez: > On Mon, 19 Jun 2006 22:02:55 +0000 (UTC), Dimitri Maziuk > wrote: > >>Yet Another Dan sez: >> >>... Requiring an array index to be an integer is considered a typing >>> problem because it can be checked based on only the variable itself, >>> whereas checking whether it's in bounds requires knowledge about the array. >> >>You mean like >> subtype MyArrayIndexType is INTEGER 7 .. 11 >> type MyArrayType is array (MyArrayIndexType) of MyElementType >> > > If the index computation involves wider types it can still produce > illegal index values. The runtime computation of an illegal index > value is not prevented by narrowing subtypes and cannot be statically > checked. My vague recollection is that no, it won't unless _you_ explicitly code an unchecked type conversion. But it's been a while. HTH Dima -- I have not been able to think of any way of describing Perl to [person] "Hello, blind man? This is color." -- DPM From rob.clewley at gmail.com Fri Jun 16 19:28:13 2006 From: rob.clewley at gmail.com (Rob Clewley) Date: Fri, 16 Jun 2006 19:28:13 -0400 Subject: ANN: updated release of PyDSTool dynamical systems package (version 0.83.2 patch #1) Message-ID: Version 0.83.2 of PyDSTool has been released, and now includes a patch for compilation of AUTO on Linux (as of 15th June). PyDSTool is an open-source project providing a range of dynamical systems simulation and analysis tools. It supports both continuous- and discrete-time systems including ordinary differential equations, differential-algebraic equations, maps, and "hybrid" event-driven systems. It also provides model building classes and templates for specification of complex networks, including the manipulation of symbolic math expressions. Other features include enhancements of SciPy and Numarray classes. The sub-package PyCont provides native continuation and bifurcation analysis tools (now including a low-level interface to AUTO). Included toolbox utilities provide template classes and functions for scientific applications, including to systems biology and computational neuroscience. Documentation and tutorial information can be found on the wiki: http://pydstool.sourceforge.net or download the package directly from http://sourceforge.net/projects/pydstool Your continuing feedback and code contributions are greatly appreciated. Please help us improve this project! Thanks for your attention, Rob Clewley, Erik Sherwood, Drew LaMar, Dept. of Mathematics and Center for Applied Mathematics, Cornell University. -------------- next part -------------- An HTML attachment was scrubbed... URL: From chris.uppal at metagnostic.REMOVE-THIS.org Wed Jun 21 05:32:40 2006 From: chris.uppal at metagnostic.REMOVE-THIS.org (Chris Uppal) Date: Wed, 21 Jun 2006 10:32:40 +0100 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> Message-ID: <44992e6c$1$664$bed64819@news.gradwell.net> Anton van Straaten wrote: > But a program as seen by the programmer has types: the programmer > performs (static) type inference when reasoning about the program, and > debugs those inferences when debugging the program, finally ending up > with a program which has a perfectly good type scheme. It's may be > messy compared to say an HM type scheme, and it's usually not proved to > be perfect, but that again is an orthogonal issue. I like this way of looking at it. -- chris From rbonvall at gmail.com Sun Jun 4 20:05:01 2006 From: rbonvall at gmail.com (Roberto Bonvallet) Date: Sun, 4 Jun 2006 20:05:01 -0400 Subject: reordering elements of a list In-Reply-To: <1149390075.653265.193370@j55g2000cwa.googlegroups.com> References: <1149382009.640607.217470@y43g2000cwc.googlegroups.com> <1149390075.653265.193370@j55g2000cwa.googlegroups.com> Message-ID: <1908cb6b0606041705r308fea60rae2e0fb6adee3115@mail.gmail.com> greenflame : > Roberto: I do not understand the first half of the last line of your > code. [mainlist[i - 1] for i in orderinglist] is a list made with the elements of orderinglist, but instead of taking the actual value i from the list, the value that is taken is mainlist[i - 1]. If orderinglist is [3, 4, 2, 1], then [mainlist[i - 1] for i in orderinglist] is: [mainlist[3 - 1], mainlist[4 - 1], mainlist[2 - 1], mainlist[1 - 1]] Remember that indexing starts from 0. -- Roberto Bonvallet From jim at trainplayer.com Tue Jun 20 15:09:54 2006 From: jim at trainplayer.com (Jim) Date: 20 Jun 2006 12:09:54 -0700 Subject: can't find win32api from embedded pyrun call In-Reply-To: <1150778593.107920.286580@b68g2000cwa.googlegroups.com> References: <1150765862.185334.53290@u72g2000cwu.googlegroups.com> <1150778593.107920.286580@b68g2000cwa.googlegroups.com> Message-ID: <1150830594.337374.48170@p79g2000cwp.googlegroups.com> Miki wrote: > IIRC you need to set the path explicitly in an embedded interpreter. > See the code in "site.py" (which again IMO is *not* imported when the > interpreter starts). Thanks Miki. Actually that doesn't turn out to be the problem. If I display sys.path within the embedded script, it shows the complete list of paths, there is no need to pre-load. The problem turned out to be a mismatch of parts. For one thing, building the debug lib from Python sources using VS2005 leads to the crash in PyInitialize (I don't know why others haven't run into this); building with VS2003 did away with that. But that then led to the well-known problem with a FILE* where the app is using one msvcrt and the lib another. At some point in fixing these issues, the "cannot find win32api" went away. I now use this trick from a colleague which allows me to build a debug version of my app but load the release version of the lib: bracket the "#include python.h" statement with undef/redef of _DEBUG. And this trick to get around the FILE* problem (since my app is VS2005 and the lib is 2003): instead of PyRun_SimpleFile, use PyRun_SimpleString ("execfile(fname)"). I got this from the win32 FAQ. I hope someone benefits from this, it cost me plenty to figure out. -- Jim From drewbert10 at mchsi.com Tue Jun 20 14:48:02 2006 From: drewbert10 at mchsi.com (Andrew Burkhardt) Date: Tue, 20 Jun 2006 18:48:02 +0000 Subject: Running a Python App from a Web Page Message-ID: <062020061848.24877.449842E2000310B30000612D219791336303010CD2079C080C03BFCFCE9B9D0A0D990A9D0B@mchsi.com> I have created an Tkinter GUI application with Python and I want to host this on a web page that is provided by my internet provider (mediacom). Whats the easiest and best method to convert my python code in order for it can be ran from a web page? -------------- next part -------------- An HTML attachment was scrubbed... URL: From siona at chiark.greenend.org.uk Wed Jun 7 07:43:08 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 07 Jun 2006 12:43:08 +0100 (BST) Subject: Bug in list comprehensions? References: <1149675723.118917.276940@j55g2000cwa.googlegroups.com> Message-ID: <0Se*Z7Air@news.chiark.greenend.org.uk> Fredrik Lundh wrote: >Iain King wrote: >> I'm guessing I'm the one confused here... but I'm confused! What's >> going on? >the clauses nest from left to right, not from right to left, so "[x for >x in y for y in beta]" is equivalent to > > out = [] > for x in y: > for y in beta: > out.append(x) And a list comprehension doesn't get a namespace to itself (cf. generator comprehensions) so "leaks" its variables. Exactly as above. So the y being iterated over in "for x in y" is the y from the previous inner iteration ("for y in beta"). -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From alex.nanou at gmail.com Thu Jun 22 13:21:44 2006 From: alex.nanou at gmail.com (Alex A. Naanou) Date: 22 Jun 2006 10:21:44 -0700 Subject: The code that could not be... In-Reply-To: References: <1150936844.874347.163060@r2g2000cwb.googlegroups.com> Message-ID: <1150996904.737708.309670@g10g2000cwb.googlegroups.com> Fredrik Lundh wrote: > Alex A. Naanou wrote: > > > To mention several tasks that can be made trivial using this technique > > are, for instance zope-like acquisitions, various ACLs, interfaces and > > other namespace manipulation patterns. > > eh ? why not use Python's OO mechanisms for this, like everyone else is > doing... > > usually, as the ammount and complexity of code grows, I try to search for simpler and more natural ways of doing things.... and if I have to compare a 5 line implementation will always win over a 50 line module especially if this module runs substantially slower! :) From boyle5 at llnl.gov Thu Jun 22 11:18:08 2006 From: boyle5 at llnl.gov (boyle5 at llnl.gov) Date: 22 Jun 2006 08:18:08 -0700 Subject: serial port servo control Message-ID: <1150989488.345731.49680@m73g2000cwd.googlegroups.com> So I ordered a mini SSC II (the servo controller), in order to control some servos from the computer. I was hoping to use python to do the control but have two questions... 1) How should I write to the serial port with python? I found the module "pyserial": http://pyserial.sourceforge.net/ on the python cheeseshop, and it looks solid but I thought you might have a better suggestion. 2) To control the servos I have to send the SSC II a string of 3 numbers, 3 bytes long (so 3 numbers in the range 0 - 255, each as a single byte, one after another). In C I'd do this by sending 3 char's, as they're only 1 byte, but i'm not exactly sure how to do it in Python. From bayerj at in.tum.de Thu Jun 22 05:39:43 2006 From: bayerj at in.tum.de (bayerj) Date: 22 Jun 2006 02:39:43 -0700 Subject: How to generate all permutations of a string? In-Reply-To: References: Message-ID: <1150969183.210456.63690@y41g2000cwy.googlegroups.com> Mind, that Lawrence's solution may contain doubles: >>> [ i for i in permute("aa") ] [('a', 'a'), ('a', 'a')] If you don't want this, use sets. From rhymes at myself.com Wed Jun 28 17:50:38 2006 From: rhymes at myself.com (Lawrence Oluyede) Date: Wed, 28 Jun 2006 23:50:38 +0200 Subject: mmap as a sequence behavior Message-ID: <1hho1x1.1ntwxi3z2hdzhN%rhymes@myself.com> While wrapping mmap indexing/sequence emulation I noticed something "strange". The source code of this oddity is: static PyObject * mmap_item(mmap_object *self, Py_ssize_t i) { CHECK_VALID(NULL); if (i < 0 || (size_t)i >= self->size) { PyErr_SetString(PyExc_IndexError, "mmap index out of range"); return NULL; } return PyString_FromStringAndSize(self->data + i, 1); } located in mmapmodule.c What's got my attention was the fact that passing -1 from Python does not trigger the exception but is changed to the last positive and valid index. Let's make an example: import mmap f = open("foo", "w+") f.write("foobar") f.flush() m = mmap.mmap(f.fileno(), 6) print m[-1] # == 'f' I expect this raise IndexError as reading the C source code but it behaves exactly like sequence types in Python. That's fair to me but I don't get *where* my index is translated. If I print the 'i' variable in the C source code before the if statement I get len(ourmap) - 1 instead of "-1" What am I missing from the C API? -- Lawrence - http://www.oluyede.org/blog "Nothing is more dangerous than an idea if it's the only one you have" - E. A. Chartier From forman.simon at gmail.com Mon Jun 19 21:57:07 2006 From: forman.simon at gmail.com (forman.simon at gmail.com) Date: 19 Jun 2006 18:57:07 -0700 Subject: Function definition References: <1150758338.302466.102040@r2g2000cwb.googlegroups.com> Message-ID: <1150768627.119025.155960@c74g2000cwc.googlegroups.com> aarondesk wrote: ... > > Now I've tried putting the function declaration after the call but the > program wouldn't work. Is there anyway to put function declarations at > the end of the program, rather than putting them at the beginning, > which is rather clunky? > > Thanks. > Aaron A function can call functions defined "below" it: def a(): return b() def b(): return 'foo' print a() # prints 'foo' because at runtime both functions exist in the current namespace. But module-level statements can't call functions defined below them because the function objects haven't been created yet. That's why you get a NameError, the name 'b' won't been bound to anything until after the def statement has been interpreted. You can, of course, put your functions in another module. Hope that helps, ~Simon From Dennis.Benzinger at gmx.net Tue Jun 27 14:46:22 2006 From: Dennis.Benzinger at gmx.net (Dennis Benzinger) Date: Tue, 27 Jun 2006 20:46:22 +0200 Subject: Problem with sets and Unicode strings Message-ID: <44a17d05$1@news.uni-ulm.de> Hi! The following program in an UTF-8 encoded file: # -*- coding: UTF-8 -*- FIELDS = ("F?cher", ) FROZEN_FIELDS = frozenset(FIELDS) FIELDS_SET = set(FIELDS) print u"F?cher" in FROZEN_FIELDS print u"F?cher" in FIELDS_SET print u"F?cher" in FIELDS gives this output False False Traceback (most recent call last): File "test.py", line 9, in ? print u"F??cher" in FIELDS UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 1: ordinal not in range(128) Why do the first two print statements succeed and the third one fails with an exception? Why does the use of set/frozenset remove the exception? Thanks, Dennis From fredrik at pythonware.com Fri Jun 30 06:29:58 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 30 Jun 2006 12:29:58 +0200 Subject: Way for see if dict has a key References: <6V6pg.21624$_J1.271925@twister2.libero.it> Message-ID: Michele Petrazzo wrote: > what the preferred way for see if the dict has a key? > We have a lot of solutions: > > key in dict new syntax (2.3 and later). > key in dict.keys() inefficient and pointless. > dict.has_key(key) old syntax; use for code that needs to be backwards compatible. > but what the better or the more "pythonic"? see above. From gene.tani at gmail.com Mon Jun 5 09:16:29 2006 From: gene.tani at gmail.com (gene tani) Date: 5 Jun 2006 06:16:29 -0700 Subject: Python to C converter In-Reply-To: References: <1149506038.843016.298470@c74g2000cwc.googlegroups.com> Message-ID: <1149513389.922653.272900@u72g2000cwu.googlegroups.com> Rene Pijlman wrote: > praveenkumar.117 at gmail.com: > >I have an application return in python. I want this to be > >converted to C. > > http://www.python.org/doc/faq/general/#can-python-be-compiled-to-machine-code-c-or-some-other-language > http://pyfaq.infogami.com/can-python-be-compiled-to-machine-code-c-or-some-other-language shd probably mention Shedskin, boost, ctypes, any others? From mwh at python.net Sun Jun 25 08:07:29 2006 From: mwh at python.net (Michael Hudson) Date: Sun, 25 Jun 2006 13:07:29 +0100 Subject: pypy-0.9.0: stackless, new extension compiler Message-ID: <2modwhigla.fsf@starship.python.net> The PyPy development team has been busy working and we've now packaged our latest improvements, completed work and new experiments as version 0.9.0, our fourth public release. The highlights of this fourth release of PyPy are: **implementation of "stackless" features** We now support the larger part of the interface of the original Stackless Python -- see http://www.stackless.com for more. A significant part of this is the pickling and unpickling of a running tasklet. These features, especially the pickling, can be considered to be a "technology preview" -- they work, but for example the error handling is a little patchy in places. **ext-compiler** The "extension compiler" is a new way of writing a C extension for CPython and PyPy at the same time. For more information, see its documentation: http://codespeak.net/pypy/dist/pypy/doc/extcompiler.html **rctypes** Most useful in combination with the ext-compiler is the fact that our translation framework can translate code that uses the standard-in-Python-2.5 ctypes module. See its documentation for more: http://codespeak.net/pypy/dist/pypy/doc/rctypes.html **framework GCs** PyPy's interpreter can now be compiled to use a garbage collector written in RPython. This added control over PyPy's execution makes the implementation of new and interesting features possible, apart from being a significant achievement in its own right. **__del__/weakref/__subclasses__** The PyPy interpreter's compatibility with CPython continues improves: now we support __del__ methods, the __subclasses__ method on types and weak references. We now pass around 95% of CPython's core tests. **logic space preview** This release contains the first version of the logic object space, which will add logical variables to Python. See its docs for more: http://codespeak.net/pypy/dist/pypy/doc/howto-logicobjspace-0.9.html **high level backends preview** This release contains the first versions of new backends targeting high level languages such as Squeak and .NET/CLI and updated versions of the JavaScript and Common Lisp backends. They can't compile the PyPy interpreter yet, but they're getting there... **bugfixes, better performance** As you would expect, performance continues to improve and bugs continue to be fixed. The performance of the translated PyPy interpreter is 2.5-3x times faster than 0.8 (on richards and pystone), and is now stable enough to be able to run CPython's test suite to the end. **testing refinements** py.test, our testing tool, now has preliminary support for doctests. We now run all our tests every night, and you can see the summary at: http://snake.cs.uni-duesseldorf.de/pypytest/summary.html What is PyPy (about)? ------------------------------------------------ PyPy is a MIT-licensed research-oriented reimplementation of Python written in Python itself, flexible and easy to experiment with. It translates itself to lower level languages. Our goals are to target a large variety of platforms, small and large, by providing a compilation toolsuite that can produce custom Python versions. Platform, memory and threading models are to become aspects of the translation process - as opposed to encoding low level details into the language implementation itself. Eventually, dynamic optimization techniques - implemented as another translation aspect - should become robust against language changes. Note that PyPy is mainly a research and development project and does not by itself focus on getting a production-ready Python implementation although we do hope and expect it to become a viable contender in that area sometime next year. PyPy is partially funded as a research project under the European Union's IST programme. Where to start? ----------------------------- Getting started: http://codespeak.net/pypy/dist/pypy/doc/getting-started.html PyPy Documentation: http://codespeak.net/pypy/dist/pypy/doc/ PyPy Homepage: http://codespeak.net/pypy/ The interpreter and object model implementations shipped with the 0.9 version can run on their own and implement the core language features of Python as of CPython 2.4. However, we still do not recommend using PyPy for anything else than for education, playing or research purposes. Ongoing work and near term goals --------------------------------- The Just-in-Time compiler and other performance improvements will be one of the main topics of the next few months' work, along with finishing the logic object space. Project Details --------------- PyPy has been developed during approximately 20 coding sprints across Europe and the US. It continues to be a very dynamically and incrementally evolving project with many of these one-week workshops to follow. PyPy has been a community effort from the start and it would not have got that far without the coding and feedback support from numerous people. Please feel free to give feedback and raise questions. contact points: http://codespeak.net/pypy/dist/pypy/doc/contact.html have fun, the pypy team, (Armin Rigo, Samuele Pedroni, Holger Krekel, Christian Tismer, Carl Friedrich Bolz, Michael Hudson, and many others: http://codespeak.net/pypy/dist/pypy/doc/contributor.html) PyPy development and activities happen as an open source project and with the support of a consortium partially funded by a two year European Union IST research grant. The full partners of that consortium are: Heinrich-Heine University (Germany), AB Strakt (Sweden) merlinux GmbH (Germany), tismerysoft GmbH (Germany) Logilab Paris (France), DFKI GmbH (Germany) ChangeMaker (Sweden), Impara (Germany) -- Monte Carlo sampling is no way to understand code. -- Gordon McMillan, comp.lang.python From tomerfiliba at gmail.com Sat Jun 3 10:10:23 2006 From: tomerfiliba at gmail.com (gangesmaster) Date: 3 Jun 2006 07:10:23 -0700 Subject: carshing the interpreter in two lines Message-ID: <1149343823.789918.210110@h76g2000cwa.googlegroups.com> the following (random) code crashes my interpreter (python 2.4.3/winxp): from types import CodeType as code exec code(0, 5, 8, 0, "hello moshe", (), (), (), "", "", 0, "") i would expect the interpreter to do some verifying, at least for sanity (valid opcodes, correct stack size, etc.) before executing artbitrary code... after all, it was the BDFL who said """I'm not saying it's uncrashable. I'm saying that if you crash it, it's a bug unless proven harebrained.""" -tomer From hendrik_maryns at despammed.com Fri Jun 16 06:28:54 2006 From: hendrik_maryns at despammed.com (Hendrik Maryns) Date: Fri, 16 Jun 2006 12:28:54 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <2006061410510511272-raffaelcavallaro@pasdespamsilvousplaitmaccom> <2006061501423327544-raffaelcavallaro@pasdespamsilvousplaitmaccom> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Sacha schreef: > "Joachim Durchholz" wrote in message > news:e6tt7j$b41$1 at online.de... >> Raffael Cavallaro schrieb: >>> On 2006-06-14 15:04:34 -0400, Joachim Durchholz said: >>> >>>> Um... heterogenous lists are not necessarily a sign of expressiveness. >>>> The vast majority of cases can be transformed to homogenous lists >>>> (though these might then contain closures or OO objects). >>>> >>>> As to references to nonexistent functions - heck, I never missed these, >>>> not even in languages without type inference :-) >>>> >>>> [[snipped - doesn't seem to relate to your answer]] >> Give a heterogenous list that would to too awkward to live in a >> statically-typed language. > > Many lists are heterogenous, even in statically typed languages. > For instance lisp code are lists, with several kinds of atoms and > sub-lists.. > A car dealer will sell cars, trucks and equipment.. > In a statically typed language you would need to type the list on a common > ancestor... > What would then be the point of statical typing , as you stilll need to type > check > each element in order to process that list ? Sure you can do this in a > statically-typed > language, you just need to make sure some relevant ancestor exists. In my > experience > you'll end up with the base object-class more often than not, and that's > what i call > dynamic typing. In my experience you won?t. I almost never have a List (Java), and when I have one, I start thinking on how I can improve the code to get rid of it. H. - -- Hendrik Maryns ================== http://aouw.org Ask smart questions, get good answers: http://www.catb.org/~esr/faqs/smart-questions.html -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2 (GNU/Linux) iD8DBQFEkofme+7xMGD3itQRAo0XAJ9DiG228ZKMLX8JH+u9X+6YGEHwgQCdH/Jn kC/F/b5rbmUvUzKYIv8agis= =iuV0 -----END PGP SIGNATURE----- From jorge.vargas at gmail.com Fri Jun 23 22:17:46 2006 From: jorge.vargas at gmail.com (Jorge Vargas) Date: Fri, 23 Jun 2006 22:17:46 -0400 Subject: module docstring, documentation, anything? please note is the module type/object NOT some module Message-ID: <32822fe60606231917r495b166i47ee7f19a6c873fb@mail.gmail.com> Hi everyone I have wasted 2 hours trying to figure out how to get a reference to the module object. that is the one returned by __import__ or when you call a module for name like >>> import sys >>> sys the reason I want this is that I want to introspec my module so I need some way to indentify what elements are inside the module, to execute something like: ""for all the classes defined in this module do " -------------- next part -------------- An HTML attachment was scrubbed... URL: From jmonnet at gmail.com Wed Jun 28 11:57:39 2006 From: jmonnet at gmail.com (Jeremy Monnet) Date: Wed, 28 Jun 2006 17:57:39 +0200 Subject: SimpleXMLRPCServer and client IP address In-Reply-To: References: <2b1bd02c0606280805m164c4fb8s1a43d76480904fb7@mail.gmail.com> Message-ID: <2b1bd02c0606280857o317eac2apaa8084d34f7ad900@mail.gmail.com> Thanks for your answer ! On 6/28/06, Fredrik Lundh wrote: > maybe the explanation in that message was good enough for the poster ? I think so ... unfortunately not for me ... yet ! :-) > > Your handler object should be getting set up with the client_address property. > If not you need to show us some small subset of your app that demonstrates the > issue. > > You can also inherit from SimpleXMLRPCServer and override verify_request, from > BaseServer, if you want the option of blocking requests based on source > address. > > the second alternative should be straightforward enough: > > class MyXMLRPCServer(SimpleXMLRPCServer.SimpleXMLRPCServer): > def verify_request(self, request, client_address): > return CheckPerms(client_address) > > server = MyXMLRPCServer(...) > ... > > if you need more control, you need to subclass SimpleXMLRPCHandler instead. this seems easy, but I'm not sure I could use it : I already provide more than one method (of course not in the snippet of code I provided, my mistake probably not to show it) and I plan to add several more in the near future. Overloading verify_request() in this way means I can't use the same xmlrpcserver for other methods ? Or am I just wrong ? (I should probably have a look at "request", maybe that's a key ?) Or is it the "more control" you talked about ? Jeremy -- Linux Registered User #317862 Linux From Scratch Registered User #16571 Please do not send me .doc, .xls, .ppt, as I will *NOT* read them. Please send me only open formats, as OpenDocument or pdf. From artur_spruce at yahoo.com Wed Jun 7 16:40:53 2006 From: artur_spruce at yahoo.com (AdSR) Date: 7 Jun 2006 13:40:53 -0700 Subject: what are you using python language for? References: Message-ID: <1149712853.094958.292240@u72g2000cwu.googlegroups.com> I'm using Python for: * log analysis * test tools * data massaging * prototyping From ken.carlino at gmail.com Thu Jun 8 21:15:48 2006 From: ken.carlino at gmail.com (ken.carlino at gmail.com) Date: 8 Jun 2006 18:15:48 -0700 Subject: Exeucte a system command in python script Message-ID: <1149815748.856808.200140@j55g2000cwa.googlegroups.com> Hi, I would like to execute a shell command like this in python: cmd = 'ant release -Dbuild=build_proxyonly -Drev=5.1.130f -Dprops=\"-MIDP20_LARGE;PUSH_FEATURE=false;MIDlet-Version=5.0;version=5.0;MIDlet-Icon=midicon15x15.png;-FOUR_WAY_NAV_FEATURE\" -DThree_Branding=true' Which of the execl command described here should I use? http://pydoc.org/1.6/os.html Thank you for any help. From maric at aristote.info Wed Jun 14 05:53:29 2006 From: maric at aristote.info (Maric Michaud) Date: Wed, 14 Jun 2006 11:53:29 +0200 Subject: determining file type In-Reply-To: <1150276935.270798.5550@i40g2000cwc.googlegroups.com> References: <1150276935.270798.5550@i40g2000cwc.googlegroups.com> Message-ID: <200606141153.30141.maric@aristote.info> Le Mercredi 14 Juin 2006 11:22, Ritesh Raj Sarraf a ?crit?: > Hi, > > I have a funtion named unzipper() which does the work of unzipping the > files. > > Is there a way I can identify what is the type of the file which'll be > passed to unzipper(). > If yes, I'll be able to make out if it's a zip file or a tar or a bz2 > file. > Under Linux you can use the file command in a pipe. In all cases, you use the "magic" repository of the file command directly like this (I found the '\xff\xd8' for jpeg in /usr/share/file/magic.mime on my debian) In [69]: f = file ('samurai_tux.jpg') In [70]: s = f.read(2) In [71]: s == '\xff\xd8' Out[71]: True > Thanks, > Ritesh -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From zach_RemoveMe at in.tu-clausthal.de Tue Jun 13 04:50:21 2006 From: zach_RemoveMe at in.tu-clausthal.de (Gabriel Zachmann) Date: Tue, 13 Jun 2006 10:50:21 +0200 Subject: urllib behaves strangely In-Reply-To: References: <87wtbmdlyz.fsf@reportlab.com> Message-ID: > On the other hand something which is simply retrieving one or two fixed > pages doesn't fit that definition of a bot so is probably alright. They i think so, too. even provide a link to some frameworks for writing bots e.g. > > http://sourceforge.net/projects/pywikipediabot/ ah, that looks nice .. Best regards, Gabriel. -- /-----------------------------------------------------------------------\ | If you know exactly what you will do -- | | why would you want to do it? | | (Picasso) | \-----------------------------------------------------------------------/ From sjmachin at lexicon.net Wed Jun 14 21:09:27 2006 From: sjmachin at lexicon.net (John Machin) Date: Thu, 15 Jun 2006 11:09:27 +1000 Subject: Negative hex to int In-Reply-To: References: <1150326597.327669.222640@r2g2000cwb.googlegroups.com> Message-ID: <4490B347.1050004@lexicon.net> On 15/06/2006 10:31 AM, Ben Finney wrote: > andreas.lydersen at gmail.com writes: > >> The problem is negative values. If the unit returns the hex value >> 'e7', it means -25, but python says it's 231: > > Python is right. There is no "negative bit" in Python numbers, now > that unification of 'long' and 'int' is complete; numbers can grow > indefinitely large. > > If you want a special interpretation of the value, you'll have to > calculate it. > > Example assuming you want a one's-complement interpretation:: Given that the OP had to ask the question at all, it is doubtful that he knows what "one's-complement" means. He may well not be alone -- see later. > > def value_from_reading(num): > """ Gets the integer value from the reading string. > num is a positive hexadecimal number as a string. > Numbers greater than 0x7F are interpreted as negative, > with magnitude greater than 0x7F being the negative value. > Only the lowest 15 bits are used for the magnitude. thing & 0x7F looks like lowest 7 bits to me. > > >>> value_from_reading('00') > 0 > >>> value_from_reading('05') > 5 > >>> value_from_reading('7f') > 127 > >>> value_from_reading('80') > -128 > >>> value_from_reading('e7') > -25 > >>> value_from_reading('ff') > -1 Looks like TWOS complement to me. > >>> value_from_reading('100') > -128 Same result as '80'? In any case the OP gave no indication that he was getting more than two hex digits. His desired interpretation of 'e7' as -25 strongly indicates that he's getting only 2 hex digits. > >>> value_from_reading('fff') > -1 > > """ > num_base = 16 > negative_threshold = 0x7F > int_val = int(num, num_base) > if int_val > negative_threshold: > magnitude = (int_val & negative_threshold) > int_val = -(1 + negative_threshold - magnitude) > return int_val > > Adjust for whatever algorithm you want to use. Consult a book of > algorithms if you want a better implementation than my off-the-cuff > brute-force approach. From venkatbo at yahoo.com Tue Jun 27 11:43:12 2006 From: venkatbo at yahoo.com (venkatbo at yahoo.com) Date: 27 Jun 2006 08:43:12 -0700 Subject: How to disable tk inclusion in py build Message-ID: <1151422992.208936.54600@j72g2000cwa.googlegroups.com> Hi folks, I'd like to disable the inclusion of tk graphics lib in my py build. Looked around but couldn't find a clear answer. Which one of the following would I need to use in the configure step: --disable-tkbuild --without-tk Thanks, /venkat From ilias at lazaridis.com Wed Jun 7 07:35:23 2006 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Wed, 07 Jun 2006 14:35:23 +0300 Subject: CENSORSHIP - Django Project (Schema Evolution Support) Message-ID: <4486B9FB.9030804@lazaridis.com> [posted publicly to comp.lang.python, with email notification to 6 recipients relevant to the topic] I have implemented a simple schema evolution support for django, due to a need for a personal project. Additionally, I've provided an Audit: http://case.lazaridis.com/wiki/DjangoAudit As a result, I was censored ('banned' from the development list) My initial non-public complain [1] about censorship on django devel, sent to six relevant project recipients [2] remained unanswered. The only 'answer' I got was an additional censorship on the _user_ list, which is _completely_ unjustified, as I've just requested comments to my code-level working results: http://groups.google.com/group/django-users/browse_frm/thread/88dcc4946c3bd7b2 - I understand that the community was possibly confused due to my past evaluations. But this gives in _no_ way the right to attack me personally and to apply censorship. "Django was originally created in late 2003 at World Online, the Web division2 of the Lawrence Journal-World newspaper in Lawrence, Kansas" http://code.djangoproject.com/browser/django/trunk/AUTHORS#L128 The Django Project should really avoid such non-liberal actions in future. Please enable my access to the user list, thus I can complete my work. Thank you. - P.S.: If anyone is interested to verify the results, in order to stabelize the simple schema evolution support for django, please review the results here: http://case.lazaridis.com/wiki/DjangoProductEvaluation http://case.lazaridis.com/wiki/DjangoSchemaEvolution http://case.lazaridis.com/browser/django/rework/evolve.py http://case.lazaridis.com/browser/django/rework/add_evolvedb_command.diff - Sidenote: I've implemented the above as the suggestions from the django project (manually create an execute ALTER TABLE statements) would hinder me to develop my application incrementally: "If you do care about deleting data, you'll have to execute the ALTER TABLE statements manually in your database. That's the way we've always done it, because dealing with data is a very sensitive operation that we've wanted to avoid automating. That said, there's some work being done to add partially automated database-upgrade functionality." http://www.djangoproject.com/documentation/faq/#if-i-make-changes-to-a-model-how-do-i-update-the-database - - - [1] ------------------------------------------------------------------------ Date : 2006-06-03 08:32 Subject: pj.audit.django.censorship/offer. *SUMMARY* * Censorship on django-developer * Personal Projects [...] - (non-public commercial part omitted) *CENSORSHIP* I would like to know for which reason I was "banned" from the developers list. Django comes from an newspaper environment, and I think you should really evaluate your information twice before you *censor* someone on the list, who has posted only topics relevant to django development in order to fulfill several tasks for an Audit: http://case.lazaridis.com/multi/wiki/DjangoAudit Is this here really enough to justify censorship?: http://groups.google.com/group/django-developers/msg/fbb5a3aafe39d239 Please, Mr. Holovaty, enable my access to the development-list again thus I can finalize my work. - *PERSONAL_PROJECTS* Instead of blocking me without any justification from the development-list, why don't you just look on my website, where I list some links (including that one found' and explain the project: http://lazaridis.com/core/eval/index.html I've worked several years on this "Core Project", which is finalized, and in 2006 I've started to define the resulting services: http://lazaridis.com/pj/index.html As stated, I use django for a personal project (which I hope will secure me some incomings). The evolve functionality was necessary in order to start with development of my project. At the same time I made the audit publicly, thus other people can benefit from my experiences. Additionally, I look for a reference customer. Although I had planned to finalize the Audit first and then to contact you, the missing access to the developer list forces me to change my schedule. [...] - (non-public commercial part omitted) ------------------------------------------------------------------------ [2] The recipients were take for the following file: http://www.djangoproject.com/documentation/faq/#who-s-behind-this and from this file: http://code.djangoproject.com/browser/django/trunk/AUTHORS . -- http://lazaridis.com From gandalf at designaproduct.biz Wed Jun 7 09:11:05 2006 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Wed, 07 Jun 2006 15:11:05 +0200 Subject: secure xmlrpc server? In-Reply-To: <4486c6ee$0$31647$e4fe514c@news.xs4all.nl> References: <4486c6ee$0$31647$e4fe514c@news.xs4all.nl> Message-ID: <4486D069.2040502@designaproduct.biz> Martin P. Hellwig wrote: > Laszlo Nagy wrote: > > Have a look at: > http://trevp.net/tlslite/ > C:\temp\ccc>python setup.py install running install running build running build_py running build_ext error: The .NET Framework SDK needs to be installed before building extensions f or Python. C:\temp\ccc> Does it mean that .NET framework is required for tlslite on Windows? Also can you please provide an example for tlslite/xmlrpc integration? The documentation of tlslite is very detailed, but it has many options and I could not find an example. Thanks, Laszlo From alikakakhel at yahoo.com Sat Jun 3 17:14:36 2006 From: alikakakhel at yahoo.com (greenflame) Date: 3 Jun 2006 14:14:36 -0700 Subject: how to erase a variable In-Reply-To: References: <1149306000.615590.30020@c74g2000cwc.googlegroups.com> Message-ID: <1149369276.885120.230110@c74g2000cwc.googlegroups.com> Ok thanks all! From johnjsal at NOSPAMgmail.com Thu Jun 15 13:29:48 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 15 Jun 2006 17:29:48 GMT Subject: Python is fun (useless social thread) ;-) In-Reply-To: <449193e3$1@nntp0.pdx.net> References: <449179b2$1@nntp0.pdx.net> <449193e3$1@nntp0.pdx.net> Message-ID: Scott David Daniels wrote: > Scott David Daniels wrote: >> John Salerno wrote: > ... > And I didn't quote him at all, so my post looks like it was > attributed to him, rather than in response to his message. Heh heh, I thought that for a few seconds until I realized I didn't pursue a PhD. :) From nexu.jin at gmail.com Sun Jun 4 02:45:27 2006 From: nexu.jin at gmail.com (Nexu) Date: Sun, 04 Jun 2006 08:45:27 +0200 Subject: Hostmask matching In-Reply-To: References: Message-ID: <1149403527.5979.14.camel@localhost.localdomain> On Sun, 2006-06-04 at 06:26 +0000, Marc Schoechlin wrote: > Hi ! > > Nexu schrieb: > > I'm trying to write a def to match a string that is an irc hostmask. eg: > > *one!~*name at a??-??-101-101.someisp.com > > But using re.search(). I get an error when the string starts with '*'. > > What is the best way to solve this? > > I suppose the problem occurs because you expression is not a valid > regular expression. > > A correct regular expression should look like this: > ".*one!~.*name at a..-..-101-101.someisp.com" Thx for everyones input. This solved the problem: host = 'someone!~thename at a80-80-101-101.someisp.com' mask = '*one!~*name at a??-??-101-101.someisp.com' newmask = re.sub('\*', '.*', re.sub('\?', '.', mask)) result in that: re.search(newmask, host) == True From nate at natefico.com Sat Jun 17 02:10:02 2006 From: nate at natefico.com (nate) Date: Fri, 16 Jun 2006 23:10:02 -0700 Subject: python texts? Message-ID: <44939CBA.4090709@natefico.com> Hello everyone, Can anyone recommend python text progression from me. Assuming I have no knowledge of python which books should I progress through? I prefer published books that I can actually hold with my hands. But if there are some awesome tutorials on-line I guess I am game. At this moment I am reading Learning Python 2nd edition by O'Reilly. I am enjoying it at the moment. I intend to be done with it in a week. But not sure where it will put me in the grand scheme of programming with python. So perhaps a more direct question would be, what do I read after this book? Should I read something before this book? Should I ditch this book? Thanks, --Nate From onurb at xiludom.gro Tue Jun 20 08:27:28 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 20 Jun 2006 14:27:28 +0200 Subject: Python is fun (useless social thread) ;-) In-Reply-To: <44965e69$0$38632$edfadb0f@dread12.news.tele.dk> References: <449433b5$0$1344$626a54ce@news.free.fr> <44965e69$0$38632$edfadb0f@dread12.news.tele.dk> Message-ID: <4497e9b2$0$1602$636a55ce@news.free.fr> Max M wrote: > bruno at modulix wrote: > >>> Or did you just like what you saw and decided to learn it for fun? >> >> >> Well, I haven't be really impressed the first time - note that it was at >> the very end of the last century, with v1.5.2. > > > > 1.5.2 was an excellent version. Not really that different in use than > current version. Nope, "not really that different" - we were just missing list-comps, generators, new-style classes, classmethods, staticmethods, usable metaclasses, descriptors, @decorators sugar, extended slices, and a few other goodies coming in 2.5 like coroutines and with: statement... -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From rpdooling at gmail.com Mon Jun 26 14:09:25 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 26 Jun 2006 11:09:25 -0700 Subject: Python is fun (useless social thread) ;-) In-Reply-To: <4492c1c6$0$11008$626a54ce@news.free.fr> References: <1150381872.958342.180420@p79g2000cwp.googlegroups.com> <44917776$1@nntp0.pdx.net> <4492c1c6$0$11008$626a54ce@news.free.fr> Message-ID: <1151345365.630616.14400@i40g2000cwc.googlegroups.com> > You know what are dicts, right ? That is, containers with keyword-access > to values ? Then you probably have dicts with a known, defined > structure, and functions working on it. What classes (and hence 00) > gives you is a way to associate these functions with the dicts > themselves. That is the big intuition about objects, the rest is just > details. Bruno, Ever seen this from Fuzzyman? It explicitly uses the dict comparison. http://www.voidspace.org.uk/python/articles/OOP.shtml#introduction Thanks for the tip, rd From deets at nospam.web.de Mon Jun 12 09:54:47 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 12 Jun 2006 15:54:47 +0200 Subject: (pre)forking server framework? References: <1150118572.252707.57460@i40g2000cwc.googlegroups.com> Message-ID: <4f5a2lF1h6t38U1@uni-berlin.de> czajnik at czajsoft.pl wrote: > > Hi! > > I'm quite new to Python development. Can someone advise me a framework > useful for building (pre-)forking or threaded TCP servers, other than > SocketServer ? I've seen source code of a few python-based app servers, > all of theme seem to reinvent the wheel, eventually reusing > SocketServer. I'd appreciate a framework with logging, process/thread > pool, signal handling etc. Just plug-in a protocol implementation and > go ! > > Yes, I know Twisted, but asynchronous model is an overkill for me in > this particular project. I do not need high performance, simple forking > suites my needs better. Why do you care if the asynchronous model is overkill or the performance is good? Twisted comes close to what you want - and using its strength as arguments against it strikes me as odd. Diez From laurent.pointal at limsi.fr Tue Jun 20 03:46:44 2006 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Tue, 20 Jun 2006 09:46:44 +0200 Subject: [OT] code is data In-Reply-To: References: <44965f53$0$12743$636a55ce@news.free.fr> <4496b29f$0$27412$626a54ce@news.free.fr> Message-ID: Fredrik Lundh a ?crit : > Laurent Pointal wrote: > >>>> The idea is to have a way to transform a Python (.py) module into XML >>>> and then do source code manipulations in XML-space using ElementTree. >>> >>> My my my... I'm not against the idea of dynamic source code >>> transformation, but for heaven's sake, *why* would one put XML in the >>> mix ??????? > > because lots of people know how to describe XML transformations, and > there are plenty of tools that implement such transformations efficiently ? > >> Because its "? la mode", and is better for a commercial point of view, >> even if inefficient for this problem. > > why would XML be inefficient ? As a storage tool, its nice, and as you says, there are many tools to deal with. But as an internal representation for an AST, I certainly prefer an ad-hoc classes definitions with well defined members. Just have a wrapper between both representations. Laurent A+ From gene.tani at gmail.com Wed Jun 7 03:22:48 2006 From: gene.tani at gmail.com (gene tani) Date: 7 Jun 2006 00:22:48 -0700 Subject: newbie: python application on a web page In-Reply-To: <1149615269.695229.88820@j55g2000cwa.googlegroups.com> References: <1149615269.695229.88820@j55g2000cwa.googlegroups.com> Message-ID: <1149664968.258497.263020@c74g2000cwc.googlegroups.com> puzz wrote: > Hi all, > I'd also appreciate a link to a beginner forum > http://www.daniweb.com/techtalkforums/forum114.html and (not really a beginner forum, not really high volume, either) http://community.livejournal.com/python_dev/ From max at alcyone.com Sun Jun 25 18:55:18 2006 From: max at alcyone.com (Erik Max Francis) Date: Sun, 25 Jun 2006 15:55:18 -0700 Subject: Python question In-Reply-To: <1151275845.423382.294260@u72g2000cwu.googlegroups.com> References: <1151275845.423382.294260@u72g2000cwu.googlegroups.com> Message-ID: <4Oednea3_q_KiQLZnZ2dnUVZ_v2dnZ2d@speakeasy.net> Harry wrote: > It is nice to join the python group. Can someone please help me with > a python question? > I have the following object which is like a list of tuples > What command do I use to get the value corresponding to 'min'? > This object seems to be non-indexable > > > row= [('name', 'x1'), ('min', 15.449041129349528), ('max', > 991.6337818245629), ('range', 976.18474069521335), ('mean', > 496.82174193958127), ('stddev', 304.78275004920454), ('variance', > 92892.524727555894), ('mode', '46.5818482111'), ('unique_count', '99'), > ('count', 99.0), ('count_missing', 0.0), ('sum_weight', 99.0)] Iterating would be the best way. There are shorter ways of writing it, for instance with list comprehensions, but it's still iteration:: for key, value in row: if key == 'min': print value break or:: results = [v for k, v in row if k == 'min'] print results[0] Another way, if you plan to access this same data structure in this way multiple times before moving on to the next one, would be to turn it into a dictionary first:: d = dict(row) print d['min'] Note that all of these solutions assume that the key you want is indeed in there. If it might not be, then you'll have to gracefully handle errors. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Divide the fire, and you will the sooner put it out. -- Publilius Syrus From hat at se-126.se.wtb.tue.nl Thu Jun 8 03:27:57 2006 From: hat at se-126.se.wtb.tue.nl (A.T.Hofkamp) Date: Thu, 08 Jun 2006 09:27:57 +0200 Subject: XML, JSON, or what? References: <1149749530.734275.181300@j55g2000cwa.googlegroups.com> Message-ID: On 2006-06-08, Frank Millman wrote: > I would rather make a decision now, otherwise I will have a lot of > changes to make later on. Does anyone have any recommendations? Did you consider XMPP? With XMPP you create XML streams between your server and the client. XMPP is an open standard (by the IETF). Jabber (jabber.org) is based on the XMPP standard. They develop protocols on XMPP for all kinds of data exchange. Currently, it is mainly used for chatting, but we use it in-house as publish/subscribe to control some machines too. They do a lot of thinking about scalabilty, privacy, authentication, and all that other stuff you need to do when you put some service on the internet. They also have protocols for using a GUI interactively (much like the wizards of Win* do, you get one page of things to decide, you press 'next', you get the next page, etc). Albert From steve at holdenweb.com Tue Jun 27 02:55:21 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 27 Jun 2006 07:55:21 +0100 Subject: SWIG problems with gcc and Cygwin? In-Reply-To: References: Message-ID: Michael Yanowitz wrote: > No response yet. The SWIG test works fine in Linux no problems. > However, I still have the problem in Cygwin. > Also, not sure if related but I do have a win32 Python 2.4.3 and > Cygwin Python 2.4.1. Not sure if there are any conflicts. Any advice > in making these two co-exist? > The only C/C++ compiler I have presently is Cygwin gcc. > I wouldn't claim to be an expert but it looks like you are missing libraries. Shouldn't you at least be loading -l c to get functions defined in libc? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From johnjsal at NOSPAMgmail.com Sat Jun 10 13:45:21 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sat, 10 Jun 2006 13:45:21 -0400 Subject: wxPython: Should you use a master sizer object? In-Reply-To: References: Message-ID: <448b072f$0$11723$c3e8da3@news.astraweb.com> Steve Holden wrote: > John Salerno wrote: >> Sorry for posting here again. I tried the wxPython list but I'm not sure >> I'm sending to the right email address! It bounced back. Besides, your >> opinions are too good to pass up. ;) >> >> My question was: >> >> I was wondering, is it recommended to always have a top-level sizer in >> which you place all other sizers, or is it acceptable to have mulitple >> sizers that are not grouped together? > > You should definitely create a master sizer, and then add sub-sizers to it. Thanks. Also, I just found out that a Frame can't have more than one sizer in it, meaning if you need multiple sizers you *have* to create a master sizer first to nest the others. Now it's just a matter of figuring out *how* to use them! I don't want to fall into the trap of using them the way you can use the element to lay out a form in HTML... From NOS at Utel.no Thu Jun 8 03:28:08 2006 From: NOS at Utel.no (=?UTF-8?B?Ik5pbHMgTy4gU2Vsw6VzZGFsIg==?=) Date: Thu, 08 Jun 2006 09:28:08 +0200 Subject: The Nature of the =?UTF-8?B?4oCcVW5peCBQaGlsb3NvcGh54oCd?= In-Reply-To: <1149730552.161534.121350@i40g2000cwc.googlegroups.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1149080931.582431.95560@j55g2000cwa.googlegroups.com> <1149730552.161534.121350@i40g2000cwc.googlegroups.com> Message-ID: <4487d188$1@news.broadpark.no> Xah Lee wrote: > The Nature of the ?Unix Philosophy? > > Xah Lee, 2006-05 > > In the computing industry, especially among unix community, we often > hear that there's a ?Unix Philosophy?. In this essay, i dissect the > nature and characterization of such ?unix philosophy?, as have been > described by Brian Kernighan, Rob Pike, Dennis Ritchie, Ken Thompson, > and Richard P Gabriel et al, and in recent years by Eric Raymond. > > There is no one definite set of priciples that is the so-called ?unix > philosophy?, but rather, it consistest of various slogans developed > over the decades by unix programers that purport to describe the way > unix is supposed to have been designed. The characteristics include: > ?keep it simple?, ?make it fast?, ?keep it small?, ?make > it work on 99% of cases, but generality and correctness are less > important?, ?diversity rules?, ?User interface is not > important, raw power is good?, ?everything should be a file?, > ?architecture is less important than immediate workability?. Often, > these are expressed by chantible slogans that exhibits juvenile humor, > such as ?small is beautiful?, ?KISS (Keep It Simple, Stupid)?. Perhaps you should take a peek at the ideas in Plan 9 from Bell Labs, which is a continuation of this philosophy, unlike the "modern" unix clones. From petr at tpc.cz Wed Jun 7 19:11:54 2006 From: petr at tpc.cz (Petr Jakes) Date: 7 Jun 2006 16:11:54 -0700 Subject: what are you using python language for? In-Reply-To: References: Message-ID: <1149721914.582713.118270@i40g2000cwc.googlegroups.com> hacker1017 wrote: > im just asking out of curiosity. a vending machine controlled from the PC (peripherals connected using I2C bus (SMBus) and the MDB coin change-giver and the bill acceptor connected to the serial port). Petr Jakes From webraviteja at gmail.com Sun Jun 18 00:48:38 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 17 Jun 2006 21:48:38 -0700 Subject: code is data In-Reply-To: References: <1150574111.415068.255900@p79g2000cwp.googlegroups.com> Message-ID: <1150606118.456390.262620@y41g2000cwy.googlegroups.com> BJ?rn Lindqvist wrote: > > Personally, I would like to see macros in Python (actually Logix > > succeeding is good enough). But I am no language designer and the > > community has no interest in it. When I absolutely need macros, I will > > go elsewhere. > > One must wonder, when is that? When do you absolutely need macros? Whenever there is significant boiler plate code that functions and classes cannot eliminate alone. Whenever there is a more elegant way to express your code. Python 2.5 introduced conditional expressions and with statement. With macros, one would not have to wait for the language team to implement them. More so for features which only a small part of the community has an interest in. I *like* 1..5 (ada, ruby) instead of range(5). If I had macros, I would have done it myself for *my* code. I would like special behaviour code blocks in my programs, for say DBC (I am aware of the work arounds). From thesamet at gmail.com Thu Jun 22 12:30:26 2006 From: thesamet at gmail.com (Nadav Samet) Date: 22 Jun 2006 09:30:26 -0700 Subject: struct.unpack on 64-bit platforms Message-ID: <1150993826.726685.301740@p79g2000cwp.googlegroups.com> Hi, I am trying to unpack a 32-bit unsigned integer from a string using struct.unpack. so using string.unpack('L', data) would work fine on 32-bit systems, But apparently, on 64-bit platforms it tries to read 64-bit unsigned integer (since that's what the C Type unsigned long means on 64-bit platforms). So what's the way to make it read exactly 32-bits, on all platforms? Thanks, Nadav From eliotm at pacbell.net Thu Jun 22 17:03:27 2006 From: eliotm at pacbell.net (Eliot Miranda) Date: Thu, 22 Jun 2006 21:03:27 GMT Subject: What is a type error? In-Reply-To: <449aaea0$2$656$bed64819@news.gradwell.net> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <7i3mg.204167$8W1.155367@fe1.news.blueyonder.co.uk> <44992e6c$2$664$bed64819@news.gradwell.net> <%Igmg.464974$xt.353729@fe3.news.blueyonder.co.uk> <449aaea0$2$656$bed64819@news.gradwell.net> Message-ID: > Chris Smith wrote: >>I suspect you'll see the Smalltalk version of the objections raised in >>response to my post earlier. In other words, whatever terminology you >>think is consistent, you'll probably have a tough time convincing >>Smalltalkers to stop saying "type" if they did before. If you exclude >>"message not understood" as a type error, then I think you're excluding >>type errors from Smalltalk entirely, which contradicts the psychological >>understanding again. > Chris Uppal wrote: > > Taking Smalltalk /specifically/, there is a definite sense in which it is > typeless -- or trivially typed -- in that in that language there are no[*] > operations which are forbidden[**], Come one Chris U. One has to distinguish an attempt to invoke an operation with it being carried out. There is nothing in Smalltalk to stop one attempting to invoke any "operation" on any object. But one can only actually carry-out operations on objects that implement them. So, apart from the argument about inadvertent operation name overloading (which is important, but avoidable), Smalltalk is in fact strongly-typed, but not statically strongly-typed. -- _______________,,,^..^,,,____________________________ Eliot Miranda Smalltalk - Scene not herd From digitalorganics at gmail.com Mon Jun 26 13:29:01 2006 From: digitalorganics at gmail.com (digitalorganics at gmail.com) Date: 26 Jun 2006 10:29:01 -0700 Subject: Replace Whole Object Through Object Method In-Reply-To: <44a0132d$0$21282$626a54ce@news.free.fr> References: <1151337453.804750.293180@b68g2000cwa.googlegroups.com> <44a0132d$0$21282$626a54ce@news.free.fr> Message-ID: <1151342941.256085.243000@p79g2000cwp.googlegroups.com> Bruno Desthuilliers wrote: > digitalorganics at gmail.com wrote: > > How can an object replace itself using its own method? > > AFAIK, It can't (but I can be wrong - some guru around ?). > > > ... > > FWIW: > Python 2.4.3 (#1, Jun 3 2006, 17:26:11) > [GCC 3.4.6 (Gentoo 3.4.6-r1, ssp-3.4.5-1.0, pie-8.7.9)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> def dumbfactory(): > ... class Dumb(object): pass > ... class Dummy: pass > ... return Dumb, Dummy > ... > >>> globals() > {'__builtins__': , '__name__': > '__main__', '__doc__': None, 'dumbfactory': 0x2aaaaab66e60>} > >>> def fun(): > ... dumb, dummy = dumbfactory() > ... return > ... > >>> fun() > >>> globals() > {'__builtins__': , '__name__': > '__main__', 'fun': , '__doc__': None, > 'dumbfactory': } > >>> > > Looks like dumb and dummy won't get listed... And also: > > >>> class Mymeta(type): > ... pass > ... > >>> class Foo(object): > ... __metaclass__ = Mymeta > ... > >>> "'type'" in str(type(globals()['Mymeta'])) > True > > Looks like this will list metaclasses too... May or may not be a problem... > > > def MixInto(Class, Mixin): > > You're aware that in this function's scope, the 'Mixin' arg name will > shadow the Mixin class name ? (sorry for asking dumb question). No sorry necessary, but yes, I am aware of it. Poor programming practice I'm sure... > ... > > > > Basically what I need is for the method to be able to find out the name > > of the instance, then I can just go to the globals dictionary to do the > > replacement. > > > > Advance thanks to all who can help... > > > > Instead of exposing problems with your solution, you may want to expose > the real use case ? *** I'm working with a team that's doing social modeling, and for example, I need to model workers that at some point in the program may or may not also become employers. Now, I want the workers to take on all behaviors and attributes of an employer in addition to their pre-existing "worker" behaviors and attributes. Also, as I'm sure you guessed, the workers' attributes need to retain their values at that point in the program, so a brand new worker-employer object wouldn't in itself do the trick. *** > > > -- > bruno desthuilliers > python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for > p in 'onurb at xiludom.gro'.split('@')])" From onurb at xiludom.gro Mon Jun 19 04:11:08 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Mon, 19 Jun 2006 10:11:08 +0200 Subject: any subway web dev experiences In-Reply-To: <1150664491.533947.61090@p79g2000cwp.googlegroups.com> References: <1150533811.911621.112430@y41g2000cwy.googlegroups.com> <1150664491.533947.61090@p79g2000cwp.googlegroups.com> Message-ID: <44965c1f$0$22857$626a54ce@news.free.fr> a wrote: > subway is pythons ruby on rails competitor Nope - it's a Python MVC web framework. Like Django, Pylons and Turborgears. And FWIW, there have been recently some discussions about merging Subway and Turbogears. > pls tell me if u hav any expereinces Please take time to learn and write readable english sentences. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From fredrik at pythonware.com Sun Jun 11 07:28:23 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 11 Jun 2006 13:28:23 +0200 Subject: Import elfclass32 issue In-Reply-To: <448bfa54@127.0.0.1> References: <448bc040@127.0.0.1> <448bfa54@127.0.0.1> Message-ID: DarkBlue wrote: > and that's all I did. The suse10.1 installation is pristine > only auto updated with the latest patches of the day. if you're using a SuSE-provided python interpreter, you should make to use the right development files (python-dev, or whatever that's called over in SuSE land). if you do, it's a SuSE problem (this wouldn't be the first time SuSE ships broken Python software) have you checked the SuSE bug databases / support forums for clues, btw? (if you google for the error message, you'll find several hundreds of non-Python-related hits, so it's more of a 32/64-bit compiler problem than a Python problem...) From tim.leeuwvander at nl.unisys.com Thu Jun 8 09:05:35 2006 From: tim.leeuwvander at nl.unisys.com (Tim N. van der Leeuw) Date: 8 Jun 2006 06:05:35 -0700 Subject: CONSTRUCT - Python's way of Ruby's "alias_method" In-Reply-To: References: Message-ID: <1149771935.391193.147360@h76g2000cwa.googlegroups.com> Since your question is so much about Django, you might want to ask on Django groups. Oops, you're not welcome there anymore, almost forgot. But if merely reading the subject of a posting I already know who's the poster, it's perhaps a bad sign. Further readers of this thread might be interested in the discussions linked from these pages: http://en.wikipedia.org/wiki/Ilias_Lazaridis http://www.encyclopediadramatica.com/index.php/Ilias http://groups.google.com/group/comp.lang.java.softwaretools/tree/browse_frm/thread/f07832cf6d0094f0/ae6315fda51d50a1?rnum=1&hl=en&_done=%2Fgroup%2Fcomp.lang.java.softwaretools%2Fbrowse_frm%2Fthread%2Ff07832cf6d0094f0%2Fae6315fda51d50a1%3Ftvc%3D1%26q%3Dilias+EVALUATION%26#doc_ae6315fda51d50a1 EOT? From robert.kern at gmail.com Thu Jun 29 15:00:55 2006 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 29 Jun 2006 14:00:55 -0500 Subject: Problem with sets and Unicode strings In-Reply-To: <44a41e06$1@news.uni-ulm.de> References: <44a17d05$1@news.uni-ulm.de> <44a19d55$2@news.uni-ulm.de> <44a2b2cc$2@news.uni-ulm.de> <4gfr58F1mijo5U2@uni-berlin.de> <44a41e06$1@news.uni-ulm.de> Message-ID: Dennis Benzinger wrote: > Ok, I understand. > But isn't it a (minor) problem that using a set like this: > > # -*- coding: UTF-8 -*- > > FIELDS_SET = set(("F?cher", )) > > print u"F?cher" in FIELDS_SET > print u"F?cher" == "F?cher" > > shadows the error of not setting sys.defaultencoding()? You can't set the default encoding. If you could, then scripts that run on your machine wouldn't run on mine. If there's an error, it's the fact that you use a regular string at the beginning ("F?cher") and a unicode string later (u"F?cher"). But set objects can't know that that's the problem or even if it *is* a problem. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From ask at me Thu Jun 8 21:14:48 2006 From: ask at me (alf) Date: Thu, 08 Jun 2006 21:14:48 -0400 Subject: dynamic inheritance Message-ID: <_IidnWMwvOnfRBXZnZ2dneKdnZydnZ2d@comcast.com> is there any way to tell the class the base class during runtime? a. From jes at nl.demon.net Fri Jun 30 11:58:02 2006 From: jes at nl.demon.net (Jim Segrave) Date: Fri, 30 Jun 2006 15:58:02 -0000 Subject: Regular Expression - old regex module vs. re module References: <1151607229.548737.145800@d56g2000cwd.googlegroups.com> Message-ID: <12aaigaohtou291@corp.supernews.com> In article , Paul McGuire wrote: >Not an re solution, but pyparsing makes for an easy-to-follow program. >TransformString only needs to scan through the string once - the >"reals-before-ints" testing is factored into the definition of the >formatters variable. > >Pyparsing's project wiki is at http://pyparsing.wikispaces.com. If fails for floats specified as ###. or .###, it outputs an integer format and the decimal point separately. It also ignores \# which should prevent the '#' from being included in a format. -- Jim Segrave (jes at jes-2.demon.nl) From marshall.spight at gmail.com Sat Jun 24 14:54:32 2006 From: marshall.spight at gmail.com (Marshall) Date: 24 Jun 2006 11:54:32 -0700 Subject: Saying "latently-typed language" is making a category mistake In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <86Qmg.10725$o4.1907@newsread2.news.pas.earthlink.net> <0neng.213767$8W1.1948@fe1.news.blueyonder.co.uk> <1151171209.684163.143410@c74g2000cwc.googlegroups.com> Message-ID: <1151175272.674919.141210@y41g2000cwy.googlegroups.com> Gabriel Dos Reis wrote: > "Marshall" writes: > > | David Hopwood wrote: > | > > | > A type system that required an annotation on all subprograms that do not > | > provably terminate, OTOH, would not impact expressiveness at all, and would > | > be very useful. > | > | Interesting. I have always imagined doing this by allowing an > | annotation on all subprograms that *do* provably terminate. If > | you go the other way, you have to annotate every function that > | uses general recursion (or iteration if you swing that way) and that > | seems like it might be burdensome. Further, it imposes the > | annotation requirement even where the programer might not > | care about it, which the reverse does not do. > > simple things should stay simple. Recursions that provably terminate > are among the simplest ones. Annotations in those cases could be > allowed, but not required. Otherwise the system might become very > irritating to program with. Yes, exactly my point. Marshall From sreeram at tachyontech.net Tue Jun 6 14:23:21 2006 From: sreeram at tachyontech.net (K.S.Sreeram) Date: Tue, 06 Jun 2006 23:53:21 +0530 Subject: 10GB XML Blows out Memory, Suggestions? In-Reply-To: <4eleh3F1eguosU1@uni-berlin.de> References: <1149594519.098115.8980@u72g2000cwu.googlegroups.com> <4eleh3F1eguosU1@uni-berlin.de> Message-ID: <4485C819.2030206@tachyontech.net> Diez B. Roggisch wrote: > What the OP needs is a different approach to XML-documents that won't > parse the whole file into one giant tree - but I'm pretty sure that > (c)ElementTree will do the job as well as expat. And I don't recall the > OP musing about performances woes, btw. There's just NO WAY that the 10gb xml file can be loaded into memory as a tree on any normal machine, irrespective of whether we use C or Python. So the *only* way is to perform some kind of 'stream' processing on the file. Perhaps using a SAX like API. So (c)ElementTree is ruled out for this. Diez B. Roggisch wrote: > No what exactly makes C grok a 10Gb file where python will fail to do so? In most typical cases where there's any kind of significant python code, its possible to achieve a *minimum* of a 10x speedup by using C. In most cases, the speedup is not worth it and we just trade it for the increased flexiblity/power of the python language. But in this situation using a bit of tight C code could make the difference between the process taking just 15mins or taking a few hours! Ofcourse I'm not asking him to write the entire application in C. It makes sense to just write the performance critical sections in C, and wrap it in Python, and write the rest of the application in Python. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 260 bytes Desc: OpenPGP digital signature URL: From david.nospam.hopwood at blueyonder.co.uk Tue Jun 27 19:50:12 2006 From: david.nospam.hopwood at blueyonder.co.uk (David Hopwood) Date: Tue, 27 Jun 2006 23:50:12 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: <1151450513.458623.139460@b68g2000cwa.googlegroups.com> References: <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <1151384511.223582.305760@m73g2000cwd.googlegroups.com> <1151425350.679754.278820@i40g2000cwc.googlegroups.com> <1151450513.458623.139460@b68g2000cwa.googlegroups.com> Message-ID: Joe Marshall wrote: > David Hopwood wrote: >>Joe Marshall wrote: >> >>>(defun blackhole (argument) >>> (declare (ignore argument)) >>> #'blackhole) >> >>This is typeable in any system with universally quantified types (including >>most practical systems with parametric polymorphism); it has type >>"forall a . a -> #'blackhole". > > The #' is just a namespace operator. The function accepts a single > argument and returns the function itself. You need a type that is a > fixed point (in addition to the universally quantified argument). Yes, see the correction in my follow-up. >>>>The real question is, are there some programs that we >>>>can't write *at all* in a statically typed language, because >>>>they'll *never* be typable? >>> >>>Certainly! As soon as you can reflect on the type system you can >>>construct programs that type-check iff they fail to type-check. >> >>A program that causes the type checker not to terminate (which is the >>effect of trying to construct such a thing in the type-reflective systems >>I know about) is hardly useful. >> >>In any case, I think the question implied the condition: "and that you >>can write in a language with no static type checking." > > Presumably the remainder of the program does something interesting! > > The point is that there exists (by construction) programs that can > never be statically checked. I don't think you've shown that. I would like to see a more explicit construction of a dynamically typed [*] program with a given specification, where it is not possible to write a statically typed program that meets the same specification using the same algorithms. AFAIK, it is *always* possible to construct such a statically typed program in a type system that supports typerec or gradual typing. The informal construction you give above doesn't contradict that, because it depends on reflecting on a [static] type system, and in a dynamically typed program there is no type system to reflect on. [*] Let's put aside disagreements about terminology for the time being, although I still don't like the term "dynamically typed". > The next question is whether such > programs are `interesting'. Certainly a program that is simply > designed to contradict the type checker is of limited entertainment > value, I don't know, it would probably have more entertainment value than most executive toys :-) > but there should be programs that are independently non > checkable against a sufficiently powerful type system. Why? Note that I'm not claiming that you can check any desirable property of a program (that would contradict Rice's Theorem), only that you can express any dynamically typed program in a statically typed language -- with static checks where possible and dynamic checks where necessary. -- David Hopwood From robert.thorpe at antenova.com Tue Jun 20 13:32:32 2006 From: robert.thorpe at antenova.com (Rob Thorpe) Date: 20 Jun 2006 10:32:32 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: <4fqonoF1kfkapU1@individual.net> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <4fpvbvF1keed1U1@individual.net> <4fqonoF1kfkapU1@individual.net> Message-ID: <1150824752.799997.206210@p79g2000cwp.googlegroups.com> Pascal Costanza wrote: > Matthias Blume wrote: > > Pascal Costanza writes: > >> (slot-value p 'address) is an attempt to access the field 'address in > >> the object p. In many languages, the notation for this is p.address. > >> > >> Although the class definition for person doesn't mention the field > >> address, the call to (eval (read)) allows the user to change the > >> definition of the class person and update its existing > >> instances. Therefore at runtime, the call to (slot-value p 'adress) > >> has a chance to succeed. > > > > I am quite comfortable with the thought that this sort of evil would > > get rejected by a statically typed language. :-) > > This sort of feature is clearly not meant for you. ;-P To be fair though that kind of thing would only really be used while debugging a program. Its no different than adding a new member to a class while in the debugger. There are other places where you might add a slot to an object at runtime, but they would be done in tidier ways. From writetoalok at googlemail.com Fri Jun 30 11:17:50 2006 From: writetoalok at googlemail.com (Alok) Date: 30 Jun 2006 08:17:50 -0700 Subject: Reddit broke - should have remained on Lisp? In-Reply-To: References: <1151626961.232761.255550@d56g2000cwd.googlegroups.com> Message-ID: <1151680670.764245.18520@m73g2000cwd.googlegroups.com> Fredrik Lundh wrote: > "Alok" wrote: > > > While posting a comment on http://www.reddit.com I got an error page > > with the following curious statement on it. > > > > "reddit broke (sorry)" > > "looks like we shouldn't have stopped using lisp..." > > > > See screenshot at > > http://photos1.blogger.com/blogger/1773/1980/1600/reddit-broke.jpg > > > > Whether they truly repent not using lisp or otherwise, their site > > appears to be 3 times slower ... > > since when? Their site was more responsive last year. Especially the form submission page to create new posts. And also being able to refresh the page with your recent comments in them. > don't you think that the massive growth in usage that they've been > seeing lately might have something to do with that ? > You are right it definitely has a major impact, I wish they scale up their hardware in line with their possible growth. -A From jzgoda at o2.usun.pl Fri Jun 2 15:53:27 2006 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Fri, 02 Jun 2006 21:53:27 +0200 Subject: How do you practice Python? In-Reply-To: <1149271920.917381.112910@u72g2000cwu.googlegroups.com> References: <1149150517.034409.292530@g10g2000cwb.googlegroups.com> <1149271920.917381.112910@u72g2000cwu.googlegroups.com> Message-ID: sjdevnull at yahoo.com napisa?(a): >>In our field, we don't always get to program in the language we'd like >>to program. So... how do you practice Python in this case? > > Write code. Lots of it. Work on a project at home, contribute to > something open source, use it to write support scripts at work, > whatever. Figure out a way to write code. I second that. I moved from Python to J2EE in my job, but I didn't stop writing Python code for my spare-time projects. Now, when tight schedule made my project's manager to shift paradigm from buzz to productivity, I am happy I can write programs in Python again. On AS/400, but still better than Java... :D -- Jarek Zgoda http://jpa.berlios.de/ From david.nospam.hopwood at blueyonder.co.uk Wed Jun 21 11:07:26 2006 From: david.nospam.hopwood at blueyonder.co.uk (David Hopwood) Date: Wed, 21 Jun 2006 15:07:26 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: <1150883442.498308.226730@b68g2000cwa.googlegroups.com> References: <7zpshbsvjy.fsf@app-1.diku.dk><4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <1150809118.677124.142230@u72g2000cwu.googlegroups.com> <1150815461.210286.53120@r2g2000cwb.googlegroups.com> <1150822150.701434.296460@u72g2000cwu.googlegroups.com> <1150883442.498308.226730@b68g2000cwa.googlegroups.com> Message-ID: Rob Thorpe wrote: > Matthias Blume wrote: >>"Rob Thorpe" writes: >> >>>I think we're discussing this at cross-purposes. In a language like C >>>or another statically typed language there is no information passed >>>with values indicating their type. >> >>You seem to be confusing "does not have a type" with "no type >>information is passed at runtime". >> >>>Have a look in a C compiler if you don't believe me. >> >>Believe me, I have. > > In a C compiler the compiler has no idea what the values are in the program. > It knows only their type in that it knows the type of the variable they > are contained within. > Would you agree with that? No. In any language, it may be possible to statically infer that the value of an expression will belong to a set of values smaller than that allowed by the expression's type in that language's type system. For example, all constants have a known value, but most constants have a type which allows more than one value. (This is an essential point, not just nitpicking.) -- David Hopwood From antroy at gmail.com Fri Jun 2 11:07:33 2006 From: antroy at gmail.com (Ant) Date: 2 Jun 2006 08:07:33 -0700 Subject: How do you practice Python? In-Reply-To: <1149150517.034409.292530@g10g2000cwb.googlegroups.com> References: <1149150517.034409.292530@g10g2000cwb.googlegroups.com> Message-ID: <1149260853.743979.32270@g10g2000cwb.googlegroups.com> > In our field, we don't always get to program in the language we'd like For sure! > to program. So... how do you practice Python in this case? Say you're > doing J2EE right now. How do you practice Python to keep your skills > sharp? Well, we have to use J2EE at work. I keep my Python skills going by playing the puzzles like the PythonChallenge you mentioned and the Maths Challenge Euler project (http://mathschallenge.net/index.php?section=project) They are good for getting the Python idioms and shortcuts nailed, such as list comprehensions, generators etc that aren't available in Java. I also use Python almost exclusively at home for my website, Wiki, Photo gallery etc - all of which I hand rolled partly for the experience, and partly to get them exactly the way I want them :-) At work I use Python for all my scripting needs. I also use it to automate running through our web-applications for test purposes, using a framework I wrote around the urllib2 module. So, there are plenty of opportunities to use it if you keep your eyes open. Unfortunately for me, using Python so much has made using J2EE very painful. Not so good seeing as it's my day job! From daniel.dittmar at sap.corp Tue Jun 20 08:38:12 2006 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Tue, 20 Jun 2006 14:38:12 +0200 Subject: Duplex communication with pipes - is possible ? In-Reply-To: References: <1150476096.873581.96560@g10g2000cwb.googlegroups.com> Message-ID: Dara Durum wrote: > Now I trying with packet size decreasing. Are PIPE-s can handle the > binary data packets, or I need to convert them with base64 ? In the client, you need to set the mode of sys.stdin to binary, otherwise, you get the DOS translation of linefeeds. See http://mail.python.org/pipermail/python-list/2000-January/020463.html for some hints. I assume that the stream returned by subprocess.popen are also opened in text mode and you have to change them tobinary, see the second hint in the link mentioned above. Daniel From junkytownMAKNI at gmail.com Mon Jun 26 13:42:38 2006 From: junkytownMAKNI at gmail.com (SuperHik) Date: Mon, 26 Jun 2006 19:42:38 +0200 Subject: Beginner Programmer Question In-Reply-To: <1151343641.509435.245210@u72g2000cwu.googlegroups.com> References: <1151342733.742416.180370@r2g2000cwb.googlegroups.com> <1151343383.139891.219270@u72g2000cwu.googlegroups.com> <1151343641.509435.245210@u72g2000cwu.googlegroups.com> Message-ID: Rune Strand wrote: >> I am doing alot of reading, and the problem didnt come with an answer. >> I dont understand how to get it to continually input numbers and add >> all those together > > Use while, raw_input, sys.argv[1] and int() and break the loop when the > sum is above 100. > > ;-) > I don't think you understood his problem. He is trying to learn how to *program*, not just learn Python ;) From shejo284 at gmail.com Fri Jun 23 03:37:30 2006 From: shejo284 at gmail.com (Sheldon) Date: 23 Jun 2006 00:37:30 -0700 Subject: OverflowError: math range error... In-Reply-To: <1150994861.611691.74220@c74g2000cwc.googlegroups.com> References: <1150965908.354492.239230@i40g2000cwc.googlegroups.com> <1150994861.611691.74220@c74g2000cwc.googlegroups.com> Message-ID: <1151048250.894370.118500@b68g2000cwa.googlegroups.com> Thanks for the tips! I am going to look into this some more. /Sheldon Simon Forman skrev: > Sheldon wrote: > > Hi, > > > > I have a written a script that will check to see if the divisor is zero > > before executing but python will not allow this: > > > > ?if statistic_array[0:4] > 0.0: > > statistic_array[0,0:4] = > > int(multiply(divide(statistic_array[0,0:4],statistic_array \ > > [0,4]),10000.0))/100.0 > > > > Does anyone know why Python is complaining: > > > > "statistic_array[0,0:4] = > > int(multiply(divide(statistic_array[0,0:4],statistic_array[0,4]),10000.0))/100.0 > > > > OverflowError: math range error" > > > > and how do I get around this problem? This stupid because there is a if > > statement preventing this "dividing by zero". > > > > Sincerely, > > Sheldon > > I don't know what special math modules you're using, but python usually > raises ZeroDivisionError for divide-by-zero problems. > > Try printing the intermediate values of each step in your problem code. > > d = divide(statistic_array[0,0:4], statistic_array[0,4]) > print d > > m = multiply(d, 10000.0) > print m > > i = int(m) > print i > > statistic_array[0,0:4] = i > > > That might help you track down what's wrong. From raffaelcavallaro at pas-d'espam-s'il-vous-plait-mac.com Fri Jun 16 11:29:12 2006 From: raffaelcavallaro at pas-d'espam-s'il-vous-plait-mac.com (Raffael Cavallaro) Date: Fri, 16 Jun 2006 11:29:12 -0400 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <2006061410510511272-raffaelcavallaro@pasdespamsilvousplaitmaccom> <2006061501423327544-raffaelcavallaro@pasdespamsilvousplaitmaccom> Message-ID: <2006061611291216807-raffaelcavallaro@pasdespamsilvousplaitmaccom> On 2006-06-16 05:22:08 -0400, Joachim Durchholz said: > And this is a typical dynamic type advocate's response when told that > static typing has different needs: > > "*I* don't see the usefulness of static typing so *you* shouldn't want > it, either." But I haven't made this sort of argument. I never said you shouldn't use static typing if you want to. There are indeed types of software where one wants the guarantees provided by static type checks. For example, software that controls irreplaceable or very expensive equipment such as space craft, or software that can kill people if it fails such as software for aircraft or medical devices. The problem for static typing advocates is that most software is not of this type. There is a very large class of software where user inputs are unpredictable and/or where input data comes from an untrusted source. In these cases run-time checks are going to be needed anyway so the advantages of static type checking are greatly reduced - you end up doing run-time checks anyway, precisely the thing you were trying to avoid by doing static analysis. In software like this it isn't worth satisfying a static type checker because you don't get much of the benefit anyway and it means forgoing such advantages of dynamic typing as being able to run and test portions of a program before other parts are written (forward references to as yet nonexistent functions). Ideally one wants a language with switchable typing - static where possible and necessary, dynamic elsewhere. To a certain extent this is what common lisp does but it requires programmer declarations. Some implementations try to move beyond this by doing type inference and alerting the programmer to potential static guarantees that the programmer could make that would allow the compiler to do a better job. In effect the argument comes down to which kind of typing one thinks should be the default. Dynamic typing advocates think that static typing is the wrong default. The notion that static typing can prove program correctness is flawed - it can only prove that type constraints are not violated but not necessarily that program logic is correct. It seems to me that if we set aside that class of software where safety is paramount - mostly embedded software such as aircraft and medical devices - we are left mostly with efficiency concerns. The 80-20 rule suggests that most code doesn't really need the efficiency provided by static guarantees. So static typing should be invoked for that small portion of a program where efficiency is really needed and that dynamic typing should be the default elswhere. This is how common lisp works - dynamic typing by default with static guarantees available where one needs them. From daniel.dittmar at sap.corp Fri Jun 16 10:38:11 2006 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Fri, 16 Jun 2006 16:38:11 +0200 Subject: XML, JSON, or what? In-Reply-To: <1150466796.646397.149890@p79g2000cwp.googlegroups.com> References: <1149749530.734275.181300@j55g2000cwa.googlegroups.com> <1149760146.136587.124710@h76g2000cwa.googlegroups.com> <1150466796.646397.149890@p79g2000cwp.googlegroups.com> Message-ID: > My client-server is Python-to-Python. At present, I am using cPickle to > transfer objects between the two. Among other things, I sometimes > transfer a tuple. Using JSON it appears on the other side as a list. As > I sometimes use the tuple as a dictionary key, this fails, as you > obviously cannot use a list as a key. [...] > Can someone confirm this, or is there an easy workaround? You can always convert a list to a tuple using the tuple () builtin right before you use it as a key. But you have to be sure that it is a list. tuple ("abc") => ('a', 'b', 'c') is probably not what you intend to do. Daniel From andre.roberge at gmail.com Thu Jun 22 22:42:29 2006 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: 22 Jun 2006 19:42:29 -0700 Subject: [ANN] RUR-PLE version 0.9.9 Message-ID: <1151030548.996950.275870@y41g2000cwy.googlegroups.com> Roberge's Used Robot: a Python Learning Environment Version 0.9.9 of RUR-PLE has been released. It can be found at: https://sourceforge.net/project/showfiles.php?group_id=125834 RUR-PLE should work properly on all major platforms (Mac, Linux and Windows) in 3 different languages (English, French, Spanish). Feedback would be appreciated to confirm this prior to release of version 1.0. -------------------------------------- Learning to program computer should be fun, for adults and children alike. RUR-PLE is an environment designed to help you learn computer programming using Python. RUR-PLE is a wxPython-based app. RUR-PLE contains four main elements: 1. Lessons viewable within an incorporated browser. Version 0.9.9 includes over 40 lessons introducing Python. A few more will be written for the 1.0 release. 2. A "robot world" with a robot that can accomplish tasks through Python programs. 3. A built-in interpreter which can be used to play with Python. 4. A built-in file editor which can be used for futher Python explorations. This version includes a triilingual (English, French and Spanish) interface. Translations to other languages are welcome. Only English lessons are included. ======= Apprendre ? programmer devrait ?tre amusant, que l'on soit un adulte ou un enfant. RUR-PLE est un environnement con?u pour vous aider ? apprendre la programmation informatique avec le langage Python. Pour utiliser RUR-PLE, vous aurez besoin de wxPython. L'interface est disponible en fran?ais, mais les le?ons ne sont malheureusement pas encore traduites en fran?ais. Andr? From imcsee at gmail.com Tue Jun 13 12:16:50 2006 From: imcsee at gmail.com (imcs ee) Date: Wed, 14 Jun 2006 00:16:50 +0800 Subject: .py and running in Windows: In-Reply-To: <1150206503.313636.50130@c74g2000cwc.googlegroups.com> References: <1150206503.313636.50130@c74g2000cwc.googlegroups.com> Message-ID: i modify "C:\Python\python.exe" -i "%1" %* to cmd /k;"C:\Python\python.exe" -i "%1" %* or cmd /k;"C:\Python\python.exe" "%1" %* just a little trick. On 13 Jun 2006 06:48:23 -0700, Iain King wrote: > > > Andrew Gwozdziewycz wrote: > > You'll have better results posting this to it's own thread. > > > > He certainly should have, but since I've read it here anyway: > > > > On Jun 13, 2006, at 9:29 AM, Michael Yanowitz wrote: > > > > > Hello: > > > > > > Presently in my Windows 2000 system, when I double-click on a > > > .py file (open it) it automatically runs it in Python. I would > > > like to change that behavour. That is fine for .pyc file, but > > > for .py files, I would either like to have it run in Python but > > > return to the Python shell prompt when finished rather than > > > exit the shell. How do I do that? > > > Or would it cause a problem (so that Python no longer works) if > > > I change the default .py extension to open in an editor rather > > > than execute it if I open it? > > > > > In an explorer window, go to Tools->Folder Options > Go to the File Types tab, find the PY extension, then click on > Advanced* > Select the 'open' action, and click Edit... > change the 'Application used to perform action', inserting a '-i' > between the exe and the first parameter. For example, I changed mine > to: > > "C:\Python\python.exe" -i "%1" %* > > The exact line will depend on where your python.exe is. > OK all the dialogs you've opened, then double click a .py file to test > it. > > *I'm using WinXP, so the exact name of some of the buttons may be > different for you. > > Iain > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rNOSPAMon at flownet.com Tue Jun 20 00:30:11 2006 From: rNOSPAMon at flownet.com (Ron Garret) Date: Mon, 19 Jun 2006 21:30:11 -0700 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> Message-ID: In article <1150765102.867144.12590 at h76g2000cwa.googlegroups.com>, "Marshall" wrote: > The conversation I would *really* like to have is the one where we > discuss what all the differences are, functionally, between the two, > and what the implications of those differences are, without trying > to address which approach is "right" or "better", because those are > dependent on the problem domain anyway, and because I can > make up my own mind just fine about which one I prefer. > > The comp.lang.functional and comp.lang.lisp people are probably > two of the smartest groups on usenet. (I do not consider myself > a member of either group.) You wouldn't *think* that conversation > would be *so* hard to have. It's hard to have because there's very little to say, which leaves the academics without enough to do to try to justify their existence. This is the long and the short of it: 1. There are mismatches between the desired behavior of code and its actual behavior. Such mismatches are generally referred to as "bugs" or "errors" (and, occasionally, "features"). 2. Some of those mismatches can be detected before the program runs. Some can be detected while the program runs. And some cannot be detected until after the program has finished running. 3. The various techniques for detecting those mismatches impose varying degrees of burden upon the programmer and the user. That's it. Everything else, including but not limited to quibbling over the meaning of the word "type", is nothing but postmodernist claptrap. IMHO of course. rg From tundra at tundraware.com Wed Jun 14 03:23:35 2006 From: tundra at tundraware.com (Tim Daneliuk) Date: 14 Jun 2006 03:23:35 EDT Subject: curses module bug in windows python? In-Reply-To: References: <1150267132.986057.226690@i40g2000cwc.googlegroups.com> <448FB38F.8040106@tundraware.com> Message-ID: Erik Max Francis wrote: > Tim Daneliuk wrote: > >> Nope - this module is not supported under Windows ... > > There's at least one Python curses module for Windows: > > http://adamv.com/dev/python/curses/ > Sorry, I should have been more specific: AFAIK, curses is not one of the *standard* Python modules for Windows. -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From onurb at xiludom.gro Fri Jun 23 09:29:09 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Fri, 23 Jun 2006 15:29:09 +0200 Subject: * in Python In-Reply-To: <1151065046.668902.23010@g10g2000cwb.googlegroups.com> References: <1151061836.557835.295820@p79g2000cwp.googlegroups.com> <1151065046.668902.23010@g10g2000cwb.googlegroups.com> Message-ID: <449beca5$0$13891$626a54ce@news.free.fr> placid wrote: > Duncan Booth wrote: > >>placid wrote: >> >> >>>Hi all, >>> >>>Can someone tell me what * in the following code means/does a Google >>>search didnt turn up anything as i dont know what the * is called >>>(related to Python and i dont think Python has pointers) >>> >> >>* is for variable number of positional arguments, ** is for variable >>keyword arguments. The syntax is symmetrical when defining functions and >>when calling them. >> >>See http://docs.python.org/ref/calls.html >>and http://docs.python.org/ref/function.html > > > so * basically means that args is a list A tuple IIRC > containing more arguments that > can change in size, whereas ** means that args is a dictionary of > key=value arguments? > Why don't you try by yourself in the Python shell ? One of the nice things with Python is that it's quite easy to explore and experiment. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From py.adriano at gmail.com Fri Jun 9 15:26:22 2006 From: py.adriano at gmail.com (py.adriano at gmail.com) Date: 9 Jun 2006 12:26:22 -0700 Subject: Interacting with a process that I ran with subprocess module In-Reply-To: <4etgguF1fef6aU1@uni-berlin.de> References: <1149864190.134947.178000@g10g2000cwb.googlegroups.com> <4etgguF1fef6aU1@uni-berlin.de> Message-ID: <1149881182.638771.318550@i39g2000cwa.googlegroups.com> Well... I found pexpect as you said, but I also found that it doesn't work on windows. I need a cross-platform solution, as the program is going to run on several operating systems. Any other sugestion? Cheers! Diez B. Roggisch wrote: > py.adriano at gmail.com schrieb: > > Hi folks, > > > > I'm trying to use the nmap runtime interaction feature while using it > > with the subprocess module. For those not familiar with nmap, the > > runtime interaction feature allow users to get informations about the > > scan stats during the nmap execution. More at: > > http://www.insecure.org/nmap/man/man-runtime-interaction.html > > If someone want to try, just run nmap and try to type some keys to see > > what happens. This only works with nmap 4.00 and above. > > > > Ok.. What I've tried is shown below: > > > > from subprocess import Popen, PIPE > > nmap = Popen("nmap -T3 -A 10.0.0.1-254", stdin=PIPE, stdout=PIPE, > > stderr=PIPE, shell=True, bufsize=1) > > > > To interact with nmap, I tried: > > > > nmap.communicate("?") > > > > And I tried this, also: > > > > nmap.stdin.write("?") > > nmap.stdout.read() > > > > What's wrong? Is that suposed to be this way? Is there a better way to > > interact with it that I've missed? Any help is very welcome. Thanks in > > advance! > > Programs that interact with users usually require a terminal to be run > from. This is not the case when using pipes. Use pexpect. > > Diez From no-spam at no-spam-no-spam.com Wed Jun 7 08:20:25 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Wed, 07 Jun 2006 14:20:25 +0200 Subject: A WAD(-like) C-level exception catcher for Windows? Message-ID: For Unix there exists the WAD (part of SWIG) to catch C/machine-level errors (mem. access error, etc. ) and transform them into nice Python exceptions. ( http://www.usenix.org/events/usenix01/full_papers/beazley/beazley.pdf ) Does something like that exist for Windows? Or does somebody know a roadmap how to do something like that with Windows most easily? -robert From faulkner612 at comcast.net Sun Jun 4 16:55:44 2006 From: faulkner612 at comcast.net (faulkner) Date: 4 Jun 2006 13:55:44 -0700 Subject: re beginner In-Reply-To: References: Message-ID: <1149454544.189377.136520@i40g2000cwc.googlegroups.com> you could write a function which takes a match object and modifies d, pass the function to re.sub, and ignore what re.sub returns. # untested code d = {} def record(match): s = match.string[match.start() : match.end()] i = s.index('\t') print s, i # debugging d[s[:i]] = int(s[i+1:]) return '' re.sub('\w+\t\d+\t', record, stuff) # end code it may be a bit faster, but it's very roundabout and difficult to debug. SuperHik wrote: > hi all, > > I'm trying to understand regex for the first time, and it would be very > helpful to get an example. I have an old(er) script with the following > task - takes a string I copy-pasted and wich always has the same format: > > >>> print stuff > Yellow hat 2 Blue shirt 1 > White socks 4 Green pants 1 > Blue bag 4 Nice perfume 3 > Wrist watch 7 Mobile phone 4 > Wireless cord! 2 Building tools 3 > One for the money 7 Two for the show 4 > > >>> stuff > 'Yellow hat\t2\tBlue shirt\t1\nWhite socks\t4\tGreen pants\t1\nBlue > bag\t4\tNice perfume\t3\nWrist watch\t7\tMobile phone\t4\nWireless > cord!\t2\tBuilding tools\t3\nOne for the money\t7\tTwo for the show\t4' > > I want to put items from stuff into a dict like this: > >>> print mydict > {'Wireless cord!': 2, 'Green pants': 1, 'Blue shirt': 1, 'White socks': > 4, 'Mobile phone': 4, 'Two for the show': 4, 'One for the money': 7, > 'Blue bag': 4, 'Wrist watch': 7, 'Nice perfume': 3, 'Yellow hat': 2, > 'Building tools': 3} > > Here's how I did it: > >>> def putindict(items): > ... items = items.replace('\n', '\t') > ... items = items.split('\t') > ... d = {} > ... for x in xrange( len(items) ): > ... if not items[x].isdigit(): d[items[x]] = int(items[x+1]) > ... return d > >>> > >>> mydict = putindict(stuff) > > > I was wondering is there a better way to do it using re module? > perheps even avoiding this for loop? > > thanks! From alanalan at newsgroup.nospam Fri Jun 2 12:16:21 2006 From: alanalan at newsgroup.nospam (A.M) Date: Fri, 2 Jun 2006 12:16:21 -0400 Subject: New to Python: Do we have the concept of Hash in Python? References: <1149182265.257263.159210@f6g2000cwb.googlegroups.com> Message-ID: "Sion Arrowsmith" wrote in message news:eYk*yxbir at news.chiark.greenend.org.uk... > gregarican wrote: >>I came from using Ruby about a year or so [ ... ] > > That's an interesting way round. Why did you consider Python if > you already knew Ruby, and which is now your preferred language? > (I've no interest in learning Ruby, but from what I've seen of it > I similarly can't imagine what would motivate me to learn Python.) > > -- > \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ > ___ | "Frankly I have no feelings towards penguins one way or the > other" > \X/ | -- Arthur C. Clarke > her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump My decision wasn't based on which language I am most comfortable with. I can do the same application in Java in one hour. We are looking for a scripting language to use across our organization. This is a strategic decision. Out 1st choice is Python, the second one is Perl and the last one is Ruby. Yesterday I proof that Python is way to go. The programming language aspects of Ruby is a brilliant, but the language itself is not everything. I encountered some problem with Ruby and I found it is not there yet. Here is some of problems I have with ruby: (consider the fact that it is my personal opinion) 1) Ruby community feel that there is strong database access support. I personally didn't find DBI distribution and documentation very organized and at the production level. For example, DBI:OCI8 is at experimental state. http://www.jiubao.org/ruby-oci8/ Oracle data access support is very important for me and DBI:OCI8 is the only way you can get data from Oracle stored procedures. 2) Komodo (my favorite scripting IDE) crashes when I debug certain type of Ruby scripts. Moreover there is no ActiveRuby from ActiveState **yet**. 3) You can find lots of excellent Python books from OREILLY. You don't have much option for Ruby **yet**. 4) Ruby became famous because of Rails. Rails is a great idea, but I am so focused on ASP.NET and J2EE and I am going to stay there. Rails doesn't have a production level support for IIS. So I am not very interested in Rails. In essence, Ruby language is the best, but Ruby platform is too young for me. I'll give Ruby another two years and come back to it again. I found the Python language quite powerful and easy. With mature and strong community support. From sjmachin at lexicon.net Sat Jun 3 21:39:55 2006 From: sjmachin at lexicon.net (John Machin) Date: Sun, 04 Jun 2006 11:39:55 +1000 Subject: Pyrex list/array In-Reply-To: <1149360983.373137.200740@i39g2000cwa.googlegroups.com> References: <1149360983.373137.200740@i39g2000cwa.googlegroups.com> Message-ID: <448239EB.6010706@lexicon.net> On 4/06/2006 4:56 AM, Jim Lewis wrote: > I'm trying to move a function into pyrex for speed. You probably didn't expect the Inquisition; nobody does. But here it is, nice red uniforms and all: 1. What is your speed requirement and how far short of that are you at the moment? 2. Are you sure there is no Python or third-party module that does what you want? 3. Is your algorithm the best possible? 4. Is your Python implementation of that algorithm the best possible? Have you exposed it to the critical gaze of the speed-freaks in this newsgroup? 5. Does your architecture support psyco? If so, have you tried that and what were the results? > The python side > needs to pass a list to the pyrex function. Do I need to convert to > array or something so pyrex can generate tight code? I'm not clear how > to do this. > The question might be better asked on the Pyrex mailing list. You don't need to convert a list to a C array, and it may not even be possible, depending on what type(s) of data you have in the list. Almost any Python code is also valid Pyrex code. For a start, just compile your function with Pyrex and compare the speed. What you do next is going to depend very much on what operations you are performing on the list and the objects it contains. Watch out for Python built-ins like range, xrange, ord, chr, abs, bool, int(a_number), float(a_number), divmod, max/min (two_numeric_args). In almost all cases you get cheap wins by replacing use of these by simple C-like code -- provided of course you are absolutely sure you know what types you are dealing with. HTH, John From certo at comeno.it Sun Jun 11 08:53:08 2006 From: certo at comeno.it (imho) Date: Sun, 11 Jun 2006 12:53:08 GMT Subject: package search In-Reply-To: <1150009850.738535.155550@m38g2000cwc.googlegroups.com> References: <1150009850.738535.155550@m38g2000cwc.googlegroups.com> Message-ID: boris ha scritto: > I have two directories, lib1 and lib2, that both contain the package > foo, one with the submodule mod1 > and the other with the submodule mod2: > [...] > Now this script: > > import sys > sys.path.append("lib1") > sys.path.append("lib2") > import foo.mod1 > > will find the module foo.mod1, while the same script with the two > append-lines interchanged will not: > > import sys > sys.path.append("lib2") > sys.path.append("lib1") > import foo.mod1 > > The error is: > > import foo.mod1 > ImportError: No module named mod1 > [...] You just have to put in "__init__.py" in "lib2" (the package directory you are "extending"), the following lines: from pkgutil import extend_path __path__ = extend_path(__path__, __name__) "__path__", in each __init__ module, is a list initialized with the module's path, but you can extend it by appending paths where you want the interpreter to look for further modules. pkgutil.extend_path automatically appends to __path__ all subdirectories of directories on sys.path named after the package. HTH :-) Diego. From scott at bogusaddress.com Thu Jun 29 07:58:28 2006 From: scott at bogusaddress.com (scott at bogusaddress.com) Date: Thu, 29 Jun 2006 11:58:28 GMT Subject: Passing a Cookie with httplib References: <12a5p6h9ug19818@corp.supernews.com> Message-ID: On Wed, 28 Jun 2006 20:21:37 -0000, Grant Edwards wrote: >On 2006-06-28, scott at bogusaddress.com wrote: > >> From a shell script, I have used /usr/bin/curl to access a web site >> and pass a cookie > >I use ClientCookie for that. > >http://wwwsearch.sourceforge.net/ClientCookie/ Thanks Grant. I'll take a look at this solution. Scott From fredrik at pythonware.com Wed Jun 21 12:04:07 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 21 Jun 2006 18:04:07 +0200 Subject: 'import site' failed; use -v for traceback In-Reply-To: <1150905019.706161.288510@y41g2000cwy.googlegroups.com> References: <1150905019.706161.288510@y41g2000cwy.googlegroups.com> Message-ID: huwjeffries at gmail.com wrote: > Hi There, > > I've installed python2.4-dev on Unbuntu linux. When I run it, it gives > an error: > > 'import site' failed; use -v for traceback > > (Get the same result if I uninstall it and install regular python2.4). > > Using -v traceback gives: > > 'import site' failed; traceback: > ImportError: No module named site > > Python is installed in: > /usr/bin/python > /usr/lib/python2.4 > > File listing of /usr/lib/python2.4: where's the site.py file ? > Bastion.py keyword.py SimpleHTTPServer.py > bdb.py lib-dynload SimpleXMLRPCServer.py > binhex.py lib-old site-packages > bisect.py LICENSE.txt smtpd.py > bsddb locale.py smtplib.py From maric at aristote.info Wed Jun 21 09:39:02 2006 From: maric at aristote.info (Maric Michaud) Date: Wed, 21 Jun 2006 15:39:02 +0200 Subject: How to override the doc of an object instance. In-Reply-To: References: Message-ID: <200606211539.02663.maric@aristote.info> Le Mercredi 21 Juin 2006 06:50, David Huard a ?crit?: > class widget (object): > ? ? """This is a widget.""" > ? ? def ?__init__(self): > ? ? ? ? self._x = None > ? ? def fget(self): > ? ? ? ? return self._x > ? ? def fset(self, value): > ? ? ? ? self._x = value > ? ? ? ? print self._x, 'Ok' > ? ? x = property(fget = fget, fset = fset, doc= "It prints") > > > print widget.x.__doc__ > > w = widget() > w.x = 5 > print w.x.__doc__ This is w.__class__.x.__doc__. w.x return the value you put in self._x, say an int, so w.x.__doc__ will print the docstring of int. -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From didier at lrde.epita.fr Wed Jun 14 05:28:20 2006 From: didier at lrde.epita.fr (Didier Verna) Date: Wed, 14 Jun 2006 11:28:20 +0200 Subject: TONIGHT! Lisp group beerfest in NYC, PyCells to be discussed References: <2QBjg.497$Yq7.348@fe12.lga> <1150258705.113102.199690@y41g2000cwy.googlegroups.com> Message-ID: "mrcsparker at gmail.com" wrote: > Why are all of the cool Lisp things up north? No Lispers down south? Of course there are. South of Paris, I mean. -- Didier Verna, didier at lrde.epita.fr, http://www.lrde.epita.fr/~didier EPITA / LRDE, 14-16 rue Voltaire Tel.+33 (1) 44 08 01 85 94276 Le Kremlin-Bic?tre, France Fax.+33 (1) 53 14 59 22 didier at xemacs.org From wescpy at gmail.com Fri Jun 23 20:36:17 2006 From: wescpy at gmail.com (w chun) Date: Fri, 23 Jun 2006 17:36:17 -0700 Subject: OpenOffice UNO export PDF help needed Message-ID: <78b3a9580606231736q638e637l42f733e40721df3c@mail.gmail.com> > > Subject: OpenOffice UNO export PDF help needed > > From: "Sells, Fred" > > Date: Sun Apr 30 04:17:43 CEST 2006 > > > > I've geen googling for 3 days now, and cannot find out how to do this. > > > > I'm trying to use OpenOffice 2.0 and UNO to generate PDF documents. I'm > > using windows, but will have to make it work under Linux for production. > > I've been able to set the parameters and call the exportToPdf method, but > > the exported file is not PDF but an .odt document, > > : > > below is a java code snippet, submitted with apologies, I'm using that > > rather than python because I found better examples and my java IDE helps me > > out. I originally started out to do python, and will eventually shift back > > to it once I get this working > > > Subject: OpenOffice UNO export PDF help needed > From: "Michele Petrazzo" > Date: Mon May 1 11:37:07 CEST 2006 > > Have you tried the ooextract.py found on: > http://udk.openoffice.org/python/python-bridge.html > > Here work well and generate a pdf file. > > See also this for more info about generate pdf: > http://mithrandr.moria.org/blog/447.html fred, have you had any luck with either your Java or Python code? did you take a look at the code that Michele had suggested? please post your progress or any errors you encounter as others on the list are interested too. what version of OOo are you using? thanks, -wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From grante at visi.com Thu Jun 15 13:33:02 2006 From: grante at visi.com (Grant Edwards) Date: Thu, 15 Jun 2006 17:33:02 -0000 Subject: code folding, a unique problem to python? References: Message-ID: <12936eejbum2e75@corp.supernews.com> On 2006-06-15, Paul McGuire wrote: > "John Salerno" wrote in message > news:jxfkg.2314$No6.48555 at news.tufts.edu... >> >> But my question is more general: is it possible to implement code >> folding with Python given that it has no real block delimiters? > > SciTE can fold Python. If only there were a way for users to bind key-sequences... -- Grant Edwards grante Yow! I was making donuts at and now I'm on a bus! visi.com From thorley at gmail.com Thu Jun 29 10:43:27 2006 From: thorley at gmail.com (thorley at gmail.com) Date: 29 Jun 2006 07:43:27 -0700 Subject: python for windows internet filter / firewall In-Reply-To: <4gi6qaF1nctcjU1@uni-berlin.de> References: <1151590961.464723.249360@p79g2000cwp.googlegroups.com> <4gi6qaF1nctcjU1@uni-berlin.de> Message-ID: <1151592207.927954.304180@y41g2000cwy.googlegroups.com> I thought speed might be an issue. At this point I'm not interested in much more than toying around, so *if* there's a way to do it, I'd like to explore the options. -- matthew Diez B. Roggisch wrote: > > 2) Is this even reasonable in python and how might I get started? (e.g. > > win32 COM?) > > Don't know much (not to say nothing) about windows firewalling & the > interfaces one needs to talk to them. > > But _what_ I know is: a firewall needs to be fast. The big guys in > networking put a lot of effort into pushing as much package processing as > possible into the hardware-layer. > > And as much as I love python - I do not see it here, beyond a > proof-of-concept. > > Diez From shejo284 at gmail.com Thu Jun 22 04:34:28 2006 From: shejo284 at gmail.com (Sheldon) Date: 22 Jun 2006 01:34:28 -0700 Subject: comparing two arrays In-Reply-To: <4fpvr0F1k8dauU1@uni-berlin.de> References: <1150721380.948808.231760@h76g2000cwa.googlegroups.com> <4fnlbiF1j83q2U1@uni-berlin.de> <4fnqoqF1k8n10U1@uni-berlin.de> <1150795424.752973.303420@g10g2000cwb.googlegroups.com> <4fpvr0F1k8dauU1@uni-berlin.de> Message-ID: <1150965263.326199.176520@c74g2000cwc.googlegroups.com> Thanks Diez, It will take a little while for this one to sink in but it gets the job done now and will for future cases. /Sheldon Diez B. Roggisch skrev: > >> print [i for i, _ in enumerate((None for x, y in zip(a, b) where x == > >> y))] > >> > >> instead. > >> > >> Diez > > > > Hi Diez, > > > > I wish I say that I understood what you wrote here but I can't. > > Do you mind explaining a little more? > > I actually made a typo, instead of "where" in the above use "if". and the > whole thing won't compute what you are after. This will: > > [i for i, equals in enumerate((x == y for x, y in zip(a, b))) if equals] > > Sorry for that. > > Its a nested list-comprehension. Actually, the outer thingy is a > list-comprehension while the inner is a generator expression. There is of > course a difference, but for now this doesn't matter too much. > > a list comprehension of form > > [ for in if ] > > is a more compact form for > > result = [] > for in : > if : > result.append() > > > A generator expression works the same with () instead of []. > > Now let's decompose the above statment: > > (x == y for x, y in zip(a, b) )) > > = x, y > = zip(a, b) > = x == y > > So: the iterable is returned by the function zip. That is a built-in which > will take 2 or more lists and return a list of tuples, where the first > element is from the first list, then the second and so on. So your example > lists become: > > a = [0,1,2,5,6,6] > b = [5,4,1,6,4,6] > zip(a, b) = [(0,5), (1,4), (2,1), (5,6), (6,4), (6,6)] > > So iterating over this yields the pairs of (0,5) and so forth. > > Next thing is that with > > x, y = p > > python unpacks a tuple and refers to its contents by name x for the first > one and y for the second. So overall, we loop in sync over both lists, and > getting x and y to point to the corresponding elements. > > Now the expression x == y will result True if x == y - False otherwise. > > So the result of the inner listcomp/genexp looks like this: > > res = [False, False, False, False, False, True] > > As you can see: for each pair x,y in the original lists we come up with the > result of comparing them. > > Now the outer listcomp using "res" instead of the genexps for clarity reads > like this: > > > > [i for i, equals in enumerate(res) if equals] > > = i, equals > = enumerate(res) > = i > = equals > > enumerate is another built-in that takes an iterable and returns a tuple of > > (pos, element) > > for each element in the iterable. > > So for our list, it will return: > > [(0, False), (1, False), (2, False), (3, False), (4, False), (5, True)] > > These tupkes values are assigened to i and equals for each element of the > above list. The condtion > > equals > > will then guarantee that only those expressions are evaluated where equals > is True - the last pair, so to speak. The expression then only stores the > index i. Which will give us the desired result. > > Diez From sleepingsquirrel at yahoo.com Tue Jun 27 17:59:57 2006 From: sleepingsquirrel at yahoo.com (Greg Buchholz) Date: 27 Jun 2006 14:59:57 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: <7pij925jg29ddfvfrn0b98crrkfm4daaef@4ax.com> References: <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <34aj92h0g7tqi9amhh7k3ieq5n568t0e6f@4ax.com> <1150927463.340542.65690@g10g2000cwb.googlegroups.com> <7pij925jg29ddfvfrn0b98crrkfm4daaef@4ax.com> Message-ID: <1151445597.574064.319180@j72g2000cwa.googlegroups.com> George Neuner wrote: > That was interesting, but the authors' method still involves runtime > checking of the array bounds. IMO, all they really succeeded in doing > was turning the original recursion into CPS and making the code a > little bit clearer. Hmm. There is a comparison in both the DML and Haskell code, but that's just there to make the binary search terminate correctly. The point of the exercise is the line in the DML code "val m = (hi + lo) div 2", or the "bmiddle" function in the Haskell code. If you change that line to something like "val m = (hi + lo)" you'll get a compiler error complaining about an unsolved constraint. The point of the Haskell code is to use the type system to ensure that array indices have a know provenance. They're derived from and statically associated with each individual array, so you can't use an index from one array with a different array. You'll probably also enjoy the paper... "Eliminating Array Bound Checking Through Dependent Types" http://citeseer.ist.psu.edu/xi98eliminating.html ...and DML itself... http://www.cs.bu.edu/~hwxi/DML/DML.html Greg Buchholz From dan_2718 at yahoo.co.uk Thu Jun 8 17:52:45 2006 From: dan_2718 at yahoo.co.uk (dan) Date: 8 Jun 2006 14:52:45 -0700 Subject: capture video from camera References: <1149598946.182874.121650@c74g2000cwc.googlegroups.com> <1149603488.012417.269760@j55g2000cwa.googlegroups.com> <1149618799.409008.33060@h76g2000cwa.googlegroups.com> <1149686461.261815.81670@i39g2000cwa.googlegroups.com> Message-ID: <1149803564.942255.244570@i40g2000cwc.googlegroups.com> aljosa wrote: > i had no intention to say that videocapture is bad but it's not what > i'm looking for. > concerning docs, everybody has their own view on how docs should look > like. > > that said, i should have written more clearly what i'm looking for. Hi aljosa, I hope you won't be deterred from posting further questions to the group by Fredrik's somewhat terse and unfriendly reply. comp.lang.python is a forum generally noted for its pleasing admixture of erudition and encouragement. Fredrik is uncommonly distinguished in the scope and depth of his knowledge. He does himself, and the group in general, an injustice by the intolerance of his response. With best wishes, Dan From fredrik at pythonware.com Fri Jun 9 09:08:51 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 09 Jun 2006 15:08:51 +0200 Subject: Short questions wrt Python & Unicode In-Reply-To: <1149854676.717074.309260@f6g2000cwb.googlegroups.com> References: <1149854676.717074.309260@f6g2000cwb.googlegroups.com> Message-ID: KvS wrote: >>>> s=u"\u0040\u0166\u00e6" >>>> s > u'@\u0166\xe6' > > (does this latter \xe6 have to do with the internal representation of > unic. objects, maybe with this UCS-2 encoding?) no, it's simply the shortest way to represent U+00E6 as Python Unicode string literal, when limited to ASCII only. From fredrik at pythonware.com Wed Jun 21 07:54:43 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 21 Jun 2006 13:54:43 +0200 Subject: help() on stdout.closed References: Message-ID: Pekka Karjalainen wrote: > Suppose I had no idea what sys.stdout.closed was and wanted to find out. > Where would I look it up? >>> help(sys.stdout) ... | closed = | True if the file is closed ... in case anyone feels like hacking, support for something like >>> help(sys.stdout, "closed") might be useful, I think. From Sibylle.Koczian at Bibliothek.Uni-Augsburg.de Fri Jun 9 06:18:01 2006 From: Sibylle.Koczian at Bibliothek.Uni-Augsburg.de (Sibylle Koczian) Date: Fri, 09 Jun 2006 12:18:01 +0200 Subject: How to generate k+1 length strings from a list of k lengthstrings? In-Reply-To: References: <1149773165.890230.228960@g10g2000cwb.googlegroups.com> <1149780416.430558.251860@h76g2000cwa.googlegroups.com> Message-ID: <4et06qF1fsab8U1@news.dfncis.de> Girish Sahani schrieb: > Yes it is the former of course.Common elements could be in any order in > both strings. > Thanks Marc :)...though we need to add an if for checking the length of > the string (k+1). > No, why? Every character from string1 is removed from string2 at most once. And string2 is added to string1 if and only if it has length 1; if not, string1 is set to the empty string. So either string1 is empty or it has length k+1. Or did you mean checking if string1 is empty? -- Dr. Sibylle Koczian Universitaetsbibliothek, Abt. Naturwiss. D-86135 Augsburg e-mail : Sibylle.Koczian at Bibliothek.Uni-Augsburg.DE From kent at kentsjohnson.com Fri Jun 9 09:29:50 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Fri, 09 Jun 2006 09:29:50 -0400 Subject: secure xmlrpc server? In-Reply-To: References: Message-ID: <448976aa$1_2@newspeer2.tds.net> Laszlo Nagy wrote: > But I do not know how to create an XML RPC server in Python that uses > HTTPS for XML transports. This recent recipe seems to do exactly what you want: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496786 Kent From ygao2004 at gmail.com Sat Jun 17 22:42:42 2006 From: ygao2004 at gmail.com (ygao) Date: 17 Jun 2006 19:42:42 -0700 Subject: how can get the module global symbol table from a function or method which it is called? In-Reply-To: <1150597845.758056.135740@p79g2000cwp.googlegroups.com> References: <1150597845.758056.135740@p79g2000cwp.googlegroups.com> Message-ID: <1150598562.526193.111630@c74g2000cwc.googlegroups.com> I mean the way not passing parameter to the fonction or the method. ygao wrote: > when a function or method is called,how can get the module global > symbol table from which > it is called,not the module where it is defined(this is easy). > thanks! From wassipaul at gmx.at Fri Jun 30 10:42:55 2006 From: wassipaul at gmx.at (Stephan Wassipaul) Date: Fri, 30 Jun 2006 16:42:55 +0200 Subject: print shell output in a file In-Reply-To: <44a52fdb$0$3892$91cee783@newsreader01.highway.telekom.at> References: <44a52fdb$0$3892$91cee783@newsreader01.highway.telekom.at> Message-ID: <44a53851$0$3882$91cee783@newsreader01.highway.telekom.at> f = file('output.txt','w') print >>f, '%-30s | %-12d | %-12d |%-12d ' % (typename, size / count, count, size) f.close() > hello, > > one more question i will have! > > now i have written a little programm, which delivers me an output on the > shell! > > > here is the print command, which delivers me the following output (see > below) on the shell: > > > print '%-30s | %-12d | %-12d |%-12d ' % (typename, > size / count, > count, > size) > > > > --------------NAME-------------|Groesse(Byte)-|----Anzahl----|-Gesamtgroesse > (Byte)-| > ---------------------------------------------------------------------------- > ---------- > ADD_REAL_N6 | 4 | 1 |4 > AND_BOOL_N10 | 4 | 1 |4 > AND_BOOL_N12 | 4 | 1 |4 > > > > Is there a way to put this output in an file?!?! i searched about 2h for > this, but i couldn`t find an answer! > > thnks, juergen > From petr at tpc.cz Thu Jun 1 06:05:21 2006 From: petr at tpc.cz (Petr Jakes) Date: 1 Jun 2006 03:05:21 -0700 Subject: what is the reasonable (best?) Exception handling strategy? Message-ID: <1149156321.440828.95150@g10g2000cwb.googlegroups.com> I am a little bit confused by all possibilities for exceptions handling in Python (probably because I am not skilled enough??) I did try to search trough this list and reading Python tutorial about Errors and Exceptions but didn't find some "general" answer about exception handling policy (strategy). In the following example each row can IMHO raise an exception (if the Firebird service is not running for example, if the database is corrupted etc.). Do I have to write "try/except" clause on each row? Or to write try/except block (function) where to handle (on one place) all exceptions expected in the program code is a good idea? Or do I have to write own "exception hook"? What about unexpected exceptions? :( def databasExample(h,d,u,p): import kinterbasdb; kinterbasdb.init(type_conv=200) con = kinterbasdb.connect(host=h, database=d,user=u, password=p) cur = con.cursor() insertStatement = cur.prep("some SQL statement......") cur.executemany(insertStatement, ListOfValues) con.commit() cur.close() Generally I am trying to find some general advices or suggestions about exception handling more than the specific answers to the above mentioned code example. Regards Petr Jakes From duncan.booth at invalid.invalid Mon Jun 12 06:47:28 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 12 Jun 2006 10:47:28 GMT Subject: urllib behaves strangely References: Message-ID: Gabriel Zachmann wrote: > Here is a very simple Python script utilizing urllib: > > import urllib > url = > "http://commons.wikimedia.org/wiki/Commons:Featured_pictures/chronologi > cal" > print url > print > file = urllib.urlopen( url ) > mime = file.info() > print mime > print file.read() > print file.geturl() > > > However, when i ecexute it, i get an html error ("access denied"). > > On the one hand, the funny thing though is that i can view the page > fine in my browser, and i can download it fine using curl. > > On the other hand, it must have something to do with the URL because > urllib works fine with any other URL i have tried ... > It looks like wikipedia checks the User-Agent header and refuses to send pages to browsers it doesn't like. Try: headers = {} headers['User-Agent'] = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.0.4) Gecko/20060508 Firefox/1.5.0.4' request = urllib2.Request(url, headers) file = urllib2.urlopen(request) ... That (or code very like it) worked when I tried it. From aahz at pythoncraft.com Fri Jun 2 13:11:42 2006 From: aahz at pythoncraft.com (Aahz) Date: 2 Jun 2006 10:11:42 -0700 Subject: Are there something like "Effective Python"? References: <1149224468.481470.74580@i39g2000cwa.googlegroups.com> Message-ID: In article <1149224468.481470.74580 at i39g2000cwa.googlegroups.com>, Mike Meng wrote: > > I just finished reading Learning Python 3rd ed, and am doing my >first Python application, which retrieves and process text and XML >documents from Web. Python helped me to write the application in a few >hours, I'm very happy with its productivity. But the performance is not >satisfactory. I decide to optimized it in Python before trying C/C++ >extensions. But I don't know Python much and have no clu to tune my >program. Also, I don't know what Pythonist's preferred styles. Are >there any books/documents which play the similar role for Python as >'Effective C++' does for C++? That's my fault. I'm technically still under contract to write _Effective Python_, but it has proven much more difficult to write than I expected. (Not in the sense of difficulty finding material, but in sitting down and *writing*.) I actually brought in David Goodger as co-author and we still haven't been able to make progress. :-( Right now, I'm finishing up _Python for Dummies_ (which is mostly being written by Stef -- I provide the technical expertise and editing), and after a suitable resting time, we'll see if we can get back on track with _Effective Python_ -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I saw `cout' being shifted "Hello world" times to the left and stopped right there." --Steve Gonedes From gregpinero at gmail.com Tue Jun 20 13:51:52 2006 From: gregpinero at gmail.com (=?ISO-8859-1?Q?Gregory_Pi=F1ero?=) Date: Tue, 20 Jun 2006 13:51:52 -0400 Subject: Psyco performance In-Reply-To: <44981e4c$0$29812$626a54ce@news.free.fr> References: <1150819763.818687.114360@y41g2000cwy.googlegroups.com> <44981e4c$0$29812$626a54ce@news.free.fr> Message-ID: <312cfe2b0606201051m8027d98q67cb19599dd535e0@mail.gmail.com> What's the reasoning behind requiring everything to be in functions? Just curious. On 6/20/06, Christophe wrote: > > Place all the code in a function. Even without psyco you might get > somewhat better performances then. And I doubt psyco can optimise code > that isn't in a function anyway. From skip at pobox.com Wed Jun 28 14:36:35 2006 From: skip at pobox.com (skip at pobox.com) Date: Wed, 28 Jun 2006 13:36:35 -0500 Subject: Psyco tagging the same function multiple times Message-ID: <17570.52275.471619.852735@montanaro.dyndns.org> I'm trying some stuff with Psyco and am confused about its apparent desire to compile the same function (or method) multiple times). Here's an abstract from a recent run: 12:45:15.99 tag function: __main__.Watcher.processUpdate % 12:45:24.95 tag function: __main__.Watcher.processUpdate % 12:45:55.12 tag function: __main__.Watcher.processUpdate % 12:46:12.29 tag function: __main__.Watcher.processUpdate % 12:46:28.09 tag function: __main__.Watcher.processUpdate % 12:47:05.32 tag function: __main__.Watcher.processUpdate % 12:47:48.62 tag function: __main__.Watcher.processUpdate % 12:48:09.63 tag function: __main__.Watcher.processUpdate % 12:48:43.20 tag function: __main__.Watcher.processUpdate % 12:49:58.80 tag function: __main__.Watcher.processUpdate % 12:50:32.20 tag function: __main__.Watcher.processUpdate % 12:51:07.91 tag function: __main__.Watcher.processUpdate % 12:52:17.14 tag function: __main__.Watcher.processUpdate % 12:52:33.67 tag function: __main__.Watcher.processUpdate % What (if anything) does it mean that it tagged Watcher.processUpdate more than once? Thanks, Skip From ketil+news at ii.uib.no Mon Jun 26 05:48:40 2006 From: ketil+news at ii.uib.no (Ketil Malde) Date: Mon, 26 Jun 2006 11:48:40 +0200 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> Message-ID: Chris Smith writes: > I've since abandoned any attempt to be picky about use of the word > "type". That was a mistake on my part. I still think it's legitimate > to object to statements of the form "statically typed languages X, but > dynamically typed languages Y", in which it is implied that Y is > distinct from X. When I used the word "type" above, I was adopting the > working definition of a type from the dynamic sense. Umm...what *is* the definition of a "dynamic type"? In this thread it's been argued from tags and memory representation to (almost?) arbitrary predicates. > That is, I'm considering whether statically typed languages may be > considered to also have dynamic types, and it's pretty clear to me > that they do. Well, if you equate tags with dynamic types: data Universal = Str String | Int Integer | Real Double | List [Universal] ... A pattern match failure can then be seen as a dynamic type error. Another question is how to treat a system (and I think C++'s RTTI qualifies, and probably related languages like Java) where static type information is available at runtime. Does this fit with the term "dynamic typing" with "typing" in the same sense as "static typing"? -k -- If I haven't seen further, it is by standing in the footprints of giants From wojciech_mula at poczta.null.onet.pl.invalid Wed Jun 14 19:24:41 2006 From: wojciech_mula at poczta.null.onet.pl.invalid (Wojciech =?iso-8859-2?Q?Mu=B3a?=) Date: Wed, 14 Jun 2006 23:24:41 +0000 (UTC) Subject: Negative hex to int References: <1150326597.327669.222640@r2g2000cwb.googlegroups.com> Message-ID: andreas.lydersen at gmail.com wrote: > The problem is negative values. If the unit returns the hex value 'e7', > it means -25, but python says it's 231: > --------------------------- >>>> int('e7', 16) > 231 > --------------------------- > > Does anyone have a clue a to what I need to do? def u2(x): if x & 0x80: # MSB set -> neg. return -((~x & 0xff) + 1) else: return x >>> u2(int('e7', 16)) -25 >>> u2(int('12', 16)) 18 >>> w. From a at tempinbox.com Thu Jun 29 13:10:17 2006 From: a at tempinbox.com (a) Date: 29 Jun 2006 10:10:17 -0700 Subject: how do i make an array global In-Reply-To: References: <1151472238.400461.42350@p79g2000cwp.googlegroups.com> <1151553485.378000.203760@p79g2000cwp.googlegroups.com> Message-ID: <1151601017.583410.192120@y41g2000cwy.googlegroups.com> i understand index error but there is no index error in my code that is the problem! Marc 'BlackJack' Rintsch wrote: > In <1151553485.378000.203760 at p79g2000cwp.googlegroups.com>, a wrote: > > > Traceback (most recent call last): > > File "C:\Python24\lib\site-packages\web.py", line 2054, in > > run_wsgi_app > > result = self.server.app(env, self.wsgi_start_response) > > File "C:\Python24\lib\site-packages\web.py", line 1894, in wsgifunc > > result = func() > > File "C:\Python24\lib\site-packages\web.py", line 1872, in > > func = lambda: handle(getattr(mod, name), mod) > > File "C:\Python24\lib\site-packages\web.py", line 1051, in handle > > return tocall(*([urllib.unquote(x) for x in args] + fna)) > > File "c:\mark\web1\code.py", line 64, in GET > > l_code.append( len(d_list_code[i]['entries']) ) > > IndexError: list index out of range > > > > it goes off when page is refreshed > > > > I m getting the following error, infrequently and if I refresh the > > page, it just displays the page properly > > I am unable to find the problem. How is this out of range and what > > does the error message mean? > > The error message means that you try to access a list item that does not > exist:: > > In [1]: a = [1, 2, 3] > > In [2]: a[0] > Out[2]: 1 > > In [3]: a[1] > Out[3]: 2 > > In [4]: a[2] > Out[4]: 3 > > In [5]: a[3] > ------------------------------------------------------------------------- > exceptions.IndexError Traceback (most recent call last) > > /home/marc/ > > IndexError: list index out of range > > So from the traceback it seems that `i` has a value that's not between 0 > and ``len(d_list_code)``. > > Ciao, > Marc 'BlackJack' Rintsch From bj_666 at gmx.net Thu Jun 29 03:13:58 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Thu, 29 Jun 2006 09:13:58 +0200 Subject: how do i make an array global References: <1151472238.400461.42350@p79g2000cwp.googlegroups.com> <1151553485.378000.203760@p79g2000cwp.googlegroups.com> Message-ID: In <1151553485.378000.203760 at p79g2000cwp.googlegroups.com>, a wrote: > Traceback (most recent call last): > File "C:\Python24\lib\site-packages\web.py", line 2054, in > run_wsgi_app > result = self.server.app(env, self.wsgi_start_response) > File "C:\Python24\lib\site-packages\web.py", line 1894, in wsgifunc > result = func() > File "C:\Python24\lib\site-packages\web.py", line 1872, in > func = lambda: handle(getattr(mod, name), mod) > File "C:\Python24\lib\site-packages\web.py", line 1051, in handle > return tocall(*([urllib.unquote(x) for x in args] + fna)) > File "c:\mark\web1\code.py", line 64, in GET > l_code.append( len(d_list_code[i]['entries']) ) > IndexError: list index out of range > > it goes off when page is refreshed > > I m getting the following error, infrequently and if I refresh the > page, it just displays the page properly > I am unable to find the problem. How is this out of range and what > does the error message mean? The error message means that you try to access a list item that does not exist:: In [1]: a = [1, 2, 3] In [2]: a[0] Out[2]: 1 In [3]: a[1] Out[3]: 2 In [4]: a[2] Out[4]: 3 In [5]: a[3] ------------------------------------------------------------------------- exceptions.IndexError Traceback (most recent call last) /home/marc/ IndexError: list index out of range So from the traceback it seems that `i` has a value that's not between 0 and ``len(d_list_code)``. Ciao, Marc 'BlackJack' Rintsch From ptmcg at austin.rr._bogus_.com Tue Jun 13 09:39:12 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Tue, 13 Jun 2006 13:39:12 GMT Subject: "Adding" dictionnaries References: <1150203354.861658.181110@h76g2000cwa.googlegroups.com> <1150203783.897858.221300@h76g2000cwa.googlegroups.com> Message-ID: <4ezjg.24272$0v4.17029@tornado.texas.rr.com> "Salvatore" wrote in message news:1150203783.897858.221300 at h76g2000cwa.googlegroups.com... > While reading the doc i've found 'update' :-) > Bless you, Salvatore!! Too often we hear about the "gross deficiencies" of the Python documentation. I'd venture to say that documentation is mostly perceived as the last resource of a scoundrel. Thank you for logging for us at least one documented case of someone finding the answer to their question in, yes, the documentation! I really and sincerely thank you! Also, you will find a wealth of help by using (from the interactive Python prompt) "help(dict)" or "help(str)" or "import unfamiliarModule; help(unfamiliarModule)". -- Paul From kay.schluehr at gmx.net Sun Jun 18 13:07:19 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 18 Jun 2006 10:07:19 -0700 Subject: Seeking regex optimizer Message-ID: <1150650439.651839.38180@y41g2000cwy.googlegroups.com> I have a list of strings ls = [s_1,s_2,...,s_n] and want to create a regular expression sx from it, such that sx.match(s) yields a SRE_Match object when s starts with an s_i for one i in [0,...,n]. There might be relations between those strings: s_k.startswith(s_1) -> True or s_k.endswith(s_1) -> True. An extreme case would be ls = ['a', 'aa', ...,'aaaa...ab']. For this reason SRE_Match should provide the longest possible match. Is there a Python module able to create an optimized regex rx from ls for the given constraints? Regards, Kay From Dennis.Benzinger at gmx.net Tue Jun 27 15:10:44 2006 From: Dennis.Benzinger at gmx.net (Dennis Benzinger) Date: Tue, 27 Jun 2006 21:10:44 +0200 Subject: Python UTF-8 and codecs In-Reply-To: References: Message-ID: <44a182b4$2@news.uni-ulm.de> Mike Currie wrote: > I'm trying to write out files that have utf-8 characters 0x85 and 0x08 in > them. Every configuration I try I get a UnicodeError: ascii codec can't > decode byte 0x85 in position 255: oridinal not in range(128) > > I've tried using the codecs.open('foo.txt', 'rU', 'utf-8', errors='strict') > and that doesn't work > [...] You want to write to a file but you used the 'rU' mode. This should be 'wU'. Don't know if this is the only reason it doesn't work. Could you show more of your code? Bye, Dennis From jean.moser at neuf.fr Sat Jun 24 04:30:25 2006 From: jean.moser at neuf.fr (jean-jeanot) Date: 24 Jun 2006 01:30:25 -0700 Subject: sum fonction in gadfly Message-ID: <1151137825.177814.217180@u72g2000cwu.googlegroups.com> I am writing a prototype program whose aim is to collect bookkeeping transactions in a Database ( Gadfly). After creating the table I create the variables with varAmount = StringVar() I then create labels in Tkinter to ease the input of data. With a function def treatment (): requete = "insert into transactions ( date,amount,,....) values(......) "% (varDate.get(), varAmount.get I transfer data from the labels in Tkinter into the Database at the end of the program with a button named "End" . I print the Database with print cur.pp(). No problem up to now but then I try to use a select command: cur.execute ("select sum(amount) from transactions").I get Sum.amout.transaction ================= 100-10.5....... instead of 110.5 It means that the select command does not add but concatenates the different amounts. Why ? Many thanks if you can help me. Jean Moser From jjlee at reportlab.com Mon Jun 5 15:14:59 2006 From: jjlee at reportlab.com (John J. Lee) Date: Mon, 05 Jun 2006 19:14:59 GMT Subject: urllib2 and HTTP 302 References: <4476C7A6.5040506@designaproduct.biz> Message-ID: <873beje7nw.fsf@reportlab.com> jjl at pobox.com (John J. Lee) writes: > Laszlo Nagy writes: > [...] > > how can I return the redirection URL? > > I tried to get this information from the exception but I could not. Is > > it possible to read it from the openerdirector? > > Any suggestions? > > > > > > try: > > self.post_multipart( > > url, > > [('uploadType','Inventory')], > > [('uploadFileName','inv.txt',fdata)] > > ) > > except urllib2.HTTPError, e: > > if e.code == 302: > > return "I would like to get the URL to be redirected > > to...." > > else: > > raise > > redirected_url = e.geturl() Sorry, didn't read that properly. If your OpenerDirector instance has an HTTPRedirectHandler, you should be able to get the final redirected URL the way I said (using .geturl()). If it doesn't (which I assume is true in your case -- why else would you be checking for a 302 status), well, you just have to do exactly the same thing that HTTPRedirectHandler does :-) Use the source luke. John From diffuser78 at gmail.com Tue Jun 27 11:59:58 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 27 Jun 2006 08:59:58 -0700 Subject: file writing question Message-ID: <1151423998.492022.269810@m73g2000cwd.googlegroups.com> Hi, I am a newbie so not very confident in file handling. I want to write to a file atrributes in this fashion #NameOfComputer:MAC_Address:IP_Address ------computer_details.txt begins----------------------------------------- IG1:8f00142a123c:192.168.2.101 IG2:8f00142a124d:192.168.2.102 IG3:8f00142a124e:192.168.2.103 IG4:8f00142a124f:192.168.2.104 IG5:8f00142a124a:192.168.2.105 IG6:8f00142a124b:192.168.2.106 ------computer_details.txt ends------------------------------------------- While writing this file I insert "\n" after every line so that details of every new computer goes into next line for readibility. After I have to read this file. While reading this file "\n" remains which I dont want. Is there a neat way of writing to a file and not having "\n" ? Please help From jurgenex at hotmail.com Sun Jun 25 13:19:27 2006 From: jurgenex at hotmail.com (Jürgen Exner) Date: Sun, 25 Jun 2006 17:19:27 GMT Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150908952.804184.218990@r2g2000cwb.googlegroups.com> <1150991074.705803.211570@m73g2000cwd.googlegroups.com> <1151244628.566060.40500@p79g2000cwp.googlegroups.com> <449eba8d$1@nntp0.pdx.net> Message-ID: Scott David Daniels wrote: > rossberg at ps.uni-sb.de wrote: >> Huh? There is a huge, fundamental difference: namely whether a type >> system is sound or not. A soundness proof is obligatory for any >> serious type theory, and failure to establish it simply is a bug in >> the theory. > > So you claim Java and Objective C are "simply bugs in the theory." They are certainly off topic in CLPM. jue From bayazee at gmail.com Sat Jun 24 06:11:01 2006 From: bayazee at gmail.com (Bayazee) Date: 24 Jun 2006 03:11:01 -0700 Subject: reaching to the notification area In-Reply-To: <1151051892.796863.76570@b68g2000cwa.googlegroups.com> References: <1151051892.796863.76570@b68g2000cwa.googlegroups.com> Message-ID: <1151143861.415719.46790@r2g2000cwb.googlegroups.com> hi i can fine somethings in google such this : http://www-128.ibm.com/developerworks/linux/library/l-wrap/ but i can not copmile files ! Any idea !!!??? From rogue_pedro at yahoo.com Thu Jun 22 12:07:44 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 22 Jun 2006 09:07:44 -0700 Subject: python + postgres psql + os.popen References: <1150946077.931411.170930@u72g2000cwu.googlegroups.com> Message-ID: <1150992464.012824.295810@r2g2000cwb.googlegroups.com> damacy wrote: > hello, everyone. ... > this works well. however, it does not show me any warning nor error > messages if there is one. for example, i am trying to create a table > which already exists in the database, it should show me a warning/error > message saying there already is one present in the database, or > something like that. > > can anyone help me? I recently needed to use psql from python on a computer that I couldn't install psycopg on and I used something similar to this to do it (I edited the code slightly to make it clearer): from subprocess import Popen, PIPE # Pass the password through an environment # variable to prevent psql asking for it. psql_env = dict(PGPASSWORD='********') # Create the subprocess. proc = Popen(cmd, shell=True, env=psql_env, stdout=PIPE, stderr=PIPE) # Try reading it's data. data = proc.stdout.read() # Check for errors. err = proc.stderr.read() if err: raise Exception(err) It worked nicely for me, YMMV. Hope that helps, ~Simon From a at tempinbox.com Wed Jun 28 00:44:12 2006 From: a at tempinbox.com (a) Date: 27 Jun 2006 21:44:12 -0700 Subject: global name is not defined - error Message-ID: <1151469851.975668.262090@d56g2000cwd.googlegroups.com> What I want --------------- I want to create a list of items from a function operating on an array of strings What I did ----------------- list=["s0","s1","s2"] l=len(list) for i in range(l): d_list[i]=f.do(list[i]) print d_list[i] Error: ------ global name 'd_list' is not defined Python c:\test.py in newClass, line 30 Please help me out thanks -a From gotletter at gmail.com Sat Jun 10 04:35:26 2006 From: gotletter at gmail.com (gotletter at gmail.com) Date: 10 Jun 2006 01:35:26 -0700 Subject: __getattr__ question In-Reply-To: <1149928254.153476.184030@f6g2000cwb.googlegroups.com> References: <1149928254.153476.184030@f6g2000cwb.googlegroups.com> Message-ID: <1149928525.972744.279790@u72g2000cwu.googlegroups.com> And yes, it is more to type ;) From vinay_sajip at yahoo.co.uk Sun Jun 4 08:23:55 2006 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 4 Jun 2006 05:23:55 -0700 Subject: logging References: <1148426018.334087.124160@i40g2000cwc.googlegroups.com> <1148577240.250304.116360@j55g2000cwa.googlegroups.com> <1149005605.819519.242350@j55g2000cwa.googlegroups.com> <1149113113.083677.235570@i39g2000cwa.googlegroups.com> Message-ID: <1149423835.166446.126240@i40g2000cwc.googlegroups.com> Hello Baurzhan, > Consider the following scenario: root is CRITICAL, l01 is DEBUG, a debug > message is logged on l01. l01 decides that the message should be > printed, and _both_ root and l01 print it. Now, it is good that the > message is propagated to root, but why doesn't root decide for itself > whether to print it or not? It's not propagated to the root logger (or to ancestor loggers in general) - just to the handlers associated with ancestor loggers. > For instance, I log root to syslog and have only critical messages > there. I log l01 to console to debug. I want that my message to l01 is > not printed by root since its level is CRITICAL. This is why I want that > each logger re-evaluates the message level for itself. Could you perhaps > give a useful example why one could want loggers to decide once? You can set levels on handlers as well as loggers. So if you add a syslog handler to the root and set its level to CRITICAL, only CRITICAL messages are sent to syslog. > And another thing I couldn't find how to do: I want to have several > debug levels. I can log messages without problems, but numeric values in > the configuration file cause error messages during > logging.config.fileConfig. Can I specify numeric values in the config > file? You should use addLevelName to add custom levels. You can do e.g. logging.MYCUSTOMLEVEL = 25 logging.addLevelName(logging.MYCUSTOMLEVEL, "MYCUSTOMLEVEL") and then reference MYCUSTOMLEVEL in the config file. Regards, Vinay From casevh at comcast.net Sun Jun 11 19:26:50 2006 From: casevh at comcast.net (casevh at comcast.net) Date: 11 Jun 2006 16:26:50 -0700 Subject: math.pow(x,y) In-Reply-To: References: <1150049976.916474.186580@j55g2000cwa.googlegroups.com> Message-ID: <1150068410.550806.73160@m38g2000cwc.googlegroups.com> K.S.Sreeram wrote: > Raymond L. Buvel wrote: > > I just tried this and it is taking an extremely long time even on a fast > > machine with 4 Gb of RAM. Killed it after a couple of minutes. > > You probably tried printing the value. > > a = 34564323**456356 (takes just 28 seconds) > whereas > b = str(a) takes forever! > > Regards > Sreeram > If you really want all 3,440,299 digits, use the DecInt module.. http://home.comcast.net/~casevh/ Using Python 2.4.3 on a 1.4Ghz Celeron, a=DecInt(34564323) ** 456356 takes 20 seconds. astr=str(a) takes just over 1 second. With DecInt and GMPY, the running times are 6.9 seconds and 0.4 seconds respectively. casevh From david.nospam.hopwood at blueyonder.co.uk Sun Jun 25 11:31:50 2006 From: david.nospam.hopwood at blueyonder.co.uk (David Hopwood) Date: Sun, 25 Jun 2006 15:31:50 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> Message-ID: Chris F Clark wrote: > Chris Smith writes: > >>Unfortunately, I have to again reject this idea. There is no such >>restriction on type theory. Rather, the word type is defined by type >>theorists to mean the things that they talk about. > > Do you reject that there could be something more general than what a > type theorist discusses? Or do you reject calling such things a type? > > Let you write: > >>because we could say that anything that checks types is a type system, >>and then worry about verifying that it's a sound type system without >>worrying about whether it's a subset of the perfect type system. > > I'm particularly interested if something unsound (and perhaps > ambiguous) could be called a type system. Yes, but not a useful one. The situation is the same as with unsound formal systems; they still satisfy the definition of a formal system. -- David Hopwood From siona at chiark.greenend.org.uk Fri Jun 9 06:32:18 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 09 Jun 2006 11:32:18 +0100 (BST) Subject: How to extract 2 integers from a string in python? References: <1149827496.857621.88550@h76g2000cwa.googlegroups.com> Message-ID: Stephen Prinster wrote: >>>> a, b, c, d = 'Total size: 173233 (371857)'.split() >>>> first_int, second_int = int(c), int(d[1:-1]) int(d[1:-1]) can be replaced by d.strip("()"), which may or may not be clearer in intent. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From michele.petrazzo at TOGLIunipex.it Thu Jun 1 12:42:50 2006 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Thu, 01 Jun 2006 16:42:50 GMT Subject: Trying to get FreeImagePy to work. In-Reply-To: <1149174938.337973.85950@g10g2000cwb.googlegroups.com> References: <1148651668.578852.3160@i40g2000cwc.googlegroups.com> <7fEdg.13375$cX1.201311@twister2.libero.it> <1148655611.990937.322350@j73g2000cwa.googlegroups.com> <1149166096.176405.22780@i40g2000cwc.googlegroups.com> <3PCfg.20835$cX1.315781@twister2.libero.it> <1149174938.337973.85950@g10g2000cwb.googlegroups.com> Message-ID: Iain King wrote: >> Can you download the last svn version from sf.net? Otherwise I'll send >> you the last sources privately. >> >> Bye, >> Michele > > I got the TortoiseSVN client though, and > checked out your newest build, copied it over the top of > site-packages/freeimagepy, updated my ctypes back to 0.9.9.6 (I'd > regressed again), ran my program, and it worked. Thanks! This is a good news! > Next question (and what I'm using FreeImagePy for): I'm loading a pile > of TIF's as thumbnails into a wx list control. I load the image with > FIPY, convert it to PIL, use PIL's antialiasing thumbnail function, > then load it from there into wx. Why use PIL for it and not FIPY directly? You can use the image.size or the other methods for resize the image > However, when I'm do the > fipy.convertToPil(), it inverts the image? No, it not invert the image... It only return the image as is. > I've inserted a > fipy.invert() before the conversion as a temporary fix, but is there a > reason for this? If you are have a min-is-white image (fax ?) that isn't the standard, you will have an "inverted" image, because PIl expect a min-is-black image! > relevant code: > > def getHeaders(files): > thumbs = [] > for f in files: > print "Adding %s" % f > fi = FIPY.Image(f) > fi.setCurrentPage(0) > fi.invert() #temp fix > thumb = fi.convertToPil() > thumb.thumbnail(THUMBNAIL_SIZE, Image.ANTIALIAS) > thumbs.append((os.path.basename(f), pilToBitmap(thumb))) > thumbs.sort() > return thumbs Just a question, why "thumbs.sort" ? Inside this list you have only images! P.s. you can use also fi.currentPage = 0 rather then fi.setCurrentPage(0). Is think it look like better :) > > Iain > > p.s. thanks again > :) Michele From stefan.behnel-n05pAM at web.de Sat Jun 3 08:32:55 2006 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Sat, 03 Jun 2006 14:32:55 +0200 Subject: [ANN] lxml 1.0 released In-Reply-To: <4480eade$1_2@newspeer2.tds.net> References: <4480eade$1_2@newspeer2.tds.net> Message-ID: <4481817a$0$11078$9b4e6d93@newsread4.arcor-online.net> Kent Johnson wrote: > Stefan Behnel wrote: >> Hallo everyone, >> >> I have the honour to announce the availability of lxml 1.0. >> >> http://codespeak.net/lxml/ >> >> It's downloadable from cheeseshop: >> http://cheeseshop.python.org/pypi/lxml > > Are there any plans to offer a Windows installer? Already there. :) It just takes a minute longer sometimes, but Windows users are not forgotten. Stefan From pc at p-cos.net Fri Jun 23 08:24:20 2006 From: pc at p-cos.net (Pascal Costanza) Date: Fri, 23 Jun 2006 14:24:20 +0200 Subject: Saying "latently-typed language" is making a category mistake In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> Message-ID: <4g24rlF1l16viU1@individual.net> Vesa Karvonen wrote: > In comp.lang.functional Anton van Straaten wrote: > [...] >> I reject this comparison. There's much more to it than that. The point >> is that the reasoning which programmers perform when working with an >> program in a latently-typed language bears many close similiarities to >> the purpose and behavior of type systems. > >> This isn't an attempt to jump on any bandwagons, it's an attempt to >> characterize what is actually happening in real programs and with real >> programmers. I'm relating that activity to type systems because that is >> what it most closely relates to. > [...] > > I think that we're finally getting to the bottom of things. While reading > your reponses something became very clear to me: latent-typing and latent- > types are not a property of languages. Latent-typing, also known as > informal reasoning, is something that all programmers do as a normal part > of programming. To say that a language is latently-typed is to make a > category mistake, because latent-typing is not a property of languages. I disagree with you and agree with Anton. Here, it is helpful to understand the history of Scheme a bit: parts of its design are a reaction to what Schemers perceived as having failed in Common Lisp (and other previous Lisp dialects). One particularly illuminating example is the treatment of nil in Common Lisp. That value is a very strange beast in Common Lisp because it stands for several concepts at the same time: most importantly the empty list and the boolean false value. Its type is also "interesting": it is both a list and a symbol at the same time. It is also "interesting" that its quoted value is equivalent to the value nil itself. This means that the following two forms are equivalent: (if nil 42 4711) (if 'nil 42 4711) Both forms evaluate to 4711. It's also the case that taking the car or cdr (first or rest) of nil doesn't give you an error, but simply returns nil as well. The advantage of this design is that it allows you to express a lot of code in a very compact way. See http://www.apl.jhu.edu/~hall/lisp/Scheme-Ballad.text for a nice illustration. The disadvantage is that it is mostly impossible to have a typed view of nil, at least one that clearly disambiguates all the cases. There are also other examples where Common Lisp conflates different types, and sometimes only for special cases. [1] Now compare this with the Scheme specification, especially this section: http://www.schemers.org/Documents/Standards/R5RS/HTML/r5rs-Z-H-6.html#%25_sec_3.2 This clearly deviates strongly from Common Lisp (and other Lisp dialects). The emphasis here is on a clear separation of all the types specified in the Scheme standard, without any exception. This is exactly what makes it straightforward in Scheme to have a latently typed view of programs, in the sense that Anton describes. So latent typing is a property that can at least be enabled / supported by a programming language, so it is reasonable to talk about this as a property of some dynamically typed languages. Pascal [1] Yet Common Lisp allows you to write beautiful code, more often than not especially _because_ of these "weird" conflations, but that's a different topic. -- 3rd European Lisp Workshop July 3 - Nantes, France - co-located with ECOOP 2006 http://lisp-ecoop06.bknr.net/ From george.sakkis at gmail.com Thu Jun 15 21:17:31 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 15 Jun 2006 18:17:31 -0700 Subject: Pickling gotcha Message-ID: <1150420651.420584.159960@r2g2000cwb.googlegroups.com> I stumbled on some weird pickling behavior that after some non-trivial debugging time turned out to be caused by __getstate__ returning an empty dict for some instances. As I found digging through the docs (http://pythondoc.kldp.net/lib/pickle-inst.html), surprisingly __setstate__ is not called nor new style instances if __getstate__ returns a false valse, without any further justification. Any pointers on the rationale for making a special case just out of the blue ? George From bdesth.quelquechose at free.quelquepart.fr Fri Jun 2 19:56:03 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 03 Jun 2006 01:56:03 +0200 Subject: integer to binary... In-Reply-To: <127ugf9jgu7av18@corp.supernews.com> References: <1149189570.376091.319890@j55g2000cwa.googlegroups.com> <127ugf9jgu7av18@corp.supernews.com> Message-ID: <4480a084$0$6172$626a54ce@news.free.fr> Grant Edwards a ?crit : > On 2006-06-01, nicolasg at gmail.com wrote: > > >>does anyone know a module or something to convert numbers like integer >>to binary format ? > > > They _are_ in binary format. Not really. >>> (7).__class__ >>> dir((7)) ['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__str__', '__sub__', '__truediv__', '__xor__'] >>> From jarrod.roberson at gmail.com Thu Jun 8 09:29:59 2006 From: jarrod.roberson at gmail.com (fuzzylollipop) Date: 8 Jun 2006 06:29:59 -0700 Subject: 10GB XML Blows out Memory, Suggestions? In-Reply-To: <1149696078.984114.51880@h76g2000cwa.googlegroups.com> References: <1149594519.098115.8980@u72g2000cwu.googlegroups.com> <4eleh3F1eguosU1@uni-berlin.de> <1149648187.891942.258300@i40g2000cwc.googlegroups.com> <1149694031.712812.304940@u72g2000cwu.googlegroups.com> <1149696078.984114.51880@h76g2000cwa.googlegroups.com> Message-ID: <1149773399.508514.223910@f6g2000cwb.googlegroups.com> axwack at gmail.com wrote: > Thanks guys for all your posts... > > So I am a bit confused....Fuzzy, the code I saw looks like it > decompresses as a stream (i.e. per byte). Is this the case or are you > just compressing for file storage but the actual data set has to be > exploded in memory? > it wasn't my code. if you zip the 10GB and read from the zip into a DOM style tree, you haven't gained anything, except adding additional CPU requirements to do the decompression. You still have to load the entire thing into memory. There are differences in XML Parsers, IN EVERY LANGUAGE a poorly written parser is a poorly written parser. Using the wrong IDIOM is more of a problem than anything else. DOM parsers are good when you need to read and process every element and attribute and the data is "small". Granted, "small" is relative, but no body will consider 10GB "small". SAX style or a pull-parser has to be used when the data is "large" or when you don't really need to process every element and attribute. This problem looks like it is just a data export / import problem. In that case you will either have to use a sax style parser and parse the 10GB file. Or as I suggested in another reply, export the data in smaller chunks and process them separately, which in almost EVERY case is a better solution to do batch processing. You should always break processing up into as many discreet steps as possible. Make for easier debugging and you can start over in the middle much easier. Even if you just write a simple SAX style parser to just break the file up into smaller pieces to actually process it you will be ahead of the game. We have systems that process streaming data coming from sockets in XML format, that run in Java with very little memory footprint and very little CPU usage. At 50 megabit a sec, that is about 4TB a day. C wouldn't read from a socket any faster than the NBIO, actually it would be harder to get the same performance in C because we would have to duplicate all the SEDA style NBIO. From scott.daniels at acm.org Tue Jun 13 01:10:48 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Mon, 12 Jun 2006 22:10:48 -0700 Subject: Writing PNG with pure Python In-Reply-To: <1150163849.760259.25250@i40g2000cwc.googlegroups.com> References: <1149853401.521169.112530@i39g2000cwa.googlegroups.com> <1149889778.182865.181600@f6g2000cwb.googlegroups.com> <1149910872.025017.60160@i40g2000cwc.googlegroups.com> <1150152913.315502.16840@u72g2000cwu.googlegroups.com> <1150163849.760259.25250@i40g2000cwc.googlegroups.com> Message-ID: <448e441e$1@nntp0.pdx.net> Johann C. Rocholl wrote: > I appreciate the simplicity of the BSD and MIT Licenses, except for the > names. "BSD License" can be confused with the original BSD License, > while "MIT License" according to the FSF "is misleading, since MIT has > used many licenses for software." I had one lawyer tell me the MIT license was better at declaring your non-liability than BSD. IANAL, your lawyer may vary, .... -- --Scott David Daniels scott.daniels at acm.org From jerry.levan at gmail.com Wed Jun 21 18:11:08 2006 From: jerry.levan at gmail.com (jerry.levan at gmail.com) Date: 21 Jun 2006 15:11:08 -0700 Subject: Is it possible to split a class definition? Message-ID: <1150927868.807640.45760@c74g2000cwc.googlegroups.com> Hi, Is it possible to split a Class definition over two or more text files? (if so, how:) Jerry From brian at sweetapp.com Thu Jun 22 12:13:58 2006 From: brian at sweetapp.com (Brian Quinlan) Date: Thu, 22 Jun 2006 18:13:58 +0200 Subject: VPW: T-Shirt design contest Message-ID: <449AC1C6.2020109@sweetapp.com> Bruno Desthuilliers submitted this really cool rant/essay/something from Tim Lesher that I hadn't seen before. I think that the original source is: http://apipes.blogspot.com/2005/01/choose-python.html Choose Python. Choose readability. Choose the simple over the complex and the complex over the complicated. Choose dynamic typing. Choose duck typing. Choose decorators. Choose generators. Choose metaclasses if you don?t value your sanity. Choose to import this. Choose an almost-fanatical devotion to the BDFL, unless he comes up with something like optional static typing, in which case choose to whine about it in your blog until he stops. Choose Effbot. Choose Timbot. Choose wx. Choose to come up with a bloody implementation before spouting off on comp.lang.python or Python-Dev. Choose the explicit rather than the implicit. Choose one obvious way to do it, especially if you are Dutch. Choose list comprehensions. Choose Paul Graham?s essays and s/LISP/Python/g. Choose Jython when your marketing people choose Java. Choose speed of development over speed of execution, but when in doubt, import psyco. Choose to finish early and laugh at your colleagues as they waste their miserable lives bowing down in subservience to that sadistic little C++ compiler. Choose your future. Choose Python. I think that it might be a bit long to put on a T-Shirt but it is definitely cool :-) Still collecting ideas at: http://www.vanpyz.org/conference/tshirt_contest.html Cheers, Brian From fredrik at pythonware.com Fri Jun 30 11:03:34 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 30 Jun 2006 17:03:34 +0200 Subject: Way for see if dict has a key In-Reply-To: <44a51f34$0$6794$626a54ce@news.free.fr> References: <6V6pg.21624$_J1.271925@twister2.libero.it><44a5041f$0$29637$636a55ce@news.free.fr><4F7pg.21676$_J1.272665@twister2.libero.it> <1151666867.604260.116320@h44g2000cwa.googlegroups.com> <44a51f34$0$6794$626a54ce@news.free.fr> Message-ID: Bruno Desthuilliers wrote: >> on my machine, "key in dict" is about twice as fast as the full >> try/getitem construct when the key is present in the dict, > > Doesn't it depends on the number of keys in the dict ? why would it depend on the number of keys in the dict ? From sjmachin at lexicon.net Mon Jun 26 19:39:10 2006 From: sjmachin at lexicon.net (John Machin) Date: Tue, 27 Jun 2006 09:39:10 +1000 Subject: replace a method in class: how? In-Reply-To: References: Message-ID: <44a0701e@news.eftel.com> On 27/06/2006 9:14 AM, Brian Blais wrote: > Hello, > > I want to replace a method in a class during run-time with another > function. I tried the obvious, but it didn't work: > > class This(object): > def update(self,val): > print val > > def another_update(obj,val): > print "another",val > > t=This() > t.update(5) > t.update=another_update > t.update(5) # this one doesn't work, gives > # TypeError: another_update() takes exactly 2 arguments (1 given) > > > clearly it isn't seeing it as a method, just an attribute which happens > to be a function. Is there a preferred way to do this? > You have a strange definition of "obvious". You say you want to replace a method in a *class*, not in an instance of that class ... so just do that: |>> class This(object): ... def update(self,val): ... print val ... |>> def another_update(obj,val): ... print "another",val ... |>> This.update = another_update |>> t = This() |>> t.update(42) another 42 Cheers, John From danb_83 at yahoo.com Thu Jun 15 23:20:19 2006 From: danb_83 at yahoo.com (Dan Bishop) Date: 15 Jun 2006 20:20:19 -0700 Subject: Python is fun (useless social thread) ;-) In-Reply-To: References: Message-ID: <1150428019.639780.177740@p79g2000cwp.googlegroups.com> John Salerno wrote: > So out of curiosity, I'm just wondering how everyone else came to learn > [Python] I first heard about Python in the footnotes for Bruce Eckels' book "Thinking in Java", which I had bought for a Java course I took in 2000. Eventually, I decided to take a look at python.org, and went through the tutorial. From Dennis.Benzinger at gmx.net Thu Jun 8 14:08:31 2006 From: Dennis.Benzinger at gmx.net (Dennis Benzinger) Date: Thu, 08 Jun 2006 20:08:31 +0200 Subject: tracking dependencies In-Reply-To: <1149760106.420216.167790@g10g2000cwb.googlegroups.com> References: <1149760106.420216.167790@g10g2000cwb.googlegroups.com> Message-ID: <4488679a$1@news.uni-ulm.de> Michele Simionato wrote: > I have a big framework (not written by me) with lots of internal > dependencies and I am > looking for a tool to see the dependency tree. I.e. given a module x, > it should show me all the modules imported by x, and the modules > imported > by them recursively. Standard library modules should be ignored > and there should be an option to turns off the visualization of certain > > modules, for instance the ones in given subpackages. I guess somebody > has already written it, maybe even with > a nice visual backend. Any hint? > > Michele Simionato > I've never tried it, but http://www.tarind.com/depgraph.html looks like what you are looking for. Bye, Dennis From cdsmith at twu.net Mon Jun 19 13:57:08 2006 From: cdsmith at twu.net (Chris Smith) Date: Mon, 19 Jun 2006 11:57:08 -0600 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <4fo19aF1jsudeU1@individual.net> Message-ID: Pascal Costanza wrote: > Types can be represented at runtime via type tags. You could insist on > using the term "dynamically tagged languages", but this wouldn't change > a lot. Exactly _because_ it doesn't make sense in a statically typed > setting, the term "dynamically typed language" is good enough to > communicate what we are talking about - i.e. not (static) typing. Okay, fair enough. It's certainly possible to use the same sequence of letters to mean two different things in different contexts. The problem arises, then, when Torben writes: : That's not really the difference between static and dynamic typing. : Static typing means that there exist a typing at compile-time that : guarantess against run-time type violations. Dynamic typing means : that such violations are detected at run-time. This is clearly not using the word "type" to mean two different things in different contexts. Rather, it is speaking under the mistaken impression that "static typing" and "dynamic typing" are varieties of some general thing called "typing." In fact, the phrase "dynamically typed" was invented to do precisely that. My argument is not really with LISP programmers talking about types, by which they would mean approximately the same thing Java programmers mean by "class." My point here concerns the confusion that results from the conception that there is this binary distinction (or continuum, or any other simple relationship) between a "statically typed" and a "dynamically typed" language. Torben's (and I don't mean to single out Torben -- the terminology is used quite widely) classification of dynamic versus static type systems depends on the misconception that there is some universal definition to the term "type error" or "type violation" and that the only question is how we address these well-defined things. It's that misconception that I aim to challenge. > No, there is more: There is safe and unsafe code (i.e., code that throws > exceptions or that potentially just does random things). There are also > runtime systems where you have the chance to fix the reason that caused > the exception and continue to run your program. The latter play very > well with dynamic types / type tags. Yes, I was oversimplifying. > What type system catches division by zero? That is, statically? I can define such a type system trivially. To do so, I simply define a type for integers, Z, and a subtype for non-zero integers, Z'. I then define the language such that division is only possible in an expression that looks like << z / z' >>, where z has type Z and z' has type Z'. The language may then contain an expression: z 0? t1 : t2 in which t1 is evaluated in the parent type environment, but t2 is evaluated in the type environment augmented by (z -> Z'), the type of the expression is the intersection type of t1 and t2 evaluated in those type environments, and the evaluation rules are defined as you probably expect. > Would you like to program in such a language? No. Type systems for real programming languages are, of course, a balance between rigor and usability. This particular set of type rules doesn't seem to exhibit a good balance. Perhaps there is a way to achieve it in a way that is more workable, but it's not immediately obvious. As another example, from Pierce's text "Types and Programming Languages", Pierce writes: "Static elimination of array-bounds checking is a long-standing goal for type system designers. In principle, the necessary mechanisms (based on dependent types) are well understood, but packaging them in a form that balances expressive power, predictability and tractability of typechecking, and complexity of program annotations remains a significant challenge." Again, this could quite validly be described as a type error, just like division by zero or ANY other program error... it's just that the type system that solves it doesn't look appealing, so everyone punts the job to runtime checks (or, in some cases, to the CPU's memory protection features and/or the user's ability to fix resulting data corruption). Why aren't these things commonly considered type errors? There is only one reason: there exists no widely used language which solves them with types. (I mean in the programming language type theory sense of "type"; since many languages "tag" arrays with annotations indicating their dimensions, I guess you could say that we do solve them with types in the LISP sense). > Your problem doesn't exist. Just say "types" when you're amongst your > own folks, and "static types" when you're amongst a broader audience, > and everything's fine. I think I've explained why that's not the case. I don't have a complaint about anyone speaking of types. It's the confusion from pretending that the two definitions are comparable that I'm pointing out. -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation From amorgan at xenon.Stanford.EDU Sun Jun 4 17:03:09 2006 From: amorgan at xenon.Stanford.EDU (Alan Morgan) Date: Sun, 4 Jun 2006 14:03:09 -0700 (PDT) Subject: Python less error-prone than Java References: Message-ID: In article , Christoph Zwerschke wrote: >>> Simon Percivall wrote: >>>> First: It's perfectly simple in Java to create a binary sort that >>>> sorts all arrays that contain objects; so wrong there. >>> My point was that the *same* Java source example, directly converted to >>> Python would *automatically* accept all kinds of arrays. >> >> And the same code converted to SML would automatically work on all >> kinds of arrays and SML is statically typed. It's a language issue, >> not a typing issue. > >Ok, here the point was that Java has *explicit* static typing. SML is >not a procedural language and uses *implicit* static typing. Therefore >it shares some of the benefits of dynamically typed languages such as >Python. However, an SML version of the program would probably still have >the same bug as the Java version, right? > >>> No need to make any extra efforts. >>> By the way, how would you do it in Java? With >>> function overloading? I would not call that perfectly simple. >> >> Since Java doesn't allow function overloading that clearly can't be >> the way. J2SE 5.0 allows generic classes and functions that operate >> on generic containers. There are some gotchas, but it's not drastically >> more complex than the original int-only java code. > >Java doesn't allow function overloading? Brain fart. You said "function" and I read "operator". Alan -- Defendit numerus From nate at natefico.com Sun Jun 18 07:28:33 2006 From: nate at natefico.com (nate) Date: Sun, 18 Jun 2006 04:28:33 -0700 Subject: maximum integer length? Message-ID: <449538E1.3030301@natefico.com> Hey everyone, I am trying to figure out what is the largest integer I can. Lets say for 400 megabytes of memory at my disposal. I have tried a few things c = 2**1000000 d = 2**2000000 print c**d Obviously I didn't have enough memory for that, but I was able to c**3. (I think anyways, it is still trying to display the result) So I am just wondering how long an integer can be with 400 megabytes of memory. I guess this is a question of logic? each integer takes up a byte right? If I have 400 megabytes that would mean I could have a long integer with up to 419,430,400,000 integers? Really I am not sure on this one and that is why I am asking. Because it is just bugging me I am not sure how it works... I know this probably seems trivial and just a stupid question, but I find this type of stuff interesting... From fuzzyman at gmail.com Wed Jun 7 08:45:16 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 7 Jun 2006 05:45:16 -0700 Subject: Use of Python in .NET In-Reply-To: <1149677283.294472.115050@f6g2000cwb.googlegroups.com> References: <1149677283.294472.115050@f6g2000cwb.googlegroups.com> Message-ID: <1149684316.872331.226500@i39g2000cwa.googlegroups.com> sushant.sirsikar at gmail.com wrote: > Hi, > I am developing a code which has MVC (Model - View - Controler) > architecture.My view is in .NET. And my controller is in Python.So can > i call Python script from .NET? If yes, > Can anybody tell me method or related documentation? http://www.google.com/search?q=python+.net There are at least two individual projects in the top ten results that may work for you... :-) Fuzzyman http://www.voidspace.org.uk/python/index.shtml > Thanks in Advamce.... From arvind.mulay at gmail.com Thu Jun 29 05:11:32 2006 From: arvind.mulay at gmail.com (arvind) Date: 29 Jun 2006 02:11:32 -0700 Subject: Database access through python using GUI(Tkinter) Message-ID: <1151572291.969023.299910@b68g2000cwa.googlegroups.com> hi all, i am accessing sql+ database through python 2.4.3. i am using Tkinter to build my screens. how can i pass parameters on the click event of button from one function to the another? how can i run another file from current file? From albalmer at att.net Thu Jun 8 12:21:44 2006 From: albalmer at att.net (Al Balmer) Date: Thu, 08 Jun 2006 16:21:44 GMT Subject: The Nature of the “Unix Philosophy” References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1149080931.582431.95560@j55g2000cwa.googlegroups.com> <1149730552.161534.121350@i40g2000cwc.googlegroups.com> Message-ID: On 7 Jun 2006 18:35:52 -0700, "Xah Lee" wrote: >The Nature of the ?Unix Philosophy? Good grief. Him again. -- Al Balmer Sun City, AZ From luismgz at gmail.com Tue Jun 13 13:53:23 2006 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 13 Jun 2006 10:53:23 -0700 Subject: Very nice python IDE (windows only) In-Reply-To: <448eb72c$0$10503$3a628fcd@textreader.nntp.hccnet.nl> References: <1149694235.741274.325200@u72g2000cwu.googlegroups.com> <1149701880.540109.10100@y43g2000cwc.googlegroups.com> <1149704292.676501.138530@h76g2000cwa.googlegroups.com> <448d5f3d$0$815$3a628fcd@textreader.nntp.hccnet.nl> <1150123984.819338.84330@u72g2000cwu.googlegroups.com> <1150175414.784581.35420@c74g2000cwc.googlegroups.com> <448eb72c$0$10503$3a628fcd@textreader.nntp.hccnet.nl> Message-ID: <1150221203.527216.78960@i40g2000cwc.googlegroups.com> Jan Bijsterbosch wrote: > Hello Luis, > > "Luis M. Gonz?lez" schreef in bericht > news:1150175414.784581.35420 at c74g2000cwc.googlegroups.com... > > > > digitalorganics at gmail.com wrote: > >> I happen to have delphi, so if someone wants me to make small changes, > >> just let me know, I'll try to help.... > > > > Hmm... now that you offer, would it be possible to have the colors of > > text just like in IDLE? > > I tried configuring the colors, but some of them don't exist as options > > in this IDE (for example "orange"). > > Hmm, it's a little bit hidden, but if you go to Options / Editor / Syntax > Colors and be sure to select Python language as editor syntax then select > 'reserved words' and after that from the color dropdown box select Custom... > (the topmost option) a color dialog pops up and you can select any color You > want...;-)) > > > I like how text looks in IDLE, with orange for reserved words, green > > for strings, etc... > > With the above, no problem at all...;-)) > > Greetings from sunny Amsterdam, > > Jan Thank you! You're right, the custom option is a litle bit hiddenm but now I customized it just as I wanted. Great IDE! I love it... Luis From axwack at gmail.com Tue Jun 6 15:48:27 2006 From: axwack at gmail.com (axwack at gmail.com) Date: 6 Jun 2006 12:48:27 -0700 Subject: 10GB XML Blows out Memory, Suggestions? In-Reply-To: References: <1149594519.098115.8980@u72g2000cwu.googlegroups.com> <2Qfhg.18186$0v4.787@tornado.texas.rr.com> Message-ID: <1149623307.191676.321400@y43g2000cwc.googlegroups.com> The file is an XML dump from Goldmine. I have built a document parser that allows for the population of data from Goldmine into SugarCRM. The clients data se is 10gb. Felipe Almeida Lessa wrote: > Em Ter, 2006-06-06 ?s 13:56 +0000, Paul McGuire escreveu: > > (just can't open it up like a text file) > > Who'll open a 10 GiB file anyway? > > -- > Felipe. From maric at aristote.info Wed Jun 21 11:15:16 2006 From: maric at aristote.info (Maric Michaud) Date: Wed, 21 Jun 2006 17:15:16 +0200 Subject: How to override the doc of an object instance. In-Reply-To: References: <200606211539.02663.maric@aristote.info> Message-ID: <200606211715.16926.maric@aristote.info> Le Mercredi 21 Juin 2006 15:58, David Huard a ?crit?: > On Wed, 21 Jun 2006 15:39:02 +0200, Maric Michaud wrote: > > This is w.__class__.x.__doc__. > > Thanks, > > So in order to implement what I want, I should rather consider an > ipython hack to print w.__class__.x.__doc__ when it exists, instead of > w.x.__doc_ ? Does this makes sense or it will ruin the standard behaviour? > You can replace __IPYTHON__.magic_pinfo at startup to honor properies, but the help command is already more explicit, try : In [53]: class a(object) : ....: x=property(lambda s: 0, doc='my doc string') ....: ....: In [54]: b=a() In [55]: help(b) Also you can do something like that (put it in some startup script) : In [27]: __IPYTHON__.old_pinfo = __IPYTHON__.magic_pinfo In [28]: def new_pinfo(obj) : ....: return __IPYTHON__.old_pinfo('modified_version_of_obj') ....: In [29]: __IPYTHON__.magic_pinfo = new_pinfo But you can also send a bug report to Ipython maintainer :) > David -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From shb*NOSPAM* at comporium.net Thu Jun 22 22:17:07 2006 From: shb*NOSPAM* at comporium.net (Si Ballenger) Date: Thu, 22 Jun 2006 22:17:07 -0400 Subject: serial port servo control References: <1150989488.345731.49680@m73g2000cwd.googlegroups.com> Message-ID: On 22 Jun 2006 08:18:08 -0700, boyle5 at llnl.gov wrote: >So I ordered a mini SSC II (the servo controller), in order to >control some servos from the computer. I was hoping to use python to >do the control but have two questions... > >1) How should I write to the serial port with python? I found the >module "pyserial": >http://pyserial.sourceforge.net/ >on the python cheeseshop, and it looks solid but I thought you might >have a better suggestion. > >2) To control the servos I have to send the SSC II a string of 3 >numbers, 3 bytes long (so 3 numbers in the range 0 - 255, each as a >single byte, one after another). In C I'd do this by sending 3 >char's, as they're only 1 byte, but i'm not exactly sure how to do it >in Python. Maybe a little off topic, but I've got a page below with some mini ssc control info. http://www.geocities.com/zoomkat/index.htm From Mike.S.Duffy at gmail.com Wed Jun 21 05:25:04 2006 From: Mike.S.Duffy at gmail.com (Mike Duffy) Date: 21 Jun 2006 02:25:04 -0700 Subject: Specifing arguments type for a function In-Reply-To: References: Message-ID: <1150881904.531320.224210@p79g2000cwp.googlegroups.com> Paolo Pantaleo wrote: > I have a function > > def f(the_arg): > ... > > and I want to state that the_arg must be only of a certain type > (actually a list). Is there a way to do that? I wrote a cool function decorator just for that purpose. It's posted on the Python Decorator Library at: http://wiki.python.org/moin/PythonDecoratorLibrary#head-308f2b3507ca91800def19d813348f78db34303e If you use it, you will be able to simply write: @accepts(list) def f(the_arg): ... and you will get a warning message if the_arg is not a list. Or, if you want an exception raised, then just: @accepts(list, debug=2) def f(the_arg): ... Let me know what you think, if you do end up using it. I'm eager for feedback. From syl_stand at yahoo.es Sat Jun 10 09:19:16 2006 From: syl_stand at yahoo.es (Davor) Date: 10 Jun 2006 06:19:16 -0700 Subject: convert .pdf files to .txt files Message-ID: <1149945556.411580.143850@j55g2000cwa.googlegroups.com> Hi, my name is david. I need to read information from .pdf files and convert to .txt files, and I have to do this on python, I have been looking for libraries on python and the pdftools seems to be the solution, but I do not know how to use them well, this is the example that I found on the internet is: from pdftools.pdffile import PDFDocument from pdftools.pdftext import Text def contents_to_text (contents): for item in contents: if isinstance (item, type ([])): for i in contents_to_text (item): yield i elif isinstance (item, Text): yield item.text doc = PDFDocument ("/home/dave/pruebas_ficheros/carlos.pdf") n_pages = doc.count_pages () text = [] for n_page in range (1, (n_pages+1)): print "Page", n_page page = doc.read_page (n_page) contents = page.read_contents ().contents text.extend (contents_to_text (contents)) print "".join (text) the problem is that on some pdf?s it generates join words and In spanish the "acentos" in words like: "cami?n" goes to --> cami/86n or "IMPLEMENTACI?N" -----> "IMPLEMENTACI?" give strange characters if someone knows how to use the pdftools and can help me it makes me very happy. Another thing is that I can see the letters readden from .pdf on the screen, but I do not know how to create a file and save this information inside the file a .txt Sorry for my english. Thanks for all. From fredrik at pythonware.com Sat Jun 10 12:21:32 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 10 Jun 2006 18:21:32 +0200 Subject: PIL problem after installation In-Reply-To: <1149954516.785869.160700@i40g2000cwc.googlegroups.com> References: <1149954516.785869.160700@i40g2000cwc.googlegroups.com> Message-ID: Lad wrote: > I installed PIL under Linux but now when I try it I get the error: > > decoder jpeg not available > How can I correct that problem? if you built PIL yourself, the setup script told you how to fix this. - make sure you have right libraries installed (see the "prerequisites" section in the README) - run setup and read the BUILD SUMMARY report carefully - if the setup script cannot find a component, you'll have to edit the setup.py file and set the appropriate ROOT variable. see in- structions in the setup.py file for details. if you got a binary release, complain to the distributor. From jjlee at reportlab.com Tue Jun 6 16:11:42 2006 From: jjlee at reportlab.com (John J. Lee) Date: Tue, 06 Jun 2006 20:11:42 GMT Subject: 10GB XML Blows out Memory, Suggestions? References: <1149594519.098115.8980@u72g2000cwu.googlegroups.com> <4eleh3F1eguosU1@uni-berlin.de> Message-ID: <874pyyrqm9.fsf@reportlab.com> "K.S.Sreeram" writes: [...] > There's just NO WAY that the 10gb xml file can be loaded into memory as > a tree on any normal machine, irrespective of whether we use C or > Python. Yes. > So the *only* way is to perform some kind of 'stream' processing > on the file. Perhaps using a SAX like API. So (c)ElementTree is ruled > out for this. No, that's not true. I guess you didn't read the other posts: http://effbot.org/zone/element-iterparse.htm > Diez B. Roggisch wrote: > > No what exactly makes C grok a 10Gb file where python will fail to do so? > > In most typical cases where there's any kind of significant python code, > its possible to achieve a *minimum* of a 10x speedup by using C. In most [...] I don't know where you got that from. And in this particular case, of course, cElementTree *is* written in C, there's presumably plenty of "significant python code" around since, one assumes, *all* of the OP's code is written in Python (does that count as "any kind" of Python code?), and yet rewriting something in C here may not make much difference. John From onurb at xiludom.gro Tue Jun 20 11:34:34 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 20 Jun 2006 17:34:34 +0200 Subject: Python is fun (useless social thread) ;-) In-Reply-To: <44980c68$0$38718$edfadb0f@dread12.news.tele.dk> References: <449433b5$0$1344$626a54ce@news.free.fr> <44965e69$0$38632$edfadb0f@dread12.news.tele.dk> <4497e9b2$0$1602$636a55ce@news.free.fr> <44980c68$0$38718$edfadb0f@dread12.news.tele.dk> Message-ID: <4498158b$0$29643$636a55ce@news.free.fr> Max M wrote: > bruno at modulix wrote: > >> Max M wrote: >> >>> bruno at modulix wrote: >>> >>>>> Or did you just like what you saw and decided to learn it for fun? >>>> >>>> >>>> Well, I haven't be really impressed the first time - note that it >>>> was at >>>> the very end of the last century, with v1.5.2. >>> >>> >>> >>> 1.5.2 was an excellent version. Not really that different in use than >>> current version. >> >> >> Nope, "not really that different" - we were just missing list-comps, >> generators, new-style classes, classmethods, staticmethods, usable >> metaclasses, descriptors, @decorators sugar, extended slices, and a few >> other goodies coming in 2.5 like coroutines and with: statement... > > I wrote "different in use". Yes. It just happens that all this really changed a lot the way I use Python (and the way I design and program in general). > Which is not the same as saying it has not > changed. The general feel of coding in Python is exactly the same to me. AFAIC, the overall feeling that the language helps me instead of getting in the way is still here, of course !-) > I believe that most of those changes you mention are rarely used by most > programmers. Too bad for them then. Not that I use all of these nice features all the time, but I have a use case for at least one of them almost everyday - and I do miss them when using other languages. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From joncle at googlemail.com Thu Jun 8 09:26:05 2006 From: joncle at googlemail.com (Jon Clements) Date: 8 Jun 2006 06:26:05 -0700 Subject: How to generate k+1 length strings from a list of k length strings? In-Reply-To: References: Message-ID: <1149773165.890230.228960@g10g2000cwb.googlegroups.com> Are you asking the question, "Which pairs of strings have one character different in each?", or "Which pairs of strings have a substring of len(string) - 1 in common?". Jon. Girish Sahani wrote: > I have a list of strings all of length k. For every pair of k length > strings which have k-1 characters in common, i want to generate a k+1 > length string(the k-1 common characters + 2 not common characters). > e.g i want to join 'abcd' with bcde' to get 'abcde' but i dont want to > join 'abcd' with 'cdef' > Currently i'm joining every 2 strings, then removing duplicate characters > from every joined string and finally removing all those strings whose > length != k+1.Here's the code i've written: > > for i in range(0,len(prunedK) - 1,1): > if k in range(1,len(prunedK),1) & i+k <= len(prunedK) -1: > colocn = prunedK[i] + prunedK[i+k] > prunedNew1.append(colocn) > continue > for string in prunedNew1: > stringNew = withoutDup(string) > prunedNew.append(stringNew) > continue > > But this one is quite bad in the time aspect :(. > Thanks in advance, > girish From zelzel.zsu at gmail.com Fri Jun 23 05:15:57 2006 From: zelzel.zsu at gmail.com (zelzel.zsu at gmail.com) Date: 23 Jun 2006 02:15:57 -0700 Subject: Is there any good methods to read a encrypted password file? Message-ID: <1151054157.279606.65950@g10g2000cwb.googlegroups.com> Is there any good methods to read a encrypted password file? hi, all: I've a zipped file with a password . currently i use it by this method: $ unzip -p secret.zip | python my-pexpect.py but i want to remove the unzip -p secret.zip process. that is : $ python my-pexpect.py [whe python prgram will ask for a password for secret.zip] how can i do this? thanks. From fredrik at pythonware.com Sat Jun 3 09:19:55 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 03 Jun 2006 15:19:55 +0200 Subject: image lib & Qt4 In-Reply-To: <44818202.8060607@tachyontech.net> References: <1149173540.470829.34940@c74g2000cwc.googlegroups.com> <4e8haiF1dp2heU1@uni-berlin.de> <1149180814.585713.209640@i39g2000cwa.googlegroups.com> <44818202.8060607@tachyontech.net> Message-ID: K.S.Sreeram wrote: > I'm getting an 'unknown raw mode' error on ImageQt.py:59: > data = im.tostring( "raw", "BGRX" ) > > Does this only work with PIL 1.1.6 snapshots? I currently have > PIL 1.1.5. it was developed on Python 2.4.3 and PIL 1.1.5, so it should work. and BGRX support has been in there for ages (at least since 1.1.1). what happens if you do: $ python >>> import Image >>> im = Image.new("RGB", (100, 100)) >>> print len(im.tostring("raw", "BGRX")) 40000 From ray_usenet at yahoo.com Thu Jun 1 04:28:37 2006 From: ray_usenet at yahoo.com (Ray) Date: 1 Jun 2006 01:28:37 -0700 Subject: How do you practice Python? Message-ID: <1149150517.034409.292530@g10g2000cwb.googlegroups.com> In our field, we don't always get to program in the language we'd like to program. So... how do you practice Python in this case? Say you're doing J2EE right now. How do you practice Python to keep your skills sharp? I liked Python Challenge, but there were too many PIL there, something that I doubt I'll ever use, so there must be a better way. Thanks Ray From steven.bethard at gmail.com Fri Jun 30 21:10:33 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 30 Jun 2006 19:10:33 -0600 Subject: optparse multiple arguments In-Reply-To: <1151657119.837675.213700@p79g2000cwp.googlegroups.com> References: <1151657119.837675.213700@p79g2000cwp.googlegroups.com> Message-ID: Ritesh Raj Sarraf wrote: > Now if someone uses it as: > ./foo --my-option a b c > > I want somehow to store all the three arguments Currently optparse doesn't support options with an arbitrary number of arguments. I'm currently working on a optparse-inspired replacement which does support this along the lines of: parser.add_option('--my-option', nargs='*') but it's not quite ready for prime-time yet. I'm hoping to put an announcement out in the next couple of weeks. STeVe From claird at lairds.us Sat Jun 3 19:48:20 2006 From: claird at lairds.us (Cameron Laird) Date: Sat, 3 Jun 2006 23:48:20 +0000 Subject: Python less error-prone than Java References: Message-ID: <4nj9l3-hgn.ln1@lairds.us> In article , Christoph Zwerschke wrote: >You will often hear that for reasons of fault minimization, you should >use a programming language with strict typing: >http://turing.une.edu.au/~comp284/Lectures/Lecture_18/lecture/node1.html > >I just came across a funny example in which the opposite is the case. . . . >What's better about the Python version? First, it will operate on *any* >sorted array, no matter which type the values have. > >But second, there is a hidden error in the Java version that the Python >version does not have. > >See the following web page if you dont find it ;-) >http://googleresearch.blogspot.com/2006/06/extra-extra-read-all-about-it-nearly.html . . . This is all worth saying, that is, I agree with the conclusions. The premises are arguable, though. For me, this example illustrates the difficulty faced by people who hear, "strict typing", and think of Java. At another level, Python's superiority here is epiphenomenal. Python probably has a better model for arithmetic than Java, but BDFL knows that Python is not without its own flaws, particulary in arithmetic. So, here's my summary: Python's a nice language--a very nice one. It's safer to use than Java in many ways. Python's typing is STRICTER than Java's, but it's also dynamic, so people get to argue for decades about which is a better model. Anyone who thinks typing is a first-order determinant of code quality is making a big mistake though, anyway. From mailer at forums.com Sat Jun 17 22:07:06 2006 From: mailer at forums.com (Dean Card) Date: Sat, 17 Jun 2006 19:07:06 -0700 Subject: Easy question on minidom Message-ID: I am using minidom to parse a 20,000 line XML file. I have a few instances where the number of child nodes of a particular node can be variable in number. To access them I am doing something like the following... xmldoc = minidom.parseString(r) results = xmldoc.childNodes[0] for myNode in results.childNodes[1].childNodes: do Stuff with myNode... problem is I am having a heck of a time trying to access the value of the node. For instance I get things like this But I need the values... any help here? From gandalf at designaproduct.biz Sat Jun 10 08:23:28 2006 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Sat, 10 Jun 2006 14:23:28 +0200 Subject: __getattr__ question In-Reply-To: <1149928254.153476.184030@f6g2000cwb.googlegroups.com> References: <1149928254.153476.184030@f6g2000cwb.googlegroups.com> Message-ID: <448AB9C0.7020902@designaproduct.biz> > print "item1" in dir(root) # False > print "item3" in dir(root) # True > > Is it the behavior you wanted? > Exactly. :-) Why I did not think of this? I'm always amazed when I see that Python can do anything we want. :-) From fredrik at pythonware.com Fri Jun 9 07:55:23 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 09 Jun 2006 13:55:23 +0200 Subject: Error in Chain of Function calls In-Reply-To: <52920.10.209.4.2.1149839931.squirrel@10.105.1.3> References: <53637.10.209.4.2.1149834663.squirrel@10.105.1.3> <52920.10.209.4.2.1149839931.squirrel@10.105.1.3> Message-ID: Girish Sahani wrote: >> what error ? > ...line 266, in colocationMiner > prunedNew = genColocations(prunedK) > genColocations is a function defined before which returns prunedNew. that's a line of code, not an error. please include the entire traceback, or at least the actual error message. also see: http://pyfaq.infogami.com/tutor-i-need-help-im-getting-an-error-in-my-program-what-should-i-do >>> The error is: >>> prunedNew.remove(s) >>> ValueError: list.remove(x): x not in list >> the ValueError means exactly what it says -- have you verified that the >> value of "s" really is present in the list? did you really mean to >> remove "s" and not, say, "string" ? > > Yes. I want to remove s from the prunedNew list if that condition is not > satisfied. are the item you want to remove in the list? if you cannot be sure of that when you call remove, you need to check first (or catch the exception). i.e. if s in prunedNew: prunedNew.remove(s) or try: prunedNew.remove(s) # remove, if present except ValueError: pass # ignore error if not present From fredrik at pythonware.com Mon Jun 5 02:57:34 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 05 Jun 2006 08:57:34 +0200 Subject: attribute error using fnmatch In-Reply-To: <1149489751.258496.259540@c74g2000cwc.googlegroups.com> References: <1149489751.258496.259540@c74g2000cwc.googlegroups.com> Message-ID: s99999999s2003 at yahoo.com wrote: > listof_files = [i for i in f if not fnmatch(os.path.join(r,i),pat) and > os.path.isfile(os.path.join(r,i))] > ... > .. > > I get this error: > File "C:\Python24\Lib\fnmatch.py", line 37, in fnmatch > pat = os.path.normcase(pat) > File "C:\Python24\lib\ntpath.py", line 42, in normcase > return s.replace("/", "\\").lower() > AttributeError: replace > > But when i do everything in interactive, there is no problem.. What > could be wrong with the script? nothing, from what I can tell. did you verify that the code you posted really have the problem (it does use the 'os' module which isn't important, and doesn't use 'glob' which is imported, so chances are that you messed something up on the way to comp.lang.python). what do you get if you add print repr(pat), type(pat) just before the list comprehension ? From python at hope.cz Thu Jun 22 11:16:06 2006 From: python at hope.cz (Lad) Date: 22 Jun 2006 08:16:06 -0700 Subject: Blog source code in Python Message-ID: <1150989366.242671.254300@g10g2000cwb.googlegroups.com> Is there a blog application source available in Python? Thank you for reply L. From diffuser78 at gmail.com Fri Jun 16 10:02:46 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 16 Jun 2006 07:02:46 -0700 Subject: wxPython question Message-ID: <1150466566.439285.304110@r2g2000cwb.googlegroups.com> I tried to follow wxPython Demo examples to understand it better. I used wxGlade to generate my code from the GUI builder. When I try to see the code for Menu and Menubar I see a little mismatch in the way functions are being used. For example, wxGlade produces code like this self.Action = wx.Menu() self.AddComputer = wx.MenuItem(self.Action, wx.NewId(), _("Add Computer"), "",wx.ITEM_NORMAL) self.Action.AppendItem(self.AddComputer) ## Code end and in the demo it is gives as self.Action = wx.Menu() Action.append(201, "Add Computer") # Code end Can somebody please explain this discrepancy ? Thanks, every help is appreciated. From adam.sven.johnson at gmail.com Thu Jun 15 17:19:48 2006 From: adam.sven.johnson at gmail.com (adam johnson) Date: Fri, 16 Jun 2006 09:19:48 +1200 Subject: Regular expression for not-group In-Reply-To: <1150405899.027971.256160@r2g2000cwb.googlegroups.com> References: <1150405899.027971.256160@r2g2000cwb.googlegroups.com> Message-ID: <6ab99bf50606151419u38759d5l7308bcdc3f9c4efb@mail.gmail.com> You want to use negative lookahead eg. \.(?!py) it matches only if the characters ahead in the regex don't match the pattern in the brackets. **http://docs.python.org/lib/re-syntax.html (about halfway down the page) On 15 Jun 2006 14:11:39 -0700, Chris Lasher wrote: > > Is it possible to write a regular expression such that a "match" is > found provided the string does not match a group in the regex? Let me > give a concrete example. > > Suppose I want to find a match to any filename that does not end in > .py, (ignoring the obvious use of the .endswith('.py') string method). > I tried the things that were obvious to me, none of which worked. > > \.^(py) > \.(^py) > \.[^p][^y] > > The last one deceived me at first because it will match "spam.spam", > but not "spam.parrot". I'm a bit stumped at this point. If this can be > done with a regular expression, I'd love to know how, and even if it > can't be, that would be very helpful to know, too. > > Many thanks in advance, > Chris > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From codecraig at gmail.com Thu Jun 1 08:30:32 2006 From: codecraig at gmail.com (abcd) Date: 1 Jun 2006 05:30:32 -0700 Subject: PythonDoc Ant Task Message-ID: <1149165032.870017.254980@i40g2000cwc.googlegroups.com> Anyone ever use the PythonDoc ant task? I have the following... ...this is a cut out of the build xml i am using...but it shows the relevant parts. Anyways I can run my "pyDoc" target and it runs successful with no errors. a "docs" directory is created but is empty. Any idea as to why? My "src" folder contains a python file, Foo.py. which looks like this class Bar: def printMe(self): """This method prints my data""" print "some data is being printed" ...Thanks in advance. From steve at holdenweb.com Wed Jun 28 04:05:36 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 28 Jun 2006 09:05:36 +0100 Subject: Function to prune dictionary keys not working In-Reply-To: <52244.10.209.4.2.1151460911.squirrel@10.105.1.3> References: <52244.10.209.4.2.1151460911.squirrel@10.105.1.3> Message-ID: Girish Sahani wrote: > hi ppl, > Here is a simple function to remove those keys of a dictionary whose > values are less than some specified value. But it isnt working. Please > help. > Besides all the good advice you've been given about not expecting string/float comparisons to be meaningful, remember too that both your function's result and the dict's .keys() method return *lists*. >>> [1, 2] == [2, 1] False >>> Easiest would be to convert both lists to sets and use if set(prune(d,cp)) == set(d.keys()): You could, instead, sort them before comparison, but that's only a win if you need them sorted elsewhere. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From bignose+hates-spam at benfinney.id.au Wed Jun 14 20:35:20 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 15 Jun 2006 10:35:20 +1000 Subject: nested functions References: <1150319279.865335.323530@u72g2000cwu.googlegroups.com> Message-ID: <87y7vzl0hj.fsf@benfinney.id.au> "Gregory Petrosyan" writes: > I often make helper functions nested, like this: > > def f(): > def helper(): > ... > ... > > is it a good practice or not? You have my blessing. Used well, it makes for more readable code. > What about performance of such constructs? What about it? Set up some examples maningful for your situation, with and without such constructs, and use the profiler to find out. -- \ "People demand freedom of speech to make up for the freedom of | `\ thought which they avoid." -- Soren Aabye Kierkegaard | _o__) (1813-1855) | Ben Finney From duncanm255 at hotmail.com Thu Jun 1 14:08:04 2006 From: duncanm255 at hotmail.com (D) Date: 1 Jun 2006 11:08:04 -0700 Subject: Starting New Process In-Reply-To: References: <1149172463.881528.131290@j55g2000cwa.googlegroups.com> Message-ID: <1149185284.820789.321130@y43g2000cwc.googlegroups.com> Thanks, Jean-Paul - is there any way to do it without using Twisted, since I am not very familiar with it? (i.e. just using the os library) Thanks. Jean-Paul Calderone wrote: > On 1 Jun 2006 07:34:23 -0700, D wrote: > >Hello, I need to write a server program that performs the following > >tasks: > > > >1) Listens on TCP port 5555 for a connection > >2) When client connects, launches application (for example, vi), then > >closes connection with client > >3) Goes back to listening on TCP port 5555 for an incoming connection > > Untested: > > from twisted.internet import protocol, reactor > > class ViRunner(protocol.Protocol): > def connectionMade(self): > reactor.spawnProcess( > None, > '/usr/bin/setsid', > ['setsid', '/usr/bin/vi']) > self.transport.loseConnection() > > f = protocol.ServerFactory() > f.protocol = ViRunner > reactor.listenTCP(5555, f) > reactor.run() > > Jean-Paul From steve at holdenweb.com Mon Jun 12 04:04:26 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 12 Jun 2006 09:04:26 +0100 Subject: How to link foreign keys & primary keys using python? In-Reply-To: <1150094463.850719.312650@i40g2000cwc.googlegroups.com> References: <1149856668.055162.209650@u72g2000cwu.googlegroups.com> <1150094463.850719.312650@i40g2000cwc.googlegroups.com> Message-ID: sonal wrote: > Hi Mr. George, > Sorry for confusing u so much... > Let me try it again... > > I am not using any relational database to store the required tables > with primary keys & foreign keys.... > > When I say PRIMARY KEY => > 1. It means an index is created on the specified fields > (Out of various fields given in the comma separated txt file) > FileFormat: CODE, FIRST_NAME, last_name, area_of_expertise, country > Eg: A1,Harry,George, python, XYZCOUNTRY--------(1st record) > > 2. The index can be formed on a single field or on multiple fields > Eg: a. 'CODE' (single field ) {pk_code} > b. 'CODE' & 'NAME' (multiple fields ) {pk_code_fname} > What, in Python, *are* these indexes - lists, dictionaries, tuples or something else? > Now when I say FOREIGN KEY => > 1. If the foreign Key is formed on the field 'CODE' in another text > file > Format: subsriber_code,CODE,first_name, no_of_posts,active(Y/N) > Eg: SUB_001, A1, Harry, 50, Y > > This means the CODE (A1) given here is checked in the index formed > above > with primary key: pk_code... > > 2. If the foreign Key is formed on the fields 'CODE' & 'FIRST_NAME' > Format: subsriber_code,CODE,FIRST_NAME, no_of_posts,active(Y/N) > Eg: SUB_001, A1, Harry, 50, Y > > This means the CODE (A1) & FIRST_NAME (Harry) given here > are checked in the index formed above with primary key: > pk_code_fname... > > I am done till here..... > > The problem starts if I have defined an index on multiple fields > (composite PK) > say: CODE & FIRST_NAME (pk_code_fname) > and if I need to define a FK on a single field out of these > say: CODE > > I am unable to do that... > Mr. George, I thought i must explain the code i am dealin with, > for better understanding.., but i am sorry i confused you all the more > (incase, u want to view the code please refer to the code snippets in > my first query posted) > > Thanks & regards, > sonal > A lot depends on the data structure that the code uses to represent the "indexes". Perhaps you could explain how things are looked up in them? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From grflanagan at yahoo.co.uk Sun Jun 18 16:38:12 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 18 Jun 2006 13:38:12 -0700 Subject: aligning SGML to text References: Message-ID: <1150663092.362101.130490@f6g2000cwb.googlegroups.com> Steven Bethard wrote: > I have some plain text data and some SGML markup for that text that I > need to align. (The SGML doesn't maintain the original whitespace, so I > have to do some alignment; I can't just calculate the indices directly.) > For example, some of my text looks like: > > TNF binding induces release of AIP1 (DAB2IP) from TNFR1, resulting in > cytoplasmic translocation and concomitant formation of an intracellular > signaling complex comprised of TRADD, RIP1, TRAF2, and AIPl. > > And the corresponding SGML looks like: > > TNF binding induces release of AIP1 > ( DAB2IP ) from TNFR1 > , resulting in cytoplasmic translocation and concomitant > formation of an intracellular signaling complex > comprised of TRADD , RIP1 , > TRAF2 , and AIPl . > > Note that the SGML inserts spaces not only within the SGML elements, but > also around punctuation. > > > I need to determine the indices in the original text that each SGML > element corresponds to. Here's some working code to do this, based on a > suggestion for a related problem by Fredrik Lundh[1]:: > > def align(text, sgml): > sgml = sgml.replace('&', '&') > tree = etree.fromstring('%s' % sgml) > words = [] > if tree.text is not None: > words.extend(tree.text.split()) > word_indices = [] > for elem in tree: > elem_words = elem.text.split() > start = len(words) > end = start + len(elem_words) > word_indices.append((start, end, elem.tag)) > words.extend(elem_words) > if elem.tail is not None: > words.extend(elem.tail.split()) > expr = '\s*'.join('(%s)' % re.escape(word) for word in words) > match = re.match(expr, text) > assert match is not None > for word_start, word_end, label in word_indices: > start = match.start(word_start + 1) > end = match.end(word_end) > yield label, start, end > [...] > >>> list(align(text, sgml)) > [('PROTEIN', 0, 3), ('PROTEIN', 31, 35), ('PROTEIN', 37, 43), > ('PROTEIN', 50, 55), ('PROTEIN', 128, 159), ('PROTEIN', 173, 178), > ('PROTEIN', 180, 184), ('PROTEIN', 186, 191)] > > The problem is, this doesn't work when my text is long (which it is) > because regular expressions are limited to 100 groups. I get an error > like:: [...] Steve This is probably an abuse of itertools... ---8<--- text = '''TNF binding induces release of AIP1 (DAB2IP) from TNFR1, resulting in cytoplasmic translocation and concomitant formation of an intracellular signaling complex comprised of TRADD, RIP1, TRAF2, and AIPl.''' sgml = ''' TNF binding induces release of AIP1 ( DAB2IP ) from TNFR1 , resulting in cytoplasmic translocation and concomitant formation of an intracellular signaling complex comprised of TRADD , RIP1 , TRAF2 , and AIPl . ''' import itertools as it import string def scan(line): if not line: return line = line.strip() parts = string.split(line, '>', maxsplit=1) return parts[0] def align(txt,sml): i = 0 for k,g in it.groupby(sml.split('<'),scan): g = list(g) if not g[0]: continue text = g[0].split('>')[1]#.replace('\n','') if k.startswith('/'): i += len(text) else: offset = len(text.strip()) yield k, i, i+offset i += offset print list(align(text,sgml)) ------------ [('PROTEIN', 0, 3), ('PROTEIN', 31, 35), ('PROTEIN', 38, 44), ('PROTEIN', 52, 57), ('PROTEIN', 131, 162), ('PROTEIN', 176, 181), ('PROTEIN', 184, 188), ('PROTEIN', 191, 196)] It's off because of the punctuation possibly, can't figure it out. maybe you can tweak it? hth Gerard From onurb at xiludom.gro Fri Jun 9 12:07:14 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 09 Jun 2006 18:07:14 +0200 Subject: References and copying In-Reply-To: <1149866118.229243.53290@g10g2000cwb.googlegroups.com> References: <1149866118.229243.53290@g10g2000cwb.googlegroups.com> Message-ID: <44899cb3$0$21184$626a54ce@news.free.fr> danmcleran at yahoo.com wrote: >>Where can I find a good explanation when does an interpreter copy the >>value, and when does it create the reference. > > Any good Python book. I have Learning Python and Programming Python 2nd > edition and they are very good IMO. > > >>I thought I understand >>it, but I have just typed in following commands: >> >> >>>>>a=[[1,2],[3,4]] >>>>>b=a[1] >>>>>b=[5,6] >>>>>a >> >>[[1, 2], [3, 4]] >> >>>>>b >> >>[5, 6] >> >>And I don't understand it. I thought, that b will be a reference to a, >>so changing b should change a as well. > > > No, you've set the name b to reference a slice of a. Slicing a list > always returns a new list. Please verify before asserting: >>> a = [[1, 2], [3, 4]] >>> b = a[1] >>> b is a[1] True >>> id(b) 46912496915448 >>> id(a[1]) 46912496915448 >>> -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From fredrik at pythonware.com Sat Jun 10 03:15:03 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 10 Jun 2006 09:15:03 +0200 Subject: regexp questoin In-Reply-To: <1149900282.616379.216200@h76g2000cwa.googlegroups.com> References: <1149868825.331142.280180@f6g2000cwb.googlegroups.com> <1149900282.616379.216200@h76g2000cwa.googlegroups.com> Message-ID: micklee74 at hotmail.com wrote: > actually, i am doing an application that allows user to delete files by > entering an input pattern. so if he has files that have special > characters such as [-] or others, then i want to filter them off .... I think you will have to define what "pattern" means here. since you're using the RE module, one would have thought that you want the user to be able to use RE patterns, but you obviously have something else in mind. > the solution for re.compile(re.escape(userinput)) might work, i have to > give it a try. re.escape(userinput) creates a RE pattern that patches userinput exactly. if that's what you want, there's no need to use regular expressions at all; just use the "in" operator: if userinput in filename: do something with file From robin at reportlab.com Mon Jun 12 06:32:52 2006 From: robin at reportlab.com (Robin Becker) Date: Mon, 12 Jun 2006 11:32:52 +0100 Subject: py2exe & tkinter In-Reply-To: <448D327F.7020209@chamonix.reportlab.co.uk> References: <448D327F.7020209@chamonix.reportlab.co.uk> Message-ID: <448D42D4.3040806@chamonix.reportlab.co.uk> Robin Becker wrote: > Don't know if this is the right place to ask, but has anyone considered using > something like tcl's freewrap code to integrate tkinter into py2xe single > executables? > > We currently use the (fairly clunky) nsis route to create single file > executables with py2exe as input, but with the new bundle_files option it should > be possible to integrate our tcl/tk stuff into a common library.zip as that > seems to be the method used by freewrap. After investigation it seems as though this ought to be doable with Tcl's vfs command, but that isn't available in Python 2.4's Tcl as it's only up to version 8.4. -- Robin Becker From wahab at chemie.uni-halle.de Sun Jun 25 07:47:04 2006 From: wahab at chemie.uni-halle.de (Mirco Wahab) Date: Sun, 25 Jun 2006 13:47:04 +0200 Subject: What is that, swearing (was: Python in HTML) In-Reply-To: <1151079048.601567.191630@g10g2000cwb.googlegroups.com> References: <1151077239.840572.175120@y41g2000cwy.googlegroups.com> <449c0c43$0$11196$636a55ce@news.free.fr> <1151078082.229271.85480@m73g2000cwd.googlegroups.com> <1151079048.601567.191630@g10g2000cwb.googlegroups.com> Message-ID: Thus spoke Andy Dingley (on 2006-06-23 18:10): > tactics40 at gmail.com wrote: > >> Python, like it's (evil?) cousin Perl, > > Isn't that evil cousin Ruby? Perl's the mad old grandmother in the > attic, spewing out incomprehensible $@^##&% swearing all day. There's actually a (real) Anecdote about that: Larry Wall, BDFL of Perl, working on some Perl4 code, was accompanied by his daughter: Larry recalls this event later: "I'm reminded of the day my daughter came in, looked over my shoulder at some Perl 4 code, and said, 'What is that, swearing? Regards Mirco From sudheerb at netapp.com Wed Jun 7 17:38:29 2006 From: sudheerb at netapp.com (Sudheer Gupta) Date: Wed, 07 Jun 2006 17:38:29 -0400 Subject: Using C struct in Python** corrected In-Reply-To: <448746BE.9080504@netapp.com> References: <448746BE.9080504@netapp.com> Message-ID: <44874755.9030809@netapp.com> Hi, I am having trouble using C struct in python. Hope anyone can help me out ... Say, I have my C struct as typedef struct call { struct call *next; // ..... } call_t; I have a global variable, namely call_pool, which is of type call_t * My python program: cp = call_pool # no error doing this, means that call_pool is accessable while cp: print cp cp = cp.next This is giving me error: " There is no member or method name c_next" Now, If I just do: print cp print cp.next there is no problem. But I am seeing a difference in the way python is looking at the struct: print cp -> (call_t*) 0xb0... print cp.next -> (struct call *) 0xb0... Is python not intelligent enough to diagnose the next pointer ?? Responses appreciated. Thanks Sudheer From rvtol+news at isolution.nl Wed Jun 21 11:17:22 2006 From: rvtol+news at isolution.nl (Dr.Ruud) Date: Wed, 21 Jun 2006 17:17:22 +0200 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <1150902019.850531.204740@g10g2000cwb.googlegroups.com> Message-ID: Marshall schreef: > "dynamic types." I don't have a firm definition for > that term, but my working model is runtime type tags. In which > case, I would say that among statically typed languages, > Java does have dynamic types, but C does not. C++ is > somewhere in the middle. C has union. -- Affijn, Ruud "Gewoon is een tijger." From aahz at pythoncraft.com Sun Jun 11 21:01:41 2006 From: aahz at pythoncraft.com (Aahz) Date: 11 Jun 2006 18:01:41 -0700 Subject: Thread specific singleton References: <448991d2$0$18298$4fafbaef@reader1.news.tin.it> Message-ID: In article <448991d2$0$18298$4fafbaef at reader1.news.tin.it>, Gabriele Farina wrote: > >I'm tring to implement a Singleton object that should be specific for >every thread who create it, not global. >I tried a solution that seems to work, but I have a very poor knowledge >of concurrent programming, so I'd like someone to help me find some >problems in my implementation. Try using threading.local(), but you'll need 2.4 or later. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I saw `cout' being shifted "Hello world" times to the left and stopped right there." --Steve Gonedes From Serge.Orlov at gmail.com Sun Jun 11 09:37:40 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 11 Jun 2006 06:37:40 -0700 Subject: Intermittent Failure on Serial Port In-Reply-To: References: <1149934488.780566.265600@j55g2000cwa.googlegroups.com> Message-ID: <1150033060.839717.87860@y43g2000cwc.googlegroups.com> H J van Rooyen wrote: > Serge Orloff wrote: > > | H J van Rooyen wrote: > | > Traceback (most recent call last): > | > File "portofile.py", line 232, in ? > | > ret_val = main_routine(port, pollstruct, pfifo) > | > File "portofile.py", line 108, in main_routine > | > send_nak(port, timeout) # so bad luck - comms error > | > File "/home/hvr/Polling/lib/readerpoll.py", line 125, in send_nak > | > port.flush() > | > IOError: [Errno 29] Illegal seek > | > close failed: [Errno 29] Illegal seek > | > > | > | > | > Where can I find out what the Errno 29 really means? > | > Is this Python, the OS or maybe hardware? > | > | It is from kernel: grep -w 29 `locate errno` > | /usr/include/asm-generic/errno-base.h: #define ESPIPE 29 > | /* Illegal seek */ > | > | man lseek: > | > | ERRORS: > | ESPIPE fildes is associated with a pipe, socket, or FIFO. > | > | RESTRICTIONS: > | Linux specific restrictions: using lseek on a tty device > | returns ESPIPE. > > > Thanks for the info - so the Kernel sometimes bombs me out - does anybody know > why the python flush sometimes calls lseek? I thought it was your own flush method. If it is file.flush method that makes the issue more complicated, since stdlib file.flush doesn't call lseek method. I suggest you run your program using strace to log system calls, without such log it's pretty hard to say what's going on. The most interesting part is the end, but make sure you have enough space for the whole log, it's going to be big. From ptmcg at austin.rr._bogus_.com Tue Jun 13 04:28:57 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Tue, 13 Jun 2006 08:28:57 GMT Subject: "groupby" is brilliant! References: <1150180151.643245.148210@y43g2000cwc.googlegroups.com> Message-ID: > > reader = csv.reader(open('trans.csv', 'rb')) > rows = [] > for row in reader: > rows.append(row) > This is untested, but you might think about converting your explicit "for... append" loop into either a list comp, rows = [row for row in reader] or just a plain list constructor: rows = list(reader) Neh? -- Paul (Oh, and I like groupby too! Combine it with sort to quickly create histograms.) # tally a histogram of a list of values from 1-10 dataValueRange = range(1,11) data = [random.choice(dataValueRange) for i in xrange(10000)] hist = [ (k,len(list(g))) for k,g in itertools.groupby(sorted(data)) ] print hist histAsDict = dict((k,len(list(g))) for k,g in itertools.groupby(sorted(data))) print histAsDict Gives: [(1, 979), (2, 1034), (3, 985), (4, 969), (5, 1020), (6, 975), (7, 981), (8, 1070), (9, 1003), (10, 984)] {1: 979, 2: 1034, 3: 985, 4: 969, 5: 1020, 6: 975, 7: 981, 8: 1070, 9: 1003, 10: 984} From rossberg at ps.uni-sb.de Wed Jun 21 11:45:18 2006 From: rossberg at ps.uni-sb.de (Andreas Rossberg) Date: Wed, 21 Jun 2006 17:45:18 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: <1150904475.363283.234730@y41g2000cwy.googlegroups.com> References: <7zpshbsvjy.fsf@app-1.diku.dk><4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <1150809118.677124.142230@u72g2000cwu.googlegroups.com> <1150815461.210286.53120@r2g2000cwb.googlegroups.com> <1150823297.816352.75370@u72g2000cwu.googlegroups.com> <7zzmg6amm1.fsf@app-3.diku.dk> <1150904475.363283.234730@y41g2000cwy.googlegroups.com> Message-ID: Marshall wrote: > > While we're on the topic of terminology, here's a pet peeve of > mine: "immutable variable." > > immutable = can't change > vary-able = can change > > Clearly a contradiction in terms. > > If you have a named value that cannot be updated, it makes > no sense to call it "variable" since it isn't *able* to *vary.* > Let's call it a named constant. The name of a function argument is a variable. Its denotation changes between calls. Still it cannot be mutated. Likewise, local "constants" depending on an argument are not constant. - Andreas From fredrik at pythonware.com Mon Jun 5 06:44:45 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 05 Jun 2006 12:44:45 +0200 Subject: Installation Problem In-Reply-To: <44836E91.7F640B4@king-cart.com> References: <44830900.155C7297@king-cart.com> <44831694.A022913A@king-cart.com> <44836E91.7F640B4@king-cart.com> Message-ID: Marshall Dudley wrote: > Is it not possible to install the latest version of python on my FreeBSD > system? Upgrading the FreeBSD is not an option since this is a production > system and everything else is working fine. that's really a FreeBSD question, isn't it? > You are using: 2.2.2 (#1, Jun 4 2006, 16:29:13) Python 2.2.2 was originally released in 2002, but your copy was built yesterday? did the FreeBSD source kit you got really contain a four year old release? heck, it's not even the 2.2 release in the 2.2 series, and there's been two major releases since then. are you sure you cannot get a *prebuilt* newer version from some FreeBSD repository? or if that's not possible, use the *standard* python.org source kit? after all, it's known to build and install on virtually any modern Unix or Unix-like system (and most non-Unix systems too), and you're free to install it everywhere you want (and the default on Unix is /usr/local, so you don't even have to read the README; just make sure you use the real thing, instead of some botched FreeBSD-specific source kit). From robert.kern at gmail.com Mon Jun 5 18:38:08 2006 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 05 Jun 2006 17:38:08 -0500 Subject: C# equivalent to range() In-Reply-To: <1149546736.728440.74700@i39g2000cwa.googlegroups.com> References: <1149468919.951745.163700@g10g2000cwb.googlegroups.com> <1149481675.192638.275140@c74g2000cwc.googlegroups.com> <1149509893.031953.19310@i40g2000cwc.googlegroups.com> <1149545140.011616.130610@y43g2000cwc.googlegroups.com> <1149546736.728440.74700@i39g2000cwa.googlegroups.com> Message-ID: Fuzzyman wrote: > Erik Max Francis wrote: >>Here were the "harsh" and "whining" responses to his question he's >>complaining about: > > Fair enough. Maybe they weren't "harsh" and "whining", just patronising > and abrupt. Welcome to USENET! -- 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 From david.nospam.hopwood at blueyonder.co.uk Thu Jun 22 18:46:02 2006 From: david.nospam.hopwood at blueyonder.co.uk (David Hopwood) Date: Thu, 22 Jun 2006 22:46:02 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <7zpshbsvjy.fsf@app-1.diku.dk><4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <0%Wlg.3521$MF6.947@tornado.socal.rr.com> <44992e6c$0$664$bed64819@news.gradwell.net> <1150916327.332627.124400@g10g2000cwb.googlegroups.com> <1150987852.784870.7610@y41g2000cwy.googlegroups.com> Message-ID: Andreas Rossberg wrote: > Marshall wrote: > >>>> What prohibits us from describing an abstract type as a set of values? >>> >>> If you identify an abstract type with the set of underlying values then >>> it is equivalent to the underlying representation type, i.e. there is no >>> abstraction. >> >> I don't follow. Are you saying that a set cannot be described >> intentionally? How is "the set of all objects that implement the >> Foo interface" not sufficiently abstract? Is it possible you are >> mixing in implementation concerns? > > "Values" refers to the concrete values existent in the semantics of a > programming language. This set is usually infinite, but basically fixed. > To describe the set of "values" of an abstract type you would need > "fresh" values that did not exist before (otherwise the abstract type > would be equivalent to some already existent type). So you'd need at > least a theory for name generation or something similar to describe > abstract types in a types-as-sets metaphor. Set theory has no difficulty with this. It's common, for example, to see "the set of strings representing propositions" used in treatments of formal systems. -- David Hopwood From fredrik at pythonware.com Sun Jun 4 05:22:42 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 04 Jun 2006 11:22:42 +0200 Subject: Python less error-prone than Java In-Reply-To: <1149408824.174844.178010@u72g2000cwu.googlegroups.com> References: <1149408824.174844.178010@u72g2000cwu.googlegroups.com> Message-ID: Kaz Kylheku wrote: > The trouble with your point is that Christoph's original posting refers > to an article, which, in turn, at the bottom, refers to a bug database > which shows that the very same defect had been found in Sun's Java > library! and as he points out at the top, it was the article author himself who wrote that library code: /.../ let me tell you how I discovered the bug: The version of binary search that I wrote for the JDK contained the same bug. It was reported to Sun recently when it broke someone's program, after lying in wait for nine years or so. From bblais at bryant.edu Mon Jun 26 19:14:51 2006 From: bblais at bryant.edu (Brian Blais) Date: Mon, 26 Jun 2006 19:14:51 -0400 Subject: replace a method in class: how? Message-ID: <44A06A6B.6010200@bryant.edu> Hello, I want to replace a method in a class during run-time with another function. I tried the obvious, but it didn't work: class This(object): def update(self,val): print val def another_update(obj,val): print "another",val t=This() t.update(5) t.update=another_update t.update(5) # this one doesn't work, gives # TypeError: another_update() takes exactly 2 arguments (1 given) clearly it isn't seeing it as a method, just an attribute which happens to be a function. Is there a preferred way to do this? thanks, Brian Blais -- ----------------- bblais at bryant.edu http://web.bryant.edu/~bblais From python.list at tim.thechases.com Tue Jun 20 09:11:35 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 20 Jun 2006 08:11:35 -0500 Subject: comparing of python =?ISO-8859-1?Q?GUI=B4s?= In-Reply-To: <4fq979F1k6o98U1@uni-berlin.de> References: <1150806788.026172.140150@h76g2000cwa.googlegroups.com> <4fq979F1k6o98U1@uni-berlin.de> Message-ID: <4497F407.10606@tim.thechases.com> > plz tell me the benefit (or any data) of each gui (pyqt , pyqtk , > wxpython , tkinter ..) Well, as you can see pyqt, pyqtk, and wxpython must be far better than tkinter because they have python (or bits of python) in their names. In turn, you can also clearly determine that wxpython is better than pyqt and pyqtk because it has the whole word "python" in its name, not some sissy-minded cropping of the word. And as far as pyqt and pyqtk go, clearly, because of the "k" suffix (which we all know means "kilobyte"), is a thousand times better than pyqt (or 1024x better, depending on whether you use computer measurements or hard-disk-space measurements). Thus, you find the ranking must be 1) wxpython (best) 2) pyqtk 3) pyqt 4) tkinter (worst) There's also pygtk which you must not have seen, because it is not on your list. This would rank at 2.5 in the above list because it 1) does have "py" in the name, and 2) "g" comes before "q" in the alphabet, and we know that later versions must be better 3) it has a "k" in its name, and must also be 1k times better than the non-existent "pygt" Hopefully these facts, unclouded by alleged "facts" that you might find during the most basic of searches on google, will help you make a *rational* decision regarding which GUI toolkit is best. ;) -tkc From deets at nospam.web.de Wed Jun 28 06:09:50 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 28 Jun 2006 12:09:50 +0200 Subject: Immutability References: Message-ID: <4gf2s0F1g9afiU1@uni-berlin.de> > Sigh. No. It's terrible. What it documents is the use of the property > FUNCTION. It does not document what properties ARE, and how they interact > with the rest of the language. Until you know that, it is so ambiguous > as to be almost totally useless - and it is THAT information that needs to > be in the reference manual, but is only in whatsnew2.2. I have to second that - I found myself reading through "What's new" from various versions to find that specific feature. It would be at least good to see all of them grouped together to make an easier read. Still, that is not optimal. Diez From onurb at xiludom.gro Fri Jun 9 04:11:37 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 09 Jun 2006 10:11:37 +0200 Subject: dynamic inheritance In-Reply-To: <_IidnWMwvOnfRBXZnZ2dneKdnZydnZ2d@comcast.com> References: <_IidnWMwvOnfRBXZnZ2dneKdnZydnZ2d@comcast.com> Message-ID: <44892d3a$0$5594$626a54ce@news.free.fr> alf wrote: > is there any way to tell the class the base class during runtime? > Technically, yes - the solution depending on your definition of "during runtime" FWIW, the class statement is evaled at import/load time, which is "during runtime".... So if you want to use one or other (compatible) classes depending on configuration or system or like, you can use a conditionnal at the top level, *before* the class statement is eval'd. ie: import os if os.name == 'posix': import posixmodule as basemodule elif os.name == 'nt': import ntmodule as basemodule # etc... class MyClass(basemodule.baseclass): # class def here If you want to dynamically change the base class (or one of the base classes) during execution (ie: after the class statement has been eval'd), read Kay Schluehr's answer. *But* you'd probably better tell us about the problem you're trying to solve. Since in Python, inheritance is mostly about implementation (ie: not needed for subtyping), your problem would probably be best solved with composition/delegation, for which Python offers a good support: class MyClass(object): def __init__(self, delegate): self._delegate = delegate def __getattr__(self, name): return getattr(self._delegate, name) or, if you don't want to explicitely pass the delegate at instanciation time: import os if os.name == 'posix': import posixmodule as basemodule elif os.name == 'nt': import ntmodule as basemodule # etc... class MyClass(object): _delegate_class = basemodule.SomeClass def __init__(self): self._delegate = self._delegate_class() # etc there are of course some variants of the above solutions, but one can't tell you which one to use without knowing more about your actual problem. HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From onurb at xiludom.gro Tue Jun 20 07:08:28 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 20 Jun 2006 13:08:28 +0200 Subject: [OT] code is data In-Reply-To: <4fpuh5F1i9bl1U1@uni-berlin.de> References: <44965f53$0$12743$636a55ce@news.free.fr> <4496b29f$0$27412$626a54ce@news.free.fr> <4496e9c9$0$14868$626a54ce@news.free.fr> <4fokj4F1ihat3U1@uni-berlin.de> <4497c20e$0$29656$636a55ce@news.free.fr> <4fpuh5F1i9bl1U1@uni-berlin.de> Message-ID: <4497d72d$0$30964$636a55ce@news.free.fr> Diez B. Roggisch wrote: > bruno at modulix wrote: > > >>Diez B. Roggisch wrote: >> >>>>>because lots of people know how to describe XML transformations, and >>>>>there are plenty of tools that implement such transformations >>>>>efficiently ? >>>> >>>> >>>>Efficiently enough for dynamic (runtime) use ? >>> >>> >>>Using XML-transformation for AST manipulation isn't my first choice >>>either - yet efficiency concerns aren't really the point here - after >>>all we're talking about generating code, >> >>I thought we were talking about *transforming* code - just like one uses >>metaclasses to transform a class definition, or @decorators to transform >>a function definition... > > > Yes we were. So where does the runtime efficiency you mention come in to > play? class transformations via metaclasses and function wrapping does happen at runtime - when the class or (decorated) def statements are eval'd. This is not the same as having a distinct preprocessing phase that would write a new .py file. > While the _result_ of a transformation might be a less efficient piece of > code (e.g. introducing a lock around each call to enable concurrent > access), the transformation itself is very - if not totally - static - really ? > and > usually only run once. Nope, it's runned each time the module is loaded (with 'loaded' distinct from 'imported') - which can make a real difference in some execution models... > So except from a start up latency, it has no impact. Having a high startup latency can be a problem in itself. But the problem may not be restricted to startup latency. If for example you use a metaclasse and a function that *dynamically* creates new classes using this metaclass, then both the class statement and the metaclass code transformation will be executed on each call to this function. The whole point of a code transformation mechanism like the one Anton is talking about is to be dynamic. Else one just needs a preprocessor... > So if for whatever > reason XSLT is someones favorite method of AST-transformation because it > fits her mindset - perfect. As I said: it wouldn't be mine either, but I > can't see your concerns about efficiency. cf above. > And XSLT certainly is suited for tree manipulation, so it might be that it > would be good for e.g. recursivly stripping type annotations of some kind > (think of e.g. type-verifying decorators that you want to get rid of for > production.) > > Diez -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From lucaberto at libero.it Fri Jun 16 10:06:33 2006 From: lucaberto at libero.it (luca72) Date: 16 Jun 2006 07:06:33 -0700 Subject: Pycrypto In-Reply-To: References: <1150446904.527285.255170@g10g2000cwb.googlegroups.com> <1150458752.342042.189650@h76g2000cwa.googlegroups.com> <1150462237.224431.213020@c74g2000cwc.googlegroups.com> Message-ID: <1150466793.537546.149690@p79g2000cwp.googlegroups.com> Excuse me again, If the string is not a sting but hex number how i have to proced : look this page: http://www.cs.eku.edu/faculty/styer/460/Encrypt/JS-AES.html Regards Luca From fredrik at pythonware.com Sat Jun 17 04:40:40 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 17 Jun 2006 10:40:40 +0200 Subject: Legitimate use of the "is" comparison operator? In-Reply-To: <1150533253.400675.232510@g10g2000cwb.googlegroups.com> References: <1150530591.422197.304300@p79g2000cwp.googlegroups.com> <1150533253.400675.232510@g10g2000cwb.googlegroups.com> Message-ID: Mike Duffy wrote: >> writing broken code is never a good practice. >> > With all due respect, for some reason it seems to work on my machine. if you always work with 5-item sequences, you don't need the test at all. From gh at ghaering.de Mon Jun 19 17:20:31 2006 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 19 Jun 2006 23:20:31 +0200 Subject: [pysqlite] memory-leak in pysqlite 2.3.0 ? In-Reply-To: <4496CCED.3020103@ghaering.de> References: <8289D4DDD352DF45B8DABD7D5852A59001C00D60@EUSRV-EXC1.eu.ta.global> <4496CCED.3020103@ghaering.de> Message-ID: <4497151F.6000307@ghaering.de> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Gerhard H?ring wrote: > Michael Husmann wrote: >>> Michael Husmann wrote: >>>> After upgrading from pysqlite 2.0.5 to pysqlite 2.3.0 writing into a >>>> sqlite database increases memory consumption heavily. A similar program >>>> with Ruby and sqlite-ruby 1.1.0 does not affect memory consumption at >>>> all. >>>> [...] >>>> Python 2.4.1, Sqlite3 3.3.6, Pysqlite 2.3.0 >>> You never COMMIT your changes here, that's probably what's causing >>> memory consumption on the SQLite side of things. >>> [...] >> I also tried that commit(). Memory consumption still grows permanently. > > Thanks for the report. Upon debugging this a little, there's indeed a > bug which crept in in pysqlite 2.2.1 because of incorrect usage of the > weak references (*). This leads to the list of weak references per > connection to always grow and never shrink. I'll try to provide a fix > real soon. > > -- Gerhard > > (*) A missing PyWeakref_GetObject(), but I'll have to take a more > careful look. Fixed in Subversion. A pysqlite 2.3.1 release will follow during the next days, which is the same code that will be in Python 2.5 beta1 btw. - -- Gerhard -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2.2 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFElxUfdIO4ozGCH14RAlk4AJ9JMMkGTdwJ5moM1/7FDFBP/XFZdACghOuj 2FNxgi7F7R+V6ARtzXgyNDY= =29Gx -----END PGP SIGNATURE----- From fredrik at pythonware.com Mon Jun 5 12:47:45 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 05 Jun 2006 18:47:45 +0200 Subject: xml.sax problem: getting parse() to read a string In-Reply-To: <1149525288.546237.78700@u72g2000cwu.googlegroups.com> References: <1149525288.546237.78700@u72g2000cwu.googlegroups.com> Message-ID: sturnfie at gmail.com wrote: > So in recap, it looks like it is trying to take my string argument as a > file handler. How can I get around this? if you want to parse a string, use xml.sax.parseString instead of xml.sax.parse. From johnjsal at NOSPAMgmail.com Thu Jun 8 15:44:08 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 08 Jun 2006 19:44:08 GMT Subject: wxpython: can't even create a Panel In-Reply-To: References: Message-ID: Tim Chase wrote: > It looks like a subtle difference between > > panel = wx.Panel(self) > > and > > panel = wx.Panel(self) Ack! Thanks guys! What's funny is that at first I even had it beneath the __init__ method, but then I unindented because it looked wrong for some reason! :P Well, now I can create a totally useless empty window, which I consider a major accomplishment! From fredrik at pythonware.com Mon Jun 26 05:47:21 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 26 Jun 2006 11:47:21 +0200 Subject: style question References: <1151314163.701348.195370@u72g2000cwu.googlegroups.com> <1151314474.696043.201250@b68g2000cwa.googlegroups.com> Message-ID: Frank Millman wrote: >> How about >> >> message = ("This is line1. " >> "This is line2 " >> "This is line3\n") >> >> The brackets mean that the lines are automatically treated as >> continuous, without the need for the ugly '\' continuation character. >> >> The opening/closing quotes on each line mean that the strings are >> contatenated into one long string. > > Don't know what happened there - Google seems to have messed up my > indentation. > > My intention was that each of the three leading quote marks line up > vertically, but when I read it back via Google Groups, the second two > lines were pushed over to the right. assuming fixed-pitch fonts isn't very Pythonic, though; to get reliable indentation no matter what font you're using, you can write: message = ( "This is line1. " "This is line2 " "This is line3\n") whether this is better than """ depends on the situation. From david.nospam.hopwood at blueyonder.co.uk Sun Jun 25 11:34:12 2006 From: david.nospam.hopwood at blueyonder.co.uk (David Hopwood) Date: Sun, 25 Jun 2006 15:34:12 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> Message-ID: David Hopwood wrote: > Chris F Clark wrote: > >>I'm particularly interested if something unsound (and perhaps >>ambiguous) could be called a type system. > > Yes, but not a useful one. The situation is the same as with unsound > formal systems; they still satisfy the definition of a formal system. I meant "inconsistent formal systems". -- David Hopwood From dingbat at codesmiths.com Fri Jun 23 12:10:48 2006 From: dingbat at codesmiths.com (Andy Dingley ) Date: 23 Jun 2006 09:10:48 -0700 Subject: Python in HTML In-Reply-To: <1151078082.229271.85480@m73g2000cwd.googlegroups.com> References: <1151077239.840572.175120@y41g2000cwy.googlegroups.com> <449c0c43$0$11196$636a55ce@news.free.fr> <1151078082.229271.85480@m73g2000cwd.googlegroups.com> Message-ID: <1151079048.601567.191630@g10g2000cwb.googlegroups.com> tactics40 at gmail.com wrote: > Python, like it's (evil?) cousin Perl, Isn't that evil cousin Ruby? Perl's the mad old grandmother in the attic, spewing out incomprehensible $@^##&% swearing all day. > can be used as a CGI. If you > don't have one already, go download Apache server to play with on your > own machine and Google "Python CGI" and "Python module cgi". Or if you're cursed with IIS for Windows, then PythonScript does the job. From liam_herron at hotmail.com Mon Jun 5 21:04:46 2006 From: liam_herron at hotmail.com (liam_herron) Date: 5 Jun 2006 18:04:46 -0700 Subject: Is there a way to pass a python function ptr to a c++ method from a python script? Message-ID: <1149555886.251441.188180@i39g2000cwa.googlegroups.com> I have a core c++ library that is exposed to python through the boost_python framework. I would like to write the core of a Newton's method solver in C++ and be able to write the functions that are evaluated to be in python. Does anyone have any ideas on this? From jcarlson at uci.edu Sat Jun 17 00:50:42 2006 From: jcarlson at uci.edu (Josiah Carlson) Date: Fri, 16 Jun 2006 21:50:42 -0700 Subject: [Python-Dev] The baby and the bathwater (Re: Scoping, augmented assignment, 'fast locals' - conclusion) In-Reply-To: <449329F0.2000703@gmail.com> References: <449329F0.2000703@gmail.com> Message-ID: <20060616155433.F33D.JCARLSON@uci.edu> Before I get started with my reply, I would just like to point out that aside from my initial 'I see your using a closure for this problem as a design bug', I have tried my best to be as reasonable as I can, not once attacking your character or abilities. However, twice now you have expressed various insults towards me in order to somehow discredit my statements. At this point I am no longer interested in this conversation, a sentiment I expect you share (perhaps along with those in comp.lang.python). If you feel the need to continue to express discontent about me publically, have at it. Heck, I'll even start you out: Josiah Carlson's nose is too big. Further self-deprecation I will mark with '*'. It is obvious to both of us that we are misunderstanding each other on various levels [1], so perhaps cutting of communication is better for the both of us, and if anyone else has anything to say about the topic, they can reply to either of us. Boris Borcic wrote: > Josiah Carlson wrote: > > In my initial and later readings of your messages, I read 2 reasons why > > you were using a closure rather than some other method to perform this > > particular operation: > > That wording already doesn't apply. I told you I was working *not* on a program > but on a *space* of programs of identical function, as of manner of probing > recent features and modules of Python that I manage to apply to it. Besides > learning, my purpose is also aesthetic. My reading of your previous message stated that while you were looking through various algorithms and codebases, your purpose seemed quite singular, and I'll quote your quoting of the requirement: ""universal sudoku solver in +-pure python, ~10ms/problem, and ~60 LOCS total"." I must be such an idiot* that I failed to understand that you were, in fact, working on modifying "a *space* of programs of identical function". I'm sorry about that. As for code aesthetics, I have little to no sympathy for relatively minor changes. Decorators, yeah, that was a significant change in aesthetics (and usefulness), and when such was pointed out, I went from a -1 to a +1. But x[0] ?= y becoming x ?= y (where ? is one of ^&|+-*/), or as provided by Noam Raphael recently, x[()] becoming x[], I can't get behind for purely aesthetic reasons, and see limited practical value to them. > > However, since no one else has responded substantively to your postings, > > other than Terry and Guido's 'not gonna change', > > That's "Terry's 'take the fairy tale' and Guido's 'not gonna change'", > to be exact. I had used the single quote as a mechanism of paraphrase rather than double quotes as exact quotation. You obviously understood this, but I would point out that while Terry said, "this will not change for 2.x", Python 3.x development has started already, so it's not so much a "fairy tale'. > > I can only presume that > > others have found that your desired result (augmented assignments for > > names not previously existing in the current scope, but existing in a > > parent lexical scope, be performed on the object bound to a parent scope > > name), is undesireable for Python 2.5 > > This is again misrepresentation. I definitely did *not* come to pydev to ask for > a change, I merely intervened in the middle on an ongoing thread at the point it > was being said that, in effect, I did not exist. Thereupon you intervened with > no other purpose than to show, in effect, that I did not exist, forcing me into > an endless chain of rectifications. Now you are telling me I want it included in > the 2.x series. That's confusing the citizen for the lobbyist. I will point you back to Terry's posts: http://mail.python.org/pipermail/python-dev/2006-June/066037.html http://mail.python.org/pipermail/python-dev/2006-June/066057.html Read them a few times. Ok, now read my post: http://mail.python.org/pipermail/python-dev/2006-June/065990.html If I understood Terry correctly (and I hope I understood myself), at no point in any of those messages did anyone state that nested augmented assignments wouldn't be useful, or that there weren't any use-cases. Terry stated how augmented assignments managed to work in alpha 2, why it was a bug generally, and why that patch was being fixed/reverted. I tried to express that I felt your use of a closure was a poor design decision, because I had understood your code to offer an external interface, where it actually offered an internal interface. Over the course of the subsequent emails, I have attempted to, essentially, make similar points as Terry, though obviously Terry was far more concise and far less aggravating than I have been. Take his emails as the authoritative source in regards to this topic (I do, even though I continue to post), and if you desire, pretend that my messages didn't exist. > The "programming project" I *did* describe was the project of *further* > exploring, with systematism, the space of nearly equivalent programs - while > slightly *relaxing* the frame of the initial result, and while exercizing > varying parts of relatively recent distribution Python or third party modules > that I did not know, or not know well. Could you please point out where you previously stated that you were "exploring, with systematism, the space of nearly equivalent programs". I've tried finding it, but I fear my glasses are far too caked with personal and professional failure for any cleaning to do any good*. > Seeking beauty, if you want. You understand the quest for beauty ? I guess not > in the manner of someone who started programming when programs had to fit in a > couple dozen kbytes. I quite likely do not appreciate the same, or to the same degree, certain aesthetic qualities of particular Python programs that you do. But we both seem to like Python to some extent, so hooray. > The "compiler feature" under discussion just pissed me off when it popped up to > veto what was emergeing as the winner of my beauty contest after examining quite > a few worthy candidates over weeks. I'm sorry to hear that. > > Great, wonderful, I wish you luck; I will not question or > > "refuse legitimacy, motivation, efficiency or methodological soundness" > > of your approach when using the Python programming language. > > What's wrong with chosing a set problem to compare features of the Python > programming language against, and learn from it ? Please tell. > > And what's wrong, when seeking beauty, with picking a stringent constraint and > then explore in parallel various manners to satisfy it, relaxing it slightly if > need be ? How do you think nature evolved birds or flowers or anything that lives ? There is nothing wrong with either. I myself have spent more time than I would care to admit comparing xml.dom, xml.sax, and elementTree, TCPServer against asyncore, various DB wrappers against each other, etc. > Well, at this point you risk an even worse fate than that ;) That is, the > intersection of the file tagged "arrogant would-be mind-readers", and of the > file tagged "you are late on the normal trajectory if you did not reproduce my > own oh-so-significant mistakes", both well-populated already, although I forgot > who I put in them. I don't have a funny walk, but you could toss me in the "has a funny dance" file (because I do have a funny dance). > The problem is that you fail to be polite about it more often than not. Most of > the time not really talking to the reasonable person I tend to be. We all tend to believe that we are being polite and/or reasonable. Aside from my first message, I thought I was being quite pleasant, though I am also a self-righteous prick*, and wasn't reading my emails aloud with a sufficiently hostile tone to understand what it may sound like to you. > > I will mention that the lack of _any_ public support in python-dev > > likely says far more about the unliklihood of acceptance than anything > > you or I have probably typed in the last few days. > > And what's the purpose of that declaration ? You are the, hum, crazed lobbyist, > not me. I am just defending that my pov is perfectly legitimate, including when > it's examined by your criterions - once the fallacious ones among them are > filtered out. The purpose was to /hopefully/ bring this thread to something of a conclusion, which it failed to do. > > My measurement is quite subjective. Have I ever made that mistake, or > > do I know of anyone who has made that mistake? In this case, I have made > > the mistake I mention, both in personal code, as well as code I was > > writing as I was tutoring. > > Thanks for the transparency. You mean code you were writing in real time before > an audience ? Hum. Surely you take the time to debug example code before > presenting it ? Writing in real time in front of a student as they were asking questions. > The error you mean - do we agree on this ? - is to intend two variables of the > same name, one in the parent scope, the other shadowing it in the child scope, > and mutating the variable in the child scope while having forgotten to > initialize it. Yes. > A few questions. First, do we agree or not that gratuitous shadowing is by > itself a mistake ? Or do you mean it happened to you while the shadowing wasn't > gratuitous ? Also, do you mean it happened to you in the Python context so that > Python stopped it at "ref to uninitialized local" - or in some other langiage > context ? In the Python case, I can only wonder as to what could make it > memorable - not the debugging, certainly. I wouldn't call the shadowing gratuitous, but it was unfortunate. It happened to me in the context of Python, through an attempt to write something very similar to what you included in your original post. The initial memory was due to a slight embarrassment during the tutoring session, followed by an identical mistake in unrelated code a few days later. I can't remember any other situations where I've run into the same problem (I try to keep away from closures except when writing decorators), but I can't say with certainty that I haven't made that mistake since. > My take on the issue, btw, is that the "scope capture" behavior of > (non-augmented) assignment statement is in Python the residual counterpart of > variable declarations in other languages; and it is significant that it shares > the most typical basic form, since in most cases declaration and initialization > are fused. This doesn't carry over to augmented assignments that are mutation > operators. If I understand you correctly, I agree with you. > > Here are two questions for you: > > > > 1. Do you have any proof showing that the error I claim exists (not > > uncommonly was my description), is in fact so rare, that I am > > essentially the only one who has made the mistake? > > Well, my take on an issue of such form is perhaps particular, but - as I already > suggested with my "hate for whatever resembles a constraining curriculum of > errors to make" - I really believe, as a matter of ethics, that the burden of > proof is on your side, not mine. I disagree. The error can happen, I have made the error, I am not a unique butterfly, so others may have made the error. What would raise an exception before then produces no exception, but may produce potentially mysterious results, hence an error would pass silently. > > 2. Do lexically nested augmented assignments happen so often as to make > > this problem a "must solve" for any Python revision? > > Hum, first of all implementation of the solution is (according to recent > records), so trivial that it occurs spontaneously as a bug. Therefore, even > conceding to you the usage be so rare that the gain is vanishingly small, the > ratio gain/effort would be one of vanishingly small quantities, which itself is > a priori not determined to be close to zero. > > This of course does not count the cost of the decision. AFAICS, you are yourself > the most significant factor in determining that cost, and because of that I > think it would not be fair dialectics that I should take that cost into account > to answer your own question. Right ? I don't believe that your use of gain/effort is sufficient to describe the total real benefit vis-a-vis potential errors. To me, while the use of augmented assignments in lexically nested scopes would be convenient, it would allow a class of errors (that are likely not common) to pass silently. Also, the ease of change is somewhat inconsequential, as with sufficient support, just about anything will be implemented (and many things with one person have been implemented). > Second, the assumption of rarity leading to insignificance - does it escape you > that's a sword that cuts both way - as concerns a sizeable part of your own > argumentation ? It does not escape me. But the rarity, in my opinion, weighs differently. We could likely toss a half-dozen of the zens back and forth as to why each of us is right, but of all zens that apply to either side, one zen trumps them all. Why? Essentially all zens relating to this topic describe relative goodness, x is better than y, z is good, etc., but there is one that is absolute: "Errors should never pass silently." > Third, to me the matter is foremost one of aesthetics. The contentious "feature" > made me briefly feel like I was confused on the identity of the lady I was > making love to. > > Fourth, of course I can survive without it. I'm glad. > > Do skilled programmers make errors? Yes. Do skilled programmers make > > errors when they are first using a programming language? Yes. > > Of course everybody makes errors, but it doesn't follow from this, that all make > the same errors, or should. If I implied that everyone has made this particular mistake, I'm sorry. I was trying to say that I made error X, and that I don't believe that I'm a unique butterfly to have made error X. If I'm not unique, then presumably someone else has made a similar mistake. And in this case, it *could* have lead to mysterious behavior, where before it would produce the equivalent of an "are you sure?" exception. > As concerns Python, the issue is that in most aspects it is carefully crafted so > that you can often "just try it and it works as you would expect". For this to > work, consistency is very important. Our whole debate is that according to me > the "feature" under discussion is not in the same spirit while you (and Terry > indeed) found preferable not to acknowledge the notion, what also prevented the > possibility to convince me that the "feature" should exist anyway, for logical > reasons a reasonable mind could hear. I agree that having nested augmented assignments "just work" would be convenient, if I have stated or expressed anything to the contrary, then I apologize. My objection with having it "just work" is that it *could* mask unintended shadowing errors. > > It has > > always been my experience with Python that it seeks to be reasonable to > > use for both newcomers to programming and long-time "skilled" > > programmers. > > Nobody forces any school to present closures to beginners. Burn SICP before your > class. > > More seriously, I believe the case you made against closures really should hit > what incites to the "simultaneous mistake", eg the ease of shadowing builtins > and globals, inadvertently to start with. A nicely fat set of keyword-like names > that one can't shadow without special action, would that not be the best of > schools against gratuitous shadowing ? > > Well, maybe that would be too much of a change for Python. OTOH, mhh, I would > need to study the matter more in depth, but at first sight I see absolutely no > obstacle to trading a ban on closures shadowing names from the outer local > scope, against the current ban on augmented assignment of variables from the > outer scope (even without including straightforward assignment in the bargain). > > This would give python closures a new educative role : a context that trains > against shadowing. If I am not mistaken, it would fulfill the "use case" you > find to the "feature" I dislike, just as well. One could make the argument that any static list of keyword-like names would be insufficient. An alternate method would be to disallow any shadowing without explicit "yes I want to shadow this", or even an explicit "this refers to an outer scoped variable" (though the latter I've already expressed my displeasure about). Then again, pychecker picks up on arbitrary shadowing if I remember correctly, and I'm sure most people don't run pychecker nearly as often as they should (I know I don't), which would clue everyone in on such mistakes. One consequence of either a fixed or variable set of non-shadowables is that you would need to use arbitrarily unique names for lexically nested for loops, and/or specify that such variables are not referencing parent scopes. def foo(...): for i in ...: ... def bar(...): ... for i in ...: #unallowed ... ... You can replace the 'i' with a name of your choosing. Is such desireable? I would say no for the same reasons why I said no in regards to being able to explicitly name variables in different levels within lexically nested scopes: I would argue that one shouldn't be using closures in the first place, so encouraging its use with a syntax is right out the door. But that's my opinion, and not really relevant to the current discussion. > > In my statements regarding possible errors related to augmented > > assignments, I merely believe that people can and will make mistakes. I > > further believe that if I manage to make a particular mistake, that > > someone else has, because while I'm not the most brilliant programmer > > out there, I'm also certainly not the worst, and I would guess that I > > lack the creativity to generate a completely new class of mistakes. > > Whatever, programming or not, I believe the most dangerous (in the sense of most > difficult to rectify) class of mistakes is the class of diagnostic errors - > meta-errors, so to say; because of that, I believe a danger with mistakes or > errors is to anticipate too much on them, and, given their diversity, to > overestimate the scope of the lessons learned from the sample of them that most > caught our attention (usually because of their painful consequences). > > Besides, I think there are subtle issues with taking errors as building material > for policies destined to public consomption by new generations. It is vital to > find a self-standing positive goal to substitute to the negative goal of > avoiding the repetition of the error, etc. > > Btw, how you dealt with my case tells me you don't particularly fear diagnostic > errors, but your way of presenting closures and classes in Python tells me that > you probably agree with my later remark. You are more or less correct. In very few things, I am conservative. One of those things is what I would consider to be reasonable in regards to language behavior change compared to previous Python versions; the fewer changes, generally, the better. I don't believe that Guido is the end-all-be-all of language design, but I do find that I agree with him more often than not (though perhaps not vv), and at least in regards to this particular functionality, I side with the 'status quo' end of things. Have a good weekend, - Josiah [1] http://www.csmonitor.com/2006/0515/p13s01-stct.html From cito at online.de Mon Jun 5 06:07:55 2006 From: cito at online.de (Christoph Zwerschke) Date: Mon, 05 Jun 2006 12:07:55 +0200 Subject: Python less error-prone than Java In-Reply-To: References: <1149408824.174844.178010@u72g2000cwu.googlegroups.com> Message-ID: Ilpo Nyyss?nen wrote: > It is not different. Your crash can tell you that it was a null > pointer. Your crash can tell you that you stomped over memory. You > just get the information about the error in different way. Not all stomping over memory must result in a crash. You might just get wrong results, and you don't notice it. Also, if you get such a crash it's much harder to find out the reason. It may show off only later in a different part of the program. -- Chris From anatoli.barski at googlemail.com Thu Jun 1 03:04:26 2006 From: anatoli.barski at googlemail.com (anatoli.barski at googlemail.com) Date: 1 Jun 2006 00:04:26 -0700 Subject: how to print newline in xml? In-Reply-To: References: <1149023930.292203.152540@u72g2000cwu.googlegroups.com> Message-ID: <1149145466.190011.146250@i39g2000cwa.googlegroups.com> Thank you for a possible solution, but it's not what I'm looking for, cause something like would look quite similar... for big elements like robot it would be ok to use comment as a child of element - but imagine I'd like to comment transformation: I wouldn't like to make this element parent of a description - it is not nice - I have lots of such elements. It is important that a user after having a glance at the document is able to quickly find and change some values. I don't want to bother him with reading documentation nodes - but if he needs - they should be there... the only possible solution I can think of would be: > How about: > > > armar3 > : > : > > > XML editor + xpath makes this way more easier to use by humans compared to > normal comments. Also, if you declare several of comment elements > (summary, description, author, etc.) you can auto generate documentation > etc. > > -- > John MexIT: http://johnbokma.com/mexit/ > personal page: http://johnbokma.com/ > Experienced programmer available: http://castleamber.com/ > Happy Customers: http://castleamber.com/testimonials.html From olsongt at verizon.net Tue Jun 20 11:03:34 2006 From: olsongt at verizon.net (olsongt at verizon.net) Date: 20 Jun 2006 08:03:34 -0700 Subject: Debugging C++ code called from Python 2.2 with Visual Studio.NET In-Reply-To: <1150814226.544579.178260@c74g2000cwc.googlegroups.com> References: <1150799634.503338.302780@b68g2000cwa.googlegroups.com> <1150812006.311261.99140@y41g2000cwy.googlegroups.com> <1150814226.544579.178260@c74g2000cwc.googlegroups.com> Message-ID: <1150815814.108623.41960@g10g2000cwb.googlegroups.com> egodet at equisys.com wrote: > I can't seem to be able to download > http://www.python.org/ftp/python/2.2/Python-2.2.tgz. > Do you know if I can find it elsewhere? > Thanks, > Emmanuel The link you gave worked for me... From mikeminer53 at hotmail.com Fri Jun 23 09:46:55 2006 From: mikeminer53 at hotmail.com (mkPyVS) Date: 23 Jun 2006 06:46:55 -0700 Subject: Flight search automation In-Reply-To: <1151069276.861472.292270@r2g2000cwb.googlegroups.com> References: <1151069276.861472.292270@r2g2000cwb.googlegroups.com> Message-ID: <1151070415.237973.265400@c74g2000cwc.googlegroups.com> Is there an http page redirect call to the client once the java releases it's wait que? George Sakkis wrote: > I'm trying to use mechanize to fill in a "find a flight" form and then > get back the results, but I'm not sure how to make it wait until the > results page appears; the response after submitting the form is the > "please wait while we are searching for your flights" page. Any ideas ? > > George From maric at aristote.info Thu Jun 8 09:01:59 2006 From: maric at aristote.info (Maric Michaud) Date: Thu, 8 Jun 2006 15:01:59 +0200 Subject: CONSTRUCT - Python's way of Ruby's "alias_method" In-Reply-To: References: Message-ID: <200606081501.59668.maric@aristote.info> Le Jeudi 08 Juin 2006 14:28, Ilias Lazaridis a ?crit?: > Another possibility is to enlink (hook?) the functionality into an > existent function > > Is there any way (beside a patch) to alter the behaviour to an existing > function. Is ther a python construct similar to the "alias_method" of Ruby: > No, there is no special construct to do this, but we do things very similar every day in Zope, it's called "monkey patch" : #patch_service.py from toto import service def my_impl(self, *args) : old_result = self._old_method(*args) # ... return new_result if not hasattr(service, '_old_method') : service._old_method = service.method service.method = my_impl once this file is imported, all future calls to "method" of service instances will use my_impl. -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From bj_666 at gmx.net Sun Jun 18 12:38:35 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sun, 18 Jun 2006 18:38:35 +0200 Subject: Date Subtraction References: Message-ID: In , Cameron Laird wrote: > In article , > Marc 'BlackJack' Rintsch wrote: >>In , >>rsutradhar_python wrote: >>> date1="2006-01-10" >>> date2="2005-12-15" >>> date = date1 - date2 >>> should give me 25 but problem is that date1 and date2 datatype is >>> string which need to be conerted into date fromat which i am not able >>> to do so please help me. >> >>from datetime import date >> >>date_str_1 = '2006-01-10' >>date_str_2 = '2005-12-15' >>date_1 = date(*map(int, date_str_1.split('-'))) >>date_2 = date(*map(int, date_str_2.split('-'))) >>print (date_1 - date_2).days - 1 > . > . > . > Apparently you understand the original poster better than I. > What's with the "- 1"? If I read you correctly, you'd calculate > that there are zero days between, for example, > 2006-01-13 > and > 2006-01-12 > Do I have that right? No that's not what I would calculate. I would do without the ``- 1`` but the OP wanted 25 as result. Without the substraction it's 26. ;-) Ciao, Marc 'BlackJack' Rintsch From bj_666 at gmx.net Sat Jun 17 04:45:36 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 17 Jun 2006 10:45:36 +0200 Subject: add elements to indexed list locations References: <1150478265.122559.283000@f6g2000cwb.googlegroups.com> <7rmdnTyLF8gNcw_ZnZ2dnUVZ_v2dnZ2d@comcast.com> <1150528979.036821.246410@g10g2000cwb.googlegroups.com> Message-ID: In <1150528979.036821.246410 at g10g2000cwb.googlegroups.com>, levent wrote: > I think I was thinking more of a linked-list idea, where you do not > store the indices as integers to some random access array but rather as > pointers into list's nodes. Then the subsequent inserts would not hurt > previously stored pointers. For those who know a bit C++/STL here is a > sketch of the idea: > > name_list heros; > heros.push_back("clark"); > // ... add the rest > indexed_name_list surnames; > surnames.push_back( > make_pair( find( heros.begin(), heros.end(), "clark"), "kent") ) > ); // the find function returns an iterator to appropriate location > // ... add the rest > > for_each(surnames.begin(), surnames.end(), insert_surnames) > // insert_surnames is a callback that receives a single indexed surname > // at a time and does the job, without affecting outer iterators. > > > I was wondering how to make indices as *robust* in Python... Any ideas? What about putting all information for each super hero into an object or at least a list? And those objects/lists can then be stored into a dictionary with the first name of the heroes as key. Something like this: heroes = [['super', 'clark'], ['spider', 'peter'], ['bat', 'bruce']] name2hero = dict((hero[1], hero) for hero in heroes) fullnames = [['clark', 'kent'], ['peter', 'parker'], ['bruce', 'wayne']] for name, surname in fullnames: name2hero[name].append(surname) for hero in heroes: print 'Hello %s a.k.a %s %s' % tuple(hero) IMHO you shouldn't try to program C++ in Python. Take a step back and describe *what* you want to achieve and not *how* you do it in another language. And then implement it in Python. Ciao, Marc 'BlackJack' Rintsch From sjmachin at lexicon.net Tue Jun 13 18:29:55 2006 From: sjmachin at lexicon.net (John Machin) Date: Wed, 14 Jun 2006 08:29:55 +1000 Subject: "groupby" is brilliant! In-Reply-To: References: <1150180151.643245.148210@y43g2000cwc.googlegroups.com> <448F351A.7000201@lexicon.net> Message-ID: <448F3C63.7030407@lexicon.net> On 14/06/2006 8:06 AM, Gary Herron wrote: > John Machin wrote: >> On 13/06/2006 6:28 PM, Paul McGuire wrote: >> >> >>> (Oh, and I like groupby too! Combine it with sort to quickly create >>> histograms.) >>> >>> # tally a histogram of a list of values from 1-10 >>> dataValueRange = range(1,11) >>> data = [random.choice(dataValueRange) for i in xrange(10000)] >>> >>> hist = [ (k,len(list(g))) for k,g in itertools.groupby(sorted(data)) ] >>> >> That len(list(g)) looks like it uses O(N) memory just to find out what N >> is :-( >> > Not at all! A python list *knows* its length at all times. len() is a > constant time lookup of an internal attribute. Did you see any reference to time in what I wrote? Did you notice the word "memory" at all? My point is that "g" is an iterator, and list(g) actually builds a list of size N, merely in order to use len(that_list) to count the number of items that g will produce. From tganss_at_t_dash_online_dot_de-remove-all-after-first-real-dash at yahoo.com Thu Jun 8 03:56:35 2006 From: tganss_at_t_dash_online_dot_de-remove-all-after-first-real-dash at yahoo.com (Thomas Ganss) Date: Thu, 08 Jun 2006 08:56:35 +0100 Subject: 10GB XML Blows out Memory, Suggestions? In-Reply-To: <9ehjl3-4um.ln1@prcm.tecont.de> References: <1149594519.098115.8980@u72g2000cwu.googlegroups.com> <2Qfhg.18186$0v4.787@tornado.texas.rr.com> <9ehjl3-4um.ln1@prcm.tecont.de> Message-ID: >>medium. Even a SQLite database table should do better, and you can ship it >>around just like a file (just can't open it up like a text file). > > > A table helps only if the data is tabular (i.e. a single relation), > i.e. probably never (otherwise the sending side would have shipped > something like CSV). Perhaps the previous poster meant "database file", which for some systems describes the "container" of the whole database. If the XML has redundancies represented in "linked" data, data normalization can cut down on the needed space. my 0.02 EUR thomas From flippa at flippac.org Sun Jun 11 03:25:54 2006 From: flippa at flippac.org (Philippa Cowderoy) Date: Sun, 11 Jun 2006 08:25:54 +0100 Subject: Xah Lee network abuse In-Reply-To: References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148495974.975395.12920@i40g2000cwc.googlegroups.com> <1149998343.493200.144990@h76g2000cwa.googlegroups.com> Message-ID: On Sun, 11 Jun 2006, Erik Max Francis wrote: > Philippa Cowderoy wrote: > > > It is. However, the onus is on the defendant to show that it's true, rather > > than on the claimant to show that it's false. > > That also depends on the jurisdiction. > Hrmm, does that one differ in Scotland? > > I assume the "he" refers to Brandon? > > No, I was referring to the person who he was replying to, i.e., you. > Wrong pronoun, then. -- flippa at flippac.org Society does not owe people jobs. Society owes it to itself to find people jobs. From marshall.spight at gmail.com Tue Jun 27 14:13:22 2006 From: marshall.spight at gmail.com (Marshall) Date: 27 Jun 2006 11:13:22 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: <1151425350.679754.278820@i40g2000cwc.googlegroups.com> References: <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <1151384511.223582.305760@m73g2000cwd.googlegroups.com> <1151425350.679754.278820@i40g2000cwc.googlegroups.com> Message-ID: <1151432002.905190.152470@y41g2000cwy.googlegroups.com> Joe Marshall wrote: > Marshall wrote: > > > > Yes, an important question (IMHO the *more* important question > > than the terminology) is what *programs* do we give up if we > > wish to use static typing? I have never been able to pin this > > one down at all. > > It would depend on the type system, naturally. Naturally! > It isn't clear to me which programs we would have to give up, either. > I don't have much experience in sophisticated typed languages. It is > rather easy to find programs that baffle an unsophisticated typed > language (C, C++, Java, etc.). C and Java, certainly, but I'm wary these days about making any statement about limitations on C++'s type system, for it is subtle and quick to anger. > Looking back in comp.lang.lisp, I see these examples: > > (defun noisy-apply (f arglist) > (format t "I am now about to apply ~s to ~s" f arglist) > (apply f arglist)) > > (defun blackhole (argument) > (declare (ignore argument)) > #'blackhole) > > But wait a sec. It seems that these were examples I invented in > response to the same question from you! Ah, how well I remember that thread, and how little I got from it. My memories of that thread are 1) the troll who claimed that Java was unable to read two numbers from standard input and add them together. 2) The fact that all the smart people agreed the blackhole function indicated something profound. 3) The fact that I didn't understand the black hole function. The noisy-apply function I think I understand; it's generic on the entire arglist. In fact, if I read it correctly, it's even generic on the *arity* of the function, which is actually pretty impressive. True? This is an issue I've been wrestling with in my own type system investigations: how to address genericity across arity. Does noisy-apply get invoked the same way as other functions? That would be cool. As to the black hole function, could you explain it a bit? I apologize for my lisp-ignorance. I am sure there is a world of significance in the # ' on the third line, but I have no idea what it is. > > > If you allow Turing Complete type systems, then I would say no--every > > > bug can be reforumlated as a type error. If you require your type > > > system to be less powerful, then some bugs must escape it. > > > > I don't think so. Even with a Turing complete type system, a program's > > runtime behavior is still something different from its static behavior. > > (This is the other side of the "types are not tags" issue--not only > > is it the case that there are things static types can do that tags > > can't, it is also the case that there are things tags can do that > > static types can't.) > > I agree. The point of static checking is to *not* run the program. If > the type system gets too complicated, it may be a de-facto interpreter. Aha! A lightbulb just want off. Consider that a program is a function parameterized on its input. Static analysis is exactly the field of what we can say about a program without know the values of its parameters. Marshall From rganesan at myrealbox.com Thu Jun 15 05:04:39 2006 From: rganesan at myrealbox.com (Ganesan Rajagopal) Date: Thu, 15 Jun 2006 14:34:39 +0530 Subject: popen and password entry References: <200604141852.59515.erchamion.beren@gmail.com> <8c05f79c0606142358n5fbafc3xd859a63909f11e90@mail.gmail.com> <200604151200.06995.erchamion.beren@gmail.com> Message-ID: >>>>> sinan nalkaya writes: > thanks for reply, i add the line you suggested, thats what i get > sinan at sinan:~/tmp/multi_server$ python deneme.py > Password: qwe123 > finished Ah, got it. You didn't wait for the rsync process to complete. Put the body of the "try:" in a while loop. Ganesan -- Ganesan Rajagopal From tjreedy at udel.edu Fri Jun 2 14:33:44 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 2 Jun 2006 14:33:44 -0400 Subject: An oddity in list comparison and element assignment References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com><1149194434.528648.148860@u72g2000cwu.googlegroups.com><1hg9onn.p25evr18a09f9N%aleax@mac.com> Message-ID: "Aahz" wrote in message news:e5pr7u$3g0$1 at panix3.panix.com... > Except, of course, that BofA doesn't exist anymore. Oh, the *name* > does, but what's now called BofA is simply the current name of the bank > that acquired BofA. In Pythonese, they performed SomeBank.extend(BofA) BofA = SomeBank del SomeBank so that id(BofA) is now what id(SomeBank) was, not what was id(the BofA I grew up with). The name was definitely part of of the acquisition value. ;-) OT, but not completely irrelevant to a discussion of names, ids, and values. Terry Jan Reedy From ptaku2_wywal_to_ at tlen.pl Tue Jun 27 11:28:26 2006 From: ptaku2_wywal_to_ at tlen.pl (w.p.) Date: Tue, 27 Jun 2006 17:28:26 +0200 Subject: [W2k, wxPython 2.6.1.0] - MDISashDemo bug? Message-ID: When i run MDISashDemo and maximize main frame, minimize and maximize again - LayoutMDIFrame in OnSize dont work more... Why? I need this feature for main MDI frame with toolbar and statusbar with panels&sizers&bitmapbuttons :) Windows 2000, wxPython 2.6.1.0 w.p. -- From xah at xahlee.org Fri Jun 9 01:04:47 2006 From: xah at xahlee.org (Xah Lee) Date: 8 Jun 2006 22:04:47 -0700 Subject: What is Expressiveness in a Computer Language Message-ID: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> in March, i posted a essay ?What is Expressiveness in a Computer Language?, archived at: http://xahlee.org/perl-python/what_is_expresiveness.html I was informed then that there is a academic paper written on this subject. On the Expressive Power of Programming Languages, by Matthias Felleisen, 1990. http://www.ccs.neu.edu/home/cobbe/pl-seminar-jr/notes/2003-sep-26/expressive-slides.pdf Has anyone read this paper? And, would anyone be interested in giving a summary? thanks. Xah xah at xahlee.org ? http://xahlee.org/ From sreeram at tachyontech.net Wed Jun 21 08:27:14 2006 From: sreeram at tachyontech.net (K.S.Sreeram) Date: Wed, 21 Jun 2006 17:57:14 +0530 Subject: Search substring in a string and get index of all occurances In-Reply-To: <200606211345.52243.maric@aristote.info> References: <4499034A.9040306@gmail.com> <200606211345.52243.maric@aristote.info> Message-ID: <44993B22.3040807@tachyontech.net> Maric Michaud wrote: > Actually it's even more efficient than Lundh's effbot's solution finds overlapping occurrences, whereas your solution finds non-overlapping occurrences. So efficiency comparisons are not valid. e.g: indices( 'aaaaa', 'aa' ) your solution gives: 0,2 effbots's solution: 0,1,2,3 Regards Sreeram -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 260 bytes Desc: OpenPGP digital signature URL: From fredrik at pythonware.com Fri Jun 30 05:12:56 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 30 Jun 2006 11:12:56 +0200 Subject: FIXED: Re: optparse multiple arguments References: <1151657119.837675.213700@p79g2000cwp.googlegroups.com><1151657634.348133.291340@x69g2000cwx.googlegroups.com> <1151658092.273456.32260@75g2000cwc.googlegroups.com> Message-ID: Ritesh Raj Sarraf wrote: >> I guess I only need to figure out now is why args isn't storing >> argument "a" also... > > I fixed it, I guess. > > parser.add_option("", "--my-option", dest="my_option", > action="store_true") > > sets my_option to True and the arguments are all stored in the list > "args". :-) note that whatever action you're using, args holds the *remaining* arguments, after option processing. From girish at cse.iitb.ac.in Tue Jun 6 02:15:58 2006 From: girish at cse.iitb.ac.in (Girish Sahani) Date: Tue, 6 Jun 2006 11:45:58 +0530 (IST) Subject: Reading from a file and converting it into a list of lines In-Reply-To: <44851010.6070503@lexicon.net> References: <1149534126.129714.131860@f6g2000cwb.googlegroups.com> <1149535195.763340.220010@y43g2000cwc.googlegroups.com> <44851010.6070503@lexicon.net> Message-ID: <38767.10.209.4.1.1149574558.squirrel@10.105.1.3> Really sorry for that indentation thing :) I tried out the code you have given, and also the one sreeram had written. In all of these,i get the same error of this type: Error i get in Sreeram's code is: n1,_,n2,_ = line.split(',') ValueError: need more than 1 value to unpack And error i get in your code is: for n1, a1, n2, a2 in reader: ValueError: need more than 0 values to unpack Any ideas why this is happening? Thanks a lot, girish From mdudley at king-cart.com Mon Jun 5 12:16:10 2006 From: mdudley at king-cart.com (Marshall Dudley) Date: Mon, 05 Jun 2006 12:16:10 -0400 Subject: Installation Problem References: <44830900.155C7297@king-cart.com> <44831694.A022913A@king-cart.com> <44836E91.7F640B4@king-cart.com> Message-ID: <448458CA.E867E532@king-cart.com> Fredrik Lundh wrote: > Marshall Dudley wrote: > > > Is it not possible to install the latest version of python on my FreeBSD > > system? Upgrading the FreeBSD is not an option since this is a production > > system and everything else is working fine. > > that's really a FreeBSD question, isn't it? > > > You are using: 2.2.2 (#1, Jun 4 2006, 16:29:13) > > Python 2.2.2 was originally released in 2002, but your copy was built > yesterday? did the FreeBSD source kit you got really contain a four > year old release? heck, it's not even the 2.2 release in the 2.2 > series, and there's been two major releases since then. No, there was no copy on the system. When I did the make the last time as directed in the previous message, it downloaded it from the python site, then compiled and installed it. The 2.2.2 release is what it downloaded. > > > are you sure you cannot get a *prebuilt* newer version from some FreeBSD > repository? I did compile a new copy originally, and it worked fine in the directory that I compiled it in, but when moved to the /usr/local/bin directory where it should have installed, it complains that it cannot find it's library. It may just be a matter of what directory I should put the sources into and compile from, but I can find nowhere that this information is provided, everything I see indicates I can compile it in any directory. > > > or if that's not possible, use the *standard* python.org source kit? > after all, it's known to build and install on virtually any modern Unix > or Unix-like system (and most non-Unix systems too), and you're free to > install it everywhere you want (and the default on Unix is /usr/local, > so you don't even have to read the README; just make sure you use the > real thing, instead of some botched FreeBSD-specific source kit). That is what I did originally, downloaded the latest version from the main python site. I compiled by the README file instructions, and I compiled by the instructions on the python url which are different, but both gave identical results, compiles fine, runs fine from the directory I compiled in, but will error out when I move the executible code to and run it from the /usr/local/bin or the /usr/local directory. Marshall > > > From s.r.clarkstone at durham.ac.uk Fri Jun 9 11:51:33 2006 From: s.r.clarkstone at durham.ac.uk (Simon Richard Clarkstone) Date: Fri, 09 Jun 2006 16:51:33 +0100 Subject: What is Expressiveness in a Computer Language In-Reply-To: <1149863687.298352.45980@h76g2000cwa.googlegroups.com> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> Message-ID: Joe Marshall wrote: > Xah Lee wrote: >>On the Expressive Power of Programming Languages, by Matthias >>Felleisen, 1990. >>http://www.ccs.neu.edu/home/cobbe/pl-seminar-jr/notes/2003-sep-26/expressive-slides.pdf > > The gist of the paper is this: Some computer languages seem to be > `more expressive' than others. But anything that can be computed in > one Turing complete language can be computed in any other Turing > complete language. Clearly the notion of expressiveness isn't > concerned with ultimately computing the answer. > > Felleisen's paper puts forth a formal definition of expressiveness in > terms of semantic equivilances of small, local constructs. In his > definition, wholescale program transformation is disallowed so you > cannot appeal to Turing completeness to claim program equivalence. I suspect that the small, local transformations versus global transformations is also to do with the practice of not saying the same thing twice. Everything from subroutines to LISP macros also helps here, increasing language expressiveness. > Expressiveness isn't necessarily a good thing. For instance, in C, > you can express the addresses of variables by using pointers. You > cannot express the same thing in Java, and most people consider this > to be a good idea. Assuming the more-expressive feature does not preclude the less-expressive one, good/bad depends on the programmer. I know *I* can't be trusted with pointers ;-) , but I know many programmers benefit greatly from them. Of course, knowing that the programmer cannot do something does help the compiler stop you shooting yourself in the foot. -- Simon Richard Clarkstone: s.r.cl?rkst?n?@durham.ac.uk/s?m?n.cl?rkst?n?@ hotmail.com ### "I have a spelling chequer / it came with my PC / it plainly marks for my revue / Mistake's I cannot sea" ... by: John Brophy (at: http://www.cfwf.ca/farmj/fjjun96/) From wahab at chemie.uni-halle.de Sun Jun 18 13:43:13 2006 From: wahab at chemie.uni-halle.de (Mirco Wahab) Date: Sun, 18 Jun 2006 19:43:13 +0200 Subject: Extracting values from text file In-Reply-To: References: <20060617232543.9a0338fb.randhol+valid_for_reply_from_news@pvv.org> <20060618133459.2a56f781.randhol+valid_for_reply_from_news@pvv.org> Message-ID: Thus spoke Marc 'BlackJack' Rintsch (on 2006-06-18 18:54): > In , Mirco Wahab wrote: >> they use the _same_ operator (+) for number _addition_ >> and string _concatenation_, which is, imho, cumbersome. > > And ``+`` means also list/tuple concatenation and really anything for user > defined types. > >> If you have an operator with meaning "add numbers" (+) >> and one for "add strings" (.), the language could then >> do the obvious for you. > > The dot also has already a meaning, it's the attribute lookup operator. Yes, that may be the real reason? >> Why would one go from C/C++ to "dynamical typed" >> things, if he has to be so explicit on easy >> things? > > Strings that act sometimes as strings and sometimes as numbers when used > with ``+`` are quite confusing. No, thats not what I tried to say, it's rather: /things/ act _always_ as strings and _always_ as numbers _when used_ as a 'string' or as a 'number'. I don't consider that one 'confusing'. > Two relevant lines from the Zen of Python: > Explicit is better than implicit. > In the face of ambiguity, refuse the temptation to guess. This is, iirc, /exactly/ the reason why in (e.g.) Perl they put sigils ($%@) in front of the variables. So all gets explicit - there's no more ambiguity ... > And don't mix up weakly and dynamically typed. > Python is dynamically and strictly typed. OK, right. I didn't separate 'strict' from 'weak' regarding data types. I think I got used too much to these nice 'backhand conversions'. I'm sure I wouldn't have blinked once if I had gone directly from C++ (or Java) to Python, but now I have still the Perl disease in my bones ;-) Regards Mirco From flippa at flippac.org Sun Jun 11 00:50:00 2006 From: flippa at flippac.org (Philippa Cowderoy) Date: Sun, 11 Jun 2006 05:50:00 +0100 Subject: Xah Lee network abuse In-Reply-To: References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148495974.975395.12920@i40g2000cwc.googlegroups.com> <1149998343.493200.144990@h76g2000cwa.googlegroups.com> Message-ID: On Sun, 11 Jun 2006, Mike Schilling wrote: > I'm not aware of any definition of libel that includes "making statements > that are not provably true". > I believe UK law uses one that's close to it. -- flippa at flippac.org Society does not owe people jobs. Society owes it to itself to find people jobs. From sjmachin at lexicon.net Sun Jun 4 19:01:46 2006 From: sjmachin at lexicon.net (John Machin) Date: Mon, 05 Jun 2006 09:01:46 +1000 Subject: re beginner In-Reply-To: <44834d62$0$6192$626a54ce@news.free.fr> References: <44834d62$0$6192$626a54ce@news.free.fr> Message-ID: <4483665A.206@lexicon.net> On 5/06/2006 10:38 AM, Bruno Desthuilliers wrote: > SuperHik a ?crit : >> hi all, >> >> I'm trying to understand regex for the first time, and it would be >> very helpful to get an example. I have an old(er) script with the >> following task - takes a string I copy-pasted and wich always has the >> same format: >> >> >>> print stuff >> Yellow hat 2 Blue shirt 1 >> White socks 4 Green pants 1 >> Blue bag 4 Nice perfume 3 >> Wrist watch 7 Mobile phone 4 >> Wireless cord! 2 Building tools 3 >> One for the money 7 Two for the show 4 >> >> >>> stuff >> 'Yellow hat\t2\tBlue shirt\t1\nWhite socks\t4\tGreen pants\t1\nBlue >> bag\t4\tNice perfume\t3\nWrist watch\t7\tMobile phone\t4\nWireless >> cord!\t2\tBuilding tools\t3\nOne for the money\t7\tTwo for the show\t4' >> >> I want to put items from stuff into a dict like this: >> >>> print mydict >> {'Wireless cord!': 2, 'Green pants': 1, 'Blue shirt': 1, 'White >> socks': 4, 'Mobile phone': 4, 'Two for the show': 4, 'One for the >> money': 7, 'Blue bag': 4, 'Wrist watch': 7, 'Nice perfume': 3, 'Yellow >> hat': 2, 'Building tools': 3} >> >> Here's how I did it: >> >>> def putindict(items): >> ... items = items.replace('\n', '\t') >> ... items = items.split('\t') >> ... d = {} >> ... for x in xrange( len(items) ): >> ... if not items[x].isdigit(): d[items[x]] = int(items[x+1]) >> ... return d >> >>> >> >>> mydict = putindict(stuff) >> >> >> I was wondering is there a better way to do it using re module? >> perheps even avoiding this for loop? > > There are better ways. One of them avoids the for loop, and even the re > module: > > def to_dict(items): > items = items.replace('\t', '\n').split('\n') In case there are leading/trailing spaces on the keys: items = [x.strip() for x in items.replace('\t', '\n').split('\n')] > return dict(zip(items[::2], map(int, items[1::2]))) > > HTH Fantastic -- at least for the OP's carefully copied-and-pasted input. Meanwhile back in the real world, there might be problems with multiple tabs used for 'prettiness' instead of 1 tab, non-integer values, etc etc. In that case a loop approach that validated as it went and was able to report the position and contents of any invalid input might be better. From maric at aristote.info Fri Jun 23 11:09:08 2006 From: maric at aristote.info (Maric Michaud) Date: Fri, 23 Jun 2006 17:09:08 +0200 Subject: Using metaclassed to dynamically generate a class based on a parameter to the objects init function. In-Reply-To: <1151071434.945199.39490@i40g2000cwc.googlegroups.com> References: <1151018669.849641.265990@g10g2000cwb.googlegroups.com> <1151071434.945199.39490@i40g2000cwc.googlegroups.com> Message-ID: <200606231709.10456.maric@aristote.info> Le Vendredi 23 Juin 2006 16:03, Carl Banks a ?crit?: > Don't follow? ?The actual source code won't be much easier. ?Here's an > example. > > ? ? class MetaThing(type): > ? ? ? ? def __new__(metacls,name,bases,clsdict,extra_information): > ? ? ? ? ? ? # use extra_information > ? ? ? ? ? ? return type.__new__(metacls,name,bases,clsdict) > > ? ? class Thing(object): > ? ? ? ? ?def __new__(cls,extra_information): > ? ? ? ? ? ? ?clsdict = {'__new__':object.__new__} > ? ? ? ? ? ? ?my_very_own_class = MetaThing( > ? ? ? ? ? ? ? ? ?"Subthing",(Thing,),clsdict,extra_information) > ? ? ? ? ? ? ?return object.__new__(my_very_own_class) Hmmm, rigourously speaking, metaclasses in OOP are classes whose instances are class. Something like that : In [114]: class MetaClass(object) : .....: def __new__(cls, name, bases=(), **some_attributes) : .....: return type('newtype %s' % name, bases, some_attributes) .....: .....: Let's play with it : In [115]: Concrete1 = MetaClass('conc1', (), classprop=1, method=lambda s : "fun") In [116]: Concrete2 = MetaClass('conc1', (), classprop=1, method=lambda s : "fun") In [117]: isinstance(Concrete1(), Concrete2) Out[117]: False In [118]: isinstance(Concrete1(), Concrete1) Out[118]: True In [119]: Concrete1().method() Out[119]: 'fun' In [120]: Concrete1.classprop Out[120]: 1 In [121]: class Abstract(object) : .....: def __init__(self) : self._attr = self._attr_type() .....: .....: In [122]: Concrete = MetaClass('concrete_with_list', (Abstract,), _attr_type=list) In [123]: Concrete()._attr Out[123]: [] In [124]: Concrete = MetaClass('concrete_with_int', (Abstract,), _attr_type=int) In [125]: Concrete()._attr Out[125]: 0 In [126]: type(Concrete) Out[126]: In [127]: type(Concrete()) Out[127]: regards, -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From george.sakkis at gmail.com Thu Jun 22 08:48:06 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 22 Jun 2006 05:48:06 -0700 Subject: (Iron)Python on new MS robotics platform Message-ID: <1150980486.500763.115250@i40g2000cwc.googlegroups.com> "Both remote (PC-based) and autonomous (robot-based) execution scenarios can be developed using a selection of programming languages, including those in Microsoft Visual Studio? and Microsoft Visual Studio Express languages (Visual C#? and Visual Basic? .NET), JScript? and Microsoft IronPython 1.0 Beta 1, and third-party languages that conform to its services-based architecture." http://www.microsoft.com/presspass/press/2006/jun06/06-20MSRoboticsStudioPR.mspx From gneuner2/ at comcast.net Sun Jun 25 15:33:07 2006 From: gneuner2/ at comcast.net (George Neuner) Date: Sun, 25 Jun 2006 15:33:07 -0400 Subject: What is Expressiveness in a Computer Language References: <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <34aj92h0g7tqi9amhh7k3ieq5n568t0e6f@4ax.com> Message-ID: On Sun, 25 Jun 2006 13:42:45 +0200, Joachim Durchholz wrote: >George Neuner schrieb: >> The point is really that the checks that prevent these things must be >> performed at runtime and can't be prevented by any practical type >> analysis performed at compile time. I'm not a type theorist but my >> opinion is that a static type system that could, a priori, prevent the >> problem is impossible. > >No type theory is needed. >Assume that the wide index type goes into a function and the result is >assigned to a variable fo the narrow type, and it's instantly clear that >the problem is undecidable. Yes ... the problem is undecidable and that can be statically checked. But the result is that your program won't compile even if it can be proved at runtime that an illegal value would never be possible. >Undecidability can always be avoided by adding annotations, but of >course that would be gross overkill in the case of index type widening. Just what sort of type annotation will convince a compiler that a narrowing conversion which could produce an illegal value will, in fact, never produce an illegal value? [Other than "don't check this" of course.] George -- for email reply remove "/" from address From vinay_sajip at yahoo.co.uk Thu Jun 29 14:13:59 2006 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 29 Jun 2006 11:13:59 -0700 Subject: logging error with RotatingFileHandler References: <_asng.501715$x64.12701762@phobos.telenet-ops.be> <1151391562.198586.249130@m73g2000cwd.googlegroups.com> Message-ID: <1151604839.290366.90950@m73g2000cwd.googlegroups.com> flupke wrote: > If this bug is fixed, where will i find a fixed version and how do i > install it? > Also, more important to me, what am i doing wrong to get this error > message in the first place? You're not doing anything particularly wrong, though it's not exactly good practice to call fileConfig lots of times. (It's really meant for one-off configuration, not incremental configuration.) I get an error with just the following script typed in at the interactive prompt: import logging.config logging.config.fileConfig("logconf.ini") logging.config.fileConfig("logconf.ini") So, I will investigate, and when I check in a fix to the Python Subversion repository, I will post a message to this thread. Regards, Vinay Sajip From onurb at xiludom.gro Mon Jun 26 05:10:58 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Mon, 26 Jun 2006 11:10:58 +0200 Subject: Python question In-Reply-To: <1151275845.423382.294260@u72g2000cwu.googlegroups.com> References: <1151275845.423382.294260@u72g2000cwu.googlegroups.com> Message-ID: <449fa4a3$0$19181$626a54ce@news.free.fr> Harry wrote: > Hi All, (snip) > I have the following object which is like a list of tuples > row= [('name', 'x1'), ('min', 15.449041129349528), ('max', > 991.6337818245629), ('range', 976.18474069521335), ('mean', > 496.82174193958127), ('stddev', 304.78275004920454), ('variance', > 92892.524727555894), ('mode', '46.5818482111'), ('unique_count', '99'), > ('count', 99.0), ('count_missing', 0.0), ('sum_weight', 99.0)] FWIW, it *is* a list of tuples. > What command What's a 'command' ? > do I use to get the value corresponding to 'min'? (see below...) > This object seems to be non-indexable It is - just like any other list. Try : print row[0] print row[1] # etc... Now if you want keyword access, try this: print dict(row)['min'] -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From defcon8 at gmail.com Sat Jun 24 10:53:49 2006 From: defcon8 at gmail.com (defcon8) Date: 24 Jun 2006 07:53:49 -0700 Subject: Python and cellular automata (It works this time!) In-Reply-To: <1151158859.422817.239810@y41g2000cwy.googlegroups.com> References: <1151158859.422817.239810@y41g2000cwy.googlegroups.com> Message-ID: <1151160829.035910.237320@p79g2000cwp.googlegroups.com> Sorry about the code. It seems to have been truncated. I have it hosted at http://xahlee.org/x/realautomata.py Thanks to Xah Lee. From thirsteh at gmail.com Tue Jun 20 21:46:28 2006 From: thirsteh at gmail.com (Patrick M. Nielsen) Date: Wed, 21 Jun 2006 03:46:28 +0200 Subject: Simple question regarding module initialization Message-ID: <28dc07920606201846q30e04f2cx28c021818774b4fb@mail.gmail.com> Hi guys. Yes, this is very much a neophyte question, but I was pondering; modules = ['stackless', 'sys', 'slsocket as socket', 'random, time', 'traceback', 'string', 'util'] for module in modules: print "Loading %s..." % module exec 'import %s' % module Although I like the outcome of writing it like this, I don't feel good about it. Is this against standard Python conventions or morals? Loading modules this way, that is (instead of just importing it all "the right way" and making a print statement for each one). -------------- next part -------------- An HTML attachment was scrubbed... URL: From dadapapa at googlemail.com Thu Jun 8 10:25:00 2006 From: dadapapa at googlemail.com (Harold Fellermann) Date: 8 Jun 2006 07:25:00 -0700 Subject: From Python to Shell In-Reply-To: <1149775916.711309.260170@i40g2000cwc.googlegroups.com> References: <1149775916.711309.260170@i40g2000cwc.googlegroups.com> Message-ID: <1149776700.157881.310110@y43g2000cwc.googlegroups.com> > Im not a total noob but i don't know the command and the module to go > from python to the default shell. there are several ways depending on what exactly you want to achieve: sys.exit(return_value): terminates the python process and gives controll back to the shell os.system(command_string): execute command string in a subshell. result is the return value of command_str subprocess.Popen(command): starts command as a subprocess and allows you to "communicate" with that process, i.e. lets you send something to its stdin and retrieve data from its stdout and stderr streams. have a look at the docs of that module for more information. - harold - From johnjsal at NOSPAMgmail.com Fri Jun 9 14:05:06 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 09 Jun 2006 18:05:06 GMT Subject: wxpython: another missing attribute Message-ID: Ah, the object-oriented stuff is just so FUN! :) Here's my code, followed by the error. I thought I was referring to the 'text' attribute correctly, but it seems not. import wx class InputForm(wx.Frame): def __init__(self, parent, id, title, pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE, name='frame'): wx.Frame.__init__(self, parent, id, title, pos, size, style, name) panel = wx.Panel(self) text = wx.StaticText(panel, -1, 'Click results') btnOK = wx.Button(panel, -1, 'OK') self.Bind(wx.EVT_BUTTON, self.clickOK, btnOK) btnCancel = wx.Button(panel, -1, 'Cancel') self.Bind(wx.EVT_BUTTON, self.clickCancel, btnCancel) sizer = wx.BoxSizer(wx.HORIZONTAL) sizer.Add(btnOK, 0, wx.ALL, 10) sizer.Add(btnCancel, 0, wx.ALL, 10) sizer.Add(text, 0, wx.ALL, 10) panel.SetSizer(sizer) def clickOK(self, event): self.text.SetLabel('You clicked OK') def clickCancel(self, event): self.text.SetLabel('You clicked Cancel') class MyApp(wx.App): def OnInit(self): frame = InputForm(None, -1, 'Data Entry Form') self.SetTopWindow(frame) frame.Show() return True app = MyApp() app.MainLoop() ------------------- Traceback (most recent call last): File "C:\Python24\myscripts\wx_tests\wxtest.py", line 23, in clickOK self.text.SetLabel('You clicked OK') AttributeError: 'InputForm' object has no attribute 'text' From fredrik at pythonware.com Sat Jun 17 04:00:00 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 17 Jun 2006 10:00:00 +0200 Subject: Legitimate use of the "is" comparison operator? In-Reply-To: <1150530591.422197.304300@p79g2000cwp.googlegroups.com> References: <1150530591.422197.304300@p79g2000cwp.googlegroups.com> Message-ID: Mike Duffy wrote: > I just recently realized that the comparison operator "is" actually > works for comparing numeric values. except that it doesn't work. > Now, I know that its intended use is for testing object identity, but > I have used it for a few other things, such as type checking, and I > was just wondering whether or not it is considered bad practice in > the Python Community to use it for numerics as well. writing broken code is never a good practice. >>> a = range(10000) >>> if len(a) is len(a): ... print "same size" ... else: ... print "not the same size" ... not the same size (the reason that it appears to work for small integers is that the interpreter is caching the objects for some commonly used values, including small integers and one-character strings. but that's an interpreter implementation detail, not something you can rely on). From deets at nospam.web.de Wed Jun 14 11:07:04 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 14 Jun 2006 17:07:04 +0200 Subject: Tiddlywiki type project in Python? In-Reply-To: <1150291679.746132.114730@y43g2000cwc.googlegroups.com> References: <1150289313.533749.52330@i40g2000cwc.googlegroups.com> <44900ae9$0$8386$626a54ce@news.free.fr> <1150291679.746132.114730@y43g2000cwc.googlegroups.com> Message-ID: <4fan0nF1i5atjU1@uni-berlin.de> > Well, that may be an/the answer, since another form of my question > would be 'how can I write a TiddlyWikiLike using Python instead of JS' > ;-). I appreciate that it might involve, for instance, a local server. > Does the idea of embedding python in a browser instead of Javascript > make any sense at all? Nope. Not really. Diez From max at alcyone.com Wed Jun 28 01:32:57 2006 From: max at alcyone.com (Erik Max Francis) Date: Tue, 27 Jun 2006 22:32:57 -0700 Subject: how do i make an array global In-Reply-To: <1151472238.400461.42350@p79g2000cwp.googlegroups.com> References: <1151472238.400461.42350@p79g2000cwp.googlegroups.com> Message-ID: a wrote: > def fn(): > for i in range(l) > global count > count[i]= .... > > how do i declare count to be global if it is an array count = [...] def fn(): global count for i in range(l): count[i] = ... -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Every human being is a problem in search of a solution. -- Ashley Montagu From brian at sweetapp.com Tue Jun 6 11:13:20 2006 From: brian at sweetapp.com (Brian Quinlan) Date: Tue, 06 Jun 2006 17:13:20 +0200 Subject: Vancouver Python Workshop: New Keynoter Message-ID: <44859B90.1010909@sweetapp.com> What's New? =========== The Vancouver Python Workshop is pleased to announce the addition of a third keynote speaker to this year's conference. Ian Cav?n is the primary developer of the Lowry Digital Images motion picture restoration system. This Python and Zope-based system has been used to restore over 150 motion pictures. Highlights include Citizen Kane, Sunset Boulevard and both the Indiana Jones and Star Wars trilogies. While Ian was Chief Scientist at Lowry Digital, his rack of computers grew from a few Macintoshes on his desktop to over six hundred Macintosh and Linux servers - at one point earning Lowry the title as the second biggest installation of parallel processing Maintoshes in the world. In 2005, Lowry Digital Images was acquired by DTS (the famous movie audio company) and renamed DTS Digital Images. The motion picture restoration system has been discussed in publications as diverse as IEEE Spectrum, USA Today, the BBC NEWS, the New York Times and Apple.com. Ian has been a Python enthusiast since 1999. About the Vancouver Python Workshop =================================== The conference will begin with keynote addresses on August 4st by Guido van Rossum [1], Jim Hugunin [2], and Ian Cav?n. Further talks (and tutorials for beginners) will take place on August 5th and 6th. The Vancouver Python Workshop is a community organized conference designed for both the beginner and for the experienced Python programmer with: * tutorials for beginning programmers * advanced lectures for Python experts * case studies of Python in action * after-hours social events * informative keynote speakers * tracks on multimedia, Web development, education and more More information see: http://www.vanpyz.org/conference/ or contact Brian Quinlan at: brian at sweetapp.com Vancouver ========= In addition to the opportunity to learn and socialize with fellow Pythonistas, the Vancouver Python Workshop also gives visitors the opportunity to visit one of the most extraordinary cities in the world [3]. For more information about traveling to Vancouver, see: http://www.vanpyz.org/conference/vancouver.html http://www.tourismvancouver.com http://en.wikipedia.org/wiki/Vancouver Important dates =============== Talk proposals accepted: May 15th to June 15th Early registration (discounted): May 22nd to June 30th Normal registration: from July 1st Keynotes: August 4th Conference and tutorial dates: August 5th and 6th [1] Guido van Rossum (Google) is the inventor of Python and has managed its growth and development for more than a decade. Guido was awarded the Free Software Foundation Award in 2002 and Dr.Dobb's 1999 Excellence in Programming Award. Guido works at Google and spends half of his time on Python. [2] Jim Hugunin (Microsoft) is the creator of numerous innovations that take Python into new application domains. Jim's most recent project, IronPython integrates Python into Microsoft's .NET runtime. Jim's previous project, Jython is Python for the Java runtime and was the second production-quality implementation of Python. Before that, Jim's Numeric Python adapted Python to the needs of number crunching applications. Jim works at Microsoft adapting the .NET runtime to the needs of dynamic languages like Python. [3] http://news.bbc.co.uk/2/hi/business/2299119.stm Cheers, Brian From bdesth.quelquechose at free.quelquepart.fr Wed Jun 28 22:16:23 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 29 Jun 2006 04:16:23 +0200 Subject: Immutability In-Reply-To: References: <4Qj*cEjkr@news.chiark.greenend.org.uk> Message-ID: <44a307a5$0$23554$626a54ce@news.free.fr> Georg Brandl a ?crit : > Nick Maclaren wrote: > >>In article , >>"Fredrik Lundh" writes: >>|> >>|> identical? you only applied @property to one of the methods, and then you're >>|> surprised that only one of the methods were turned into a property? >> >>I wasn't expecting EITHER to be turned INTO a property - I was expecting >>both methods to be the same, but one would have non-default properties >>attached to it. > > > That's another sign that property isn't intended to be used as a decorator. > Normally, decorators wrap functions with other functions. Normally, decorators take a function and return anything appropriate. > property doesn't > return a function but a descriptor object. FWIW, function *are* descriptors (well, Python functions at least, cf the recent thread about pyrex functions). >>> def fun(): pass ... >>> fun.__get__ >>> From laurent.pointal at limsi.fr Tue Jun 20 05:29:16 2006 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Tue, 20 Jun 2006 11:29:16 +0200 Subject: How to truncate/round-off decimal numbers? In-Reply-To: References: Message-ID: Girish Sahani a ?crit : > Hi, > > I want to truncate every number to 2 digits after the decimal point. I > tried the following but it doesnt work. > >>>> a = 2 >>>> b = 3 >>>> round(a*1.0 / b,2) > 0.67000000000000004 > > Inspite of specifying 2 in 2nd attribute of round, it outputs all the > digits after decimal. There are two operations: 1) calculate of round(), which return a float number result, with the well known problem of floating point numbers represantation (see the FAQ). 2) print that number, where default printing of last expression result in the cli interpreter displays up to the highest precision, print statement works differently: >>> a=2 >>> b=3 >>> c=round(a*1.0/b,2) >>> c 0.67000000000000004 >>> print c 0.67 >>> A+ Laurent. From onurb at xiludom.gro Thu Jun 22 06:10:43 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Thu, 22 Jun 2006 12:10:43 +0200 Subject: Help req: Problems with MySQLdb In-Reply-To: <1150969803.984843.111950@y41g2000cwy.googlegroups.com> References: <1150968147.565850.156870@u72g2000cwu.googlegroups.com> <1150969803.984843.111950@y41g2000cwy.googlegroups.com> Message-ID: <449a6ca4$0$4476$636a55ce@news.free.fr> rodmc wrote: (top-post corrected) > Sybren Stuvel wrote: > >>rodmc enlightened us with: >> >>>--- it refuses to connect on the above line and the exception is >>>caught and a message displayed. >> >>So.... why do you think this exception and the error message contain >>no useful information at all? > Hi, > > Thanks for your email. Well I am kind of new to exceptions in Python, > but here is the code used below, as you can see it is somewhat basic. > Is there a way to display more information about the exception? Yes : don't catch it. You'll then have all the needed infos. If you want to catch it so you can do some logging, issue a more user-friendly error message etc, then do something like this: try: SomethingThatMayRaise() except ClassOfExceptedException, e: # e is the exception, let you access error message, traceback etc doSomethingWithException(e) Some general rules about exception handling: - *don't* use bare except clause. Never. Well, almost never (cf below) - if you can't fix the problem, just let the exception propagate - at the top level of the main program, have a catch-almost-all exception handler, that will do logging if possible, proper error reporting if possible, sanity clean-up if possible, and then crash as noisily as possible. > > try: #Exception handler for database queries > db = MySQLdb.connect(host=DBSERVERIP, user="user", > passwd="password", db="nuke") > except: > print "A database connection error has occurred" > return False This is the most useless and worst possible way to handle exceptions. Just get rid of this exception handler - letting the program crash with full traceback would be much much better - at least you'd have a chance to get some usefull informations about what went wrong. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From ptmcg at austin.rr._bogus_.com Tue Jun 6 09:43:24 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Tue, 06 Jun 2006 13:43:24 GMT Subject: Vectorization References: <1149595753.611358.189070@i39g2000cwa.googlegroups.com> Message-ID: <0Efhg.18184$0v4.13198@tornado.texas.rr.com> "RonnyM" wrote in message news:1149595753.611358.189070 at i39g2000cwa.googlegroups.com... > Hi! > > Need to vectorize this, but do not have a clue. > > a = n*m matrix > x and y are n and m vectors > > Suggestions? > > > > def fill(a, x, y): > for i in range(1,a.shape[0]): > xp = x[i] > for j in range(a.shape[1]): > yp = y[j] > a[i,j] = sin(xp*yp)*exp(-xp*yp) + a[i-1,j] > return a > > Thanks in advance, > > Ronny Mandal > Something like this, but the first row in a is never modified, is this correct? Note: this is a brute force Python attempt at a matrix, using a list of lists. Look also at the array and numarray modules. -- Paul from math import sin,exp def fill(a,x,y): aRowCount = len(x) aColCount = len(y) #a = [[0]*aColCount for i in range(aRowCount)] for ii,xp in enumerate(x[1:]): i = ii+1 for j,yp in enumerate(y): a[i][j] = sin(xp*yp)*exp(-xp*yp) + a[i-1][j] return a or more tersely (note - no side-effect of modifying a in place, makes a new copy): def fill2(a,x,y): fn = lambda t,u,v:sin(t*u)*exp(-t*u) + v return [a[0]] + [ [ fn(xp,yp,aa) for (yp,aa) in zip(y,arow) ] for (xp,arow) in zip(x[1:],a[:-1]) ] From dadapapa at googlemail.com Thu Jun 8 10:44:38 2006 From: dadapapa at googlemail.com (Harold Fellermann) Date: 8 Jun 2006 07:44:38 -0700 Subject: how to switch from os.tmpnam to os.tmpfile In-Reply-To: References: <1149773439.534989.54450@i40g2000cwc.googlegroups.com> Message-ID: <1149777877.945829.25390@h76g2000cwa.googlegroups.com> Maric Michaud wrote: > Le Jeudi 08 Juin 2006 15:30, Harold Fellermann a ?crit : > > to os.tmpfile() which is supposed to be safer, but I do not know how to > > get > > the path information from the file object returned by tmpfile(). any > > clues? > There is no path for tmpfile, once it's closed, the file and its content are > lost. from the doc : > " The file has no directory entries associated with it and will be > automatically deleted once there are no file descriptors for the file." > > You must maintain a reference to it in your program untill you don't need it > anymore. I am doing so. But still, I need its path. To give you some context: I have an app built on Tk that uses gnuplot behind the scenes. My application creates a temporary file where which gnuplot writes its results to (using the tkcanvas terminal). Later, I load the contents of that file into the a tk canvas. I don't care about the temporary file after my app is closed, so I have its reference all the time. But I need its path to tell both gnuplot and tk where to read/write data to/from. class PlotWindow(Tk.Canvas) : def plot(self,commands) : tmp = os.tmpnam() gnuplot = subprocess.Popen( "gnuplot", shell=True, stdin=subprocess.PIPE, stdout=file(tmp,"w") ) stdout,stderr = gnuplot.communicate(""" set terminal tkcanvas interact set output "%s" """ % tmp + commands) assert not stderr self.tk.call("source",tmp) self.tk.call("gnuplot",self._w) Of course, I could just use matplotlib or Gnuplot.py but the problem is not necessary enough to make any refacturing. If there is no way to use os.tmpfile(), I just go ahead with the security warning. Its only a small personal app, anyway. - harold - From robert.kern at gmail.com Wed Jun 14 18:58:01 2006 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 14 Jun 2006 17:58:01 -0500 Subject: memory leak problem with arrays In-Reply-To: <1150317325.614389.14770@i40g2000cwc.googlegroups.com> References: <1150317325.614389.14770@i40g2000cwc.googlegroups.com> Message-ID: sonjaa wrote: > Hi > > I'm new to programming in python and I hope that this is the problem. > > I've created a cellular automata program in python with the numpy array > extensions. After each cycle/iteration the memory used to examine and > change the array as determined by the transition rules is never freed. > I've tried using "del" on every variable possible, but that hasn't > worked. I've read all the forums for helpful hints on what to do, but > nothing has worked so far. I've even tried the "python memory > verification" (beta) program, which did point to numpy.dtype and > numpy.ndarray as increasing objects, before the whole computer crashed. Please post to numpy-discussion: http://www.scipy.org/Mailing_Lists We will need to know the version of numpy which you are using. There used to be a bug that sounds like this, but it was fixed some time ago. Also, please try to narrow your program down to the smallest piece of code that runs and still displays the memory leak. Thank you. -- 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 From bnblazer at gmail.com Thu Jun 1 06:29:35 2006 From: bnblazer at gmail.com (Brian) Date: 1 Jun 2006 03:29:35 -0700 Subject: TSV to HTML In-Reply-To: References: <1149098823.979329.9220@f6g2000cwb.googlegroups.com> <447e268a$0$3699$4d3efbfe@news.sover.net> <1149126509.984331.306530@h76g2000cwa.googlegroups.com> Message-ID: <1149157775.490474.173970@y43g2000cwc.googlegroups.com> Dennis, Thank you for that response. Your code was very helpful to me. I think that actually seeing how it should be done in Python was a lot more educational than spending hours with trial and error. One question (and this is a topic that I still have trouble getting my arms around). Why is the text in STYLEBLOCK tripple quoted? Thanks again, Brian From jo at durchholz.org Sun Jun 25 07:42:45 2006 From: jo at durchholz.org (Joachim Durchholz) Date: Sun, 25 Jun 2006 13:42:45 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: <34aj92h0g7tqi9amhh7k3ieq5n568t0e6f@4ax.com> References: <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <34aj92h0g7tqi9amhh7k3ieq5n568t0e6f@4ax.com> Message-ID: George Neuner schrieb: > The point is really that the checks that prevent these things must be > performed at runtime and can't be prevented by any practical type > analysis performed at compile time. I'm not a type theorist but my > opinion is that a static type system that could, a priori, prevent the > problem is impossible. No type theory is needed. Assume that the wide index type goes into a function and the result is assigned to a variable fo the narrow type, and it's instantly clear that the problem is undecidable. Undecidability can always be avoided by adding annotations, but of course that would be gross overkill in the case of index type widening. Regards, Jo From robert.kern at gmail.com Tue Jun 27 18:05:51 2006 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 27 Jun 2006 17:05:51 -0500 Subject: Problem with sets and Unicode strings In-Reply-To: <44a19d55$2@news.uni-ulm.de> References: <44a17d05$1@news.uni-ulm.de> <44a19d55$2@news.uni-ulm.de> Message-ID: Dennis Benzinger wrote: > Serge Orlov wrote: >> On 6/27/06, Dennis Benzinger wrote: >>> Hi! >>> >>> The following program in an UTF-8 encoded file: >>> >>> >>> # -*- coding: UTF-8 -*- >>> >>> FIELDS = ("F?cher", ) >>> FROZEN_FIELDS = frozenset(FIELDS) >>> FIELDS_SET = set(FIELDS) >>> >>> print u"F?cher" in FROZEN_FIELDS >>> print u"F?cher" in FIELDS_SET >>> print u"F?cher" in FIELDS >>> >>> >>> gives this output >>> >>> >>> False >>> False >>> Traceback (most recent call last): >>> File "test.py", line 9, in ? >>> print u"F??cher" in FIELDS >>> UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 1: >>> ordinal not in range(128) >>> >>> >>> Why do the first two print statements succeed and the third one fails >>> with an exception? >> Actually all three statements fail to produce correct result. > > So this is a bug in Python? No. >> frozenset remove the exception? >> >> Because sets use hash algorithm to find matches, whereas the last >> statement directly compares a unicode string with a byte string. Byte >> strings can only contain ascii characters, that's why python raises an >> exception. The problem is very easy to fix: use unicode strings for >> all non-ascii strings. > > No, byte strings contain characters which are at least 8-bit wide > . But I don't understand what > Python is trying to decode and why the exception says something about > the ASCII codec, because my file is encoded with UTF-8. Please read http://www.amk.ca/python/howto/unicode The string in all of the containers (FIELDS, FROZEN_FIELDS, FIELDS_SET) is a regular byte string, not a Unicode string. The encoding declaration only controls how the file is parsed. The string literal that you use for FIELDS is a regular string literal, not a Unicode string literal, so the object it creates is an 8-bit byte string. The tuple containment test is attempting to compare your Unicode string object to the regular string object for equality. Python does these comparisons by attempting to decode the regular string into a Unicode string. Since there is no encoding information present on regular strings at this point (since the encoding declaration in your file only controls parsing, nothing else), Python assumes ASCII and throws an exception otherwise. -- 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 From aleax at mac.com Wed Jun 28 23:03:50 2006 From: aleax at mac.com (Alex Martelli) Date: Wed, 28 Jun 2006 20:03:50 -0700 Subject: decimal by default References: <1151547269.842597.319600@y41g2000cwy.googlegroups.com> Message-ID: <1hhnr9n.74ctg51k4vtc0N%aleax@mac.com> Daniel <4daniel at gmail.com> wrote: ... > Ideally I'd like to have a way to tell the interpreter to use Decimal > by default instead of float (but only in the eval() calls). I > understand the performance implications and they are of no concern. I'm > also willing to define a single global Decimal context for the > expressions (not sure if that matters or not). Is there a way to do > what I want without rolling my own parser and/or interpreter? Is there > some other alternative that would solve my problem? What about: c = compile(thestring, thestring, '') cc = new.code( ...all args from c's attributes, except the 5th one, constants, which should instead be: decimalize(c.co_consts)...) i.e. cc = new.code(c.co_argcount, c.co_nlocals, c.co_stacksize, c.co_flags, c.co_code, decimalize(c.co_consts), c.co_names, c.co_varnames, c.co_filename, c.co_name, c.co_firstlineno, c.co_lnotab) where def decimalize(tuple_of_consts): return tuple( maydec(c) for c in tuple_of_consts ) and def maydec(c): if isinstance(c, float): c = decimal.Decimal(str(c)) return c Yeah, the new.code call IS very verbose, just because it needs to tediously and boilerplatedly repeat every attribute as an argument, but you can easily wrap the boilerplate in an auxiliary function and forget about it. (If you often want to change one or two tiny thing in a code object you probably already have a suitable auxiliary function around). Now, you can eval(cc) [[I suggest you also explicitly pass dictionaries for locals and globals, but, hey, that's just a good idea with eval in general!-)]] and, ta-da! Alex From rpdooling at gmail.com Mon Jun 5 21:10:36 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 5 Jun 2006 18:10:36 -0700 Subject: Expanding Search to Subfolders In-Reply-To: <1149526866.681348.273590@c74g2000cwc.googlegroups.com> References: <1149526866.681348.273590@c74g2000cwc.googlegroups.com> Message-ID: <1149556236.331440.117490@g10g2000cwb.googlegroups.com> >>> Could someone tell me where to learn more about directory >>> processes or show me an improved version of my first >>> script snippet? Use os.walk http://docs.python.org/lib/os-file-dir.html It takes a little reading to get it if you are a beginner, but there are zillions of examples if you just search this Google Group on "os.walk" http://tinyurl.com/kr3m6 Good luck rd "I don't have any solution, but I certainly admire the problem."--Ashleigh Brilliant From pete.forman at westerngeco.com Wed Jun 28 04:28:55 2006 From: pete.forman at westerngeco.com (Pete Forman) Date: 28 Jun 2006 10:28:55 +0200 Subject: How to measure execution time of a program References: <54032.10.209.4.1.1151481158.squirrel@10.105.1.3> Message-ID: "Fredrik Lundh" writes: > simplest way: > > t0 = time.time() You can get better resolution by using time.clock() instead of time.time(). -- Pete Forman -./\.- Disclaimer: This post is originated WesternGeco -./\.- by myself and does not represent pete.forman at westerngeco.com -./\.- opinion of Schlumberger, Baker http://petef.port5.com -./\.- Hughes or their divisions. Inviato da X-Privat.Org - Registrazione gratuita http://www.x-privat.org/join.php From greg.kujawa at gmail.com Fri Jun 2 17:50:13 2006 From: greg.kujawa at gmail.com (gregarican) Date: 2 Jun 2006 14:50:13 -0700 Subject: New to Python: Do we have the concept of Hash in Python? References: <1149182265.257263.159210@f6g2000cwb.googlegroups.com> Message-ID: <1149285013.705410.323330@j55g2000cwa.googlegroups.com> I needed certain Windows specific libraries that were difficult to impossible to do in Ruby. For example the Qt toolkit, LDAP support, and a WinCE implementation. Python is more Windows-friendly so I ported certain apps over to Python since Ruby left me hanging in just those specifics areas. As for my preferred language I use Smalltalk, Ruby, and Python each about a third of the time depending on what I'm looking to accomplish. For quick admin scripts Ruby is my choice, but perhaps that's just because I learned it first :-) Sion Arrowsmith wrote: > gregarican wrote: > >I came from using Ruby about a year or so [ ... ] > > That's an interesting way round. Why did you consider Python if > you already knew Ruby, and which is now your preferred language? > (I've no interest in learning Ruby, but from what I've seen of it > I similarly can't imagine what would motivate me to learn Python.) > > -- > \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ > ___ | "Frankly I have no feelings towards penguins one way or the other" > \X/ | -- Arthur C. Clarke > her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From kay.schluehr at gmx.net Thu Jun 29 12:41:25 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 29 Jun 2006 09:41:25 -0700 Subject: Immutability In-Reply-To: References: Message-ID: <1151599285.128721.37640@d56g2000cwd.googlegroups.com> Nick Maclaren wrote: > In article , > Robert Kern writes: > |> Nick Maclaren wrote: > |> > The way that I read it, Python allows only values (and hence types) > |> > to be immutable, and not class members. The nearest approach to the > |> > latter is to use the name hiding conventions. > |> > > |> > Is that correct? > |> > |> You can also make properties that don't allow writing. > |> > |> class Foo(object): > |> > |> def __init__(self, bar): > |> self._bar = bar > |> > |> @property > |> def bar(self): > |> return self._bar > > Thanks very much. And, what's more, I have even found its documentation! > Whatsnew2.2. The 2.4.2 reference is, er, unhelpful. > > One of Python's less-lovable attributes is the inscrutability of its > documentation :-( > > But you knew that .... > > > Regards, > Nick Maclaren. When I want to read about descriptors I use Raymond Hettingers "How To" article which explains the matter quite fine: http://users.rcn.com/python/download/Descriptor.htm From sybrenUSE at YOURthirdtower.com.imagination Thu Jun 1 04:02:34 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Thu, 1 Jun 2006 10:02:34 +0200 Subject: Best way to do data source abstraction References: Message-ID: Arthur Pemberton enlightened us with: > What is the best way to do data source abtraction? That depends on your data source. For files, file-like objects are an abstraction. For databases there is PEP 249. > I was thinking of almost having classA as my main class, and have > classA dynamically "absorb" classFood into to based on the extension > of the input file received by classA. But this doesn't seem > possible. You don't explain the most important part - "absorb". What does that mean? And what does it mean to have classA "almost" as your main class? Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From fredrik at pythonware.com Fri Jun 2 09:54:07 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 2 Jun 2006 15:54:07 +0200 Subject: Tkinter References: <9583ed900606020629n6b54b522j117b521ca7ac616e@mail.gmail.com> Message-ID: "david brochu jr" wrote: > Does anyone know how to get the value of the file selected when using > tk_getOpenFile in Tkinter? why not use the tkFileDialog module: http://www.pythonware.com/library/tkinter/introduction/x1164-data-entry.htm ? From onurb at xiludom.gro Wed Jun 14 10:03:27 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 14 Jun 2006 16:03:27 +0200 Subject: Tiddlywiki type project in Python? In-Reply-To: <1150291679.746132.114730@y43g2000cwc.googlegroups.com> References: <1150289313.533749.52330@i40g2000cwc.googlegroups.com> <44900ae9$0$8386$626a54ce@news.free.fr> <1150291679.746132.114730@y43g2000cwc.googlegroups.com> Message-ID: <4490172f$0$1949$626a54ce@news.free.fr> jkn wrote: (snip) > Does the idea of embedding python in a browser instead of Javascript > make any sense at all? >From a purely theoretical POV, yes, this idea makes sens - Python could be an interesting alternative to javascript for client-side scripting (and I'd really prefer using Python for this - but I may be a bit biased !-). But note that there may be some issues wrt/ significative indentation and security. Now the problem is that no browser actually supports Python for client-side scripting. And I really doubt this will change in a near future. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From maric at aristote.info Sat Jun 10 06:45:19 2006 From: maric at aristote.info (Maric Michaud) Date: Sat, 10 Jun 2006 12:45:19 +0200 Subject: CONSTRUCT - Python's way of Ruby's "alias_method" In-Reply-To: References: Message-ID: <200606101245.20149.maric@aristote.info> Le Vendredi 09 Juin 2006 20:06, Ilias Lazaridis a ?crit?: > the code below works, but has the limitation that I cannot import the > syncdb_hook within "django.core.management". In [4]: from b import CONS In [5]: import b In [6]: b.CONS = 3 In [7]: CONS Out[7]: 5 In [8]: from b import CONS In [9]: CONS Out[9]: 3 So, if you change one module name, a function or a class or a constant, you must do it before it is imported, or you must reload modules using it. But either are not always possible, and the later is not what you want to achieve here as it will re-execute all initialisation code in those modules. But think of that, a function is hopefully an object in python, hmmm : In [1]: from temp import func In [2]: func(5) Out[2]: 5 In [3]: def g(s) : return s*2 ...: In [4]: func.func_code = g.func_code In [5]: func(5) Out[5]: 10 hey, that should work ! -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From juho.schultz at pp.inet.fi Fri Jun 30 14:03:22 2006 From: juho.schultz at pp.inet.fi (Juho Schultz) Date: 30 Jun 2006 11:03:22 -0700 Subject: print shell output in a file In-Reply-To: <44a52fdb$0$3892$91cee783@newsreader01.highway.telekom.at> References: <44a52fdb$0$3892$91cee783@newsreader01.highway.telekom.at> Message-ID: <1151690602.661847.197630@d56g2000cwd.googlegroups.com> Juergen Huber wrote: > hello, > > one more question i will have! > > now i have written a little programm, which delivers me an output on the > shell! > > > Is there a way to put this output in an file?!?! i searched about 2h for > this, but i couldn`t find an answer! > > thnks, juergen Others have suggested creating a file. You could also let the shell to do the work. If you run the program "normally", output goes to screen: python myprog.py Run and redirect the output to a file: python myprog.py > output_of_myprog.txt This also makes controlling the output filename much easier. You could find the following useful: http://www.swc.scipy.org/lec/shell01.html From python.list at tim.thechases.com Fri Jun 23 14:05:31 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 23 Jun 2006 13:05:31 -0500 Subject: hard to explain for a french ;-) In-Reply-To: <5f56302b0606231054u10743a95ke6768492519fa225@mail.gmail.com> References: <007b01c696c9$dc8c1a40$33067a37@d11610100.cpamalencon.cnamts.fr> <5f56302b0606231054u10743a95ke6768492519fa225@mail.gmail.com> Message-ID: <449C2D6B.9090604@tim.thechases.com> > As explained in this thread > http://mail.python.org/pipermail/python-list/2006-June/348241.html > what you try to do will never work because your attempts are > at using python on the client side and only javascript works > for that purpose. Sounds like an opportunity to write JSPython...written in JavaScript, akin to CPython (written in C), Jython (written in Java), and PyPy (written in Python)...for those sick enough to undertake such a freakish task... :) No...that wouldn't be slow... -tkc From fredrik at pythonware.com Wed Jun 14 04:04:31 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 14 Jun 2006 10:04:31 +0200 Subject: Looping through a file a block of text at a time not by line References: <1150269957.652173.118640@i40g2000cwc.googlegroups.com> Message-ID: Rune Strand wrote: > Probably a more terse way to do this, but this seems to work > import os > > offset = 0 > grab_size = 6000 > file_size = os.stat('hotels.xml')[6] ouch. why not just loop until f.read returns an empty string ? > f = open('hotels.xml', 'r') > > while offset < file_size: > f.seek(offset) > data_block = f.read(grab_size) > offset += grab_size > print data_block > f.close() here's a shorter and more reliable version: f = open(filename) for block in iter(lambda: f.read(6000), ""): ... process block here's the terse version: for block in iter(lambda f=open(filename): f.read(6000), ""): ... ::: what happens if a element straddles the border between two 6000 byte blocks, btw ? From spam.noam at gmail.com Fri Jun 9 11:59:15 2006 From: spam.noam at gmail.com (spam.noam at gmail.com) Date: 9 Jun 2006 08:59:15 -0700 Subject: Allowing zero-dimensional subscripts References: <1149801040.936452.26270@i40g2000cwc.googlegroups.com> Message-ID: <1149868755.354650.272370@f6g2000cwb.googlegroups.com> Hello, Following Fredrik's suggestion, I wrote a pre-PEP. It's available on the wiki, at http://wiki.python.org/moin/EmptySubscriptListPEP and I also copied it to this message. Have a good day, Noam PEP: XXX Title: Allow Empty Subscript List Without Parentheses Version: $Revision$ Last-Modified: $Date$ Author: Noam Raphael Status: Draft Type: Standards Track Content-Type: text/x-rst Created: 09-Jun-2006 Python-Version: 2.5? Post-History: 30-Aug-2002 Abstract ======== This PEP suggests to allow the use of an empty subscript list, for example ``x[]``, which is currently a syntax error. It is suggested that in such a case, an empty tuple will be passed as an argument to the __getitem__ and __setitem__ methods. This is consistent with the current behaviour of passing a tuple with n elements to those methods when a subscript list of length n is used, if it includes a comma. Specification ============= The Python grammar specifies that inside the square brackets trailing an expression, a list of "subscripts", separated by commas, should be given. If the list consists of a single subscript without a trailing comma, a single object (an ellipsis, a slice or any other object) is passed to the resulting __getitem__ or __setitem__ call. If the list consists of many subscripts, or of a single subscript with a trailing comma, a tuple is passed to the resulting __getitem__ or __setitem__ call, with an item for each subscript. Here is the formal definition of the grammar: :: trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME subscriptlist: subscript (',' subscript)* [','] subscript: '.' '.' '.' | test | [test] ':' [test] [sliceop] sliceop: ':' [test] This PEP suggests to allow an empty subscript list, with nothing inside the square brackets. It will result in passing an empty tuple to the resulting __getitem__ or __setitem__ call. The change in the grammar is to make "subscriptlist" in the first quoted line optional: :: trailer: '(' [arglist] ')' | '[' [subscriptlist] ']' | '.' NAME Motivation ========== This suggestion allows you to refer to zero-dimensional arrays elegantly. In NumPy, you can have arrays with a different number of dimensions. In order to refer to a value in a two-dimensional array, you write ``a[i, j]``. In order to refer to a value in a one-dimensional array, you write ``a[i]``. You can also have a zero-dimensional array, which holds a single value (a scalar). To refer to its value, you currently need to write ``a[()]``, which is unexpected - the user may not even know that when he writes ``a[i, j]`` he constructs a tuple, so he won't guess the ``a[()]`` syntax. If the suggestion is accepted, the user will be able to write ``a[]`` in order to refer to the value, as expected. It will even work without changing the NumPy package at all! In the normal use of NumPy, you usually don't encounter zero-dimensional arrays. However, the author of this PEP is designing another library for managing multi-dimensional arrays of data. Its purpose is similar to that of a spreadsheet - to analyze data and preserve the relations between a source of a calculation and its destination. In such an environment you may have many multi-dimensional arrays - for example, the sales of several products over several time periods. But you may also have several zero-dimensional arrays, that is, single values - for example, the income tax rate. It is desired that the access to the zero-dimensional arrays will be consistent with the access to the multi-dimensional arrays. Just using the name of the zero-dimensional array to obtain its value isn't going to work - the array and the value it contains have to be distinguished. Rationale ========= Passing an empty tuple to the __getitem__ or __setitem__ call was chosen because it is consistent with passing a tuple of n elements when a subscript list of n elements is used. Also, it will make NumPy and similar packages work as expected for zero-dimensional arrays without any changes. Another hint for consistency: Currently, these equivalences hold: :: x[i, j, k] <--> x[(i, j, k)] x[i, j] <--> x[(i, j)] x[i, ] <--> x[(i, )] x[i] <--> x[(i)] If this PEP is accepted, another equivalence will hold: :: x[] <--> x[()] Backwards Compatibility ======================= This change is fully backwards compatible, since it only assigns a meaning to a previously illegal syntax. Reference Implementation ======================== Available as SF Patch no. 1503556. (and also in http://python.pastebin.com/768317 ) It passes the Python test suite, but currently doesn't provide additional tests or documentation. Copyright ========= This document has been placed in the public domain. From girish at cse.iitb.ac.in Tue Jun 13 03:23:04 2006 From: girish at cse.iitb.ac.in (Girish Sahani) Date: Tue, 13 Jun 2006 12:53:04 +0530 (IST) Subject: Getting "TypeError:list indices must be integers" In-Reply-To: <448E6466.10908@lexicon.net> References: <448E6466.10908@lexicon.net> Message-ID: <52271.10.209.4.1.1150183384.squirrel@10.105.1.3> > On 13/06/2006 4:11 PM, Girish Sahani wrote: > [snip] >> instance = ti2(k) >> tiNew = ti1.append(instance) > > ti2 is quacking "function" but ti1 is quacking "list". > > Possibilities: > (1) You meant to type ti2[k] ... and this section of code has not yet > been executed, and would have featured as episode N+1 had morbid > curiosity not led me to read further. That is corrected. I'm appending a particular element of ti2 to ti1. It hasnt been executed because i'm stuck on that TypeError since 2 hours :( (2) You have the weirdest system of choosing names that I have seen for > decades. :(( > (3) Both of the above. > > Cheers, > John > From edreamleo at charter.net Thu Jun 29 12:39:08 2006 From: edreamleo at charter.net (Edward K. Ream) Date: Thu, 29 Jun 2006 11:39:08 -0500 Subject: Leo 4.4.1 beta 3 released Message-ID: Leo 4.4.1 beta 3 is now available at: http://sourceforge.net/project/showfiles.php?group_id=3458&package_id=29106 This release corrects several long-standing bugs and adds optional flashing of matching brackets. Leo is a text editor, data organizer, project manager and much more. See: http://webpages.charter.net/edreamleo/intro.html The highlights of Leo 4.4.1: ---------------------------- - Multiple editors in Leo's body pane. - Search commands now support regex replace patterns: \1, \2, etc. - Support for external debuggers: see http://webpages.charter.net/edreamleo/debuggers.html - The scripting plugin now creates a Debug Script button. - New commands including run-unit-test, python-help and toggle-invisibles. Links: ------ 4.4.1: http://webpages.charter.net/edreamleo/new-4-4-1.html 4.4: http://webpages.charter.net/edreamleo/new-4-4.html Leo: http://webpages.charter.net/edreamleo/front.html Home: http://sourceforge.net/projects/leo/ Download: http://sourceforge.net/project/showfiles.php?group_id=3458 CVS: http://leo.tigris.org/source/browse/leo/ Quotes: http://webpages.charter.net/edreamleo/testimonials.html -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From JohnJohnUSA at hotmail-dot-com.no-spam.invalid Fri Jun 30 22:52:06 2006 From: JohnJohnUSA at hotmail-dot-com.no-spam.invalid (JohnJohnUSA) Date: 01 Jul 2006 02:52:06 GMT Subject: Maximize main window with code Message-ID: <44a5e356$0$14238$892e7fe2@authen.yellow.readfreenews.net> I am new to Python. How do I get the following program to appear initially with the window maximized? Thanks for your help! from Tkinter import * # set up the window itself top = Tk() F = Frame(top) F.pack() # add the widgets lHello = Label(F, text="Hello") lHello.pack() bQuit = Button(F, text="Quit", command=F.quit) bQuit.pack() # set the loop running top.mainloop() From girish at cse.iitb.ac.in Thu Jun 22 04:07:07 2006 From: girish at cse.iitb.ac.in (Girish Sahani) Date: Thu, 22 Jun 2006 13:37:07 +0530 (IST) Subject: How to generate all permutations of a string? Message-ID: <53564.10.209.4.1.1150963627.squirrel@10.105.1.3> Hi guys, I want to generate all permutations of a string. I've managed to generate all cyclic permutations. Please help :) def permute(string): l= [] l.append(string) string1 = '' for i in range(0,len(string)-1,1): string1 = string[1:len(string)] + string[:1] l.append(string1) string = string1 return l From gandalf at designaproduct.biz Wed Jun 7 09:29:23 2006 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Wed, 07 Jun 2006 15:29:23 +0200 Subject: secure xmlrpc server? In-Reply-To: <4486d1e9$0$31646$e4fe514c@news.xs4all.nl> References: <4486c6ee$0$31647$e4fe514c@news.xs4all.nl> <4486d1e9$0$31646$e4fe514c@news.xs4all.nl> Message-ID: <4486D4B3.8020502@designaproduct.biz> Martin P. Hellwig ?rta: > Laszlo Nagy wrote: > >> Martin P. Hellwig wrote: >> >>> Laszlo Nagy wrote: >>> >>> Have a look at: >>> http://trevp.net/tlslite/ >>> >>> >> C:\temp\ccc>python setup.py install >> running install >> running build >> running build_py >> running build_ext >> error: The .NET Framework SDK needs to be installed before building >> extensions f >> or Python. >> >> C:\temp\ccc> >> >> > > In the installers directory is exe for windows installation. > http://trevp.net/tlslite/ - no exe installers. http://sourceforge.net/projects/tlslite/ - no file packages to download :-( > SimpleXMLRPCServer uses SimpleHTTPServer for its transfer stuff, so you > might want to look more in that direction. > Yes, In fact I read the whole source code of SimpleXMLRPCServer and other examples like http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81549 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/165375 but I cannot combine the two. I see that the request handler is a customised HTTP request handler: class SimpleXMLRPCRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): but I have no idea how to use it with https. Do you know a small example (like the ones above)? That would help a lot. Laszlo From fredrik at pythonware.com Sat Jun 10 16:08:42 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 10 Jun 2006 22:08:42 +0200 Subject: Questions about extending Python... In-Reply-To: <1149968921.972194.153430@c74g2000cwc.googlegroups.com> References: <1149968921.972194.153430@c74g2000cwc.googlegroups.com> Message-ID: malv wrote: > Over the years, many posts (and questions) have come up on dynamically > importing and reloading modules and the inadequacy of the now available > import and reload() features. and this is related to extending Python with code from existing C libraries in exactly what way ? > Reading Coplien may further the cause of this very basic missing > requirement in Python, so, what are you waiting for ? just do it, and post a patch when you're done. From m.yanowitz at kearfott.com Mon Jun 26 08:47:08 2006 From: m.yanowitz at kearfott.com (Michael Yanowitz) Date: Mon, 26 Jun 2006 08:47:08 -0400 Subject: SWIG problems with gcc and Cygwin? In-Reply-To: Message-ID: No response yet. The SWIG test works fine in Linux no problems. However, I still have the problem in Cygwin. Also, not sure if related but I do have a win32 Python 2.4.3 and Cygwin Python 2.4.1. Not sure if there are any conflicts. Any advice in making these two co-exist? The only C/C++ compiler I have presently is Cygwin gcc. Thanks in advance: Michael Yanowitz -----Original Message----- From: python-list-bounces+m.yanowitz=kearfott.com at python.org [mailto:python-list-bounces+m.yanowitz=kearfott.com at python.org]On Behalf Of Michael Yanowitz Sent: Tuesday, June 20, 2006 3:39 PM To: python-list at python.org Subject: SWIG problems with gcc and Cygwin? Hello: I am just trying out SWIG, but quickly ran into problems. Using Cygwin gcc, I tried the following: 1) Created example.c (as given on http://www.swig.org/tutorial.html ) /* File : example.c */ #include double My_variable = 3.0; int fact(int n) { if (n <= 1) return 1; else return n*fact(n-1); } int my_mod(int x, int y) { return (x%y); } char *get_time() { time_t ltime; time(<ime); return ctime(<ime); } 2) Create interface file, example.i /* example.i */ %module example %{ /* Put header files here or function declarations like below */ extern double My_variable; extern int fact(int n); extern int my_mod(int x, int y); extern char *get_time(); %} extern double My_variable; extern int fact(int n); extern int my_mod(int x, int y); extern char *get_time(); 3)ran in cygwin: swig -i python example.i 4)Attempted to run on cygwin: ld -shared example.o example_wrap.o -o _example.so But got back many errors: example.o:example.c:(.text+0x55): undefined reference to `time' example.o:example.c:(.text+0x60): undefined reference to `ctime' example_wrap.o:example_wrap.c:(.text+0x9c): undefined reference to `strlen' example_wrap.o:example_wrap.c:(.text+0x12c): undefined reference to `strlen' example_wrap.o:example_wrap.c:(.text+0x1dd): undefined reference to `strcmp' example_wrap.o:example_wrap.c:(.text+0x494): undefined reference to `strcmp' example_wrap.o:example_wrap.c:(.text+0x748): undefined reference to `strlen' example_wrap.o:example_wrap.c:(.text+0x779): undefined reference to `strcpy' example_wrap.o:example_wrap.c:(.text+0x7a5): undefined reference to `strcmp' example_wrap.o:example_wrap.c:(.text+0x805): undefined reference to `strlen' example_wrap.o:example_wrap.c:(.text+0x877): undefined reference to `strncpy' example_wrap.o:example_wrap.c:(.text+0x8ab): undefined reference to `strcmp' example_wrap.o:example_wrap.c:(.text+0x8c9): undefined reference to `memset' example_wrap.o:example_wrap.c:(.text+0x948): undefined reference to `fputs' example_wrap.o:example_wrap.c:(.text+0x95d): undefined reference to `fputs' example_wrap.o:example_wrap.c:(.text+0x970): undefined reference to `fputs' example_wrap.o:example_wrap.c:(.text+0x9db): undefined reference to `PyString_Fr omFormat' example_wrap.o:example_wrap.c:(.text+0xa3a): undefined reference to `PyString_Fr omString' example_wrap.o:example_wrap.c:(.text+0xa68): undefined reference to `PyLong_From VoidPtr' example_wrap.o:example_wrap.c:(.text+0xa83): undefined reference to `PyTuple_New etc... Any idea what I am doing wrong or omitted? Of course when I then try to go into python and import example, I get: >>> import example Traceback (most recent call last): File "", line 1, in ? File "example.py", line 5, in ? import _example ImportError: No module named _example Thanks in advance: Michael Yanowitz -- http://mail.python.org/mailman/listinfo/python-list From jes at nl.demon.net Thu Jun 1 16:14:09 2006 From: jes at nl.demon.net (Jim Segrave) Date: Thu, 01 Jun 2006 20:14:09 -0000 Subject: An oddity in list comparison and element assignment References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> <127u81kdf70ch8d@corp.supernews.com> <1149186735.650036.62670@i39g2000cwa.googlegroups.com> Message-ID: <127uikhii16hpf0@corp.supernews.com> In article <1149186735.650036.62670 at i39g2000cwa.googlegroups.com>, wrote: >Yes. You stated it quite precisely. I believe l1==l2 should always >return True and l1==l3 should always be False. (unless l3 is reassigned >as l3=l1). Your idea of a separate operator for 'all elements have >numerically equal values at the moment of comparision' is a good one. >For want of a better name, it could be called DeepCopyEquality(a,b) and >would be equivalent to a byte-by-byte comparison of two distinct >regions in memory created by a deep copies of a and b. The operator which works at the moment of comaprision is already there - that's what == does. If you really think there's a need for a comparision which includes dealing with aliasing, then it seems to me a python module with a set of functions for comparisions would make more sense. -- Jim Segrave (jes at jes-2.demon.nl) From no-spam at no-spam-no-spam.com Wed Jun 7 09:37:54 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Wed, 07 Jun 2006 15:37:54 +0200 Subject: what are you (not) using python language for? In-Reply-To: References: Message-ID: hacker1017 wrote: > im just asking out of curiosity. > I am curious for what kind of (new) serious programs and projects the Python language and its offsprings like Pyrex would not be the optimal programming language currently? (Unless you completely misbelieve in Ruby) Device drivers, small memory mics and browser client software - areas which (still) lack Python support ? -robert From pc at p-cos.net Wed Jun 21 03:42:22 2006 From: pc at p-cos.net (Pascal Costanza) Date: Wed, 21 Jun 2006 09:42:22 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: <2N3mg.462963$xt.331923@fe3.news.blueyonder.co.uk> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <4fpvbvF1keed1U1@individual.net> <4fqonoF1kfkapU1@individual.net> <1150824752.799997.206210@p79g2000cwp.googlegroups.com> <4fqt33F1kfd1jU1@individual.net> <2N3mg.462963$xt.331923@fe3.news.blueyonder.co.uk> Message-ID: <4fsbivF1jqb81U1@individual.net> David Hopwood wrote: > Pascal Costanza wrote: >> Rob Thorpe wrote: >>> Pascal Costanza wrote: >>>> Matthias Blume wrote: >>>>> Pascal Costanza writes: >>>>> >>>>>> (slot-value p 'address) is an attempt to access the field 'address in >>>>>> the object p. In many languages, the notation for this is p.address. >>>>>> >>>>>> Although the class definition for person doesn't mention the field >>>>>> address, the call to (eval (read)) allows the user to change the >>>>>> definition of the class person and update its existing >>>>>> instances. Therefore at runtime, the call to (slot-value p 'adress) >>>>>> has a chance to succeed. >>>>> I am quite comfortable with the thought that this sort of evil would >>>>> get rejected by a statically typed language. :-) >>>> This sort of feature is clearly not meant for you. ;-P >>> To be fair though that kind of thing would only really be used while >>> debugging a program. >>> Its no different than adding a new member to a class while in the >>> debugger. >>> >>> There are other places where you might add a slot to an object at >>> runtime, but they would be done in tidier ways. >> Yes, but the question remains how a static type system can deal with >> this kind of updates. > > It's not difficult in principle: > > - for each class [*], define a function which converts an 'old' value of > that class to a 'new' value (the ability to do this is necessary anyway > to support some kinds of upgrade). A default conversion function may be > autogenerated if the class definition has changed only in minor ways. Yep, this is more or less exactly how CLOS does it. (The conversion function is called update-instance-for-redefined-class, and you can provide your own methods on it.) > - typecheck the new program and the conversion functions, using the old > type definitions for the argument of each conversion function, and the > new type definitions for its result. The problem here is: The program is already executing, so this typecheck isn't performed at compile-time, in the strict sense of the word (i.e., before the program is deployed). It may still be a syntactic analysis, but you don't get the kind of guarantees anymore that you typically expect from a static type checker _before_ the program is started in the first place. (It's really important to understand that the idea is to use this for deployed programs - albeit hopefully in a more structured fashion - and not only for debugging. The example I have given is an extreme one that you would probably not use as such in a "real-world" setting, but it shows that there is a boundary beyond which static type systems cannot be used in a meaningful way anymore, at least as far as I can tell.) > - have the debugger apply the conversions to all values, and then resume > the program. In CLOS, this conversion is defined as part of the language proper, but this is mostly because Common Lisp doesn't make a sharp distinction between debugging capabilities and "regular" language features. (I think it's a good thing that there is no strong barrier against having debugging capabilities in a deployed program.) > [*] or nearest equivalent in a non-OO language. Pascal -- 3rd European Lisp Workshop July 3 - Nantes, France - co-located with ECOOP 2006 http://lisp-ecoop06.bknr.net/ From neuruss at gmail.com Thu Jun 1 23:07:07 2006 From: neuruss at gmail.com (Neuruss) Date: 1 Jun 2006 20:07:07 -0700 Subject: C# equivalent to range() In-Reply-To: References: <1149214153.359809.288610@i39g2000cwa.googlegroups.com> Message-ID: <1149217627.026986.215280@i39g2000cwa.googlegroups.com> Thank you DH!! D H wrote: > Neuruss wrote: > > I'm sorry for asking about another language here, but since I only know > > Python and I'm trying to write something in C#, I guess this is the > > best place... > > > > I'd like to know how to write this in C#: > > > > x=[] > > sz = 10000000 > > x.extend(range(sz)) > > > > My question is about "range" and "extend". Is there any equivalent in > > C#? > > > > Thanks in advance, > > Neuruss > > > > List mylist = new List(); > for (int i=0; i<10000000; i++) > { > mylist.Add(i); > } > > You can use AddRange, C# 2.0 anonymous delegates, IEnumerable, yield, > foreach, and so forth instead, but for your example this is simplest. > > Another option is to use boo. http://boo.codehaus.org/ > It uses python's syntax but is as fast as C#. The only change you'd > have to make in that code is to capitalize the Extend method call. From aleax at mac.com Fri Jun 23 11:21:39 2006 From: aleax at mac.com (Alex Martelli) Date: Fri, 23 Jun 2006 08:21:39 -0700 Subject: Absolute noob to Linux programming needs language choice help References: <1150854682.904891.274480@c74g2000cwc.googlegroups.com> Message-ID: <1hhdlmq.xxmlwo27govgN%aleax@mac.com> wrote: > Hey guys, > > I am absolutely new to Linux programming, with no w######s programming > experience except a small amount of C++ console apps. > Reasonably new to Linux, BSD etc, got good sound networking base of > knowledge and dont have any problem working the command line etc. > > I want to learn a language that I can use in my networking duties that > is most likely to be of use to me. I have a few choices I can think of > being: > > Python > Perl > C > > Any other Langs out there that would be better suited? > > I want to be able to use the app's I write in OpenBSD and RH versions > of Linux > > What would you reccomend (Unbiased opinion please, I'm after the > functionality I'll love it later :) ) C is extremely low-level -- you'll want to know it well if you ever need to program something inside the kernel (or study kernel sources to understand some detail or anomaly), but for general programming it's a lot of unwarranted effort. Python, Perl, and a third language you have not mentioned, Ruby, are very high level, and each is suitable for just about the same range of programming (almost any programming, except very low-level;-). The choice between the three cannot really be based on language level or power because those aspects essentially coincide; rather, you should choose based on your tastes, and practical considerations such as the availability of libraries and other tools (which tends to be excellent for all three languages, so it's unlikely to guide your choice all that much). If you want to make sure you have no regrets later, a minimal amount of study of all three is warranted before you pick one to get deeper into, IMHO. Me, I knew the Perl of the time very well when I met Python, and I've studied Ruby later -- Python definitely meets _my_ needs optimally; but other people, with very different tastes, could well choose differently! Alex From durumdara at gmail.com Fri Jun 16 10:02:13 2006 From: durumdara at gmail.com (Dara Durum) Date: Fri, 16 Jun 2006 16:02:13 +0200 Subject: Duplex communication with pipes - is possible ? Message-ID: <9e384ef60606160702h1d9dc577m@mail.gmail.com> Hi ! I want to create a Process Pool Object. I can hold started processes, and can communicate with them. I tryed with many ipc methods, but every of them have bug or other problem. Sockets are unavailabe (because Windows Firewall hold them). I think I will use pipe. The object's pseudocode: while not Quit: CheckProcessOutputs; ProcessReceivedData; SendDataToSubProcesses; if NoMoreData: Quit=1 If I used pipes and subprocess module in Windows, I got big freezes, and deadlocks. Main proc: subprocpipe.write('aaaa\n') subprocpipe.readlines() Sub proc: input=sys.stdin.readlines().strip() print input+'!!!' It is working. But when I move this client code to cycle, I got deadlock. while not Quit: input=sys.stdin.readlines().strip() print input+'!!!' Quit=input=='q' Why ? Why I cannot create cyclic communication with client ? Subprocess must "staying alive" (don't die), and need to stay in reuseable state ? Simply: subprocess pool needed !!! Thanks for help: dd From will at willNOmcguganSPAM.com Sun Jun 18 13:53:18 2006 From: will at willNOmcguganSPAM.com (Will McGugan) Date: Sun, 18 Jun 2006 18:53:18 +0100 Subject: Chess module blog Message-ID: <44959310$0$1228$db0fefd9@news.zen.co.uk> Hi folks, I have just blogged about a Python chess module of mine that I wrote a while back. I plan on using it for a commerical project, but making the module open source. So I would be interested in comments / advice reagarding programming style and also optimization. http://www.willmcgugan.com/2006/06/18/chesspy/ Regards, Will McGugan -- work: http://www.kelpiesoft.com blog: http://www.willmcgugan.com From klaus at seistrup.dk Thu Jun 22 11:31:22 2006 From: klaus at seistrup.dk (Klaus Alexander Seistrup) Date: Thu, 22 Jun 2006 15:31:22 +0000 (UTC) Subject: Blog source code in Python References: <1150989366.242671.254300@g10g2000cwb.googlegroups.com> Message-ID: Lazy Lad wrote: > Is there a blog application source available in Python? Several. Did you try Google before you posted your question? The search term "python blog" has within the first 10 hits. Cheers, -- Klaus Alexander Seistrup Copenhagen, Denmark http://surdej.dk/ From iainking at gmail.com Wed Jun 28 11:48:02 2006 From: iainking at gmail.com (Iain King) Date: 28 Jun 2006 08:48:02 -0700 Subject: String Question In-Reply-To: <1151508909.273667.270910@x69g2000cwx.googlegroups.com> References: <1151508909.273667.270910@x69g2000cwx.googlegroups.com> Message-ID: <1151509682.897441.165480@y41g2000cwy.googlegroups.com> diffuser78 at gmail.com wrote: > mac_string = '001485e55503' (This is the mac address of a computer.) > > I am using wake on LAN python script to start computer remote.It uses > format like this .... > > s.sendto('\xff'*6 + '\x00\x014\x85\xe5\x55\x03'*16, ('192.168.1.255', > 80)) > > where '\x00\x14\x85\xe5\x55\x03' is the MAC address to be used. > > > What I do is break the string into 6 parts like this, > > str01=mac_string[0:2] > str02=mac_string[2:4] > str03=mac_string[4:6] > str04=mac_string[6:8] > str05=mac_string[8:10] > str06=mac_string[10:12] > > and if I use it like this > > s.sendto('\xff'*6 + '\xstr01\xstr02\xstr03\xstr04\xstr05\xstr06'*16, > ('192.168.1.255', 80)) > I get an error > > > I also tried like this > s.sendto('\xff'*6 + 'mac_string'*16, ('192.168.1.255', 80)) > > Thiis also didnt work. > > > Since the MAC adddress are hexadecimal, how should I go about it here. > > Please help, every help is appreciated. Thanks See http://docs.python.org/lib/typesseq-strings.html You probably want: s.sendto('\xff'*6 + ('\x%s\x%s\x%s\x%s\x%s\x%s' % (str01, str02, str03, sttr04, str05, str06))*16, ('192.168.1.255', 80)) Iain From juergen.huber at kirchnersoft.com Fri Jun 30 10:06:25 2006 From: juergen.huber at kirchnersoft.com (Juergen Huber) Date: Fri, 30 Jun 2006 16:06:25 +0200 Subject: print shell output in a file Message-ID: <44a52fdb$0$3892$91cee783@newsreader01.highway.telekom.at> hello, one more question i will have! now i have written a little programm, which delivers me an output on the shell! here is the print command, which delivers me the following output (see below) on the shell: print '%-30s | %-12d | %-12d |%-12d ' % (typename, size / count, count, size) --------------NAME-------------|Groesse(Byte)-|----Anzahl----|-Gesamtgroesse (Byte)-| ---------------------------------------------------------------------------- ---------- ADD_REAL_N6 | 4 | 1 |4 AND_BOOL_N10 | 4 | 1 |4 AND_BOOL_N12 | 4 | 1 |4 Is there a way to put this output in an file?!?! i searched about 2h for this, but i couldn`t find an answer! thnks, juergen From pc at p-cos.net Tue Jun 20 06:01:34 2006 From: pc at p-cos.net (Pascal Costanza) Date: Tue, 20 Jun 2006 12:01:34 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: <1150765102.867144.12590@h76g2000cwa.googlegroups.com> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> Message-ID: <4fpvbvF1keed1U1@individual.net> Marshall wrote: > The conversation I would *really* like to have is the one where we > discuss what all the differences are, functionally, between the two, > and what the implications of those differences are, without trying > to address which approach is "right" or "better", because those are > dependent on the problem domain anyway, and because I can > make up my own mind just fine about which one I prefer. My current take on this is that static typing and dynamic typing are incompatible, at least in their "extreme" variants. The simplest examples I have found are this: - In a statically typed language, you can have variables that contain only first-class functions at runtime that are guaranteed to have a specific return type. Other values are rejected, and the rejection happens at compile time. In dynamically typed languages, this is impossible because you can never be sure about the types of return values - you cannot predict the future. This can at best be approximated. - In a dynamically typed language, you can run programs successfully that are not acceptable by static type systems. Here is an example in Common Lisp: ; A class "person" with no superclasses and with the only field "name": (defclass person () (name)) ; A test program: (defun test () (let ((p (make-instance 'person))) (eval (read)) (slot-value p 'address))) (slot-value p 'address) is an attempt to access the field 'address in the object p. In many languages, the notation for this is p.address. Although the class definition for person doesn't mention the field address, the call to (eval (read)) allows the user to change the definition of the class person and update its existing instances. Therefore at runtime, the call to (slot-value p 'adress) has a chance to succeed. (Even without the call to (eval (read)), in Common Lisp the call to (slot-value p 'address) would raise an exception which gives the user a chance to fix things and continue from the point in the control flow where the exception was raised.) I cannot imagine a static type system which has a chance to predict that this program can successfully run without essentially accepting all kinds of programs. At least, development environments for languages like Smalltalk, Common Lisp, Java, etc., make use of such program updates to improve edit-compile-test cycles. However, it is also possible (and done in practice) to use such program updates to minimize downtimes when adding new features to deployed systems. Pascal -- 3rd European Lisp Workshop July 3 - Nantes, France - co-located with ECOOP 2006 http://lisp-ecoop06.bknr.net/ From deets at nospam.web.de Sun Jun 25 11:26:28 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 25 Jun 2006 17:26:28 +0200 Subject: MSoffice metadata In-Reply-To: <1151209771.276872.299240@b68g2000cwa.googlegroups.com> References: <1151209771.276872.299240@b68g2000cwa.googlegroups.com> Message-ID: <4g7o8tF1lqt6dU1@uni-berlin.de> micklee74 at hotmail.com schrieb: > hi > is there a module in Python to extract metadata in MS office documents You can automate MS Office using the python win32 com extensions of Mark Hammond. They come bundled with the active-state python build, or can be obtained separately. Diez From bborcic at gmail.com Fri Jun 9 07:01:00 2006 From: bborcic at gmail.com (Boris Borcic) Date: Fri, 09 Jun 2006 13:01:00 +0200 Subject: How to generate k+1 length strings from a list of k length strings? In-Reply-To: <44883789$1_4@news.bluewin.ch> References: <44883789$1_4@news.bluewin.ch> Message-ID: <4489550c$1_3@news.bluewin.ch> > Hum, since your code is not syntactically correct, anything will run > faster :) in fact it parses, I was fooled by this line >> if k in range(1,len(prunedK),1) & i+k <= len(prunedK) -1: I was fooled because the form "k in range(" tends to imply a for statement ; in the case of an if statement, one usually uses chained comparisons instead. If you know i>=0 and i,k are integers (as is implied by context), you could simply write something like: if 0 < k < i+k < len(prunedK) : in the contrary case, assuming your line does what you want, you should really write it as if 1 <= k < len(prunedK) and i+k <= len(prunedK)-1 : or more concisely if 1 <= k < len(prunedK) >= i+k+1 : or even if i+k < len(prunedK) > k > 0 : From matt at overlook.homelinux.net Wed Jun 21 17:15:49 2006 From: matt at overlook.homelinux.net (Matthew Wilson) Date: Wed, 21 Jun 2006 21:15:49 GMT Subject: random.jumpahead: How to jump ahead exactly N steps? Message-ID: The random.jumpahead documentation says this: Changed in version 2.3: Instead of jumping to a specific state, n steps ahead, jumpahead(n) jumps to another state likely to be separated by many steps.. I really want a way to get to the Nth value in a random series started with a particular seed. Is there any way to quickly do what jumpahead apparently used to do? I devised this function, but I suspect it runs really slowly: def trudgeforward(n): '''Advance the random generator's state by n calls.''' for _ in xrange(n): random.random() So any speed tips would be very appreciated. TIA -- A better way of running series of SAS programs: http://overlook.homelinux.net/wilsonwiki/SasAndMakefiles From bj_666 at gmx.net Mon Jun 19 11:51:06 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 19 Jun 2006 17:51:06 +0200 Subject: pyfcp References: Message-ID: In , aum wrote: > On Mon, 19 Jun 2006 14:45:19 +0800, Thomas Moore wrote: > >>> http://www.python.org/pyfcp >>> >> >> It gets me to Error 404. > > Apologies - that URL should have been: > > http://www.python.org.nz/pyfcp I get: Unknown host www.python.org.nz Ciao, Marc 'BlackJack' Rintsch From fredrik at pythonware.com Thu Jun 15 13:46:29 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 15 Jun 2006 19:46:29 +0200 Subject: Which compiler will Python 2.5 / Windows (Intel) be built with? In-Reply-To: <1150391891.130185.4640@f6g2000cwb.googlegroups.com> References: <1150367139.495114.148550@g10g2000cwb.googlegroups.com> <44917535$1@nntp0.pdx.net> <1150391891.130185.4640@f6g2000cwb.googlegroups.com> Message-ID: meyer at mesw.de wrote: > the problem is not the ABI, but the runtime libraries. From what you're > saying, it looks like we will have to standardize on VS2003. As I said, > we need to buy VS anyway because of the MFC support. On the other hand, > I really worry about all those people that want to build open source > extensions for Python 2.5. It is really possible that there will be no > legal, free way to do that soon if you don't have an old installation > of the 2003 toolkit lying around somewhere... So I'd like to ask you: > why was the decision taken a while ago (and is not subject to > reconsideration) and what are the reasons for using VS2003? I mean > there must be a real good reason why you're doing this, as I only see > disadvantages in it. hint: most people who provide third-party extensions to Python support more than just the latest Python version... From jarrod.roberson at gmail.com Tue Jun 6 22:43:07 2006 From: jarrod.roberson at gmail.com (fuzzylollipop) Date: 6 Jun 2006 19:43:07 -0700 Subject: 10GB XML Blows out Memory, Suggestions? In-Reply-To: References: <1149594519.098115.8980@u72g2000cwu.googlegroups.com> <4eleh3F1eguosU1@uni-berlin.de> Message-ID: <1149648187.891942.258300@i40g2000cwc.googlegroups.com> K.S.Sreeram wrote: > Diez B. Roggisch wrote: > > What the OP needs is a different approach to XML-documents that won't > > parse the whole file into one giant tree - but I'm pretty sure that > > (c)ElementTree will do the job as well as expat. And I don't recall the > > OP musing about performances woes, btw. > > > There's just NO WAY that the 10gb xml file can be loaded into memory as > a tree on any normal machine, irrespective of whether we use C or > Python. So the *only* way is to perform some kind of 'stream' processing > on the file. Perhaps using a SAX like API. So (c)ElementTree is ruled > out for this. > > Diez B. Roggisch wrote: > > No what exactly makes C grok a 10Gb file where python will fail to do so? > > In most typical cases where there's any kind of significant python code, > its possible to achieve a *minimum* of a 10x speedup by using C. In most > cases, the speedup is not worth it and we just trade it for the > increased flexiblity/power of the python language. But in this situation > using a bit of tight C code could make the difference between the > process taking just 15mins or taking a few hours! > > Ofcourse I'm not asking him to write the entire application in C. It > makes sense to just write the performance critical sections in C, and > wrap it in Python, and write the rest of the application in Python. you got no idea what you are talking about, anyone knows that something like this is IO bound. CPU is the least of his worries. And for IO bound applications Python is just as fast as any other language. From kay.schluehr at gmx.net Thu Jun 22 16:43:36 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 22 Jun 2006 13:43:36 -0700 Subject: Status of optional static typing in Python? In-Reply-To: References: Message-ID: <1151009015.966187.325270@p79g2000cwp.googlegroups.com> Christian Convey wrote: > Hi guys, > > I'm looking at developing a somewhat complex system, and I think some > static typing will help me keep limit my confusion. I.e.: > > http://www.artima.com/weblogs/viewpost.jsp?thread=87182 > > Does anyone know if/when that feature may become part of Python? > > Thanks very much, > Christian It was discussed recently at the Python 3000 mailing list and it seems that the goals are not very ambitious but this was already clear from Guidos Artima blog post you cited. So it may happen that type annotation syntax in function signatures will be introduced in Py3K but the semantics is reduced to a "protocol" i.e. Python will still be untyped in a strict sense ( or dynamically type checked to put it more positive ). An proposed alternative for type annotation syntax and runtime type-checks that comes up from time to time is using decorators for this job. Here is a recipe that might be usefull in your project right now: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/426123 Regards, Kay From wahab at chemie.uni-halle.de Fri Jun 16 15:21:17 2006 From: wahab at chemie.uni-halle.de (Mirco Wahab) Date: Fri, 16 Jun 2006 21:21:17 +0200 Subject: Extracting values from text file In-Reply-To: References: Message-ID: Thus spoke Preben Randhol (on 2006-06-16 10:36): > A short newbie question. I would like to extract some values from a > given text file directly into python variables. Can this be done simply > by either standard library or other libraries? Some pointers where to > get started would be much appreciated. I used your example just to try that in python (i have to improve my python skills), but waved the white flag after realizing that there's no easy string/var-into-string interpolation. I tried to build some parser table which will then translate hings into a dictionary v_apples = '\b\S+'; v_ducks = '\b\S+'; v_butter = '\b\S+'; rg_ar = [ "Apples (v_apples)" , "(v_ducks) Ducks" , "(v_butter) butter" ] the above interpolation won't work, so I gave up. To give an idea what I intended, I'll add the short perl script which I took as a blue print for my python effort (your example text may be used): my @filter = ( # define filter table "Apples (apples)", "(ducks) Ducks", "(butter) g butter", ); my %varname = (); # variable names will be found in text my $example = do { local$/; }; # read the appended example text # change to <> for std input for (@filter) { # iterate over filter rules if( s/\((.+)\)/\\b(\\S+?)\\b/ ) { # pull out variable names ($1) my $v = $1; # and replace them by '\b(\S)\b' $varname{$v} = $1 if $example =~ /$_/; # pull values from } # text to varnames } your text prints then: (for (keys %varname) { print "$_\t=>\t$varname{$_}\n"; }) apples => 34 butter => 0.5 ducks => 56 with variable names taken from your text: __DATA__ An example text file: ----------- Some text that can span some lines. Apples 34 56 Ducks Some more text. 0.5 g butter ----------------- Above will do the job in perl, but I have no idea how to translate this to python, especially, as I said, the string-to-string interpolation thing for the build-up regex. Maybe some experts may help out? Regards Mirco From dongdonglove8 at hotmail.com Sun Jun 4 08:10:26 2006 From: dongdonglove8 at hotmail.com (python) Date: 4 Jun 2006 05:10:26 -0700 Subject: in python , could I accomplish the purpose that "a=Console.read()" used in C? Message-ID: <1149423026.134144.58940@i40g2000cwc.googlegroups.com> in python , could I accomplish the purpose that "a=Console.read()" used in C? when program is running, I wanna add a statement like "a=Console.read()" in C language,it will wait for user's input, after user's typing a character , and click "enter" key, the program will go on running. From fredrik at pythonware.com Wed Jun 28 04:41:40 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 28 Jun 2006 10:41:40 +0200 Subject: How to disable tk inclusion in py build References: <1151422992.208936.54600@j72g2000cwa.googlegroups.com> <1151436404.809094.220650@j72g2000cwa.googlegroups.com> Message-ID: venkatbo at yahoo.com wrote: >> since _tkinter.so is only built if it's found by the setup script, >> and if built, it's only loaded if you actually use it, why bother >> "disabling" it ? > > I don't want it to build tk into the py dist, even if it finds it on > the build box - its not needed in the deployment. Keeping it > out will make the deployed pkg leaner. so don't deploy it. if you want a lean package, you should use a deployment script that copies the stuff you need; relying on the build process isn't very reliable (and means more work when it's time to upgrade to a newer Python). From dsandrade at gmail.com Wed Jun 28 10:05:53 2006 From: dsandrade at gmail.com (Douglas Andrade) Date: Wed, 28 Jun 2006 11:05:53 -0300 Subject: MySQLdb not updating rows In-Reply-To: <1151502414.717043.234520@d56g2000cwd.googlegroups.com> References: <1151500514.817456.65510@d56g2000cwd.googlegroups.com> <1151502414.717043.234520@d56g2000cwd.googlegroups.com> Message-ID: Hello Simon, Take a look at this link: http://python.codezoo.com/pub/component/3583 May autocommit (or commit, as Fredrik pointed out) be the solution. On 28 Jun 2006 06:46:54 -0700, Bowen wrote: > > Thanks for that, it appears it was the db.commit() that sorted it > out.....lesson learnt :) > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From robert.thorpe at antenova.com Tue Jun 20 12:49:10 2006 From: robert.thorpe at antenova.com (Rob Thorpe) Date: 20 Jun 2006 09:49:10 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <1150809118.677124.142230@u72g2000cwu.googlegroups.com> <1150815461.210286.53120@r2g2000cwb.googlegroups.com> Message-ID: <1150822150.701434.296460@u72g2000cwu.googlegroups.com> Matthias Blume wrote: > "Rob Thorpe" writes: > > Andreas Rossberg wrote: > >> Rob Thorpe wrote: > >> >> > >> >>>No, that isn't what I said. What I said was: > >> >>>"A language is latently typed if a value has a property - called it's > >> >>>type - attached to it, and given it's type it can only represent values > >> >>>defined by a certain class." > >> >> > >> >>"it [= a value] [...] can [...] represent values"? > >> > > >> > ??? > >> > >> I just quoted, in condensed form, what you said above: namely, that a > >> value represents values - which I find a strange and circular definition. > > > > Yes, but the point is, as the other poster mentioned: values defined by > > a class. > > For example, in lisp: > > "xyz" is a string, #(1 2 3) is an array, '(1 2 3) is a list, 45 is a > > fixed-point number. > > Each item that can be stored has a type, no item can be stored without > > one. The types can be tested. Most dynamic typed languages are like > > that. > > Your "types" are just predicates. You can call them predicates if you like. Most people programming in python, perl, or lisp will call them types though. > > Compare this to an untyped language where types cannot generally be > > tested. > > You mean there are no predicates in untyped languages? Well, no there aren't. That's what defines a language as untyped. Of-course you can make them with your own code, in for example assembler, but that's outside the language. > >> They all have - the whole purpose of a type system is to ensure that any > >> expression of type T always evaluates to a value of type T. > > > > But it only gaurantees this because the variables themselves have a > > type, the values themselves do not. > > Of course they do. I think we're discussing this at cross-purposes. In a language like C or another statically typed language there is no information passed with values indicating their type. Have a look in a C compiler if you don't believe me. You store 56 in a location in memory then in most compilers all that will be store is 56, nothing more. The compiler relys entirely on the types of the variables to know how to correctly operate on the values. The values themselves have no type information associated with them. > > Most of the time the fact that the > > variable they are held in has a type infers that the value does too. > > But the value itself has no type, in a C program for example I can take > > the value from some variable and recast it in any way I feel and the > > language cannot correct any errors I make because their is no > > information in the variable to indicate what type it is. > > Casting in C takes values of one type to values of another type. No it doesn't. Casting reinterprets a value of one type as a value of another type. There is a difference. If I cast an unsigned integer 2000000000 to a signed integer in C on the machine I'm using then the result I will get will not make any sense. > >> So when you > >> look at type systems formally then you certainly have to assign types to > >> values, otherwise you couldn't prove any useful property about those > >> systems (esp. soundness). > > > > Yes, but indirectly. > > No, this is usually done very directly and very explicitly. No it isn't. If I say "4 is a integer" that is a direct statement about 4. If I say "X is and integer and X is 4, therefore 4 is an integer" that is a slightly less direct statement about 4. The difference in directness is only small, and much more indirectness is needed to prove anything useful about a system formally. From steven.bethard at gmail.com Thu Jun 1 15:08:32 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 01 Jun 2006 13:08:32 -0600 Subject: argmax In-Reply-To: References: Message-ID: <57SdneDWRNGypuLZRVn-tg@comcast.com> David Isaac wrote: > 2. Is this a good argmax (as long as I know the iterable is finite)? > def argmax(iterable): return max(izip( iterable, count() ))[1] In Python 2.5: Python 2.5a2 (trunk:46491M, May 27 2006, 14:43:55) [MSC v.1310 32 bit (Intel)] on win32 >>> iterable = [5, 8, 2, 11, 6] >>> import operator >>> max(enumerate(iterable), key=operator.itemgetter(1)) (3, 11) STeVe From rpdooling at gmail.com Fri Jun 2 13:47:43 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 2 Jun 2006 10:47:43 -0700 Subject: os.chdir doesn't accept variables sometimes References: <1149267516.348440.60290@u72g2000cwu.googlegroups.com> Message-ID: <1149270463.305631.22070@c74g2000cwc.googlegroups.com> >> for album in listdir(getcwd()): doesn't listdir give you subdirectories AND files? So, then if you try to: chdir(album) If album is a file, it chokes? Just a guess. I'm on Windows, not Linux. rd From jjlee at reportlab.com Mon Jun 12 18:41:20 2006 From: jjlee at reportlab.com (John J. Lee) Date: Mon, 12 Jun 2006 22:41:20 GMT Subject: what are you using python language for? References: <128b8cg1d0p7uce@corp.supernews.com> <1149637612.712298.309010@y43g2000cwc.googlegroups.com> Message-ID: <871wtuf14f.fsf@reportlab.com> mauriceling at gmail.com writes: > I am using Python to assemble a biomedical literature analysis pipeline > as part of my PhD thesis. (http://ib-dwb.sf.net/Muscorian.html) What's a literature analysis pipeline? (mental picture: fat pressurised pipe leading to big noisy wood chipper-style machine spewing out a flapping stream of stapled A4 into a large skip :-) One of the first things I used the language for was to avoid using a nasty web interface when I wanted to do lots of scientific literature searches. Now, I use it to write nasty web interfaces ;-) Poacher turned gamekeeper... John From mail at microcorp.co.za Sat Jun 10 05:21:49 2006 From: mail at microcorp.co.za (H J van Rooyen) Date: Sat, 10 Jun 2006 11:21:49 +0200 Subject: Intermittent Failure on Serial Port Message-ID: <000d01c68c6f$697b8900$03000080@hendrik> Hi All, I am writing a polling controller for an RS-485 line that has several addressable devices connected. It is a small access control system. All is well- the code runs for anything from three hours to three days, then sometimes when I get a comms error and have to send out a nak character, it fails hard... The traceback below pops up. - the first lines are just some debug prints. and the four records show reader number, id number, name... _______________start of Konsole Messages __________________ /dev/ttyS0 set to 9600 sane cread raw -echo ../logs/composite/rawlog Pipe exists already we get here - thread identity is: 1079298992 New Thread identity printed by new thread is: 1079298992 we get here too 5 0123456789012345 Sefie Sewenstein is in 2 DE0000085ABF8A01 Error record - catch her, catch him 2 8A00000870BEDE01 Bertus Bierdrinker is in 5 0123456789012345 Sefie Sewenstein is out Traceback (most recent call last): File "portofile.py", line 232, in ? ret_val = main_routine(port, pollstruct, pfifo) File "portofile.py", line 108, in main_routine send_nak(port, timeout) # so bad luck - comms error File "/home/hvr/Polling/lib/readerpoll.py", line 125, in send_nak port.flush() IOError: [Errno 29] Illegal seek close failed: [Errno 29] Illegal seek _______________end of Konsole Messages ___________________ The additional thread referred to is used to maintain a file of people on the premises,- it is not relevant to this, as it just writes out a global dictionary when something has changed, and it works quite merrily... Some of what I think are the relevant code snippets: This one works all the time, as I send out an ack on the succesful receipt of a message from one of the readers, and I have not seen it fail yet: def send_ack(port, timeout): """Routine to send out an ack on port""" ack_string = ack # Ascii ack = '\x06' s = '' port.write(ack_string) port.flush() flush_out(port,timeout) # eat the echoed ack This one is called after a comms error, and sometimes falls over in the above manner... def send_nak(port, timeout): """Routine to send out a nak on port""" nak_string = nak # Ascii nak = '\x15' s = '' port.write(nak_string) port.flush() flush_out(port, timeout) # eat the echoed nak # here we read to end, to flush a port buffer def flush_out(file, time_out): """Reads the port till no more chars come in for a while""" start_time = time.time() s = '' while (time.time() - start_time < time_out): s, ret_val = read_char(file, s) if ret_val == 0: # if there is input... start_time = time.time() # We make a function to read a char of file data def read_char(file, s): """Reads file data returns string, ret_val is 0 on success, 1 for KbdInt, 2 no input.""" ret_val = 0 # No error yet k = '' # Nothing read yet try: k = file.read(1) # read one char in as a string except KeyboardInterrupt: print "\n^C - Returning to Shell - Error is:", KeyboardInterrupt ret_val = 1 # ^C while waiting for input return k, ret_val # go out on error except IOError: ret_val = 2 # IOError on input - no record available return s, ret_val # so no extra chars if k == '': # empty string is nfg ret_val = 2 return s, ret_val # so no extra chars s = s + k # something to add in to passed buffer return s, ret_val # ok exit no error Note that the file is unblocked with some magic from fcntl module... The file is the serial port /dev/ttyS0 There is hardware connected to the port that has the effect of a loopback - you hear what you say.. Out of the box distribution - SuSe 10: Python 2.4.1 (#1, Sep 13 2005, 00:39:20) [GCC 4.0.2 20050901 (prerelease) (SUSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> Where can I find out what the Errno 29 really means? Is this Python, the OS or maybe hardware? Any Ideas or suggestions will be appreciated (I am doing this via email - so I am not on line all the time- so my responses may be slow...) - Hendrik van Rooyen From ldo at geek-central.gen.new_zealand Thu Jun 29 05:26:30 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 29 Jun 2006 21:26:30 +1200 Subject: Select in Python References: <1151388082.261840.306260@75g2000cwc.googlegroups.com> Message-ID: In article , Gary Herron wrote: >If you want select to start blocking again, you must read all bytes from >stdin whenever select says there are bytes to be read. To add to this, it is a good idea to read the select_tut(2) man page, particularly the "SELECT LAW" section. There's a lot of dos and don'ts there on how to avoid common bugs. From fredrik at pythonware.com Tue Jun 6 13:55:48 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 06 Jun 2006 19:55:48 +0200 Subject: Newbie: returning dynamicly built lists (using win32com) In-Reply-To: <1149613586.862299.125070@u72g2000cwu.googlegroups.com> References: <1149613586.862299.125070@u72g2000cwu.googlegroups.com> Message-ID: Ransom wrote: > Very newb here, but my question will hopefully be obvious to someone. > OK, so what is happening is that I am sending a list of data to an > overly complicated spreadsheet that produces it's own output (in cell > 32,6). As I loop through multiple test cases, the print statement > calling into COM for the cell data seems to be printing out results > just fine. But when I try and put the output from the spreadsheet into > a dynamic list after the TODO section thusly: > > outputlist = [] > outputlist.extend(excel.ActiveSheet.Cells(32,6) > return outputlist > > I get an error like: > [ 0x15450880>] the Cells call returns some kind of internal win32com object, not strings. Python has two different ways of converting an object to a string of characters; str() and repr(): http://pyref.infogami.com/str http://pyref.infogami.com/repr when you print an object, Python uses str() to do the conversion. however, when you print a container, the container object's str() implementation often uses repr() on the members. to apply str() to all list members, you can simply do: outputlist = map(str, outputlist) print outputlist or print map(str, outputlist) or some other variation thereof. From cdsmith at twu.net Mon Jun 19 23:31:37 2006 From: cdsmith at twu.net (Chris Smith) Date: Mon, 19 Jun 2006 21:31:37 -0600 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> Message-ID: I wrote: > Static type systems detect some bugs at compile time, whereas > dynamic type systems detect type violations at runtime. PS: In order to satisfy the Python group (among others not on the cross- post list), we'd need to include "duck typing," which fits neither of the two definitions above. We'd probably need to modify the definition of dynamic type systems, since most source tend to classify it as a dynamic type system. It's getting rather late, though, and I don't intend to think about how to do that. -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation From bignose+hates-spam at benfinney.id.au Sat Jun 3 00:59:15 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 03 Jun 2006 14:59:15 +1000 Subject: how to erase a variable References: <1149306000.615590.30020@c74g2000cwc.googlegroups.com> Message-ID: <87k67yygv0.fsf@benfinney.id.au> "greenflame" writes: > Is there a way to get rid of a variable as though it never existed? I > know this sounds very basic but I have not come across any such > methods. You can use the 'del' statement to delete a name. > Also is the fact that I will have a bunch of extra variables just > haning around because my use for them is over a bad thing? I will > likely have on the order of 10 to 50 or so of these for the > particular program I an working on at the moment. It doesn't cause the computer any grief to have extra objects; they'll eventually be cleaned up by garbage collection anyway. That said, it sounds like your program is not modular enough, which is a burden on the *programmer* to need to keep so many items in their head at once. It's far better to divide your program into discrete functional units, and write each conceptual step as a function. By dividing your program into functional modules (whether they be functions, classes with methods, or separate program modules) each unit of functionality has a limited scope, and the variables are local and get cleaned up after the function ends. This greatly aids the person reading the program: they have fewer things to concentrate on at any point in your program. -- \ "For every complex problem, there is a solution that is simple, | `\ neat, and wrong." -- Henry L. Mencken | _o__) | Ben Finney From exarkun at divmod.com Thu Jun 1 11:09:14 2006 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 1 Jun 2006 11:09:14 -0400 Subject: Starting New Process In-Reply-To: <1149172463.881528.131290@j55g2000cwa.googlegroups.com> Message-ID: <20060601150914.28682.2078896178.divmod.quotient.9318@ohm> On 1 Jun 2006 07:34:23 -0700, D wrote: >Hello, I need to write a server program that performs the following >tasks: > >1) Listens on TCP port 5555 for a connection >2) When client connects, launches application (for example, vi), then >closes connection with client >3) Goes back to listening on TCP port 5555 for an incoming connection Untested: from twisted.internet import protocol, reactor class ViRunner(protocol.Protocol): def connectionMade(self): reactor.spawnProcess( None, '/usr/bin/setsid', ['setsid', '/usr/bin/vi']) self.transport.loseConnection() f = protocol.ServerFactory() f.protocol = ViRunner reactor.listenTCP(5555, f) reactor.run() Jean-Paul From serge.orlov at gmail.com Mon Jun 26 00:32:55 2006 From: serge.orlov at gmail.com (Serge Orlov) Date: Sun, 25 Jun 2006 21:32:55 -0700 Subject: Python database access In-Reply-To: <1151295558.067744.91470@b68g2000cwa.googlegroups.com> References: <1151295558.067744.91470@b68g2000cwa.googlegroups.com> Message-ID: On 25 Jun 2006 21:19:18 -0700, arvind wrote: > Hi all, > I am going to work on Python 2.4.3 and MSSQL database server on > Windows platform. > But I don't know how to make the connectivity or rather which module to > import. > I searched for the modules in the Python library, but I couldn't find > which module to go for. The module you're looking for is the first result if you search "python mysql" on google or if you search "mysql" on python package index From nmm1 at cus.cam.ac.uk Fri Jun 30 04:58:45 2006 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 30 Jun 2006 08:58:45 GMT Subject: File naming [was Re: Bug reporting impossible] References: <1151598979.369897.140770@x69g2000cwx.googlegroups.com> Message-ID: In article , "Fredrik Lundh" writes: |> |> > |> Why would you have a file named '' in your current directory? |> > |> > Why would Python search for one? :-) |> > |> > In both cases, the normal answer is "Someone made a mistake" but, if |> > you have a script that creates a files of the same names specified in |> > the current directory, what name should it use if you specify stdin? |> |> given that "" is an invalid filename on some platforms, why would any |> serious programmer use "" for an external file ? You can't be serious, surely? Firstly, why does Python? Well, I can answer that :-) Secondly, EVERY string is an invalid filename on some platforms, without exception! As every single (not system-specific) language has done since languages imported the concept of filenames, Python says that the set of strings that are valid filenames is implementation-dependent or perhaps implementation-defined. Thirdly, I had better explain what a LOT of programs and scripts actually do. You have a command 'fred' that takes filenames as arguments and, if there are none, uses stdin; as part of its function, it needs to create a file of the same name as those in its arguments, in the current directory. What filename should it use for stdin? I sincerely HOPE that you are not proposing to use the null filename (which could and probably still can be created on some systems), as it is a gibbering nightmare to handle thereafter, and a poor sod of an ordinary user has little hope of cleaning up the mess. Been there - done that for them :-) It can't use 'stdin', as that is a possible file name, so it uses an obvious derivation that is unlikely to be created by accident. '' is one of the standard conventions - I am one of perhaps a few hundred (perhaps more) people who invented it independently, 20 years back, but doubt that I was even close to the first. It is quite a good name for Unix, as you can't easily create it by accident in any normal shell. |> > It is one of the standard conventions, which is (after all) why Python |> > is searching for it. |> |> the only reason Python's searching for it is that the CLI implementation passes |> "" as the second argument to compile: |> |> http://pyref.infogami.com/compile And the reason that it does that is because it is using one of the standard conventions for naming stdin. Python didn't INVENT that convention, you know. The bug isn't in passing an information string "" but in using that string (which is not meant to represent a real file) to perform a file search. Regards, Nick Maclaren. From nun at example.com Fri Jun 2 14:58:29 2006 From: nun at example.com (Mitja Trampus) Date: Fri, 02 Jun 2006 20:58:29 +0200 Subject: Sampling a population In-Reply-To: References: Message-ID: Brian Quinlan wrote: > The fastest algorithm that I have been able to devise for doing so is: > O(n * log(len(lst))). Can anyone think or a solution with a better time > complexity? If not, is there an obviously better way to do this > (assuming n is big and the list size is small). If list is indeed short, I'd say common sense speaks against complicating and optimizing further - you can only get log(len(lst))-fold speedup, which is in your case more or less a small constant. _IF_ this part of code later turns out to be a bottleneck, you might profit more by porting it to C than searching for an O(n) solution, if it even exists. From bdesth.quelquechose at free.quelquepart.fr Fri Jun 2 19:47:45 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 03 Jun 2006 01:47:45 +0200 Subject: Using print instead of file.write(str) In-Reply-To: <2Iq*Jzbir@news.chiark.greenend.org.uk> References: <2Iq*Jzbir@news.chiark.greenend.org.uk> Message-ID: <44809e93$0$13657$636a55ce@news.free.fr> Sion Arrowsmith a ?crit : > A.M wrote: > >>I found print much more flexible that write method. > > > "more flexible"? More convenient, yes. More powerful, maybe. But I > don't see more flexible. Everything print can to stdout.write() can > do. The reverse isn't true. eg (this appears to be a FAQ on this > group, although I can't find it in the FAQ): > > for x in range(10): > sys.stdout.write(str(x)) > > to print: > > 0123456789 > The reverse isn't true ??? print "".join(str(x) for x in range(10)) (which BTW should be faster, since it's only one I/O, instead of ten with your version.) Now, given: bird = "parrot" beautiful = "dead" How would you do the following with f.write() ? print "this", bird, "is", beautiful (without using string formating, of course...) From rvtol+news at isolution.nl Fri Jun 23 12:34:02 2006 From: rvtol+news at isolution.nl (Dr.Ruud) Date: Fri, 23 Jun 2006 18:34:02 +0200 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150904134.520639.71070@b68g2000cwa.googlegroups.com> <1151030140.202720.245140@y41g2000cwy.googlegroups.com> Message-ID: Marshall schreef: > It seems we have languages: > with or without static analysis > with or without runtime type information (RTTI or "tags") > with or without (runtime) safety > with or without explicit type annotations > with or without type inference > > Wow. And I don't think that's a complete list, either. Right. And don't forget that some languages are hybrids in any of those areas. -- Affijn, Ruud "Gewoon is een tijger." From benjamin.franksen at bessy.de Thu Jun 22 17:47:22 2006 From: benjamin.franksen at bessy.de (Benjamin Franksen) Date: Thu, 22 Jun 2006 23:47:22 +0200 Subject: What is Expressiveness in a Computer Language References: <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <34aj92h0g7tqi9amhh7k3ieq5n568t0e6f@4ax.com> Message-ID: George Neuner wrote: > The point is really that the checks that prevent these things [such as 'array index out of bounds'] > must be > performed at runtime and can't be prevented by any practical type > analysis performed at compile time. I'm not a type theorist but my > opinion is that a static type system that could, a priori, prevent the > problem is impossible. It is not impossible. Dependent type systems can -- in principle -- do all such things. Take a look at Epigram (http://www.e-pig.org/). Systems based on dependent types such as Epigram are not yet mature enough to be used for serious programming. However, they clearly show that these things /are/ possible. Cheers Ben From me at privacy.net Tue Jun 27 22:04:48 2006 From: me at privacy.net (Dan Sommers) Date: Tue, 27 Jun 2006 22:04:48 -0400 Subject: How do you use this list ? References: <12a2foromcuj30b@corp.supernews.com> Message-ID: On Tue, 27 Jun 2006 14:22:19 -0000, Grant Edwards wrote: > Actually having mailing lists send you mail is insane. +1 QOTW I remember an episode of M*A*S*H (first there was the book, then there was an American TV show) where some General or other high ranking army type said, "This is a press conference. The last thing I want to do is answer a lot of questions." Regards, Dan -- Dan Sommers "I wish people would die in alphabetical order." -- My wife, the genealogist From steve at holdenweb.com Wed Jun 7 22:20:32 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 08 Jun 2006 03:20:32 +0100 Subject: Debugging a pickle In-Reply-To: References: Message-ID: <44878970.8080704@holdenweb.com> Jeffrey Barish wrote: > I use cPickle to serialize some data so that I can read it back later. It > works sometimes, but other times I get an EOFError at the > > data = cPickle.load(fileobj) > > statement. I assume that this error indicates that cPickle is not able to > retrieve as much data from the file as it expects -- or that the dump did > not write as much data as it should have. Is that assumption correct? Are > there any debugging techniques I can use to figure out what is going wrong? First of all, verify that you are opening the file in binary mode. Not doing this is the biggest cause of problems for Windows users, which the intermittent failure makes me suspect you may be. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From rossberg at ps.uni-sb.de Sun Jun 25 13:52:13 2006 From: rossberg at ps.uni-sb.de (rossberg at ps.uni-sb.de) Date: 25 Jun 2006 10:52:13 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: <449eba8d$1@nntp0.pdx.net> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150908952.804184.218990@r2g2000cwb.googlegroups.com> <1150991074.705803.211570@m73g2000cwd.googlegroups.com> <1151244628.566060.40500@p79g2000cwp.googlegroups.com> <449eba8d$1@nntp0.pdx.net> Message-ID: <1151257933.443578.245450@r2g2000cwb.googlegroups.com> Scott David Daniels wrote: > rossberg at ps.uni-sb.de wrote: > > Huh? There is a huge, fundamental difference: namely whether a type > > system is sound or not. A soundness proof is obligatory for any serious > > type theory, and failure to establish it simply is a bug in the theory. > > So you claim Java and Objective C are "simply bugs in the theory." You're misquoting me. What I said is that lack of soundness of a particular type theory (i.e. a language plus type system) is a bug in that theory. But anyway, Java in fact is frequently characterised as having a bogus type system (e.g. with respect to array subtyping). Of course, in a hybrid language like Java with its dynamic checks it can be argued either way. Naturally, the type system of Objective-C is as broken as the one of plain C. - Andreas From chase_jo at nnnn.com Thu Jun 15 20:26:18 2006 From: chase_jo at nnnn.com (Joseph Chase) Date: Fri, 16 Jun 2006 00:26:18 GMT Subject: Video capture from webcam on Mac? Message-ID: Is there a cross-platform solution for video capture from a webcam? I am aware of the Win32 videocapture library, but am unaware of how to accomplish the same functionality on the Mac side. Thanks in advance. From kraus at hagen-partner.de Wed Jun 28 05:14:13 2006 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Wed, 28 Jun 2006 11:14:13 +0200 Subject: How to measure execution time of a program In-Reply-To: References: <54032.10.209.4.1.1151481158.squirrel@10.105.1.3> Message-ID: On 28.06.2006 10:01, Girish Sahani wrote: > Sorry for spamming again, but please also enlighten me with some way to > time a function i.e. to find out how much time each function takes for > execution in a big program. >> Hi all, >> >> Can anyone tell me the simplest way to do it (some code snippet that >> could be included in the program's main function) ?? >> >> Thanks, >> girish >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > Use the Python profiler: http://docs.python.org/lib/profile.html HTH, Wolfram From maric at aristote.info Mon Jun 26 21:21:33 2006 From: maric at aristote.info (Maric Michaud) Date: Tue, 27 Jun 2006 03:21:33 +0200 Subject: replace a method in class: how? In-Reply-To: <44a08221$0$19040$636a55ce@news.free.fr> References: <44A06A6B.6010200@bryant.edu> <44a08221$0$19040$636a55ce@news.free.fr> Message-ID: <200606270321.34112.maric@aristote.info> Le mardi 27 juin 2006 06:21, Bruno Desthuilliers a ?crit?: > Maric Michaud a ?crit : > (snip) > > > In OOP Methods are defined in *classes* not in any arbitrary object > > Chapter and verse, please ? AFAIK, the first O in OOP stands for > "object", not for "class" !-) > Hard to find it, indeed. > Classes are just an implementation convenience, and the fact that the > class-based model is the most usual one doesn't imply it's the only > valid one. Maybe, never been told of another one, do you think of javascript prototypes ? Well, there are no methods in this model, only functions. > So there's no reason one shouldn't override (or add) a method > on a per-object basis. As a matter of fact, it's perfectly legal (and > can be very convenient) to do so in Python. I never saw the term "method" used for anything except for what it means for classes, and moreover, the class model, even if it's just an implementation, it's the one chosen by python. For the common understanding of the model, IMHO, classes bind methods, instances bind functions. -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From jstroud at ucla.edu Fri Jun 9 21:16:16 2006 From: jstroud at ucla.edu (James Stroud) Date: Fri, 09 Jun 2006 18:16:16 -0700 Subject: Most elegant way to generate 3-char sequence In-Reply-To: References: <1149889784.391965.271570@h76g2000cwa.googlegroups.com> Message-ID: SuperHik wrote: > and the winner is... :D > David Isaac wrote: > >> alpha = string.lowercase >> x=(a+b+c for a in alpha for b in alpha for c in alpha) > > > Not necessarily vying for winner, but David's solution is highly specific as it doesn't do so well for something like aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab . . . zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzy zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From steven.bethard at gmail.com Fri Jun 23 13:08:38 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 23 Jun 2006 11:08:38 -0600 Subject: Clearing pythonwin environment In-Reply-To: <1151012168.838694.235610@c74g2000cwc.googlegroups.com> References: <1151012168.838694.235610@c74g2000cwc.googlegroups.com> Message-ID: Network Ninja wrote: > I want to restart the environment occasionally to default (like I > restarted pythonwin). I wrote this script. I know why it doesn't work, > cause it deletes my variable (item) on each iteration. My question is: > is it possible to do this? What other things might I try? > > # Reset Pythonwin enviroment > > # Variables > keep = ['__builtins__', '__doc__', '__name__', 'pywin', 'keep', 'item'] > > print > for item in dir(): > if item not in keep: > del item ^^^^^^^^ del globals()[item] I believe that should work. Note that this won't cause imported modules to be reloaded though, so I wouldn't rely on it too heavily. The imported modules problem can only really be solved by restarting the interpreter. STeVe From cdsmith at twu.net Mon Jun 26 19:47:40 2006 From: cdsmith at twu.net (Chris Smith) Date: Mon, 26 Jun 2006 17:47:40 -0600 Subject: What is a type error? References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <7i3mg.204167$8W1.155367@fe1.news.blueyonder.co.uk> <44992e6c$2$664$bed64819@news.gradwell.net> <%Igmg.464974$xt.353729@fe3.news.blueyonder.co.uk> <4fv0v3F1kipa6U1@individual.net> <4gakhiF1m698cU1@individual.net> <4galqlF1mae4qU1@individual.net> <4gb8tiF1e75njU1@individual.net> Message-ID: Pascal Costanza wrote: > > Clearly, in this example, the program > > is invoking an operation (division) on values that are not appropriate > > (zero for the second argument). Hence, if your definition really is a > > definition, then this must qualify. > > Here, you are asking more from dynamic type systems than any existing > type system provides. The definition of what is considered to be a type > error and what not is always part of the specification of a type system. No, I'm not. Were we to follow this path of definition, it would not require that dynamic type systems catch ALL type errors; only that they catch some. Not that it matters, though. I am analyzing the logical consequences of your own definition. If those logical consequences were impossible to fulfill, that would be an even more convincing reason to find a new definition. Concepts of fairness don't enter into the equation. > > If you want to make a statement instead of the sort you've implied > > above... namely that a type error is *any* error that's raised by a type > > system, then that's fine. It certainly brings us closer to static > > types. Now, though, the task is to define a type system without making > > a circular reference to types. You've already rejected the statement > > that all runtime errors are type errors, because you specifically reject > > the division by zero case as a type error for most languages. What is > > that distinction? > > I don't need such a distinction. I can just define what is covered by a > type system and what is not. All type systems work that way. You've got to define something... or, I suppose, just go on using words without definitions. You claimed to give a definition, though. I have been led by others to believe that the right way to go in the dynamic type sense is to first define type errors, and then just call anything that finds type errors a type system. That would work, but it would require a type error. You seem to want to push that work off of the word "type error" and back onto "type system", but that requires that you define what a type system is. It doesn't work for you to say BOTH that a type system is anything that catches type errors, AND that a type error is anything that's caught by a type system. That's not a definition; it's just circular reasoning. If I can plug in: type error = fly, type system = frog, and get a valid instance of your definitions, then you aren't giving much of a definition. (Unless you think that frogs are perfectly good examples of type systems.) Incidentally, in the case of static type systems, we define the system (for example, using the definition given from Pierce many times this thread), and then infer the definition of types and type errors from there. Because a solid definition has been given first for a type system without invoking the concepts of types or type errors, this avoids being circular. -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation From jstroud at ucla.edu Fri Jun 2 17:31:23 2006 From: jstroud at ucla.edu (James Stroud) Date: Fri, 02 Jun 2006 14:31:23 -0700 Subject: Making a second window with Tkinter In-Reply-To: <1149282184.587252.59160@y43g2000cwc.googlegroups.com> References: <1149282184.587252.59160@y43g2000cwc.googlegroups.com> Message-ID: greenflame wrote: > I have a script that will make a window that shows the text I want > using Tkinter. What I need to do is to make another window popup above > the current window showing other text. I tryed: > > ----------- > from Tkinter imprt * > > root = Tk() > > L = Label(root, text="Blah") > L.grid(row=0, column=0) > > # Other labels are also here but their inclusion is not so relavent. > > root.mainloop() > > sub = Tk() > > subL = Label(root, text="Blah") > subL.grid(row=0, column=0) > > sub.mainloop() > ---------- > However, when I ran the script it only showed the second window after I > closed the first one. After looking at the code I guess I can see why. > The problem is that I do not know how to fix the issue. Thank you for > you help. > Use Toplevel(). from Tkinter import * root = Tk() def callback(e=None): t = Toplevel() Label(t, text='blah').pack() b = Button(root, text='new top', command=callback) b.pack() root.mainloop() Also, do not do this twice in the same script: Tk(). James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From onurb at xiludom.gro Mon Jun 19 04:42:42 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Mon, 19 Jun 2006 10:42:42 +0200 Subject: code is data In-Reply-To: <1150658597.272001.171840@r2g2000cwb.googlegroups.com> References: <1150574111.415068.255900@p79g2000cwp.googlegroups.com> <1150606118.456390.262620@y41g2000cwy.googlegroups.com> <1150626424.563673.175060@c74g2000cwc.googlegroups.com> <1150650852.275956.249340@p79g2000cwp.googlegroups.com> <1150658597.272001.171840@r2g2000cwb.googlegroups.com> Message-ID: <44966383$0$30351$636a55ce@news.free.fr> Ravi Teja wrote: (snip) > Annoted variables, symbols and code > layout visually cue more efficiently to the object nature than do > explicit text definitions. Of course, this is only sensible when there > aren't too many of any of those. In that case, the cognitive cost of > notation outweighs the representational cost of text. > > Representational minimalism is troublesome in general code (ala Perl), > but not so in a DSL where the context is constrained. This still impose the need to learn a new language. > I would also like to symbolize field types since they occur so commonly > in a definition file and only a few of them are commonly used. I admit > though that I find the code below a bit visually jarring and I might > use something else. But it serves to illustrate the point. I chose the > respective symbols based on their colloquial use and association with > the field types. > > @Poll: > $question: length 200 > %pub_date('date published') > > @Choice: > poll -> Poll > $choice: length 200 > #votes Yuck. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From rupole at hotmail.com Tue Jun 27 04:42:15 2006 From: rupole at hotmail.com (Roger Upole) Date: Tue, 27 Jun 2006 04:42:15 -0400 Subject: Help with conversion VB script to Python : COM objects References: <1151326097.306855.11880@y41g2000cwy.googlegroups.com> Message-ID: <1151397373_47421@sp6iad.superfeed.net> wrote in message news:1151326097.306855.11880 at y41g2000cwy.googlegroups.com... > Hi, > > I need to re-write a VB script into Python (because I really don't like > VB). > > The VB script is used to create a Windows COM object. > (I am more of Unix guy, so COM objects are a little bit alien for me). > > At a certain point in the VB script, I have the following line: > objPolTypes = objPmad.Cvar(objPmad.GetPolicyTypeList) > > Does anybody what the equivalent in Python would be? > I tried: > objPolTypes = objPmad.Cvar(objPmad.GetPolicyTypeList() ) > > but then I get the following error: > " > Traceback (most recent call last): > File "C:\Python24\MyProgs\FodFin\test.py", line 11, in ? > objPolTypes = objPmad.cvar(objPmad.GetPolicyTypeList() ) > File "", line 2, in cvar > pywintypes.com_error: (-2147352571, 'Type mismatch.', None, 1) > " > > I also tried : > objPolTypes = objPmad.GetPolicyTypeList() > > this works but I end of with a list of COM object and have no clue how > to query/use them or what methods are defined for those type of > objects. > > Any help really appreciated. > > With kind regards, > > KRis > If the application has a typelib, you can use makepy to generate a wrapper module that will show you the objects' methods and properties. Otherwise, you'll have to depend on the documentation for the app. Roger ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= East/West-Coast Server Farms - Total Privacy via Encryption =--- From ajones1 at gmail.com Tue Jun 27 11:44:20 2006 From: ajones1 at gmail.com (Adam Jones) Date: 27 Jun 2006 08:44:20 -0700 Subject: What technologies should I use for my application manager? References: <1151260635.570013.87210@b68g2000cwa.googlegroups.com> <1151307031.166916.232330@m73g2000cwd.googlegroups.com> <1151394573.819701.242240@c74g2000cwc.googlegroups.com> Message-ID: <1151423060.719953.213310@x69g2000cwx.googlegroups.com> MrBlueSky wrote: > Thanks for the advice, Adam! > > Turbogears sounds like it does everything I want and looks like a > great... except you've made me nervous with your comment on the > instability of the Oracle API! It is not impossible to find a stable ORM for access to Oracle, just slightly more difficult. Both of the systems in question are working on perfecting the currently experimental support. > > Stability, good documentation and a wide user base are priorities. I > was delighted by the quality of Tkinter in this regard. Am I wishing > for the moon in hoping for the same quality in the framework I choose > for this? > > Anyone else like to try and sell me on Zope or Django?! From Bulkan at gmail.com Tue Jun 27 03:28:10 2006 From: Bulkan at gmail.com (placid) Date: 27 Jun 2006 00:28:10 -0700 Subject: How do you use this list ? In-Reply-To: References: Message-ID: <1151393290.819789.219220@b68g2000cwa.googlegroups.com> Bo Yang wrote: > Hi everyone , > I have join this list for about 4 months , and everyday I receive > hundreds of > mails . There is no means to read all of them , so I just read something > interesting > for me . But if so , there are too much mails pile up in my inbox , I > want to ask > how do you use this list , reading every mail come in or just read what > you think > interesting ? > your recieving those emails because you choose (in your My Account settings) to received emails, you can deselect this and then just read any post that interests you and ask questions of your own. Cheers From aleax at mac.com Mon Jun 19 11:18:13 2006 From: aleax at mac.com (Alex Martelli) Date: Mon, 19 Jun 2006 08:18:13 -0700 Subject: Just out of curiosity: Which languages are they using at Google and what for? References: <1150710705.482745.230070@r2g2000cwb.googlegroups.com> <44967eb4$0$21298$626a54ce@news.free.fr> Message-ID: <1hh6662.o3iw84ym7cieN%aleax@mac.com> bruno at modulix wrote: ... > * Packaging. Google has an internal packaging format like RPM. > These packages are created using python. > * Binary Data Pusher. This is the area where Alex Martelli is > working, on optimizing pushing bits between thousands of servers > * Production servers. All monitoring, restarting and data > collection functionality is done with python Yep, Greg did say that at SDForum, but in fact I'm working on a much wider range of problems than just the datapush -- I lead Production Systems, which includes parts of all of the above and yet more stuff (account management, network verification, etc etc) -- done mostly in Python, but with substantial helpers in C++ as well (not so much for CPU efficiency reasons, as for keeping memory use under strict control when necessary, the area where C/C++ really shines;-). Alex From aurora00 at gmail.com Wed Jun 28 14:52:00 2006 From: aurora00 at gmail.com (aurora00 at gmail.com) Date: 28 Jun 2006 11:52:00 -0700 Subject: Generator naming convention? Message-ID: <1151520720.749818.131460@i40g2000cwc.googlegroups.com> I use generators a lot. E.g. def gen_words(text) ... parse text ... yield each word in text for word in gen_words(text): print word I don't like the name gen_xxx() very much. Looking for some inspiration to name generators. Here are some of my ideas: enumerate_words gen_words generate_words parse_words walk_words Any idea? Do you have a naming convention for generators? wy From jo at durchholz.org Wed Jun 21 07:07:18 2006 From: jo at durchholz.org (Joachim Durchholz) Date: Wed, 21 Jun 2006 13:07:18 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <1150809118.677124.142230@u72g2000cwu.googlegroups.com> <1150815461.210286.53120@r2g2000cwb.googlegroups.com> <1150823297.816352.75370@u72g2000cwu.googlegroups.com> Message-ID: Andreas Rossberg schrieb: > Rob Thorpe wrote: >> Hmm. You're right, ML is no-where in my definition since it has no >> variables. > > Um, it has. Mind you, it has no /mutable/ variables, but that was not > even what I was talking about. Indeed. A (possibly nonexhaustive) list of program entities that (can) have type would comprise of mutable variables, immutable variables (i.e. constants and parameter names), and functions resp. their results. Regards, Jo From fredrik at pythonware.com Sun Jun 11 16:47:58 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 11 Jun 2006 22:47:58 +0200 Subject: Killing a thread In-Reply-To: <1150058584.276456.278840@u72g2000cwu.googlegroups.com> References: <7c8a9a970606091338t174fbcb0wc73cdb8b385f8ccd@mail.gmail.com> <7c8a9a970606091354u73308bf8o2758eea5ef690c39@mail.gmail.com> <1149889827.2754.6.camel@kenshin.CASA> <448A0D8A.4000008@mvista.com> <1149965895.702667.3970@u72g2000cwu.googlegroups.com> <1150058584.276456.278840@u72g2000cwu.googlegroups.com> Message-ID: MacDonald wrote: >> I'm not sure using a non-portable API to run the code under a "custom >> debugger" qualifies as a "portable implementation", though... > > Everything used is a part of the standard library, which is portable, > AFAICT. Could you say specifically what is non-portable? from the documentation: Note: The settrace() function is intended only for implementing debuggers, profilers, coverage tools and the like. Its behavior is part of the implementation platform, rather than part of the language definition, and thus may not be available in all Python implementations. From Serge.Orlov at gmail.com Mon Jun 5 21:57:18 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 5 Jun 2006 18:57:18 -0700 Subject: Get EXE (made with py2exe) path directory name In-Reply-To: <1149557188.392915.287220@i39g2000cwa.googlegroups.com> References: <1149557188.392915.287220@i39g2000cwa.googlegroups.com> Message-ID: <1149559038.533248.117640@i40g2000cwc.googlegroups.com> Andrei B wrote: > I need to get absolute path name of a file that's in the same dir as > the exe, however the Current Working Directory is changed to somthing > else. > Use sys.path[0] From alsmeirelles at gmail.com Fri Jun 9 09:37:18 2006 From: alsmeirelles at gmail.com (alsmeirelles at gmail.com) Date: 9 Jun 2006 06:37:18 -0700 Subject: Select hangs after some reads In-Reply-To: <128gg87h3sgqu93@corp.supernews.com> References: <1149737234.816833.177710@j55g2000cwa.googlegroups.com> <1149764138.868847.326250@i39g2000cwa.googlegroups.com> <128g8uvi6aj4240@corp.supernews.com> <1149779056.498540.46620@f6g2000cwb.googlegroups.com> <128gg87h3sgqu93@corp.supernews.com> Message-ID: <1149860238.570237.133820@f6g2000cwb.googlegroups.com> Grant Edwards escreveu: > On 2006-06-08, alsmeirelles at gmail.com wrote: > > >>> Well, actually I?m using a very simple protocol wich sends > >>> only strings ended by newline. I need to send 3 chunks of > >>> information and a newline after them. On the reader side I > >>> make 3 readline(), this way I wouldn?t have to care about this > >>> problem, but maybe that?s where I?m falling. If that?s the > >>> case, I?ll have to use a more complex protocol. > >> > >> You can't use readline() with select(). Select tells you > >> whether recv() called on the underlying socket will block or > >> not. What's probably happening is that all of the data has > >> been read from the underlying socket and is being held in a > >> buffer waiting to be read by readline(). > > > > Yes, as I expected, its the buffers. In my opinion the problem > > is that the socket module doesn't provide a way of reading all > > its internal buffer. > > What internal buffer? > > > readlines() just make subsequent calls to readline and > > readline may call recv, so we have a locked scene. I want to > > know if I will block anyway. > > I'm lost. > > > Of course I can clean the buffer myself, but I think the > > socket module should provide a way of doing this. > > I'm afraid I don't understand what you mean. > > Since you talked about calling readline(), I assumed that you > had called the socket object's makefile() method to create a > file-object. The select system call can only tell you whether > a recv on the socket will block or not. It knows nothing about > the state of the file object on which you're calling readline(). Yes, that's right. The problem I was having and discussing is that, if you read one request at a time, using a readline, and used select to check for the incoming of new ones, you will block and the other unread requests will rest in the socket buffer (_rbuf class attribute, wich is a string). If you use several readline() (that's readlines()), to try to read all the buffer, and use select to check for the new ones, you will block because after the buffer is empty readline() will try a recv(). So the problem: readline() and readlines() can block and there's nothing (given by the module) to prevent you from it happening. There are solutions to this of course, but what I was arguing is that the module and the documentation don't warn and dont treat this case. > > -- > Grant Edwards grante Yow! Is this an out-take > at from the "BRADY BUNCH"? > visi.com From luismgz at gmail.com Wed Jun 28 23:40:34 2006 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 28 Jun 2006 20:40:34 -0700 Subject: Correr Programas Externos In-Reply-To: References: Message-ID: <1151552434.864745.268550@j72g2000cwa.googlegroups.com> Gabriel wrote: > Hola a todos: > > Necesitar?a correr otros programas desde python. Es decir Cuando > aprieto un boton que se abra el block de notas (por ejemplo) ?Alguien > sabe como hacerlo? > Gracias > > -- > Gabriel Se hace as?: import os os.startfile("notepad.exe") Esto te sirve para abrir cualquier archivo que funcione con cualquier programa. Por ejemplo, del mismo modo pod?s abrir un archivo de word: os.startfile('miarchivo.doc') (A prop?sito, busca en google que me parece que hay una lista de python en espa?ol por ah?, por que ac? te van a putear un poco...). Saludos, Luis From invalidemail at aerojockey.com Sat Jun 24 22:44:23 2006 From: invalidemail at aerojockey.com (Carl Banks) Date: 24 Jun 2006 19:44:23 -0700 Subject: Absolute noob to Linux programming needs language choice help References: <1150854682.904891.274480@c74g2000cwc.googlegroups.com> Message-ID: <1151203463.625160.114190@i40g2000cwc.googlegroups.com> stylecomputers at gmail.com wrote: > Hey guys, > > I am absolutely new to Linux programming, with no w######s programming > experience except a small amount of C++ console apps. > Reasonably new to Linux, BSD etc, got good sound networking base of > knowledge and dont have any problem working the command line etc. > > I want to learn a language that I can use in my networking duties that > is most likely to be of use to me. I have a few choices I can think of > being: > > Python > Perl > C > > Any other Langs out there that would be better suited? > > I want to be able to use the app's I write in OpenBSD and RH versions > of Linux > > What would you reccomend (Unbiased opinion please, I'm after the > functionality I'll love it later :) ) I'm known as a Perl hator, but I'll try to be as unbiased as I can. I'm limiting myself to the three you mentioned. C is a very simple (meaning "straightforward", not "easy to learn") language. Almost everything in C is reduced to basic building blocks that are quite close to how the CPU itself runs. For example, there's no such thing as a "list" or even a "string" in C; instead, what you have are pointers, arrays, and a small number of built-in types (and a small standard library that provides more complex things like strings). This makes C an excellent language for programming hardware and low-level stuff like that. However, it's really not optimal for application programming--it forces you to worry about stuff like freeing memory and buffer overflows. I was frustrated with C because I mostly do application stuff, so one day I sat down to learn Perl. I was amazed at the leap in productivity--I was able to write an email autoresponder the very same day I began the tutorial (granted, I was an expert programmer at the time, but still). Perl freed me from having to worry about stuff like memory management, and it provided useful things like growable arrays and dictionaries. However, unlike C, Perl is not simple. Perl is complicated, ad hoc, and inconsistent. It never really fit inside my head--I was always afraid there was something going on, some obscure rule or behavior was lurking. In addition (and here the Perl hator in me comes out), it's poorly designed as a language: it often makes you do extra work to do things the better way (for example, local variables have to be declared, but not globals). So we have C, which is simple and straightforward but too low-level to be efficicient at application programming. We have Perl, which is high-level enough for application programming, but is complicated and inconsistent. Then we have Python, which is both simple and high-level. So, yeah, I like Python best of those three. For someone new to programming, I definitely recommend learning Python first, unless you intend to be a expert or professional programmer or to do low-level stuff, in which case I'd say start with C. Definitely don't start learning with Perl. It might be the best choice for some people (in some universes), but it encourages bad programming habits, so I don't recommend it for newbies. Learning to program in Perl is like learning to do stand-up comedy by laughing at your own jokes. For someone looking for looking to learn preferrably only one language, I'd say Python, without knowing more about your intended problem domain. Carl Banks From mrmakent at cox.net Tue Jun 20 09:15:06 2006 From: mrmakent at cox.net (Mike Kent) Date: 20 Jun 2006 06:15:06 -0700 Subject: unittest behaving oddly References: Message-ID: <1150809306.287758.48870@h76g2000cwa.googlegroups.com> David Vincent wrote: > > import unittest > > > > class IntegerArithmenticTestCase(unittest.TestCase): > > def testAdd(self): ## test method names begin 'test*' > > assertEquals((1 + 2), 3) > > assertEquals(0 + 1, 1) assertEquals is a member function, inherited from unittest.TestCase, so you must call it as self.assertEquals. ForEx: class IntegerArithmenticTestCase(unittest.TestCase): def testAdd(self): ## test method names begin 'test*' self.assertEquals((1 + 2), 3) From laurent.pointal at limsi.fr Fri Jun 16 03:15:37 2006 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Fri, 16 Jun 2006 09:15:37 +0200 Subject: Python is fun (useless social thread) ;-) In-Reply-To: References: <1150380401.422325.119360@h76g2000cwa.googlegroups.com> Message-ID: John Salerno a ?crit : ... > I do, however, think the docs are pretty good, although I sometimes find > myself just wishing that a function definition was simply laid out in an > easy to read format that included all of its parameters, so I would know > exactly what to pass to it (I guess help() is good for this though). http://www.limsi.fr/Individu/pointal/python/pqrc/ A+ Laurent. From fredrik at pythonware.com Wed Jun 28 09:26:08 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 28 Jun 2006 15:26:08 +0200 Subject: MySQLdb not updating rows References: <1151500514.817456.65510@d56g2000cwd.googlegroups.com> Message-ID: "Bowen" wrote: > boo = raw_input("Sure you want to update password with above details? Y or N: ") > > if boo == 'y': if you're asking for Y or N, maybe you should check for Y or N ? or better, use something like: if boo.lower() == 'y': ... or even if boo.lower().startswith("y"): ... > db = MySQLdb.connect("copweb2", "******", "******", "*******") > cursor = db.cursor() > if cursor.execute("UPDATE teachers SET password = '%s' WHERE > teacher_code = '%s'" % (h, tc)): > print "Done" > else: > print "Error" > else: > print "cancelled" > > cursor.close() what happens if you add db.commit() here? > db.close() From onurb at xiludom.gro Mon Jun 19 12:49:15 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Mon, 19 Jun 2006 18:49:15 +0200 Subject: Formatted string to object In-Reply-To: References: <1150731552.799052.47320@r2g2000cwb.googlegroups.com> Message-ID: <4496d58c$0$11208$636a55ce@news.free.fr> Tim Chase wrote: >> Can you use strings or %s strings like in the above or >> >> aaa = 'string' >> aaa.%s() % 'upper' >> >> Somehow? > > > Looks like you want to play with the eval() function. > >>>> aaa = 'hello' >>>> result = eval("aaa.%s()" % 'upper') >>>> result > 'HELLO' Using eval() or exec should be really avoided whenever possible IMHO. This one is best done with getattr(obj, attribute_name [,default]), ie: >>> aaa = "string" >>> getattr(aaa, 'upper')() 'STRING' >>> -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From writetoalok at googlemail.com Thu Jun 29 20:22:41 2006 From: writetoalok at googlemail.com (Alok) Date: 29 Jun 2006 17:22:41 -0700 Subject: Reddit broke - should have remained on Lisp? Message-ID: <1151626961.232761.255550@d56g2000cwd.googlegroups.com> While posting a comment on http://www.reddit.com I got an error page with the following curious statement on it. "reddit broke (sorry)" "looks like we shouldn't have stopped using lisp..." See screenshot at http://photos1.blogger.com/blogger/1773/1980/1600/reddit-broke.jpg Whether they truly repent not using lisp or otherwise, their site appears to be 3 times slower ... Alok From onurb at xiludom.gro Tue Jun 27 07:01:47 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Tue, 27 Jun 2006 13:01:47 +0200 Subject: classes and interfaces In-Reply-To: <1151401318.703216.288850@x69g2000cwx.googlegroups.com> References: <1151401318.703216.288850@x69g2000cwx.googlegroups.com> Message-ID: <44a1101c$0$9623$626a54ce@news.free.fr> s99999999s2003 at yahoo.com wrote: > hi > i come from a non OO environment. now i am learning about classes. can > i ask, in JAva, there are things like interface. eg > public interface someinterface { > public somemethod (); > .... > ... > } > > In python , how to implement interface like the above? is it just > define a class?? Java interfaces are a workaround the combination of static typing (limiting polymorphism) and lack of multiple inheritance. Since Python is dynamically typed (polymorphism does not depend on type), there's no such need: class Foo(object): def doThis(self): print "in Foo.doThis" class Bar(object): def doThis(self): print "in Bar.doThis" def doIt(obj): obj.doThis() f = Foo() b = Bar() doIt(f) doIt(b) A you can see, doIt() works for any object having a doThis() method. No need for inheritance or interface here. Note that we do have something like interfaces (in some third-part librairies), but with a somewhat different (and much more powerful) usage: http://peak.telecommunity.com/protocol_ref/ref.html But if you're new to OO, this may not be the best starting point !-) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From aleax at mac.com Thu Jun 1 10:24:24 2006 From: aleax at mac.com (Alex Martelli) Date: Thu, 1 Jun 2006 07:24:24 -0700 Subject: shuffling elements of a list References: <1149045499.212967.13120@f6g2000cwb.googlegroups.com> <1149147164.012044.66960@u72g2000cwu.googlegroups.com> Message-ID: <1hg8scu.94jp741hydj6dN%aleax@mac.com> Peter Otten <__peter__ at web.de> wrote: > Gerard Flanagan wrote: > > Ben Finney wrote: > > >> pile_index = 0 > >> for card in deck: > >> piles[pile_index].append(card) > >> pile_index = (pile_index + 1) % numpiles > > > > no need to maintain an index ;-) > > > > piles = [ list() for _ in range(n) ] > > for i, card in enumerate(deck): > > piles[i % numpiles].append(card) > > No need to maintain an index ;-) > > piles = [deck[start::numpiles] for start in range(numpiles)] > > Assuming deck is a list, that is. Or, for deck hypothetically being an arbitrary iterable, import itertools as it piles = [ list() for _ in range(numpiles) ] for pile, card in it.izip(it.cycle(piles), deck): pile.append(card) i.e., let itertools do the cycling for you. But, sure, for this problem one can no doubt assume that deck is sliceable, and extended slicing (==slicing with a stride) comes in handy. Alex From shalinmangar at gmail.com Sun Jun 25 04:40:30 2006 From: shalinmangar at gmail.com (shalinmangar) Date: 25 Jun 2006 01:40:30 -0700 Subject: Skunk file upload problem Message-ID: <1151224830.135097.65900@i40g2000cwc.googlegroups.com> Hi, I am using Skunk web application server. The problem is that when I try to upload files from a form, the web.protocol.Connection object that I use in my python script can only give me the name of the uploaded file. I have no clue as to how to get the binary data itself or where the temp file is stored on the server. The scarce documentation of Skunk is hardly a help. If you have any leads please reply to this post. Regards, shalinmangar From jstroud at ucla.edu Thu Jun 15 15:49:22 2006 From: jstroud at ucla.edu (James Stroud) Date: Thu, 15 Jun 2006 12:49:22 -0700 Subject: a good programming text editor (not IDE) In-Reply-To: <1150393919.514359.55580@h76g2000cwa.googlegroups.com> References: <_xgkg.2317$No6.48542@news.tufts.edu> <1150393919.514359.55580@h76g2000cwa.googlegroups.com> Message-ID: Ant wrote: >>I've tried a few others, like TextPad and Crimson, and right now I use >>UltraEdit, which I love actually, except for minor issues here and >>there. But it'd be nice to make the move, as much as possible, to free, >>open-source, cross-platform software. > > > Vim is great if you have a good memory... Otherwise you end up trawling > through the help to find out how to do stuff that would in another IDE > be just a few menu clicks away. > Mental memory (the painful kind of memory) rapidly turns into muscle memory (the fun kind of memory) and all of those mind boggling keystrokes begin to feel like an artistic expression reminiscent of playing the piano. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From ksheka at gmail.com Mon Jun 19 22:06:33 2006 From: ksheka at gmail.com (K P S) Date: 19 Jun 2006 19:06:33 -0700 Subject: Simple script to make .png thumbnails from .zip archive... In-Reply-To: References: <1150660266.413889.217280@c74g2000cwc.googlegroups.com> Message-ID: <1150769193.295701.246330@g10g2000cwb.googlegroups.com> Thanks everyone. One last thing (I hope). How can I get the name of just the first file in a zipfile? I see routines to list all the files in a zip archive, but I don't see any to list only the first, or only the second, etc. It doesn't look like zipfile is storing info in a useful array that I can hash into. Or is it? Actually, I would like to get the name of the first file with a .jpg extension, if that's not asking too much. :-) zip=zipfile.ZipFile("text.zip",mode="r") picture=zip.read(zip.namelist(0)) This doesn't seem to work. :-( From carpentier.th at free.fr Wed Jun 21 02:33:17 2006 From: carpentier.th at free.fr (thomas carpentier) Date: Wed, 21 Jun 2006 08:33:17 +0200 Subject: Problem Py2exe pygtk and Pil In-Reply-To: <1150846148.550072.194350@m73g2000cwd.googlegroups.com> References: <44987851$0$29874$636a55ce@news.free.fr> <1150846148.550072.194350@m73g2000cwd.googlegroups.com> Message-ID: <4498e82b$0$24938$626a54ce@news.free.fr> I have already read the py2exe docs. When I come back at home, I will write a message who contains the script and the errors faulkner a ?crit : > read the py2exe docs. py2exe should put everything a new user should > need in the dist directory. if it doesn't, copy the libraries [be they > .pyc or .pyd or .dll] that py2exe missed into dist. > i know for a fact that py2exe is intelligent with the gtk libraries, so > check if the PIL libraries are in the dist directory. > > thomas carpentier wrote: >> Hello, >> >> I have created a program with a GUI ( glade). In this script I call the >> Python Imaging Library. >> >> I have developped this program onto linux, but il would like export it >> on Windows, however I have a problem with py2exe. If the new user has >> not python and library(PIL, GLADE) installed, it doesn't work. I don't >> know how integrate library into my setup. >> >> Thank you for your help. >> >> Thomas > From ianb at colorstudy.com Tue Jun 20 23:36:21 2006 From: ianb at colorstudy.com (Ian Bicking) Date: 20 Jun 2006 20:36:21 -0700 Subject: code is data In-Reply-To: <1150841588.382821.218340@i40g2000cwc.googlegroups.com> References: <1150574111.415068.255900@p79g2000cwp.googlegroups.com> <1150606118.456390.262620@y41g2000cwy.googlegroups.com> <1150626424.563673.175060@c74g2000cwc.googlegroups.com> <1150650852.275956.249340@p79g2000cwp.googlegroups.com> <1150658597.272001.171840@r2g2000cwb.googlegroups.com> <1150772934.314520.165200@p79g2000cwp.googlegroups.com> <1150841588.382821.218340@i40g2000cwc.googlegroups.com> Message-ID: <1150860981.560847.206050@u72g2000cwu.googlegroups.com> Ravi Teja wrote: > > Or... maybe to be more specific, the hard work later on goes into > > *code*. If you are enhancing your model, you do so with methods on the > > model classes, and those methods don't effect the DSL, they are just > > "code". You create some raw XML in the beginning, but quickly it's > > just a matter of gluing those pieces together, using functions instead > > of DSLs, and that's just "code". > > > That doesn't look that much better. How do you create it > > programmatically? I know how to pass a variable to > > CharField(maxlength=200); can I pass a variable to "char length 200" > > just as easily? Can I use **kw? Can I read it from a CSV file and > > construct the class that way? Maybe, but only by recreating all the > > native patterns that I can infer easily looking at the Django class. > > I am looking at it from the cognitive perspective. You are looking at > it from the compiler perspective. I don't think that distinction is very meaningful. As a programmer I have to understand both. I have to be able to synthesize correct expressions. I need to understand the compiler. I understand the Python compiler well, and it gives me reasonably good feedback when I get things wrong, and it has a lot of flexibility along several orthogonal lines. We're talking about programming languages, so it's useless to consider a cognitive perspective without considering the compiler perspective. > I think you are talking about full blown DSLs like SQL which try to be > self contained for a given domain. The ones I am referring are only > thin layers on Python. I understand you, but it's very unclear to me how you can make a thin layer that's not horribly leaky or stunted. In my experience one or both are likely in DSLs, and the result is horrible and only useful as a toy. If you are really serious about the implementation, sure. But DSL almost screams out that it lacks seriousness, and a long-term commitment to debuggability, generality, and documentation. > However I think that you are seeing my sample differently than I meant > it. I did not mean to create a special syntax file that would be parsed > as a text file such that it would loose all the benefits of Python. It > is just a thin layer over Python code for specific representational > benefits. Kay Schluehr does a good job of identifying it as such in his > reply. I understood the distinction you were making. But you were also speaking generally about generally programmable syntax, and I don't think that's a good idea, and it's very unclear how that mixes with Python. You can always do: model = make_model(""" my funny syntax """) And you actually get something that can be a close peer to normal Python code. But if you are talking about Python and some novel syntax interleaved, then the details seem to matter a lot, because the implementation is substantial and potentially invasive. There are also very *specific* things that can be discussed that are more conventional, and driven as much by the ease of implementation as expressiveness. I think that is much more productive, because I think the general case is a bad idea. The 'make' syntax is an example of this. Ian From michael.f.ellis at gmail.com Thu Jun 1 13:44:58 2006 From: michael.f.ellis at gmail.com (michael.f.ellis at gmail.com) Date: 1 Jun 2006 10:44:58 -0700 Subject: An oddity in list comparison and element assignment References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> Message-ID: <1149183898.338397.199070@y43g2000cwc.googlegroups.com> Hi Tim, In your example, a & b are references to the same object. I agree they should compare equally. But please note that a==b is True at every point in your example, even after the ValueError raised by b.remove(1). That's good consistent behavior. My original example is a little different. a and b never referred to the same object. They were containers created by different expressions with no object in common. The problem arises because the overloaded * operator makes row level copies of the lists in b. There's nothing wrong with that, but the fact remains that a and b are different in a very significant way. I agree with Alex that checking for this type of inequality is not a trivial programming exercise. It requires (at least) a parallel recursion that counts references with the containers being compared . At the same time, I know that much harder programming problems have been solved. Where I disagree with Alex is in the labeling of the existing behavior as 'natural'. Alternatively, it might make sense to disallow == for containers by raising a TypeError although that would eliminate a largely useful feature. Realistically, I know that Python is unlikely to adopt either alternative. It would probably break a lot of existing code. My point in the original post was to raise what I felt was a useful topic for discussion and to help others avoid a pitfall that cost me a couple of hours of head-scratching. By the way, I've been programming professionally for over 25 years and have used at least 30 different languages. During the past few years, Python has become my language of choice for almost everything because it helps me deliver more productivity and value to my clients. Cheers, Mike Tim Peters wrote: > Think about a simpler case: > > a = [1] > b = a > assert(a == b) > a.remove(1) > b.remove(1) > > Oops. The last line dies with an exception, despite that a==b at the > third statement and that ".remove(1)" is applied to both a and b. From larry.bates at websafe.com Sat Jun 10 12:15:51 2006 From: larry.bates at websafe.com (Larry Bates) Date: Sat, 10 Jun 2006 11:15:51 -0500 Subject: "parent" in a class __init__ def? In-Reply-To: References: Message-ID: <448AF037.60207@websafe.com> Ray Schumacher wrote: > What is the feeling on using "parent" in a class definition that class > methods can refer to, vs. some other organization ? > Should all relevant objects/vars just be passed into the method as needed? > It seems like including "parent" in the class def is just like a class > variable, which most do not recommend. > > An example: > class LXSerial: > def __init__(self, parent, debug=False): > ... > def connect(self, port, baud=9600, ptimeout=10): > if self.debug: > self.connectedPort = StringIO.StringIO(':A#') > else: > if self.parent.model=='LX200GPS': ptimeout = 240 > ... > > Ray > > Passing parent instance into a class is perfectly legal and is used extensively in modules like wxPython GUI. It isn't really anything like a class variable as the instance is normally passed not the class itself. Each instance can have different attributes. So if you have many parents with many children this can be an effective way to structure them. I think it depends on how deeply nested things get and how many parameters need to be passed. I've used it when I want to nest my objects more than 2 deep and I must pass around lots of attributes. I find it is easier to just look "upwards" into the parent to get the attribute than to clutter up my argument list passing arguments deeper and deeper into the class hierarchy. It can simplify the argument lists quite a bit. Maybe others can comment with their thoughts as well. -Larry Bates From esj at harvee.org Tue Jun 13 22:14:06 2006 From: esj at harvee.org (Eric S. Johansson) Date: Tue, 13 Jun 2006 22:14:06 -0400 Subject: question on dict subclassing and overriding __setitems__ In-Reply-To: <4f911aF12jediU1@uni-berlin.de> References: <4f911aF12jediU1@uni-berlin.de> Message-ID: <448F70EE.4090305@harvee.org> Diez B. Roggisch wrote: > dict.__setitem__(self, index.upper()) = value oh duh. > Or better even > > super(subclass, self).__setitem__(key.upper(), value) hmm. http://fuhm.net/super-harmful/ I think I need to do some more reading. ---eric From reply.in.the.newsgroup at my.address.is.invalid Thu Jun 1 19:18:29 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Fri, 02 Jun 2006 01:18:29 +0200 Subject: Zope / Plone Groups References: <1149178209.825191.128050@c74g2000cwc.googlegroups.com> Message-ID: d.schulz81 at gmx.net: >are there any specific groups for zope / plone regarding questions? Try plone-users: http://plone.org/support -- Ren? Pijlman From onurb at xiludom.gro Tue Jun 13 07:38:06 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 13 Jun 2006 13:38:06 +0200 Subject: What's wrong in this HTML Source file of a Bank In-Reply-To: <1150196896.819711.154640@c74g2000cwc.googlegroups.com> References: <1150196896.819711.154640@c74g2000cwc.googlegroups.com> Message-ID: <448ea39e$0$1757$626a54ce@news.free.fr> Thaqalainnaqvi at gmail.com wrote: > Several times I logged-in successfully but after log-in I can't use > features/services which were shown prior to my login. Can anyone exoert > > from this forum check , is it technical fault of Bank Web Site or this > problem pertaining to the user(me). It's definitively a problem with the user. The problem is : "user posts in the wrong newsgroup". (snip a whole page of crappy tag soup) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From deets at nospam.web.de Tue Jun 20 08:49:37 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 20 Jun 2006 14:49:37 +0200 Subject: comparing of python =?UTF-8?B?R1VJwrRz?= References: <1150806788.026172.140150@h76g2000cwa.googlegroups.com> Message-ID: <4fq979F1k6o98U1@uni-berlin.de> Bayazee wrote: > Hi > i want some info ... > plz tell me the benefit (or any data) of each gui (pyqt , pyqtk , > wxpython , tkinter ..) > in the other hand wich one you offer (and why ?) ? They are solely offered to confuse newbies - especially the ones google'cally challenged that can't search this NG for the bazillion discussions regarding their respective cons and pros. Diez From onurb at xiludom.gro Fri Jun 23 05:19:24 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Fri, 23 Jun 2006 11:19:24 +0200 Subject: Help req: Problems with MySQLdb In-Reply-To: <1150995682.162673.238130@u72g2000cwu.googlegroups.com> References: <1150968147.565850.156870@u72g2000cwu.googlegroups.com> <1150969803.984843.111950@y41g2000cwy.googlegroups.com> <1150995682.162673.238130@u72g2000cwu.googlegroups.com> Message-ID: <449bb21e$0$11019$626a54ce@news.free.fr> Simon Forman wrote: > rodmc wrote: > >>Hi, >> >>Thanks for your email. Well I am kind of new to exceptions in Python, >>but here is the code used below, as you can see it is somewhat basic. >>Is there a way to display more information about the exception? >> >>Best, >> >>rod >> > > > Use the traceback module (See > http://docs.python.org/lib/module-traceback.html for info on it.) > > import traceback > > try: > db = MySQLdb.connect(host=DBSERVERIP, user="user", > passwd="password", db="nuke") > except: > print "A database connection error has occurred" How can you assert it is a database connection error ? > traceback.print_exc() > return False > else: > pass > > #The rest of the program You get the same result - with a more accurate error message - by not handling the exception at all. > > It's generally very difficult to figure out what's going wrong without > the traceback in front of you. indeed. > Also, try an empty string (i.e. "") as your hostname, it's shorthand > for 'localhost'. > > > Hope this helps, > ~Simon > -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From marshall.spight at gmail.com Fri Jun 23 18:08:03 2006 From: marshall.spight at gmail.com (Marshall) Date: 23 Jun 2006 15:08:03 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: <1151086320.564736.272500@y41g2000cwy.googlegroups.com> References: <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150908952.804184.218990@r2g2000cwb.googlegroups.com> <1150991074.705803.211570@m73g2000cwd.googlegroups.com> <1151083239.829296.33030@i40g2000cwc.googlegroups.com> <1151083931.162325.268050@g10g2000cwb.googlegroups.com> <1151086320.564736.272500@y41g2000cwy.googlegroups.com> Message-ID: <1151100483.057344.310970@g10g2000cwb.googlegroups.com> Rob Thorpe wrote: > > Can I make a type in C that can only have values between 1 and 10? > How about a variable that can only hold odd numbers, or, to make it > more difficult, say fibonacci numbers? Well, of course you can't in *C*; you can barely zip you pants with C. But I believe you can do the above in C++, can't you? Marshall From digitalorganics at gmail.com Mon Jun 26 15:54:56 2006 From: digitalorganics at gmail.com (digitalorganics at gmail.com) Date: 26 Jun 2006 12:54:56 -0700 Subject: TypeError: Cannot create a consistent method resolution order (MRO)for bases object In-Reply-To: References: <1151345197.691600.200060@y41g2000cwy.googlegroups.com> Message-ID: <1151351696.790169.245960@m73g2000cwd.googlegroups.com> Oh, I forgot the line that bombed, sorry: line 52, in __main__ Bat.__bases__ += (Dog,) TypeError: Cannot create a consistent method resolution order (MRO) for bases object, Mixin, Dog See my other post for the complete code and my relevant note about new-style classes, thanks... Terry Reedy wrote: > wrote in message > news:1151345197.691600.200060 at y41g2000cwy.googlegroups.com... > > What are the reason one would get this error: TypeError: Cannot create > > a consistent method resolution order (MRO) for bases object ?? > > Because the interpreter cannot ;-) > > > I can provide the code if needed.... > > Details beget details ;-) > Yes, the class statement (header line up to ':') that bombed and the same > (first line) for classes it inherits from (and their base classes). The > conflict should be in the latter. > > tjr From fc14301589 at icqmail.com Sun Jun 11 11:41:41 2006 From: fc14301589 at icqmail.com (TheSaint) Date: Sun, 11 Jun 2006 23:41:41 +0800 Subject: Very newbie programming References: <448ae8ce_1@news.tm.net.my> <448bb2c7_1@news.tm.net.my> <1150035400.493116.319830@j55g2000cwa.googlegroups.com> Message-ID: <448c39b7_2@news.tm.net.my> George Sakkis wrote: > > If by 'rooted' you mean old enough, so is 'goto'... I was meaning a sort of (very) old style of programming. In fact I wrote some few hundreds lines on my own, but probably memory was much better the :) > will > thank yourself for doing so if you have to go back at this code a few > months later. I have to admit that's purely true :) > You can set a boolean "found" flag to False, make it True in the if Thank you to point it out, I forgotten such solution. BTW I was on the way of an "try/exept". But I should go back study the corect use :) > from fileinput import FileInput I'll read the manual (as you pointed hereby) and I think I can read the entire directory file by file. > Btw, you can delete a file or directory with os.unlink and os.rmdir, > respectively; no need for os.system. I still on learning, you know? :) Reading is the way to solve some problem, and your suggestions (you all) are very precious. F From onurb at xiludom.gro Wed Jun 14 09:11:04 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 14 Jun 2006 15:11:04 +0200 Subject: Tiddlywiki type project in Python? In-Reply-To: <1150289313.533749.52330@i40g2000cwc.googlegroups.com> References: <1150289313.533749.52330@i40g2000cwc.googlegroups.com> Message-ID: <44900ae9$0$8386$626a54ce@news.free.fr> jkn wrote: > Hi all > I'm trying out, and in general finding really useful, the various > TiddlyWiki variants that I guess many people here know about, for > organising my activities in a GTD way. One mild annoyance is in the > speed of the Javascript applications. I fancy having a go at writing > something like this for myself, where update speed would be a higher > priority. > > I don't know Javascript (although it looks moderately simple from a > brief peruse, It's not as simple as it may seem at first look. There are some real gotchas. But if you want a more pythonic javascript, you should have a look at mochikit. > and I know enough languages to know I'll be able to pick > it up); however I do know and use Python, although not nuch in a > web-oriented way. Since unlike JS, python is at least pre-compiled, I > have hopes that this would make things quicker. I do appreciate that JS > is built into the browser, which might make my Python approach slower. > I'm not sure of the 'architectural' approach to this; any suggestions, > and maybe pointers to previous work? I don't really understand what you're after here, since TiddlyWikiLikes can *not* work without javascript. Anyway, there's at least a Zope-based TiddlyWikiLike, so you may want to have a look here: http://ziddlywiki.org/ HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From find at my.address.elsewhere Tue Jun 20 18:30:29 2006 From: find at my.address.elsewhere (Matthias Blume) Date: Tue, 20 Jun 2006 17:30:29 -0500 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> Message-ID: Joachim Durchholz writes: > Matthias Blume schrieb: >> Perhaps better: A language is statically typed if its definition >> includes (or ever better: is based on) a static type system, i.e., a >> static semantics with typing judgments derivable by typing rules. >> Usually typing judgmets associate program phrases ("expressions") with >> types given a typing environment. > > This is defining a single term ("statically typed") using three > undefined terms ("typing judgements", "typing rules", "typing > environment"). This was not meant to be a rigorous definition. Also, I'm not going to repeat the textbook definitions for those three standard terms here. Next thing you are going to ask me to define the meaning of the word "is"... From chris.uppal at metagnostic.REMOVE-THIS.org Wed Jun 28 07:38:04 2006 From: chris.uppal at metagnostic.REMOVE-THIS.org (Chris Uppal) Date: Wed, 28 Jun 2006 12:38:04 +0100 Subject: languages with full unicode support References: <1151251736.590910.36050@u72g2000cwu.googlegroups.com> Message-ID: <44a26911$1$660$bed64819@news.gradwell.net> Joachim Durchholz wrote: > > This is implementation-defined in C. A compiler is allowed to accept > > variable names with alphabetic Unicode characters outside of ASCII. > > Hmm... that could would be nonportable, so C support for Unicode is > half-baked at best. Since the interpretation of characters which are yet to be added to Unicode is undefined (will they be digits, "letters", operators, symbol, punctuation.... ?), there doesn't seem to be any sane way that a language could allow an unrestricted choice of Unicode in identifiers. Hence, it must define a specific allowed sub-set. C certainly defines an allowed subset of Unicode characters -- so I don't think you could call its Unicode support "half-baked" (not in that respect, anyway). A case -- not entirely convincing, IMO -- could be made that it would be better to allow a wider range of characters. And no, I don't think Java's approach -- where there /is no defined set of allowed identifier characters/ -- makes any sense at all :-( -- chris From marshall.spight at gmail.com Sat Jun 24 21:33:16 2006 From: marshall.spight at gmail.com (Marshall) Date: 24 Jun 2006 18:33:16 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> Message-ID: <1151199196.870389.81960@p79g2000cwp.googlegroups.com> Chris F Clark wrote: > > I'm particularly interested if something unsound (and perhaps > ambiguous) could be called a type system. I definitely consider such > things type systems. I don't understand. You are saying you prefer to investigate the unsound over the sound? > However, I like my definitions very general and > vague. Your writing suggests the opposite preference. Again, I cannot understand this. In a technical realm, vagueness is the opposite of understanding. To me, it sounds like you are saying that you prefer not to understand the field you work in. > To me if > something works in an analogous way to how a known type system, I tend > to consider it a "type system". That probably isn't going to be at > all satisfactory to someone wanting a more rigorous definition. Analogies are one thing; definitions are another. > Of > course, to my mind, the rigorous definitions are just an attempt to > capture something that is already known informally and put it on a > more rational foundation. If something is informal and non-rational, it cannot be said to be "known." At best, it could be called "suspected." Even if you think something which turns out to be true, we could not say that you "knew" it unless your reasons for your thoughts were valid. I flipped a coin to see who would win the election; it came up "Bush". Therefore I *knew* who was going to win the election before it happened. See the probem? Marshall From sigzero at gmail.com Fri Jun 30 14:50:10 2006 From: sigzero at gmail.com (Robert Hicks) Date: 30 Jun 2006 11:50:10 -0700 Subject: sum fonction in gadfly In-Reply-To: <1151692151.751726.74500@d30g2000cwa.googlegroups.com> References: <1151137825.177814.217180@u72g2000cwu.googlegroups.com> <449d253d$1@nntp0.pdx.net> <1151154192.030596.223840@r2g2000cwb.googlegroups.com> <1151614282.661048.103630@b68g2000cwa.googlegroups.com> <1151689981.253966.146830@d56g2000cwd.googlegroups.com> <1151692151.751726.74500@d30g2000cwa.googlegroups.com> Message-ID: <1151693410.750596.54430@b68g2000cwa.googlegroups.com> aaronwmail-usenet at yahoo.com wrote: > Robert Hicks wrote: > > aaronwmail-usenet at yahoo.com wrote: > > > .... why are people so concerned > > > that it's not changing? > > > > > > > I didn't mean to be irritating and I wasn't concerned about it not > > changing but I could probably have stated the question a little better. > > For some reason I thought it was a dead project so maybe "still being > > maintained" would be a better statement. I dunno. > > You're not the only one. Why do I keep seeing "gadfly...dead" > in the same sentence? > > What if it doesn't need maintenance? Does that make it dead? > No offense to you personally, you are just repeating what > everyone else has been saying for years for reasons that > totally escape me. Several times people have suggested that > gadfly be added to the python standard library and then the > question comes up... who will maintain it? And I answer I'll > maintain it if anyone finds serious problems with it and then > a few months later I hear that it was decided that gadfly was > a dead project. This has been going on since about '97. > It's irritating and tiresome. Sorry, I'm grumpy today. > Hey, that is okay. I know now never to ask that question. : D Robert From apgwoz at gmail.com Tue Jun 13 09:42:02 2006 From: apgwoz at gmail.com (Andrew Gwozdziewycz) Date: Tue, 13 Jun 2006 09:42:02 -0400 Subject: Making a Label that looks the same as a button. In-Reply-To: <1150204443.568118.185030@c74g2000cwc.googlegroups.com> References: <1150204443.568118.185030@c74g2000cwc.googlegroups.com> Message-ID: It's imperative that you explain which toolkit you are using since they all have differences. On Jun 13, 2006, at 9:14 AM, Dustan wrote: > I have a Button object that gets replaced by a Label when clicked. > > Button(buttonsframe,text=' ',command=c,font=buttonsFont) > Note that the text is a single space. buttonsFont uses 'Courier > New' as > a family. > > When clicked, the Button is destroyed and replaced with a Label > object: > Label(buttonsframe,text=x,font=buttonsFont,relief=RAISED) > > The intent is for the Label object to look identical to the button > object, except for the non-space character x. The Label object is a > little smaller than the Button object. When I set borderwidth, the > label object does increase in size, but that's not going to make it > look the same, since it makes the border thicker. > > How do I get the Label object to look just like the Button object? > > -- > http://mail.python.org/mailman/listinfo/python-list --- Andrew Gwozdziewycz apgwoz at gmail.com http://23excuses.com | http://ihadagreatview.org | http://and.rovir.us From donn at u.washington.edu Thu Jun 8 14:59:37 2006 From: donn at u.washington.edu (Donn Cave) Date: Thu, 08 Jun 2006 11:59:37 -0700 Subject: Select hangs after some reads References: <1149737234.816833.177710@j55g2000cwa.googlegroups.com> <1149764138.868847.326250@i39g2000cwa.googlegroups.com> <128g8uvi6aj4240@corp.supernews.com> <1149779056.498540.46620@f6g2000cwb.googlegroups.com> Message-ID: In article , Steve Holden wrote: > The PSH flag indicates that the data stream must be flushed right > through to the other end. This is essential for interactive protocols > such as FTP: without it the server has no way to know that the client > has sent a complete command, and vice versa. So you would expect to see this done explicitly in the source for an FTP client or server implementation -- something that sets this PSH flag or else the protocol won't work? Or am I misunderstanding what you mean? I don't see that specific string anywhere in a the particular FTP implementation whose source happened to be handy, basically a Berkeley 4.4 variant as I think most are on UNIX. Somewhere around here I have a pass-through FTP client/server application that adds GSSAPI-Kerberos5 authentication to the protocol traffic, and I don't remember needing to do any such thing there. I'd have to look harder at the details, but as I recall it, like any sane application the protocol is defined in terms of data, so you know if you have a complete command by looking at what you have. Donn Cave, donn at u.washington.edu From invalid at invalid.net Thu Jun 8 09:25:40 2006 From: invalid at invalid.net (Frank Silvermann) Date: Thu, 08 Jun 2006 09:25:40 -0400 Subject: The Nature of the =?UTF-8?B?4oCcVW5peCBQaGlsb3NvcGh54oCd?= In-Reply-To: <4487d188$1@news.broadpark.no> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1149080931.582431.95560@j55g2000cwa.googlegroups.com> <1149730552.161534.121350@i40g2000cwc.googlegroups.com> <4487d188$1@news.broadpark.no> Message-ID: <44882412$0$20779$ec3e2dad@news.usenetmonster.com> Nils O. Sel?sdal wrote: > Xah Lee wrote: >> The Nature of the ?Unix Philosophy? [snip] > Perhaps you should take a peek at the ideas in Plan 9 from Bell Labs, > which is a continuation of this philosophy, unlike the "modern" unix > clones. Is there an actual Plan 9? I'm only aware of the one from Outer Space. frank From pipehappy at gmail.com Tue Jun 27 22:35:06 2006 From: pipehappy at gmail.com (pipehappy) Date: 27 Jun 2006 19:35:06 -0700 Subject: error in ConfigParser Message-ID: <1151462106.410114.240200@j72g2000cwa.googlegroups.com> Hello everyone: I came across the module ConfigParser and can use it correctly. import ConfigParser fp = open('test.cfg','w+') config = ConfigParser.ConfigParser() config.readfp(fp) config.add_section('test') config.set('test', 'haha', 'hehe') print config.sections() config.write(fp) ['test'] Traceback (most recent call last): File "configparser.py", line 8, in ? config.write(fp) File "C:\Python24\lib\ConfigParser.py", line 369, in write fp.write("[%s]\n" % section) IOError: (0, 'Error') I trace into the module and when executing the line "fp.write("[%s]\n" % section)", I find every parameter is correct: fp is still a open file object and section is 'test', I may miss something, but I just cannot figure it out. Can someone tell me what's going wrong here? Thanks From drtimhill at comcast.net Thu Jun 22 21:07:27 2006 From: drtimhill at comcast.net (drtimhill at comcast.net) Date: Fri, 23 Jun 2006 01:07:27 +0000 Subject: String negative indices? Message-ID: <062320060107.23611.449B3ECF00018C6C00005C3B22007348300404070803079B9D0B@comcast.net> I'm just starting out on Python, and am stumped by what appears an oddity in the way negative indices are handled. For example, to get the last character in a string, I can enter "x[-1]". To get the 2nd and 3rd to last, I can enter x[-3:-1] etc. This is fine. Logically, I should be able to enter x[-2:-0] to get the last and next to last characters. However, since Python doesn't distinguish between positive and negative zero, this doesn't work. Instead, I have to enter x[-2:]. With simple constants, this is ok, but it's a little more annoying when the start and end of the range are in variables somewhere. The only way I can find of making this work without lots of special-case "if" logic is to translate negative subscripts to positive, which kinda defeats the purpose of the negative subscripts anyway. Is there some magic I'm missing here? Wouldn't it actually be better for Python to treat 0 as a special case here, so that x[-2:0] and x[-2:] generated the same result? --Tim From hancock at anansispaceworks.com Fri Jun 2 15:11:11 2006 From: hancock at anansispaceworks.com (Terry Hancock) Date: Fri, 02 Jun 2006 19:11:11 +0000 Subject: An oddity in list comparison and element assignment In-Reply-To: <1hg9onn.p25evr18a09f9N%aleax@mac.com> References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> <447f152f@nntp0.pdx.net> <1149194434.528648.148860@u72g2000cwu.googlegroups.com> <1hg9onn.p25evr18a09f9N%aleax@mac.com> Message-ID: <44808D4F.9070001@anansispaceworks.com> Alex Martelli wrote: > Slawomir Nowaczyk wrote: > > On Thu, 01 Jun 2006 13:40:34 -0700 michael.f.ellis at gmail.com wrote: > > #> Scott David Daniels wrote: #> > Would you say that envelope > > containing five $100 bills is equal to #> > an envelope containing > > five $100 bills with different serial numbers? > > > > #> Yes (unless I was testing the assertion that the second envelope > > did #> not contain counterfeits of the first) > > > > So, what if Bank of America later decided that bills with serial > > numbers containing "7" are no longer valid? > > Then Wachowia would no doubt be happy to take my business away from > BoA;-). > > I suspect you believe BoA is some kind of "official" body -- it > isn't, just like Deutschebank is not one in Germany (rather, > Bundesbank is). Yeah, it's a funny mistake, but what he meant, is what if the US Treasury Department declared bills with serial numbers containing "7" invalid. That would indeed complete the analogy. And it's a sharp example -- because money is conceived of as fungible, one $100 is as good as another, so two $100 bills compare as equal, whether they are equal or not. Of course, the counter argument is that it's not unlike counting a reflection of a $100 bill as another $100 and concluding that you have $200 (you need two mirrors to double your money, technically ;-)). I don't think there's any way to make it "more logical" -- it's going to break somewhere no matter what assumption you make, so you just have to learn what's really going on in order to avoid confusion. Cheers, Terry -- Terry Hancock (hancock at AnansiSpaceworks.com) Anansi Spaceworks http://www.AnansiSpaceworks.com From steven.bethard at gmail.com Sun Jun 4 21:39:16 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 04 Jun 2006 19:39:16 -0600 Subject: Max function question: How do I return the index of the maximum value of a list? In-Reply-To: <1149459320.802652.186930@i40g2000cwc.googlegroups.com> References: <1149459320.802652.186930@i40g2000cwc.googlegroups.com> Message-ID: <38adnTLbg47fFh7ZnZ2dnUVZ_qednZ2d@comcast.com> jj_frap wrote: > I'm new to programming in Python and am currently writing a three-card > poker simulator. I have completed the entire simulator other than > determining who has the best hand (which will be far more difficult > than the aspects I've codes thus far)...I store each player's hand in a > list of hand objects and I determine hand strength via a handstrength > list with one element for each player. > > When I try to print the "winner" (I've not coded for kicker strength > and ties yet) via the max function, it returns the maximum value in the > list rather than the index associated with that value. > > How do I return the index? Can you do something like:: max_val, max_index = max((x, i) for i, x in enumerate(my_list)) ? If any two "x" values are equal, this will return the one with the lower index. Don't know if that matters to you. STeVe From programer_vedran_d at net-dot-hr.no-spam.invalid Sat Jun 24 08:02:52 2006 From: programer_vedran_d at net-dot-hr.no-spam.invalid (veki) Date: 24 Jun 2006 12:02:52 GMT Subject: FTPUTIL WITH TKFILEDIALOG Message-ID: <449d29eb$0$79453$892e7fe2@authen.yellow.readfreenews.net> HI,ALL I am new ftputil user and I need help about something: my prog: >>> import tkFileDialog >>> import ftputil >>> name=tkFileDialog.askopenfile() >>>ftp=ftputil.FTPHost() #Please when you want try this prog use your ftp server >>> nesto1=name.name >>> ftp.upload(nesto1,nesto1,'b') ERROR IS: Traceback (most recent call last): File "", line 1, in -toplevel- ftp.upload(nesto1,nesto1,'b') File "C:\Python24\lib\ftputil.py", line 463, in upload self.__copy_file(source, target, mode, open, self.file) File "C:\Python24\lib\ftputil.py", line 452, in __copy_file target = target_open(target, target_mode) File "C:\Python24\lib\ftputil.py", line 282, in file raise ftp_error.FTPIOError("directory '%s' is not accessible" % FTPIOError: directory '/C:/Python24' is not accessible THANKS!!!!!!!!!!!!!! From cdsmith at twu.net Mon Jun 26 15:02:33 2006 From: cdsmith at twu.net (Chris Smith) Date: Mon, 26 Jun 2006 13:02:33 -0600 Subject: What is Expressiveness in a Computer Language References: <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <34aj92h0g7tqi9amhh7k3ieq5n568t0e6f@4ax.com> Message-ID: George Neuner wrote: > On Sun, 25 Jun 2006 14:28:22 -0600, Chris Smith > wrote: > > >George Neuner wrote: > >> >Undecidability can always be avoided by adding annotations, but of > >> >course that would be gross overkill in the case of index type widening. > >> > >> Just what sort of type annotation will convince a compiler that a > >> narrowing conversion which could produce an illegal value will, in > >> fact, never produce an illegal value? > > > >The annotation doesn't make the narrowing conversion safe; it prevents > >the narrowing conversion from happening. > > That was my point ... you get a program that won't compile. That's not actually the case here. If we're talking only about type conversions and not value conversions (see below), then narrowing conversions are only necessary because you've forgotten some important bit of type information. By adding annotations, you can preserve that piece of information and thus avoid the conversion and get a program that runs fine. > I worked in signal and image processing for many years and those are > places where narrowing conversions are used all the time - in the form > of floating point calculations reduced to integer to value samples or > pixels, or to value or index lookup tables. Often the same > calculation needs to be done for several different purposes. These are value conversions, not type conversions. Basically, when you convert a floating point number to an integer, you are not simply promising the compiler something about the type; you are actually asking the compiler to convert one value to another -- i.e., see to it that whatever this is now, it /becomes/ an integer by the time we're done. This also results in a type conversion, but you've just converted the value to the appropriate form. There is a narrowing value conversion, but the type conversion is perfectly safe. > I can know that my conversion of floating point to integer is going to > produce a value within a certain range ... but, in general, the > compiler can't determine what that range will be. If you mean "my compiler can't", then this is probably the case. If you mean "no possible compiler could", then I'm not sure this is really very likely at all. > Like I said to Ben, I haven't seen any _practical_ static type system > that can deal with things like this. I agree. Such a thing doesn't currently exist for general-purpose programming languages, although it does exist in limited languages for some specific domains. -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation From alanalan at newsgroup.nospam Fri Jun 2 16:01:17 2006 From: alanalan at newsgroup.nospam (A.M) Date: Fri, 2 Jun 2006 16:01:17 -0400 Subject: Open Source Charting Tool Message-ID: <1L0gg.1841$Su3.159041@news20.bellglobal.com> Hi, I developed a HTML reporting tool that renders Oracle data to HTML and Oracle. At this point I have to add charts (3d bars and pie charts) to this application. I don't think that I have to do it from scratch. Is there any open source charting tool that help me create charts in JPG or gif format? Thanks, Alan From artur_spruce at yahoo.com Wed Jun 7 17:40:51 2006 From: artur_spruce at yahoo.com (AdSR) Date: 7 Jun 2006 14:40:51 -0700 Subject: Mutual interdependency problem References: Message-ID: <1149716451.372274.258280@u72g2000cwu.googlegroups.com> Jeremy Sanders wrote: > I'm getting problems with modules with interdependencies when using the > import form "import foo.bar as bar". > > [snip] > > Maybe the "from foo import *" style in __init__.py is a bad idea, but it > allows you to expose a flat namespace without having to put all the code > into one file. Then naturally you need mutual interdependencies, and then > it breaks! I can work around it by removing the "as XXX" parts on the > import statement, but it gets annoying having to specify the full path. What worries me is that you have two modules that import each other. Are you sure you can't do it any other way? AdSR From fredrik at pythonware.com Mon Jun 19 12:07:54 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 19 Jun 2006 18:07:54 +0200 Subject: pyfcp In-Reply-To: References: Message-ID: Marc 'BlackJack' Rintsch wrote: >> http://www.python.org.nz/pyfcp > > I get: Unknown host www.python.org.nz for future announcements, I'd recommend using: http://www.google.com/search?q=pyfcp From slomojo83 at gmail.com Thu Jun 15 12:49:00 2006 From: slomojo83 at gmail.com (Josiah Manson) Date: 15 Jun 2006 09:49:00 -0700 Subject: list of polynomial functions Message-ID: <1150390140.459461.169900@i40g2000cwc.googlegroups.com> In the following program I am trying to learn how to use functional programming aspects of python, but the following program will crash, claiming that the recursion depth is too great. I am attempting to make a list of polynomial functions such that poly[0](3) = 1, poly[1](3) = 3, poly[2](3) = 9, etc. Could someone point me in the right direction? Thanks. def make_polys(n): """Make a list of polynomial functions up to order n. """ p = lambda x: 1 polys = [p] for i in range(n): polys.append(lambda x: polys[i](x)*x) return polys # construct a vector of polynomials polys = make_polys(5) # print for p in polys: print p(3) From rupole at hotmail.com Thu Jun 22 23:29:47 2006 From: rupole at hotmail.com (Roger Upole) Date: Thu, 22 Jun 2006 23:29:47 -0400 Subject: win32com and name of com References: <1151001177.360087.202620@m73g2000cwd.googlegroups.com> Message-ID: <1151033037_11067@sp6iad.superfeed.net> "bli" wrote in message news:1151001177.360087.202620 at m73g2000cwd.googlegroups.com... > hi all > first post. > I am using python to connect to dll. I have read everything I can find > on com!#@! > and tried all variations of the name of the dll to use in the Dispatch. > I get a com error-(-2147...1005, 'Invalid class string',None,None) > Do I add .Application to the name? (eg 'XXXX Control > Library.Application') > Any help appreciated?!? How do I get the info? > I have tried the gencache lines suggested in the lit. maybe I use them > wrong. > (All authors are fairly sparse on the topic using Microsoft examples > that are more self evident.) > thanks muchly! > Your best bet is the documentation for the application. However, if the dll is registered correctly you can also find the progid in the registry by searching for the dll name. Roger ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= East/West-Coast Server Farms - Total Privacy via Encryption =--- From rhcarvalho at gmail.com Sat Jun 10 22:04:06 2006 From: rhcarvalho at gmail.com (Rodolfo) Date: 10 Jun 2006 19:04:06 -0700 Subject: Algorithm for Labels like in Gmail In-Reply-To: <1149988373.769406.305720@i40g2000cwc.googlegroups.com> References: <1149985001.668803.121260@c74g2000cwc.googlegroups.com> <1149988373.769406.305720@i40g2000cwc.googlegroups.com> Message-ID: <1149991446.047249.92020@m38g2000cwc.googlegroups.com> Hi George, George Sakkis wrote: > Google for "many-to-many relationships". In short, you have two entity > classes (say emails and labels) where each instance of one entity may > be associated to zero or more instances of the other entity. In > databases you implement this by having three tables, one for each > entity and one for their association: > > Email RelEmailLabel Label > ---------- -------------- --------- > ID <--- EmailID ID > subject LabelID ---> name > ... ... > Ok, but how can I keep my Relationship Table out of bugs, bad data?! I wonder how i'll control the following: 1st) Given an generic email, in which group(s) is it contained? 2nd) Given a group, which Emails/contacts does it contain? I don't have much expererience with databases (yet). Will the pysqlite work with ease? Because I don't mean to make a big big program, just something very simple for my personal use. > > Then you can associate mails to labels by joining all three tables > together on the IDs. Of course you can implement this in memory as well > but you should probably want to store them in some persistent area > anyway, so an rdbms the way to go. Sqlite (with pysqlite) would meet > your needs just fine. I'll google for this module tomorrow and try to learn something about it. I plan to post the code I manage to write. BTW which is the best way to store all those data files? Plain text files? Some kind of binary file? or what? Thank you once again, Rodolfo From pkarjala at mail.student.oulu.fi Wed Jun 21 05:51:35 2006 From: pkarjala at mail.student.oulu.fi (Pekka Karjalainen) Date: Wed, 21 Jun 2006 09:51:35 +0000 (UTC) Subject: help() on stdout.closed Message-ID: Python 2.4.1 (#1, May 16 2005, 15:19:29) [GCC 4.0.0 20050512 (Red Hat 4.0.0-5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from sys import stdout >>> help (stdout.closed) If I do this, it gives me help on the bool object. Also: >>> stdout.closed.__doc__ 'bool(x) -> bool\n\nReturns True when the argument x is true, False otherwise.\nThe builtins True and False are the only two instances of the class bool.\nThe class bool is a subclass of the class int, and cannot be subclassed.' What's going on here? Other docstrings in sys.stdout work fine. Pekka (uses 2.4.3 on another comp) From arvind.mulay at gmail.com Thu Jun 29 05:29:10 2006 From: arvind.mulay at gmail.com (arvind) Date: 29 Jun 2006 02:29:10 -0700 Subject: Widget access Message-ID: <1151573350.717362.216900@j72g2000cwa.googlegroups.com> how to make the widgets defined inside the function available outside it without using OOPs concept? From nmm1 at cus.cam.ac.uk Wed Jun 21 04:57:57 2006 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 21 Jun 2006 08:57:57 GMT Subject: How to truncate/round-off decimal numbers? References: <1150875897.866447.312150@g10g2000cwb.googlegroups.com> Message-ID: In article <1150875897.866447.312150 at g10g2000cwb.googlegroups.com>, "per9000" writes: |> |> just a thought: if you *always* work with "floats" with two decimals, |> you are in fact working with integers, but you represent them as a |> floats - confusing for the internal representation. No, you aren't - you are working with fixed-point, which is something that is neither integers nor floating-point, but is somewhere in between. I am (just) old enough to remember when it was used for numeric work, and to have used it for that myself, but not old enough to have done any numeric work using fixed-point hardware. |> So why not work with int(float * 100) instead? This way you only have |> to take care of roundoffs etc when dividing. And multiplying, and calling most mathematical functions. Regards, Nick Maclaren. From michele.petrazzo at TOGLIunipex.it Fri Jun 30 13:12:23 2006 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Fri, 30 Jun 2006 17:12:23 GMT Subject: python for windows internet filter / firewall In-Reply-To: <1151684855.966099.297980@i40g2000cwc.googlegroups.com> References: <1151590961.464723.249360@p79g2000cwp.googlegroups.com> <1151684855.966099.297980@i40g2000cwc.googlegroups.com> Message-ID: thorley at gmail.com wrote: > Thanks for a detailed reply. > I thing that now we are becoming OT... :) > because is restricts traffic on a port based on content, but you're > correct, they aren't the same thing at all. > So, what you want to do? Open and close a destination IP (domain), following what the user see, with a firewall? It's so hard to do, and it doesnt' sound like a good think. This is the work of a proxy, not of a firewall. >> win32COM for do what? > > My knowledge of COM is miniscule, but I assumed it has a low level > interface for packet filtering. > Yes, but you have to create a dll that work at low level and has an low level features... Something like that wipfw do: create a .sys/.vxd (if I remember correctly) that in your case are the dll and after with an exe (that are the python program) that teach the rules... Very bas idea, for me! >> You can do it in not so difficult manner: Take twisted and its >> proxy class, make some outline code (for filter the pages) and >> enjoy! (work also on win) > > Proxy would be an easy way, but I wanted to do it at a lower level. > But you _can't_ with python. How you create a .sys/.vxd file? Also that has only few kb program? And don't such more than few kb memory? Keep the proxy way or switch to another language :) > Thanks again. --matthew > Michele From gneuner2/ at comcast.net Wed Jun 21 16:55:55 2006 From: gneuner2/ at comcast.net (George Neuner) Date: Wed, 21 Jun 2006 16:55:55 -0400 Subject: What is Expressiveness in a Computer Language References: <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> Message-ID: <34aj92h0g7tqi9amhh7k3ieq5n568t0e6f@4ax.com> On Wed, 21 Jun 2006 16:12:48 +0000 (UTC), Dimitri Maziuk wrote: >George Neuner sez: >> On Mon, 19 Jun 2006 22:02:55 +0000 (UTC), Dimitri Maziuk >> wrote: >> >>>Yet Another Dan sez: >>> >>>... Requiring an array index to be an integer is considered a typing >>>> problem because it can be checked based on only the variable itself, >>>> whereas checking whether it's in bounds requires knowledge about the array. >>> >>>You mean like >>> subtype MyArrayIndexType is INTEGER 7 .. 11 >>> type MyArrayType is array (MyArrayIndexType) of MyElementType >>> >> >> If the index computation involves wider types it can still produce >> illegal index values. The runtime computation of an illegal index >> value is not prevented by narrowing subtypes and cannot be statically >> checked. > >My vague recollection is that no, it won't unless _you_ explicitly code an >unchecked type conversion. But it's been a while. You can't totally prevent it ... if the index computation involves types having a wider range, frequently the solution is to compute a wide index value and then narrow it. But if the wider value is out of range for the narrow type you have a problem. Using the illegal wide value in a checked narrowing conversion will throw a CONSTRAINT_ERROR exception - it doesn't matter whether you access the array directly using the wide value or try to assign the value to a variable of the narrow index type. Using the wide value unchecked will access memory beyond the array which is not what you wanted and may cause a crash. The point is really that the checks that prevent these things must be performed at runtime and can't be prevented by any practical type analysis performed at compile time. I'm not a type theorist but my opinion is that a static type system that could, a priori, prevent the problem is impossible. George -- for email reply remove "/" from address From sashang at gmail.com Fri Jun 23 07:19:17 2006 From: sashang at gmail.com (sashang at gmail.com) Date: 23 Jun 2006 04:19:17 -0700 Subject: Using metaclassed to dynamically generate a class based on a parameter to the objects init function. In-Reply-To: <449bb4d6$0$32258$626a54ce@news.free.fr> References: <1151018669.849641.265990@g10g2000cwb.googlegroups.com> <449bb4d6$0$32258$626a54ce@news.free.fr> Message-ID: <1151061557.682689.189440@c74g2000cwc.googlegroups.com> Bruno Desthuilliers wrote: > sashang at gmail.com wrote: > > Hi > > > > I'd like to use metaclasses to dynamically generate a class based on a > > parameter to the objects init function. > > Do you really need a metaclass for this ? > > > For example: > > > > class MetaThing(type): > > def __init__(cls, name, bases, dict, extra_information): > > super(MetaThing, cls).__init__(name, bases, dict) > > #setup the class based on the parameter extra_information > > > > class Thing: > > __metaclass__ = MetaThing > > def __init__(self, extra_information): > > #Somehow pass extra_information to the MetaThing > > > > extra_information = 1 > > t = Thing(extra_information) > > Why would you want a new *class* here ? > > > The above sample won't work but I hope it demonstrates what I'm trying > > to do. > > Not enough, I'm afraid - unless it's just me being dumb. From what I see > here, you just can add the extra informations on the object in the > initializer. What's your *real* use case ? > > The extra_information is used in MetaThing to tell it what attributes to add to the class. For example: class MetaThing(type): def __init__(cls, name, bases, dict, extra_information): super(MetaThing, cls).__init__(name, bases, dict) #setup the class based on the parameter extra_information setattr(cls, make_name(extra_information), make_object(extra_information)) Does that clarify things? I might have the wrong approach - I'm new to metaclasses. However I do think the solution to my problem lies with them since I have to dynamically generate a class and metaclasses provide a mechanism for doing this. From bussieremaillist at gmail.com Sun Jun 11 20:28:25 2006 From: bussieremaillist at gmail.com (bussiere) Date: Mon, 12 Jun 2006 02:28:25 +0200 Subject: Z39.50 and tyrannioware website seems to be down Message-ID: <001b01c68db7$1ee8e970$6801a8c0@Iris> sorry to disturb you but from here : http://lists.indexdata.dk/pipermail/zoom/2005-October/000806.html if yes i cannot take this three files : asn1.py z3950_2001.py zdefs.py the website seems to be down : http://cvs.sourceforge.net/viewcvs.py/tyrannioware/ may i ask you if someone always have these three files and if someone can mail me them , then ? Regards Bussiere -------------- next part -------------- An HTML attachment was scrubbed... URL: From johnjsal at NOSPAMgmail.com Thu Jun 15 14:06:19 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 15 Jun 2006 18:06:19 GMT Subject: a good programming text editor (not IDE) In-Reply-To: References: <_xgkg.2317$No6.48542@news.tufts.edu> <1150393919.514359.55580@h76g2000cwa.googlegroups.com> Message-ID: Fredrik Lundh wrote: > John Salerno wrote: > >>> jEdit is for me still the best text editor available. Very extensible >>> with macros (which can be written in Jython with the appropriate plugin >>> installed). >> >> I like the idea of being extensible, but of course I can only write in >> Python. Are there any editors that support that? > > Jython is a Python implementation for Java. > > > Oh, I know, but doesn't it require knowledge of Java? Or am I being even more newbie-ish than I thought I was? :) From mail at microcorp.co.za Sat Jun 17 04:50:11 2006 From: mail at microcorp.co.za (H J van Rooyen) Date: Sat, 17 Jun 2006 10:50:11 +0200 Subject: Python is fun (useless social thread) ;-) References: <1150381872.958342.180420@p79g2000cwp.googlegroups.com> <4492c276$0$5272$636a55ce@news.free.fr> Message-ID: <032701c691f0$6f41ce40$03000080@hendrik> Bruno wrote: 8<------------(snip)-------------- | The answer is 42. That's all you need to know. Right on, Ford Prefect !!! What's for Lunch? - Hendrik From n.estner at gmx.de Sun Jun 4 08:41:23 2006 From: n.estner at gmx.de (nikie) Date: 4 Jun 2006 05:41:23 -0700 Subject: Python less error-prone than Java References: Message-ID: <1149424883.529756.13700@j55g2000cwa.googlegroups.com> Let's look at two different examples: Consider the following C# code: static decimal test() { decimal x = 10001; x /= 100; x -= 100; return x; } It returns "0.01", as you would expect it. Now, consider the python equivalent: def test(): x = 10001 x /= 100 x -= 100 return x It returns "0". Clearly an error! Even if you used "from __future__ import division", it would actually return "0.010000000000005116", which, depending on the context, may still be an intolerable error. Morale: the problem isn't whether the the types are chosen at compile-time or at runtime, it's simply _what_ type is chosen, and whether it's appropriate or not. I can even think of an example where C's (and Java's) bounded ints are the right choice, while Python's arbitraty-precision math isn't: Assume you get two 32-bit integers containing two time values (or values from an incremental encoder, or counter values). How do you find out how many timer ticks (or increments, or counts) have occured between those two values, and which one was earlier? In C, you can just write: long Distance(long t1, long t0) { return t1-t0; } And all the wraparound cases will be handled correctly (assuming there have been less than 2^31 timer ticks between these two time values). "Distance" will return a positive value if t1 was measured after t0, a negative value otherwise, even if there's been a wraparound in between. Try the same in Python and tell me which version is simpler! From digitalorganics at gmail.com Mon Jun 26 12:00:02 2006 From: digitalorganics at gmail.com (digitalorganics at gmail.com) Date: 26 Jun 2006 09:00:02 -0700 Subject: Search String for Word In-Reply-To: References: <1151332947.985001.226510@r2g2000cwb.googlegroups.com> Message-ID: <1151337602.185178.61830@p79g2000cwp.googlegroups.com> Thank you thank you! Tim Williams wrote: > On 26 Jun 2006 08:24:54 -0700, digitalorganics at gmail.com > wrote: > > And what if I want to search for an item in a tuple, is there a > > similarly easy method? > > > > Tim Chase wrote: > > > > What's the best way to search a string for a particular word and get a > > > > booleen value indicating whether it exists in the string or not? > > > > > > >>> substring = 'foo' > > > >>> targetstring = 'blah foo bar' > > > >>> substring in targetstring > > > True > > > >>> if substring in targetstring: print 'yup' > > > yup > > >>> t = ('a', 'b', 'c', 'd', 'e') > >>> a = 'a' > >>> a in t > True > >>> y = 'y' > >>> y in t > False > > >>> t = ('test', 'black', 'white') > >>> a = 'a' > >>> [i for i in t if a in i] > ['black'] > >>> > > HTH :) From dadapapa at googlemail.com Thu Jun 8 11:24:37 2006 From: dadapapa at googlemail.com (Harold Fellermann) Date: 8 Jun 2006 08:24:37 -0700 Subject: how to switch from os.tmpnam to os.tmpfile In-Reply-To: References: <1149773439.534989.54450@i40g2000cwc.googlegroups.com> <1149777877.945829.25390@h76g2000cwa.googlegroups.com> Message-ID: <1149780277.397600.201420@j55g2000cwa.googlegroups.com> Chris Lambacher wrote: > You should be able to find exactly what you need in the tempfile module. > http://docs.python.org/lib/module-tempfile.html thanks! tempfile.NamedTemporaryFile() is exaclty what I have been looking for. Using python for such a long time now, and still there are unknown goodies in the library, great :-) - harold - From ilias at lazaridis.com Thu Jun 8 08:28:39 2006 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Thu, 08 Jun 2006 15:28:39 +0300 Subject: CONSTRUCT - Python's way of Ruby's "alias_method" Message-ID: I have a few small questions subjecting python functionality, most importantly the "alias_method". - *IMPORT* I would like to know, if this construct is valid, or if it can result in problems (that I do not see as a newcomer): 1082 try: 1083 from django.rework.evolve import evolvedb 1084 except ImportError: 1085 def evolvedb(): 1086 "Evolve Command Dummy" 1087 print 'Command evolvedb not imported' 1088 evolvedb.args ='' - *PATCHING* A second problem is, how to make the setup for users (testers) more convenient. Is there e.g. any mechanism to apply a patch in an automated manner (e.g. using a python library)? - *ALIAS_METHOD* The django commands are hard-coded: http://code.djangoproject.com/browser/django/trunk/django/core/management.py#L1180 thus elegant/dynamic additions of commands seem not possible. Another possibility is to enlink (hook?) the functionality into an existent function Is there any way (beside a patch) to alter the behaviour to an existing function. Is ther a python construct similar to the "alias_method" of Ruby: (example from an simple evolution support for a ruby orm) #------------------------------------------------------------------------------ # use "alias_method" to enlink the code #------------------------------------------------------------------------------ class SqliteAdapter alias_method :old_create_table, :create_table def create_table(*args) table_evolve(*args) result = old_create_table(*args) return result end end http://lazaridis.com/case/persist/og-evolve.rb - - - If anyone is interested to verify the results in order to stabelize the simple schema evolution support for django, please review the results here: http://case.lazaridis.com/wiki/DjangoProductEvaluation http://case.lazaridis.com/wiki/DjangoSchemaEvolution http://case.lazaridis.com/browser/django/rework/evolve.py http://case.lazaridis.com/browser/django/rework/add_evolvedb_command.diff . -- http://lazaridis.com From iainking at gmail.com Wed Jun 7 11:23:36 2006 From: iainking at gmail.com (Iain King) Date: 7 Jun 2006 08:23:36 -0700 Subject: pyqt show wizard In-Reply-To: <1149686821.537392.154130@h76g2000cwa.googlegroups.com> References: <1149686724.992518.104290@i39g2000cwa.googlegroups.com> <1149686821.537392.154130@h76g2000cwa.googlegroups.com> Message-ID: <1149693816.914007.15260@c74g2000cwc.googlegroups.com> David Boddie wrote: > Summary of the usual mess made by the Google Groups web interface: > > > I suspect that you really want to call w.exec_loop() instead, since > this will only return control to the method after the user has finished > interacting with the wizard. > > > Take a look at the QWizard documentation for more information: > > > http://doc.trolltech.com/3.3/qwizard.html > > > David test From bumtool at yahoo.com Sun Jun 25 09:25:22 2006 From: bumtool at yahoo.com (kilnhead) Date: 25 Jun 2006 06:25:22 -0700 Subject: Eclipse IDE question Message-ID: <1151241922.620601.218580@r2g2000cwb.googlegroups.com> I am trying to use eclipse for python development. Is it possible to run a python script without having to name/setup a configuration? Can eclipse be set up so that "run" loads the code into the interpreter and goes? I don't want to create a new run config every time I want to run a script. From ianb at colorstudy.com Mon Jun 19 23:08:54 2006 From: ianb at colorstudy.com (Ian Bicking) Date: 19 Jun 2006 20:08:54 -0700 Subject: code is data In-Reply-To: <1150658597.272001.171840@r2g2000cwb.googlegroups.com> References: <1150574111.415068.255900@p79g2000cwp.googlegroups.com> <1150606118.456390.262620@y41g2000cwy.googlegroups.com> <1150626424.563673.175060@c74g2000cwc.googlegroups.com> <1150650852.275956.249340@p79g2000cwp.googlegroups.com> <1150658597.272001.171840@r2g2000cwb.googlegroups.com> Message-ID: <1150772934.314520.165200@p79g2000cwp.googlegroups.com> Ravi Teja wrote: > Fredrik Lundh wrote: > > Ravi Teja wrote: > > > > > Web frameworks, which seem to be the rage now in Python community could > > > have benefited tremendously from Macro capabilities since they have a > > > lot of boiler plate. > > > > they do? methinks you haven't done much web programming lately... > > > > > > You blogged on Django. Let's use that. Don't you think model creation > in Django can be represented better, given that it is done often > enough? Actually, no, it's not done that much. Creating and managing tables isn't something done lightly. It's essential to building a new application, but (at least in my experience, in similar systems) the database models stabalize early and you don't spend that much time with them. Especially not with the DSL aspects. I add and remove methods often, but I am loathe to add and remove columns. Now, this might seem like I'm being pedantic, but in my experience lots of seemingly obvious DSLs end up not being that obvious. XML generation, for instance. It's nice to have a good syntax -- and you can get a pretty good syntax in Python (e.g., HTMLGen, stan, etc). But efforts that go further are generally misplaced, because it's actually not a very hard or common thing to do, even when you are slinging around lots of XML. Or... maybe to be more specific, the hard work later on goes into *code*. If you are enhancing your model, you do so with methods on the model classes, and those methods don't effect the DSL, they are just "code". You create some raw XML in the beginning, but quickly it's just a matter of gluing those pieces together, using functions instead of DSLs, and that's just "code". > Let's take an example from the official tutorial > from > http://www.djangoproject.com/documentation/tutorial1/#creating-models > > class Poll(models.Model): > question = models.CharField(maxlength=200) > pub_date = models.DateTimeField('date published') > > class Choice(models.Model): > poll = models.ForeignKey(Poll) > choice = models.CharField(maxlength=200) > votes = models.IntegerField() > > I don't use Django and I made this up quickly, so please don't pick on > subtleties. > > @Poll: > question: char length 200 > pub_date('date published'): date > > @Choice: > poll -> Poll > choice: char length 200 > votes: int That doesn't look that much better. How do you create it programmatically? I know how to pass a variable to CharField(maxlength=200); can I pass a variable to "char length 200" just as easily? Can I use **kw? Can I read it from a CSV file and construct the class that way? Maybe, but only by recreating all the native patterns that I can infer easily looking at the Django class. > The following is my rationale. Annoted variables, symbols and code > layout visually cue more efficiently to the object nature than do > explicit text definitions. Of course, this is only sensible when there > aren't too many of any of those. In that case, the cognitive cost of > notation outweighs the representational cost of text. Words are great. Python is light on symbols, and that is good. Python is not perfect when it comes to expressing data structures (the more I think about it, the more PEP 359 grows on me), but real DSLs are questionable to me. Even the Lisps stick to an incredibly homogenous syntax (far more homogeneous than Python) to make macros feel familiar. > Representational minimalism is troublesome in general code (ala Perl), > but not so in a DSL where the context is constrained. Constrained context is a step backward! How do you add methods? How do you do looping? How do you write *code*? If you aren't going to allow those things, then just make a parser and build the structure from the file, and make it a DSL implemented entirely external to Python. That's completely okay, though in my experience it's not very satisfying for something like a model definition (see MiddleKit for an example of an ORM that doesn't use Python code). Ian From fredrik at pythonware.com Fri Jun 9 03:19:22 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 09 Jun 2006 09:19:22 +0200 Subject: Win XP: Problem with shell scripting in Python In-Reply-To: References: Message-ID: A.M wrote: > It works very fine with DIR command, but for commands like "MD :" it doesn't > return the error message into the string: > > print os.popen('MD :').read() > > # No error message in python, "MD" is spelled os.mkdir. > Am I missing anything? the difference between STDOUT and STDERR, and the difference between buffered output and non-buffered output, and perhaps a few other things related to how STDIO behaves on modern computers... however, if you want to pretend that STDOUT and STDERR are the same thing, you can use os.popen4: >>> o, i = os.popen4("md :") >>> i.read() 'The filename, directory name, or volume label syntax is incorrect.\n' or the subprocess module. > Considering the fact that Ruby doesn't have any problem with redirecting > STDOUT into files or string variables, is Python the right tool for > this kinds of shell scripting? rewriting BAT files as a series of os.system or os.popen calls isn't exactly optimal (neither for the computer nor the programmer nor the future user); better take an hour to skim the "generic operating system services" section in the library reference, and use built-in functions wherever you can: http://docs.python.org/lib/allos.html the following modules are especially useful: http://docs.python.org/lib/module-os.html http://docs.python.org/lib/module-os.path.html http://docs.python.org/lib/module-glob.html http://docs.python.org/lib/module-shutil.html by using the built-in tools, you get better performance in many cases, better error handling, and code that's a lot easier to reuse (also on non-Windows platforms). From chris.uppal at metagnostic.REMOVE-THIS.org Fri Jun 23 14:41:37 2006 From: chris.uppal at metagnostic.REMOVE-THIS.org (Chris Uppal) Date: Fri, 23 Jun 2006 19:41:37 +0100 Subject: What is Expressiveness in a Computer Language References: <7zpshbsvjy.fsf@app-1.diku.dk><4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <0%Wlg.3521$MF6.947@tornado.socal.rr.com> <44992e6c$0$664$bed64819@news.gradwell.net> <449aaea0$0$656$bed64819@news.gradwell.net> <449bde5e$1$663$bed64819@news.gradwell.net> <1151082956.067238.45100@b68g2000cwa.googlegroups.com> Message-ID: <449c4826$0$657$bed64819@news.gradwell.net> Marshall wrote: [me:] > > But, as a sort of half-way, semi-formal, example: consider the type > > environment in a Java runtime. The JVM does formal type-checking of > > classfiles as it loads them. In most ways that checking is static -- > > it's treating the bytecode as program text and doing a static analysis > > on it before allowing it to run (and rejecting what it can't prove to > > be acceptable by its criteria). However, it isn't /entirely/ static > > because the collection of classes varies at runtime in a (potentially) > > highly dynamic way. So it can't really examine the "whole" text of the > > program -- indeed there is no such thing. So it ends up with a hybrid > > static/dynamic type system -- it records any assumptions it had to make > > in order to find a proof of the acceptability of the new code, and if > > (sometime in the future) another class is proposed which violates those > > assumptions, then that second class is rejected. > > I have to object to the term "hybrid". > > Java has a static type system. > Java has runtime tags and tag checks. It has both, agreed, but that isn't the full story. I think I explained what I meant, and why I feel the term is justified as well as I can in the second half of the paragraph you quoted. I doubt if I can do better. Maybe you are thinking that I mean that /because/ the JVM does verification, etc, at "runtime" the system is hybrid ? Anyway that is /not/ what I mean. I'm (for these purposes) completely uninterested in the static checking done by the Java to bytecode translator, javac. I'm interested in what happens to the high-level, statically typed, OO, language called "java bytecode" when the JVM sees it. That language has a strict static type system which the JVM is required to check. That's a /static/ check in my book -- it happens before the purportedly correct code is accepted, rather than while that code is running. I am also completely uninterested (for these immediate purposes) in the run time checking that the JVM does (the stuff that results in NoSuchMethodException, and the like). In the wider context of the thread, I do want to call that kind of thing (dynamic) type checking -- but those checks are not why I call the JVMs type system hybrid either. Oh well, having got that far, I may as well take another stab at "hybrid". Since the JVM is running a static type system without access to the whole text of the program, there are some things that it is expected to check which it can't. So it records preconditions on classes which might subsequently be loaded. Those are added to the static checks on future classes, but -- as far as the original class is concerned -- those checks happen dynamically. So part of the static type checking which is supposed to happen, has been postponed to a dynamic check. It's that, and /only/ that which I meant by "hybrid". Of course, /if/ we grant that runtime checking of the sort done by Smalltalk or Lisp also constitutes a "type system" in some sense that puts it on a par with static type checking, then that would be another, very different, reason to claim that Java had a hybrid type system (though, in fact, I'd rather claim that it had two independent type systems). But that's the bigger question point under discussion here and I wasn't trying to beg it by using the word "hybrid". -- chris From fb at frank-buss.de Sun Jun 25 12:30:22 2006 From: fb at frank-buss.de (Frank Buss) Date: Sun, 25 Jun 2006 18:30:22 +0200 Subject: languages with full unicode support References: <1151251736.590910.36050@u72g2000cwu.googlegroups.com> Message-ID: <4eeycqavp7ld$.1sthhf3vp4w84$.dlg@40tude.net> Xah Lee wrote: > Lisps ? No. The Common Lisp spec (CLHS) doesn't require that implementations support Unicode characters, but it doesn't forbid it and some implementations support it, e.g. http://clisp.cons.org/impnotes.html -- Frank Buss, fb at frank-buss.de http://www.frank-buss.de, http://www.it4-systems.de From barry.j.kelly at gmail.com Tue Jun 20 19:17:49 2006 From: barry.j.kelly at gmail.com (Barry Kelly) Date: Wed, 21 Jun 2006 00:17:49 +0100 Subject: __getattribute__ doesn't work on 'type' type for '__class__' References: <8k8g92tgqmhu70au13od2fn1ihut04sr0o@4ax.com> Message-ID: Barry Kelly wrote: > From "pydoc __getattribute__": > > ---8<--- > Help on method-wrapper object: > > __getattribute__ = class method-wrapper(object) > | Methods defined here: > | > | __call__(...) > | x.__call__(...) <==> x(...) > | > | __getattribute__(...) > | x.__getattribute__('name') <==> x.name > --->8--- Thanks for the answers, folks. I did find getattr() quite quickly from Google, but it's clear that the documentation with Python is wrong. -- Barry -- http://barrkel.blogspot.com/ From dieter at handshake.de Fri Jun 23 16:24:00 2006 From: dieter at handshake.de (Dieter Maurer) Date: 23 Jun 2006 22:24:00 +0200 Subject: Remote Boot Manager Scripting (Python) References: <1150900997.367853.106320@g10g2000cwb.googlegroups.com> Message-ID: diffuser78 at gmail.com writes on 21 Jun 2006 07:43:17 -0700: > ... > I have to remotely start a computer. It has dual boot (WinXP and > Linux). > My remote computer is Linux which will send command to remotely boot > the other computer. > > Can we write python script or some utility which would let us select > the Operating System to boot ? For example If we send parameter "WIN" > it boots into Windows and if we send "NIX" it boots into Linux. Probably yes -- but it is rather a remote boot protocol than a Python questions. Your remote boot protocol must in some way specify which os should be booted. When you implement the client site boot protocol in Python and you know how to select the os, then simply do it. I can tell something about "grub" (GRand Unified Boot loader). It can be configured to be controlled by a serial line. In this case, the boot protocol would be very simple: send "down" characters to the serial line until the correct os is selected; then send a "return" to boot. It would be trivial for a small Python script (with access to this serial line) to implement this. Dieter From mwilliams at mgreg.com Thu Jun 15 22:48:17 2006 From: mwilliams at mgreg.com (Michael Williams) Date: Thu, 15 Jun 2006 22:48:17 -0400 Subject: a good programming text editor (not IDE) In-Reply-To: References: Message-ID: <764D0D78-8C8A-424F-A694-EC4FF81EF76B@mgreg.com> If you're on a Mac, I'd recommend TextWrangler (http:// www.barebones.com/products/textwrangler/) hands down. From anton at appsolutions.com Mon Jun 26 03:03:24 2006 From: anton at appsolutions.com (Anton van Straaten) Date: Mon, 26 Jun 2006 07:03:24 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150904134.520639.71070@b68g2000cwa.googlegroups.com> Message-ID: <0FLng.159806$F_3.1840@newssvr29.news.prodigy.net> Joachim Durchholz wrote: > Anton van Straaten schrieb: > >> Marshall wrote: >> >>> Can you be more explicit about what "latent types" means? >> >> >> Sorry, that was a huge omission. (What I get for posting at 3:30am.) >> >> The short answer is that I'm most directly referring to "the types in >> the programmer's head". > > > Ah, finally that terminology starts to make sense to me. I have been > wondering whether there's any useful difference between "latent" and > "run-time" typing. (I tend to avoid the term "dynamic typing" because > it's overloaded with too many vague ideas.) Right, that's the reason for using a different term. Runtime and dynamic types are both usually associated with the idea of tagged values, and don't address the types of program phrases. >> there are usually many possible static type schemes that can be >> assigned to a given program. > > > This seems to apply to latent types as well. That's what I meant, yes. > Actually the set of latent types seems to be the set of possible static > type schemes. > Um, well, a superset of these - static type schemes tend to be slightly > less expressive than what the programmer in his head. (Most type schemes > cannot really express things like "the range of this index variable is > such-and-so", and the boundary to general assertions about the code is > quite blurry anyway.) Yes, although this raises the type theory objection of how you know something is a type if you haven't formalized it. For the purposes of comparison to static types, I'm inclined to be conservative and stick to things that have close correlates in traditional static types. >> There's a close connection between latent types in the sense I've >> described, and the "tagged values" present at runtime. However, as >> type theorists will tell you, the tags used to tag values at runtime, >> as e.g. a number or a string or a FooBar object, are not the same >> thing as the sort of types which statically-typed languages have. > > > Would that be a profound difference, or is it just that annotating a > value with a full type expression would cause just too much runtime > overhead? It's a profound difference. The issue is that it's not just the values that need to be annotated with types, it's also other program terms. In addition, during a single run of a program, all it can ever normally do is record the types seen on the path followed during that run, which doesn't get you to static types of terms. To figure out the static types, you really need to do static analysis. Of course, static types give an approximation of the actual types of values that flow at runtime, and if you come at it from the other direction, recording the types of values flowing through terms on multiple runs, you can get an approximation to the static type. Some systems use that kind of thing for method lookup optimization. > In your terminology: > >> So, where do tagged values fit into this? Tags help to check types at >> runtime, but that doesn't mean that there's a 1:1 correspondence >> between tags and types. > > > Would it be possible to establish such a correspondence, would it be > common consensus that such a system should be called "tags" anymore, or > are there other, even more profound differences? There's a non 1:1 correspondence which I gave an example of in the quoted message. For 1:1 correspondence, you'd need to associate types with terms, which would need some static analysis. It might result in an interesting program browsing and debugging tool... Anton From robert.kern at gmail.com Fri Jun 2 16:03:16 2006 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 02 Jun 2006 15:03:16 -0500 Subject: Sampling a population In-Reply-To: <44805F53.6090409@sweetapp.com> References: <44805F53.6090409@sweetapp.com> Message-ID: Brian Quinlan wrote: > The fastest algorithm that I have been able to devise for doing so is: > O(n * log(len(lst))). Can anyone think or a solution with a better time > complexity? If not, is there an obviously better way to do this > (assuming n is big and the list size is small). numpy.searchsorted() can do all of the n lookups in C. # Untested. import numpy as np def draw(n, lst): ps = np.cumsum([0.0] + [x[1] for x in lst]) # watch for floating point errors here. It's likely that the last # item won't be quite 1.0 r = np.random.random(n) # n psuedorandom numbers uniform on [0, 1) indices = np.searchsorted(ps, r) # now do what you like with indices, which is an array of indices into # lst. Ed Schofield has an implementation of an algorithm by Marsaglia[1] which turns sampling into a fast table lookup. If your probabilities have limited precision (2**-30 or so rather than the full double precision 2**-52 or so), then this might be an attractive option. [1] http://www.jstatsoft.org/v11/i03/v11i03.pdf The implementation is in the scipy sandbox currently, but I don't think it builds painlessly at the moment. http://svn.scipy.org/svn/scipy/trunk/Lib/sandbox/montecarlo/ Ask on one of the scipy mailing lists if you need help building it. http://www.scipy.org/Mailing_Lists -- 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 From steven.bethard at gmail.com Sun Jun 18 23:05:17 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 18 Jun 2006 21:05:17 -0600 Subject: aligning SGML to text In-Reply-To: <1150663092.362101.130490@f6g2000cwb.googlegroups.com> References: <1150663092.362101.130490@f6g2000cwb.googlegroups.com> Message-ID: Gerard Flanagan wrote: > Steven Bethard wrote: >> I have some plain text data and some SGML markup for that text that I >> need to align. (The SGML doesn't maintain the original whitespace, so I >> have to do some alignment; I can't just calculate the indices directly.) >> For example, some of my text looks like: >> >> TNF binding induces release of AIP1 (DAB2IP) from TNFR1, resulting in >> cytoplasmic translocation and concomitant formation of an intracellular >> signaling complex comprised of TRADD, RIP1, TRAF2, and AIPl. >> >> And the corresponding SGML looks like: >> >> TNF binding induces release of AIP1 >> ( DAB2IP ) from TNFR1 >> , resulting in cytoplasmic translocation and concomitant >> formation of an intracellular signaling complex >> comprised of TRADD , RIP1 , >> TRAF2 , and AIPl . >> >> Note that the SGML inserts spaces not only within the SGML elements, but >> also around punctuation. >> >> >> I need to determine the indices in the original text that each SGML >> element corresponds to. Here's some working code to do this, based on a >> suggestion for a related problem by Fredrik Lundh[1]:: >> >> def align(text, sgml): >> sgml = sgml.replace('&', '&') >> tree = etree.fromstring('%s' % sgml) >> words = [] >> if tree.text is not None: >> words.extend(tree.text.split()) >> word_indices = [] >> for elem in tree: >> elem_words = elem.text.split() >> start = len(words) >> end = start + len(elem_words) >> word_indices.append((start, end, elem.tag)) >> words.extend(elem_words) >> if elem.tail is not None: >> words.extend(elem.tail.split()) >> expr = '\s*'.join('(%s)' % re.escape(word) for word in words) >> match = re.match(expr, text) >> assert match is not None >> for word_start, word_end, label in word_indices: >> start = match.start(word_start + 1) >> end = match.end(word_end) >> yield label, start, end >> > [...] >> >>> list(align(text, sgml)) >> [('PROTEIN', 0, 3), ('PROTEIN', 31, 35), ('PROTEIN', 37, 43), >> ('PROTEIN', 50, 55), ('PROTEIN', 128, 159), ('PROTEIN', 173, 178), >> ('PROTEIN', 180, 184), ('PROTEIN', 186, 191)] >> >> The problem is, this doesn't work when my text is long (which it is) >> because regular expressions are limited to 100 groups. I get an error >> like:: > [...] > > Steve > > This is probably an abuse of itertools... > > ---8<--- > text = '''TNF binding induces release of AIP1 (DAB2IP) from > TNFR1, resulting in cytoplasmic translocation and concomitant > formation of an intracellular signaling complex comprised of TRADD, > RIP1, TRAF2, and AIPl.''' > > sgml = ''' TNF binding induces release of > AIP1 ( DAB2IP ) from > TNFR1 , resulting in cytoplasmic translocation > and concomitant formation of an intracellular signaling > complex comprised of TRADD , > RIP1 , TRAF2 , and AIPl . > ''' > > import itertools as it > import string > > def scan(line): > if not line: return > line = line.strip() > parts = string.split(line, '>', maxsplit=1) > return parts[0] > > def align(txt,sml): > i = 0 > for k,g in it.groupby(sml.split('<'),scan): > g = list(g) > if not g[0]: continue > text = g[0].split('>')[1]#.replace('\n','') > if k.startswith('/'): > i += len(text) > else: > offset = len(text.strip()) > yield k, i, i+offset > i += offset > > print list(align(text,sgml)) > > ------------ > > [('PROTEIN', 0, 3), ('PROTEIN', 31, 35), ('PROTEIN', 38, 44), > ('PROTEIN', 52, 57), ('PROTEIN', 131, 162), ('PROTEIN', 176, 181), > ('PROTEIN', 184, 188), ('PROTEIN', 191, 196)] > > It's off because of the punctuation possibly, can't figure it out. Thanks for taking a look. Yeah, the alignment's a big part of the problem. It'd be really nice if the thing that gives me SGML didn't add whitespace haphazardly. ;-) STeVe From marshall.spight at gmail.com Wed Jun 21 15:05:37 2006 From: marshall.spight at gmail.com (Marshall) Date: 21 Jun 2006 12:05:37 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <1150902019.850531.204740@g10g2000cwb.googlegroups.com> Message-ID: <1150916736.943255.131190@i40g2000cwc.googlegroups.com> Dr.Ruud wrote: > Marshall schreef: > > > "dynamic types." I don't have a firm definition for > > that term, but my working model is runtime type tags. In which > > case, I would say that among statically typed languages, > > Java does have dynamic types, but C does not. C++ is > > somewhere in the middle. > > C has union. But it does not have tagged unions, so my point is unaffected. Marshall From jo at durchholz.org Wed Jun 28 05:37:04 2006 From: jo at durchholz.org (Joachim Durchholz) Date: Wed, 28 Jun 2006 11:37:04 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: <7xwtb2j8ir.fsf@ruckus.brouhaha.com> References: <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <1151384511.223582.305760@m73g2000cwd.googlegroups.com> <1151425350.679754.278820@i40g2000cwc.googlegroups.com> <1151450513.458623.139460@b68g2000cwa.googlegroups.com> <7xwtb2j8ir.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin schrieb: > It starts to look like sufficiently powerful static type systems are > confusing enough, that programming with them is at least as bug-prone > as imperative programming in dynamically typed languages. The static > type checker can spot type mismatches at compile time, but the > types themselves are easier and easier to get wrong. That's where type inference comes into play. Usually you don't write the types, the compiler infers them for you, so you don't get them wrong. Occasionally, you still write down the types, if only for documentation purposes (the general advice is: do the type annotations for external interfaces, but not internally). BTW if you get a type wrong, you'll be told by the compiler, so this is still less evil than bugs in the code that pop up during testing (and *far* less evil than bugs that pop up after roll-out). And the general consensus among FPL programmers is that you get the hang of it fairly quickly (one poster mentioned "two to three months" - this doesn't seem to be slower than learning to interpret synax error messages, so it's OK considering it's an entirely new kind of diagnostics). Regards, Jo From robert.kern at gmail.com Thu Jun 22 14:25:11 2006 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 22 Jun 2006 13:25:11 -0500 Subject: Numeric N-dimensional array initialization In-Reply-To: <1150999204.839644.179940@g10g2000cwb.googlegroups.com> References: <1150999204.839644.179940@g10g2000cwb.googlegroups.com> Message-ID: TG wrote: > Hi there ! > > I'm just starting to use Numeric here, and I'm wondering : how can I > efficiently initialize every values of a N-dimensional array, given I > don't know the number of dimensions ? > > I'm looking for something like a map function, or a way to conveniently > iterate through the whole N-array, but I didn't find anything ... yet. > If anyone has a clue, I'm listening. Since you're just starting, you should know that Numeric is no longer being developed. The actively developed version is numpy: http://www.scipy.org/NumPy You will want to ask numpy questions on the numpy-discussion mailing list. The answers one gets here tend to be hit or miss. https://lists.sourceforge.net/lists/listinfo/numpy-discussion As to your actual question, I'm not entirely sure what you are asking for, but you should look at the .flat attribute. In [5]: from numpy import * In [6]: a = empty((2, 3)) In [7]: a.flat[:] = 10 In [8]: a Out[8]: array([[10, 10, 10], [10, 10, 10]]) # Note, in numpy, .flat is not a real array although it should be usable in most # places that need an array. However, unlike Numeric, it can always be used # even if the array is not contiguous. If you need a real array, use the # .ravel() method, but know that it will make a copy if the array is not # contiguous (for example, if it is the result of a .transpose() call). In [9]: a.flat Out[9]: In [10]: a.flat = arange(10) In [11]: a Out[11]: array([[0, 1, 2], [3, 4, 5]]) In [12]: for i in a.flat: ....: print i ....: ....: 0 1 2 3 4 5 -- 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 From onurb at xiludom.gro Fri Jun 16 10:38:44 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 16 Jun 2006 16:38:44 +0200 Subject: Python is fun (useless social thread) ;-) In-Reply-To: <1150381872.958342.180420@p79g2000cwp.googlegroups.com> References: <1150381872.958342.180420@p79g2000cwp.googlegroups.com> Message-ID: <4492c276$0$5272$636a55ce@news.free.fr> BartlebyScrivener wrote: (snip) > I am not touching OO, classes, You may not be aware of this, but as soon as you're programming in Python, you *are* using OO. Strings are objects, dicts are objects, tuples are objects, lists are objects, numbers are objects, and even functions and modules are objects. Classes are just a way to create your own object types. > or GUIs until I understand EVERYTHING The answer is 42. That's all you need to know. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From bdesth.quelquechose at free.quelquepart.fr Sun Jun 4 22:33:48 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 05 Jun 2006 04:33:48 +0200 Subject: Proposed new PEP: print to expand generators In-Reply-To: References: Message-ID: <44836870$0$10284$636a55ce@news.free.fr> James J. Besemer a ?crit : > (snip) > > PEP -- EXTEND PRINT TO EXPAND GENERATORS > > NUTSHELL > > I propose that we extend the semantics of "print" such that if the > object to be printed is a generator then print would iterate over the > resulting sequence of sub-objects and recursively print each of the > items in order. > Please, don't: from itertools import cycle def mygen(): return cycle('this is a very bad idea'.split()) From __peter__ at web.de Sat Jun 17 04:28:21 2006 From: __peter__ at web.de (Peter Otten) Date: Sat, 17 Jun 2006 10:28:21 +0200 Subject: add elements to indexed list locations References: <1150478265.122559.283000@f6g2000cwb.googlegroups.com> <7rmdnTyLF8gNcw_ZnZ2dnUVZ_v2dnZ2d@comcast.com> <1150528979.036821.246410@g10g2000cwb.googlegroups.com> Message-ID: levent wrote: > Thanks for the answers. Enumerating in reverse is indeed quite a smart > idea. > > The fact is though, I overly simplified the task in the super-hero > example. In the real case, the dictionary keys are not necessarily the > indices for inserts; that is to say, the inserts do not necessarily > take place in some sorted order. > > I think I was thinking more of a linked-list idea, where you do not > store the indices as integers to some random access array but rather as > pointers into list's nodes. Then the subsequent inserts would not hurt > previously stored pointers. For those who know a bit C++/STL here is a > sketch of the idea: > > name_list heros; > heros.push_back("clark"); > // ... add the rest > indexed_name_list surnames; > surnames.push_back( > make_pair( find( heros.begin(), heros.end(), "clark"), "kent") ) > ); // the find function returns an iterator to appropriate location > // ... add the rest > > for_each(surnames.begin(), surnames.end(), insert_surnames) > // insert_surnames is a callback that receives a single indexed surname > // at a time and does the job, without affecting outer iterators. > > > I was wondering how to make indices as *robust* in Python... Any ideas? Python's list is technically a vector. You can therefore either search for the insertion point in a timely fashion: heros = ["super", "clark", "spider", "peter", "bat", "bruce"] names = [("clark", "kent"), ("peter", "parker"), ("bruce", "wayne")] for first, last in names: heros.insert(heros.index(first)+1, last) print heros or you have to snatch a real (linked) list from somewhere. Here's an ad-hoc implementation: class Node(object): def __init__(self, value, next=None): self.value = value self.right = next def __str__(self): return "List(%s)" % ", ".join(repr(n.value) for n in self) def __iter__(self): item = self while item: yield item item = item.right def find(self, value): for item in self: if item.value == value: return item raise ValueError("%r not found" % (value,)) def insert_after(self, value): self.right = Node(value, self.right) @staticmethod def from_list(items): items = iter(items) try: first = items.next() except StopIteration: raise ValueError("empty lists not supported") cur = head = Node(first) for value in items: node = Node(value) cur.right = node cur = node return head if __name__ == "__main__": heros = ["super", "clark", "spider", "peter", "bat", "bruce"] heros = Node.from_list(heros) names = [("clark", "kent"), ("peter", "parker"), ("bruce", "wayne")] surnames = [(heros.find(f), s) for f, s in names] print heros for node, value in surnames: node.insert_after(value) print heros Peter From siona at chiark.greenend.org.uk Fri Jun 2 11:30:22 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 02 Jun 2006 16:30:22 +0100 (BST) Subject: Using print instead of file.write(str) References: Message-ID: <2Iq*Jzbir@news.chiark.greenend.org.uk> A.M wrote: >I found print much more flexible that write method. "more flexible"? More convenient, yes. More powerful, maybe. But I don't see more flexible. Everything print can to stdout.write() can do. The reverse isn't true. eg (this appears to be a FAQ on this group, although I can't find it in the FAQ): for x in range(10): sys.stdout.write(str(x)) to print: 0123456789 -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From maric at aristote.info Thu Jun 15 10:01:20 2006 From: maric at aristote.info (Maric Michaud) Date: Thu, 15 Jun 2006 16:01:20 +0200 Subject: __lt__ slowing the "in" operator even if not called In-Reply-To: <1150373671.227640.50910@f6g2000cwb.googlegroups.com> References: <1150318630.203249.191250@r2g2000cwb.googlegroups.com> <1150373671.227640.50910@f6g2000cwb.googlegroups.com> Message-ID: <200606151601.21408.maric@aristote.info> Le Jeudi 15 Juin 2006 14:14, Emanuele Aina a ?crit?: > > Every classes that define the __eq__ operator will find quickly the > > elements if they are at the beginning of the list. > > If they are at the end, the in oprerator is slower in these classes > > because of the overhead of function calls (in StateLt there is also an > > overhead due to > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ > > > internal lookup, IMO). > > ? ^^^^^^^^^^^^^^^ > > Yes, that was my question! :) > > But I hoped in a more exaustive answer: why python has to do this > lookup when the __lt__ method is not involved at all? Ah, ok sorry, got your point, I didn't notice it in first time. There is effectively an overhead when the class defines at less one of __lt__, __gt__, __neq__ ... special attributes (comparison attributes), it seems in my example that this overhead is a ratio of 1,5x. It is related to comparison, as the following code show : import timing class State(object): def __init__(self, value): self.v = value class StateFoo(State) : def foo(self) : pass class StateNew(State) : def __nonzero__(self) : return None class StateGT(State) : def __gt__(self) : return None class StateGTLT(StateGT) : def __lt__(self) : return None def test(cls) : print cls inst = cls(5) timing.start() for i in xrange(10**6) : i == inst timing.finish() print timing.milli() test(State) test(StateFoo) test(StateNew) test(StateGT) test(StateGTLT) for which ouput is : 589 596 615 815 836 Can't say more about what in the internals of python produce this non negligeable overhead, but looking at the source code of builtin comparison (for new style classes as it seems we have not this overhead with old style classes) should be the fist step... -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From grante at visi.com Thu Jun 15 09:43:26 2006 From: grante at visi.com (Grant Edwards) Date: Thu, 15 Jun 2006 13:43:26 -0000 Subject: Numerics, NaNs, IEEE 754 and C99 References: <12904mjhl493t49@corp.supernews.com> <1290aik50hmk94a@corp.supernews.com> <4490329e$0$12356$636a55ce@news.free.fr> <12917f6jp7u90f8@corp.supernews.com> Message-ID: <1292ovuf3ih91ae@corp.supernews.com> On 2006-06-15, Nick Maclaren wrote: > > In article <12917f6jp7u90f8 at corp.supernews.com>, > Grant Edwards writes: >|> >|> I assume the "you" in that sentence refers to the IEEE FP >|> standards group. I just try to follow the standard, but I have >|> found that the behavior required by the IEEE standard is >|> generally what works best for my applications. > > Well, it could be, but actually it was a reference to the > sentence "This makes sense since such is the limit of division > by a quantity that goes to zero." That sentence was written by the IEEE FP standards committee explaining why they chose the behavior they did. > The point here is that +infinity is the correct answer when the zero is > known to be a positive infinitesimal, just as -infinity is when it is > known to be a negative one. NaN is the only numerically respectable > result if the sign is not known, or it might be a true zero. OK, you're right. I still prefer that Python follow the standard they everything else does. Part of what I use Python for is to simulate devices that obey the IEEE 754 floating point standards. I need Python to follow the standard. -- Grant Edwards grante Yow! Yow! Now we can at become alcoholics! visi.com From and-google at doxdesk.com Tue Jun 27 23:39:19 2006 From: and-google at doxdesk.com (and-google at doxdesk.com) Date: 27 Jun 2006 20:39:19 -0700 Subject: Having problems with strings in HTML In-Reply-To: References: Message-ID: <1151465959.551278.301900@d56g2000cwd.googlegroups.com> Sion Arrowsmith wrote: > I've never encountred a browser getting tripped up by it. I suppose you > might need it if you've got parameters called quot or nbsp There are many more entities than you can comfortably remember, and browsers can interpret anything starting with one as being an entity reference, hence all the problems with parameters like 'section' (-> §). Plus of course there's nothing stopping future browsers supporting more entities, breaking your apps. Just write &. There's no reason not to (except ignorance). The fact that so much of the web is written with broken HTML is not an argument for doing the same. -- And Clover mailto:and at doxdesk.com http://www.doxdesk.com/ From michele.petrazzo at TOGLIunipex.it Fri Jun 30 07:27:57 2006 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Fri, 30 Jun 2006 11:27:57 GMT Subject: delete first line in a file In-Reply-To: <44a50825$0$3888$91cee783@newsreader01.highway.telekom.at> References: <44a4f854$0$12942$91cee783@newsreader02.highway.telekom.at><44a50151$0$12935$91cee783@newsreader02.highway.telekom.at> <44a50825$0$3888$91cee783@newsreader01.highway.telekom.at> Message-ID: <1V7pg.21784$zy5.445630@twister1.libero.it> Juergen Huber wrote: > but...how can i say python, delete the first line?! > thats my problem! You can open the file, read its lines with readlines function ( that return a list), so make your modifies and save to another file. Now, do you know how to work with lists? http://python.org/doc/2.4.2/tut/node5.html#SECTION005140000000000000000 and now you have only to wrote it http://python.org/doc/2.4.2/tut/node9.html#SECTION009200000000000000000 Michele From reedobrien at gmail.com Sun Jun 18 21:20:39 2006 From: reedobrien at gmail.com (reed) Date: 18 Jun 2006 18:20:39 -0700 Subject: Popen3 on Windows In-Reply-To: References: Message-ID: <1150680039.807987.184850@u72g2000cwu.googlegroups.com> Jeffrey Barish wrote: > I have an application that has been working fine on Linux, but now I need to > port it to Windows XP. The program uses Popen3 to run another program. I > use Popen3 so that I can access the pid attribute, which I use to kill the > auxiliary program when necessary. Popen3 does not exist on Windows. I see > os.popen2 and os.popen3, but they provide only file objects for stdin, > stdout, and stderr so I don't see a way to kill the auxiliary program that > I start. Is there a way to do this on Windows? > -- > Jeffrey Barish >>>import subprocess >>>x = subprocess.Popen('nc -l 22222') >>>x.pid 2783 >>>subprocess.Popen('taskkill %s' % x.pid) >>> x.poll() 1 From onurb at xiludom.gro Thu Jun 15 04:57:48 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 15 Jun 2006 10:57:48 +0200 Subject: __cmp__ method In-Reply-To: <1150324916.775821.142390@u72g2000cwu.googlegroups.com> References: <1150324916.775821.142390@u72g2000cwu.googlegroups.com> Message-ID: <4491210d$0$23263$626a54ce@news.free.fr> JH wrote: > Hi > > Can anyone explain to me why the following codes do not work? I want to > try out using __cmp__ method to change the sorting order. I subclass > the str and override the __cmp__ method so the strings can be sorted by > the lengh. I expect the shortest string should be in the front. Thanks AFAIK (please a Guru correct me if I'm wrong), __cmp__ is used as a fallback when other comparison operators ( __lt__ etc) are not implemented : >>> class MyStr(str): ... def __lt__(self, other): ... return len(self) < len(other) ... def __le__(self, other): ... return len(self) <= len(other) ... def __gt__(self, other): ... return len(self) > len(other) ... def __ge__(self, other): ... return len(self) >= len(other) ... >>> items = [MyStr("lolo lala"), MyStr("lolo"), MyStr("alal"), MyStr("a")] >>> sorted(items) ['a', 'lolo', 'alal', 'lolo lala'] >>> But anyway, all this is a WTF. Just using the correct params for sorted is enough: >>> items2 = ['lolo lala', 'lolo', 'alal', 'a'] >>> sorted(items2, key=len) ['a', 'lolo', 'alal', 'lolo lala'] > >>>>class myStr(str): > > def __init__(self, s): > str.__init__(self, s) # Ensure super class is initialized This is useless. If you don't override it, parent's init will be called anyway. (snip) HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From jzgoda at o2.usun.pl Fri Jun 16 13:42:41 2006 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Fri, 16 Jun 2006 19:42:41 +0200 Subject: MS VC++ Toolkit 2003 installer (VCToolkitSetup.exe) In-Reply-To: <1150431229.182271.61070@h76g2000cwa.googlegroups.com> References: <1150431229.182271.61070@h76g2000cwa.googlegroups.com> Message-ID: atwardoch at op.pl napisa?(a): > I need to build some Win32 Python extensions. If somebody happens to > have the Microsoft Visual C++ Toolkit 2003 installer > (VCToolkitSetup.exe), please kindly contact me off-list at: I think only Microsoft has enough rights to distribute this. -- Jarek Zgoda http://jpa.berlios.de/ From digitalorganics at gmail.com Sat Jun 24 19:23:26 2006 From: digitalorganics at gmail.com (digitalorganics at gmail.com) Date: 24 Jun 2006 16:23:26 -0700 Subject: Mix-In Class Methods At Run-Time Message-ID: <1151191406.755252.210300@i40g2000cwc.googlegroups.com> Hi all. If I have an instance of class A, called say foo, and I need to mix-in the functions and variables of another class (class B) to this instance at runtime, how do I do it? In other words, I want to make foo an instance of an anonymous and temporary class that inherits its functionality from classes A and B, while at the same time I want the pre-existing contents of foo to remain intact. Possible in Python? Thanks.... From mystilleef at gmail.com Thu Jun 1 15:27:41 2006 From: mystilleef at gmail.com (mystilleef) Date: 1 Jun 2006 12:27:41 -0700 Subject: Best Python Editor In-Reply-To: References: Message-ID: <1149190061.258740.66740@y43g2000cwc.googlegroups.com> http://scribes.sourceforge.net/ http://scribes.sourceforge.net/snippets.htm (Flash Demo) Manoj Kumar P wrote: > Hi, > > Can anyone tell me a good python editor/IDE? > It would be great if you can provide the download link also. > > Thank You, > -Manoj- > > > "SASKEN RATED Among THE Top 3 BEST COMPANIES TO WORK FOR IN INDIA - SURVEY 2005 conducted by the BUSINESS TODAY - Mercer - TNS India" > > SASKEN BUSINESS DISCLAIMER > This message may contain confidential, proprietary or legally Privileged information. In case you are not the original intended Recipient of the message, you must not, directly or indirectly, use, Disclose, distribute, print, or copy any part of this message and you are requested to delete it and inform the sender. Any views expressed in this message are those of the individual sender unless otherwise stated. Nothing contained in this message shall be construed as an offer or acceptance of any offer by Sasken Communication Technologies Limited ("Sasken") unless sent with that express intent and with due authority of Sasken. Sasken has taken enough precautions to prevent the spread of viruses. However the company accepts no liability for any damage caused by any virus transmitted by this email From fredrik at pythonware.com Fri Jun 9 15:50:56 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 09 Jun 2006 21:50:56 +0200 Subject: regexp questoin In-Reply-To: <1149868825.331142.280180@f6g2000cwb.googlegroups.com> References: <1149868825.331142.280180@f6g2000cwb.googlegroups.com> Message-ID: micklee74 at hotmail.com wrote: > pat = re.compile(r"%s" %(userinput) ) #userinput is passed from > command line argument that r"%s" % (userinput) thing is a pointless operation: the "r" prefix controls how backslashes in a string literal is parsed; the result is an ordinary string ("%s" in this case). in other words, pat = re.compile(r"%s" % (userinput)) is just a slightly convoluted way to write pat = re.compile(str(userinput)) and since you know that userinput is a string (at least if you got it from sys.argv), you might as well write pat = re.compile(userinput) > if the user key in a pattern , eg [-] , and my script will search some > lines that contains [-] > > pat.findall(lines) > > but the script produce some error: sre_constants.error: unexpected end > of regular expression for what pattern? "[-]" is a valid regular expression (it matches a single minus), but e.g. "[-" is invalid. to deal with this, catch the exception: try: pat = re.compile(userinput) except re.error: print "invalid regular expression:", userinput sys.exit() hope this helps! From johnjsal at NOSPAMgmail.com Thu Jun 8 09:55:24 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 08 Jun 2006 13:55:24 GMT Subject: GUI Program Error In-Reply-To: References: <1149536396.375285.319390@y43g2000cwc.googlegroups.com> <920hg.2238$No6.47697@news.tufts.edu> <1149700099.634036.88090@f6g2000cwb.googlegroups.com> Message-ID: Fredrik Lundh wrote: > Eric Brunel wrote: > >> It may be a platform-specific issue: On Unix/Linux, a window *does* >> appear when you instantiate Tk, at least with tcl/tk 8.3 and 8.4 >> (which is the latest stable version AFAIK). > > same on Windows, but it often appears *beneath* the window you're typing > into, so you have to look for it in the task bar. > > this also relies on Python being able to keep the Tkinter event loop > going behind the scenes; different command-line implementations have > different limitations. > > for example, on Windows, the event loop runs only when you're at an > empty Python prompt; as soon as you start typing the next command, the > interpreter switches over to "text input mode", and the event loop is > paused until you press return. > > > I thought it might be something like that. A window doesn't appear for me at all, but it may be because I haven't updated Tkinter since installing Python, so maybe it's a little older. From ask at me Mon Jun 5 23:27:26 2006 From: ask at me (alf) Date: Mon, 05 Jun 2006 23:27:26 -0400 Subject: the most efficient method of adding elements to the list Message-ID: Hi, Would it be .append()? Does it reallocate te list with each apend? l=[] for i in xrange(n): l.append(i) Thx, A. From jjlee at reportlab.com Fri Jun 23 21:28:29 2006 From: jjlee at reportlab.com (John J. Lee) Date: Sat, 24 Jun 2006 01:28:29 GMT Subject: Python to PHP Login System (HTTP Post) References: <1151018390.792574.102920@b68g2000cwa.googlegroups.com> Message-ID: <87mzc3fikh.fsf@reportlab.com> test at test.test writes: > On 22 Jun 2006 16:19:50 -0700, "Justin Azoff" > wrote: > > >Jeethu Rao wrote: > >> You need to use httplib. > >> http://docs.python.org/lib/httplib-examples.html > >> > >> Jeethu Rao > > > >Not at all. They need to read the documentation for urrlib: > > > >http://docs.python.org/lib/module-urllib.html > >http://docs.python.org/lib/node483.html > >"The following example uses the "POST" method instead:".... > > > >Additionally, they probably need to use cookielib, otherwise the logged > >in state will not be persistant. Or you may not be able to log in at all, for an everyday meaning of "log in". > Here's what's strange... I tried using urllib like this: > ---------------------------------------------------------------------------------- > try: > msparams = urllib.urlencode({'user': > self.components.User.text, 'pass': > self.components.MagnetSharePassword.text, 'sublogin': 1}) > f = urllib.urlopen("http://www.magnetshare.com/process.php", > msparams) > fc = f.read() > fc.close() > print fc > except: > self.statusBar.text = "Disconnected" > result = dialog.alertDialog(self, 'Couldn\'t connect to > MagnetShare.com! Please check your Internet connection, and then try > again.') > else: > print fc > ----------------------------------------------------------------------------------- > ...and then I visited http://www.magnetshare.com/main.php to see if I > was logged in. Sure enough I was logged in, but the exception was That's not how it works (assuming you visited that URL in a browser, not using Python). The "logged-in-ness" comes from a "session ID" cookie that is stored in your browser (or in your Python code). The server sends a cookie when you log in (and usually stores your cookie in a database). The browser keeps the cookie. When you come back later using the same browser (maybe even after you've closed the browser, if it's the right kind of cookie), your browser sends the cookie back and the server looks up the session ID from that cookie in the database, and sees it's you. If you come back using a different browser (and your Python program is effectively just a different browser than your copy of Firefox or IE or whatever), then the server won't remember who you are, so you're not logged in *in that browser session*, even if the server has you recorded in its database as logged in from a different browser session. So, the fact that you saw yourself as logged in when you looked using your web browser doesn't really help your Python program -- it's still out in the cold. > thrown anyway. I commented out the urlopen, f, and fc lines and > tested it again. This time I made it to "else:" > > I'm stumped. I'm glad that the user can log in; however, the > MagnetShare application needs to read in the response from the server, > and then decide what to do with the information. Here's one way: easy_install mechanize (install easy_install first if you don't have that: http://peak.telecommunity.com/DevCenter/EasyInstall#installing-easy-install ) #------------------------------- import mechanize SHOW_COOKIES = True br = mechanize.Browser() if SHOW_COOKIES: cj = mechanize.CookieJar() br.set_cookiejar(cj) br.open("http://www.magnetshare.com/main.php") br.select_form(nr=0) br["user"] = "joe" br["pass"] = "password" r = br.submit() assert "Logged In" in r.get_data() if SHOW_COOKIES: for cookie in cj: print cj #------------------------------- (note the cookiejar is always there; you only need to create one and pass it in in order to get at it to e.g. print out the cookies you've collected) John From filipwasilewski at gmail.com Sun Jun 25 19:56:55 2006 From: filipwasilewski at gmail.com (Filip Wasilewski) Date: 25 Jun 2006 16:56:55 -0700 Subject: String negative indices? References: <1151054259.765401.252230@b68g2000cwa.googlegroups.com> <1151152577.661130.5690@g10g2000cwb.googlegroups.com> Message-ID: <1151279815.309801.78900@m73g2000cwd.googlegroups.com> Steven D'Aprano wrote: > On Sat, 24 Jun 2006 05:36:17 -0700, Filip Wasilewski wrote: > > > Steven D'Aprano wrote: > >> On Fri, 23 Jun 2006 02:17:39 -0700, Filip Wasilewski wrote: > >> > >> > drtimhill at comcast.net wrote: > >> > > >> >> Logically, I should be able to enter x[-2:-0] to get the last and next to last characters. However, since Python doesn't distinguish between positive and negative zero, this doesn't work. Instead, I have to enter x[-2:]. > >> > > >> > Hooray! Logically there is no such thing as positive or negative zero, > >> > or did I miss something in the primary? > >> > >> No, not in the primary, or even in the secondary, but possibly in the > >> tertiary. > >> > >> For many purposes, it doesn't make sense to distinguish +0 from -0. But > >> for other purposes, it does. > > > > I believe you will agree that this is mostly a matter of notation of > > some fact rather than really trying to sign zero. > > No. > > In floating point, +0 *really is* different from -0 -- the two floats > have different bit patterns. Floating point libraries must be specifically > programmed to ignore that difference, making zero treated differently than > other floats. That's -- usually -- a good thing. So does the fact that the "-0.0" and "+0.0" strings can be converted by C compilator to floats and stored with different bit patterns means that they can behave much different in computation and comparison than real numbers written in an expression on a piece of paper? Rather not. Floating point is only a (very useful) finite precision model (there are others) of real (rational) numbers and these differences are implementation details for me. And as far as the division by signed floating point zero and similar operations in IEEE 754 are concerned, again, this is only a model in which 0.0 means a value that is either equal to real zero or greater, but too small to be distinguished from zero using finite amount of bits (similarly -0.0), so the expressions like 1.0/-0.0 -> -1.#INF 1.0/0.0 -> 1.#INF have some justification, although being meaningless in ordinary arithmetic. To be not so off-topic, I also expect from Python's integer, float and Decimal computer formats to behave as much similar to their equivalents known from math lessons as possible, which in particular means '==' equality of -0 and 0, -0.0 and 0.0, and Decimal("-0") and Decimal("0"), no matter what. > In mathematics, well, maybe... certainly in the Real number system, there > is no difference, and +0 and -0 are just two ways of writing the same > thing. In the hyperreals, +0 and -0 are the same, but there are > infinitesimals which are different, and signed. I don't know enough about > the surreals to comment. In matrix maths, there are an infinite number of > different matrices where all the elements are zero -- they are all > distinct, different, zeroes. > > And in "the real world", all numbers are an abstraction anyway, so I'm > not too worried about correspondence to reality. If mathematicians find a > use for distinguishing +0 from -0 (as the statistical physicists have > done) they will treat them as "really" different. If they don't, they > won't. As far as math stuff is concerned I will make it short. You can't deny that there is still unique additive identity in an additive group. I also wouldn't mix symbols of physics states or others with ordinary math expressions as this is only a matter of notation of some concept (feel free to use any symbol you want). Thanks for stimulating my neural cells, cheers, fw From spamspam at spam.eggs Sat Jun 24 07:10:03 2006 From: spamspam at spam.eggs (Ben C) Date: 24 Jun 2006 11:10:03 GMT Subject: Absolute noob to Linux programming needs language choice help References: <1150854682.904891.274480@c74g2000cwc.googlegroups.com> Message-ID: On 2006-06-21, stylecomputers at gmail.com wrote: > Hey guys, > > I am absolutely new to Linux programming, with no w######s programming > experience except a small amount of C++ console apps. > Reasonably new to Linux, BSD etc, got good sound networking base of > knowledge and dont have any problem working the command line etc. > > I want to learn a language that I can use in my networking duties that > is most likely to be of use to me. I have a few choices I can think of > being: > > Python > Perl > C > > Any other Langs out there that would be better suited? > > I want to be able to use the app's I write in OpenBSD and RH versions > of Linux > > What would you reccomend (Unbiased opinion please, I'm after the > functionality I'll love it later :) ) My favourite's Python, but Tcl is definitely worth a look. It's been around a bit longer than Python (so more time for every conceivable problem to have been met by someone and fixed), and I'm not an expert but I think it's particularly good for things like sockets-- they're just sort of built in and are very easy to work with. From irmen.NOSPAM at xs4all.nl Thu Jun 15 17:43:16 2006 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Thu, 15 Jun 2006 23:43:16 +0200 Subject: billionlaughs, on me :-(( - on winXP help! In-Reply-To: <1150401890.073634.131930@h76g2000cwa.googlegroups.com> References: <1150397596.520219.125780@c74g2000cwc.googlegroups.com> <1150401890.073634.131930@h76g2000cwa.googlegroups.com> Message-ID: <4491d476$0$31649$e4fe514c@news.xs4all.nl> jmdeschamps at gmail.com wrote: > Fredrik Lundh wrote: >> jmdeschamps at gmail.com wrote: >> >>> Looking up different blogs etc on xml parsers I wind up on the site of >>> Computer stuff, www.razorvine.net. >>> And in the browser torture section, the billionlaughs.xml link (that >>> you shouldn't use if you don't know what your doing, as was my case >>> (mea culpa)) > ... >> reboot as usual, and the next time you see a link that says "do NOT >> click if you don't know what you're doing", don't click on it. >> >> > > Right ;-) > and thanks for your very fast reply ! > The site is mine. And sorry for crashing your computer... But there really is a warning there to not click on it, like Fredrik pointed out ;-) You *can* try the millionlaughs version though, that more or less shows what the problem is. And it is small enough to not crash your browser. Right click on any of the link and "save link as" to download the XML file for viewing in your favorite editor.... :) Cheers, --Irmen de Jong From rossberg at ps.uni-sb.de Wed Jun 28 05:56:39 2006 From: rossberg at ps.uni-sb.de (Andreas Rossberg) Date: Wed, 28 Jun 2006 11:56:39 +0200 Subject: What is Expressiveness in a Computer Language [correction] In-Reply-To: <7bjog.229500$8W1.29971@fe1.news.blueyonder.co.uk> References: <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <1151384511.223582.305760@m73g2000cwd.googlegroups.com> <1151425350.679754.278820@i40g2000cwc.googlegroups.com> <7bjog.229500$8W1.29971@fe1.news.blueyonder.co.uk> Message-ID: David Hopwood wrote: >> >>>(defun blackhole (argument) >>> (declare (ignore argument)) >>> #'blackhole) > I believe this example requires recursive types. It can also be expressed > in a gradual typing system, but possibly only using an unknown ('?') type. > > ISTR that O'Caml at one point (before version 1.06) supported general > recursive types, although I don't know whether it would have supported > this particular example. No problem at all. It still is possible today if you really want: ~/> ocaml -rectypes Objective Caml version 3.08.3 # let rec blackhole x = blackhole;; val blackhole : 'b -> 'a as 'a = The problem is, though, that almost everything can be typed once you have unrestricted recursive types (e.g. missing arguments etc), and consequently many actual errors remain unflagged (which clearly shows that typing is not only about potential value class mismatches). Moreover, there are very few practical uses of such a feature, and they can always be coded easily with recursive datatypes. It is a pragmatic decision born from experience that you simply do *not want* to have this, even though you easily could. E.g. for OCaml, unrestricted recursive typing was removed as default because of frequent user complaints. Which is why this actually is a very bad example to chose for dynamic typing advocacy... ;-) - Andreas From niemand.leermann at thomas-guettler.de Mon Jun 12 10:49:57 2006 From: niemand.leermann at thomas-guettler.de (Thomas Guettler) Date: Mon, 12 Jun 2006 16:49:57 +0200 Subject: (pre)forking server framework? References: <1150118572.252707.57460@i40g2000cwc.googlegroups.com> Message-ID: Am Mon, 12 Jun 2006 06:22:52 -0700 schrieb czajnik: > > Hi! > > I'm quite new to Python development. Can someone advise me a framework > useful for building (pre-)forking or threaded TCP servers, other than > SocketServer ? I've seen source code of a few python-based app servers, > all of theme seem to reinvent the wheel, eventually reusing > SocketServer. I'd appreciate a framework with logging, process/thread > pool, signal handling etc. Just plug-in a protocol implementation and > go ! quixote has an scgi server which uses pre-forking worker processes. http://www.mems-exchange.org/software/quixote/ HTH, Thomas -- Thomas G?ttler, http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de Spam Catcher: niemand.leermann at thomas-guettler.de From girish at cse.iitb.ac.in Thu Jun 22 21:42:10 2006 From: girish at cse.iitb.ac.in (Girish Sahani) Date: Fri, 23 Jun 2006 07:12:10 +0530 (IST) Subject: How to generate all permutations of a string? In-Reply-To: References: Message-ID: <45211.10.209.4.2.1151026930.squirrel@10.105.1.3> >> thanks lawrence...however this func doesnt return the permuted strings, >> so >> i added some code as follows to generate a list of all the permutations: >> >> def permute(seq): >> l = [] >> if len(seq) == 0: >> yield [] >> else: >> for i in range(0,len(seq)): >> for rest in permute(seq[:i] + seq[i+1:]): >> yield (seq[i],) + rest >> for t in permute(seq): >> l.append(''.join(t)) >> return l >> >> This gives me a syntax error! >> I need to output a list that has all the permutations of the input >> string. >> >> >> >> >>>-- >>>http://mail.python.org/mailman/listinfo/python-list >>> >> >> > > p = ["".join(s) for s in permute('abcdefg')] This fails to work too. I'm trying to call permute func from another func, python gives me a TypeError as follows: def permute(seq): l = [] if len(seq) == 0: yield [] else: for i in range(0,len(seq)): for rest in permute(seq[:i] + seq[i+1:]): yield (seq[i],) + rest def main(stringList): for string in stringList: permList = list(permute(string)) l = ["".join(s) for s in permList] >>> l = ['abc','abd','bcd'] >>> main(l) TypeError: can only concatenate tuple (not "list") to tuple > > -- > James Stroud > UCLA-DOE Institute for Genomics and Proteomics > Box 951570 > Los Angeles, CA 90095 > > http://www.jamesstroud.com/ > -- > http://mail.python.org/mailman/listinfo/python-list > From fredrik at pythonware.com Fri Jun 9 16:47:02 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 09 Jun 2006 22:47:02 +0200 Subject: Killing a thread In-Reply-To: <7c8a9a970606091338t174fbcb0wc73cdb8b385f8ccd@mail.gmail.com> References: <7c8a9a970606091338t174fbcb0wc73cdb8b385f8ccd@mail.gmail.com> Message-ID: Manish Marathe wrote: > I am creating threads using my self defined class which inherits the > threading.Thread class. I want to know how can I kill the threads which > are being created by the object of my self defined class. you cannot kill a thread "from the outside"; you have to design your thread tasks so they can kill themselves, when asked to do that. From onurb at xiludom.gro Mon Jun 12 04:44:11 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Mon, 12 Jun 2006 10:44:11 +0200 Subject: "parent" in a class __init__ def? In-Reply-To: <1149999409.650251.251240@g10g2000cwb.googlegroups.com> References: <1149999409.650251.251240@g10g2000cwb.googlegroups.com> Message-ID: <448d295c$0$19196$636a55ce@news.free.fr> akameswaran at gmail.com wrote: (meta : please don't top-post) > Intuitively, the name lookup on > self.parent.foo would be faster than if you passed in the object in > question Each dot means doing a lookup in a namespace. The more dots, the more lookups. And lookups do have a cost. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From python-url at phaseit.net Mon Jun 12 09:55:42 2006 From: python-url at phaseit.net (Cameron Laird) Date: Mon, 12 Jun 2006 13:55:42 +0000 (UTC) Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jun 12) Message-ID: QOTW: "Check out BeautifulSoup -- you will never write HTMLParser-based screen scrapers again. :)" - Jonathan Ellis "You clearly need something instead of XML." - Paul McGuire http://groups.google.com/group/comp.lang.python/msg/09e943c8dbf1e8c5? Johann C. Rocholl donates a PNG manager in pure Python: http://groups.google.com/group/comp.lang.python/browse_thread/thread/97c035f8b3646fd/ Andrew Clover provides new Python icons: http://doxdesk.com/img/software/py/icons2.png http://mail.python.org/pipermail/python-dev/2006-March/063235.html http://mail.python.org/pipermail/python-dev/2006-April/063517.html Might it be practical to use py2exe to make single-file executables of Tkinter applications? Perhaps when Tkinter reaches 8.5 of Tk: http://groups.google.com/group/comp.lang.python/browse_thread/thread/b6a61337d86c3b4e/ Even more primitive compilation abilities have advanced lately. Paul Moore details construction of Python with the fee-free Microsoft compiler, while Anthony Baxter compiles Python with C++ (!): http://wiki.python.org/moin/Building_Python_with_the_free_MS_C_Toolkit?highlight=%28building%29 http://svn.python.org/projects/python/trunk/PCbuild/readme.txt http://mail.python.org/pipermail/python-dev/2006-April/063719.html http://mail.python.org/pipermail/python-dev/2006-April/063632.html Danny Yee accurately describes David Mertz' Python book: http://dannyreviews.com/h/Text_Python.html Anthony Baxter has created a "Firefox searchbar" which finds Python bugs by their SourceForge IDs. There are also two Firefox sidebar options: http://mail.python.org/pipermail/python-dev/2006-April/063285.html http://www.python.org/~anthony/searchbar/ http://starship.python.net/~skippy/mozilla/ http://projects.edgewall.com/python-sidebar/ A few low-level technical touches have the potential to affect wider audiences: a patch from Georg Brandl effects a ratified improvement to traceback, but one which breaks several exising doctests: http://mail.python.org/pipermail/python-dev/2006-April/063662.html Also, Zachary Pincus and others worked out a dlopen()-based upgrade to dynamic loading under Mac OS X (or Darwin more broadly): http://mail.python.org/pipermail/python-dev/2006-April/063336.html ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. For far, FAR more Python reading than any one mind should absorb, much of it quite interesting, several pages index much of the universe of Pybloggers. http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog http://www.planetpython.org/ http://mechanicalcat.net/pyblagg.html comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html Steve Bethard, Tim Lesher, and Tony Meyer continue the marvelous tradition early borne by Andrew Kuchling, Michael Hudson and Brett Cannon 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/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 http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topic/python/ (requires subscription) http://groups-beta.google.com/groups?q=python-url+group:comp.lang.python*&start=0&scoring=d& http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From faulkner612 at comcast.net Sun Jun 18 17:36:44 2006 From: faulkner612 at comcast.net (faulkner) Date: 18 Jun 2006 14:36:44 -0700 Subject: Passing data to system command In-Reply-To: References: Message-ID: <1150666604.684435.140870@u72g2000cwu.googlegroups.com> import os, subprocess xys = [[1,2],[3,4]] msg = '\n'.join([str(x) + ',' + str(y) for x, y in xys]) os.popen('command', 'w').write(msg) os.popen2('command')[0].write(msg) p = subprocess.Popen('command', stdin=subprocess.PIPE) p.stdin.write(msg) help(subprocess) help(os.popen) help(os.popen3) Chris Hieronymus wrote: > Hi, > > I have a bunch of x-y data contained in an array. I would like to > plot the data using an > external program (psxy in GMT). The plotting program takes x-y > couples as standard > input. How do I get the data into the system call? I used to do > things in csh and awk, > i.e., something like > > awk '{; print $1, $2}' filename | psxy options> >! output.ps > > The reason I'm trying to use python is because the manipulations are > getting too cumbersome > in awk. Now I have all the manipulations done in python, but I'm > missing that last step. > > I've tried various things with os.system, popen, and subprocess, but > so far without success. > Does anyone know how to do this? > > chris > > > ------------------------------------------------------------------------ > ------------------------------------------- > Christoph > Hieronymus > christoph.hieronymus at geo.uu.se > Associate > Professor > phone: (+46) 18-471 2383 > Uppsala > University > fax: (+46) 18-501 110 > Dept. of Earth Sciences (Geophysics) > Villav?gen 16 > SE-752 36 Uppsala, Sweden From bignose+hates-spam at benfinney.id.au Thu Jun 15 21:41:31 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 16 Jun 2006 11:41:31 +1000 Subject: Need Help comparing dates References: <1150419503.224684.320550@c74g2000cwc.googlegroups.com> <44920965.3060204@tim.thechases.com> Message-ID: <878xnxlvw4.fsf@benfinney.id.au> Tim Chase writes: > If you need to map the month-strings back into actual dates, you > can use this dictionary: > > >>> month_numbers = dict([(date(2006, m, 1).strftime("%b"), m) > for m in range(1,13)]) Or you can just use the same format codes to specify that time.strptime() should do the parsing for you. (Which I remembered too late for my initial reply.) -- \ "War is God's way of teaching geography to Americans." -- | `\ Ambrose Bierce | _o__) | Ben Finney From bapolis at gmail.com Tue Jun 13 04:48:36 2006 From: bapolis at gmail.com (Tgone) Date: 13 Jun 2006 01:48:36 -0700 Subject: Decimals Message-ID: <1150188516.739925.102810@h76g2000cwa.googlegroups.com> Hello, I have a price column in a MySQL table: price decimal(5,2) When I access them in Python with SQLObject, prices display as 15.0 instead of 15.00. Why is this happening? I can't figure out why Python is trimming off the hundredth place. I'm not doing any formatting... Thanks, Tony From oscarp at acay.com.au Sun Jun 18 23:06:58 2006 From: oscarp at acay.com.au (O Plameras) Date: Mon, 19 Jun 2006 13:06:58 +1000 Subject: Change value of element in list Message-ID: Hi, I'm doing python tutorial, > http://docs.python.org/tut/node5.html and I have these, lists = ['spam', 'eggs', 100, 1234] lists[2] = lists[2] + 23 I expected this, lists = ['spam', 'eggs', 123, 1234] but got this, lists = ['spam', 'eggs', 100, 1234] What's my problem here ? I have Fedora C5 with python2.4. Thanks. O Plameras From alanalan at newsgroup.nospam Fri Jun 2 13:09:08 2006 From: alanalan at newsgroup.nospam (A.M) Date: Fri, 2 Jun 2006 13:09:08 -0400 Subject: Conditional Expressions in Python 2.4 References: <4480042b$0$29879$636a55ce@news.free.fr> Message-ID: >> a = 1 == 1 and "Yes" or "No" >> a = ("No", "Yes")[1 == 1] Smart! Thanks alot. From fredrik at pythonware.com Fri Jun 30 03:00:25 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 30 Jun 2006 09:00:25 +0200 Subject: Import: Multiple modules with same name References: <1360b7230606292346h224fcf8bs51818361f39b1d4e@mail.gmail.com> Message-ID: Amit Khemka wrote: > But It looked like an overkill, Is there a more elegant and better way > of doing it ? try: path = sys.path[:] sys.path.insert(0, mypath) # or something import mymodule finally: sys.path = path From sharidas at zeomega.com Wed Jun 14 17:20:42 2006 From: sharidas at zeomega.com (Satchidanand Haridas) Date: Wed, 14 Jun 2006 16:20:42 -0500 Subject: WS-Security support for Python SOAP libraries Message-ID: <44907DAA.6070601@zeomega.com> Hi, Do any of the existing SOAP libraries for Python have support for WS-Security? thanks, Satchit From sonaldgr8 at gmail.com Fri Jun 9 08:37:48 2006 From: sonaldgr8 at gmail.com (sonal) Date: 9 Jun 2006 05:37:48 -0700 Subject: How to link foreign keys & primary keys using python? Message-ID: <1149856668.055162.209650@u72g2000cwu.googlegroups.com> Hi all, I hv started with python just recently... and have been assigned to make an utility which would be used for data validations... In short we take up various comma separated data files for eg: area.txt, school.txt, students.txt.... and so on (ok?!?) now, 1. area code used in the school.txt must be defined in the area.txt (Primary key in area => area_code defined in area.txt & Foreign key on school => area_code defined in school.txt) i hv created primary key using the following piece of code: # primary key for area.txt (index created on the column AREACODE as per the # schema defined earlier ) area_pk = PartitionedPK( name = 'Area PK ', save_to = '../Index/area_code.idx', fields = ['A_AREACODE'] ) # col name in area schema # foreign key is defined as follows... school_fk = HashedFK( name = ' School code FK', load_from = '../Index/area_code.idx', fields = ['S_AREACODE'] ) # col name in school schema Description for abv code: 1. An index {area_code.idx } is formed on the field AREACODE in the area.txt (i.e.,A_AREACODE) 2. The data values in the S_AREACODE field in the school.txt are checked in the index {area_code.idx} If the area code given in school.txt is not present in the area code, then the record is not validated(as foreign key constraint fails.) Now if the Primary key is on mutiple columns...the foreign key, which is also definedon the same no. of columns works.. for eg.. # primary key for school.txt (index created on the columns AREACODE & SCHOOLCODE as per the # schema defined earlier ) school_pk = PartitionedPK( name = 'School PK ', save_to = '../Index/school.idx', fields = ['S_AREACODE','S_SCHOOLCODE'] ) # col names in school schema # foreign key for students is defined as follows... student_fk = HashedFK( name = ' STUDENT code FK', load_from = '../Index/student.idx', fields = ['STUD_AREACODE','STUD_SCHOOLCODE'] ) # col name in student schema Now if I hv to define foreign key on student.txt but with only one field, school code, so as to make sure that the school name given in the student.txt exists in the school.txt whatever be the area code... I am unable to do this... Say, if the AREACODE field is not present in the student.txt file.... then??? I tried using the foll code student_fk = HashedFK( name = ' Student FK', load_from = '../Index/school.idx', fields = ['STUD_SCHOOLCODE'] ) Its showing an AttributeError : 'list' object has no attribute 'has_key' I also tried making another index with only SCHOOLCODE field (another PK for school.txt) and the foreign key on student.txt to be loaded from this index... it still shows the same error That's may be becoz... one SCHOOLCODE may repeat often, with a different AREACODE... so may be we need to index on distinct SCHOOLCODES in school.txt... how do i do that?? I hope i am not confusing the genious' ... plz help me... till get my hands on python... :) From d.schulz81 at gmx.net Thu Jun 1 12:10:09 2006 From: d.schulz81 at gmx.net (d.schulz81 at gmx.net) Date: 1 Jun 2006 09:10:09 -0700 Subject: Zope / Plone Groups Message-ID: <1149178209.825191.128050@c74g2000cwc.googlegroups.com> Hi, are there any specific groups for zope / plone regarding questions? my question is: How is it possible to use Zope 3 Products with Plone, which is an extension based on Zope 2? Thank you Dennis From buzzard at urubu.freeserve.co.uk Fri Jun 2 13:19:32 2006 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Fri, 02 Jun 2006 18:19:32 +0100 Subject: Sampling a population In-Reply-To: References: Message-ID: <44807544.0@entanet> Brian Quinlan wrote: > This is less a Python question and more a optimization/probability > question. Imaging that you have a list of objects and there frequency in > a population e.g. > > lst = [(a, 0.01), (b, 0.05), (c, 0.50), (d, 0.30), (e, 0.04), (f, 0.10)] > > and you want to drawn n items from that list (duplicates allowed), with > that probability distribution. > > The fastest algorithm that I have been able to devise for doing so is: > O(n * log(len(lst))). Can anyone think or a solution with a better time > complexity? If not, is there an obviously better way to do this > (assuming n is big and the list size is small). > > Here is the code: > > from random import random > from bisect import bisect > > def draw(n, lst): > ps = [] > last = 0 > for p in lst: > ps.append(last + p) > last += p > > # ps = [0.01, 0.06, 0.56, 0.86, 0.90, 1.00] > > chosen = [0] * len(lst) # track frequency > for i in range(n): > r = random() > > chosen[bisect(ps, r)] += 1 # binary search and increment > > result = [] # rescale probability based on frequency > for c in chosen: > result.append(float(c) / n) > return result > > lst = [0.01, 0.05, 0.50, 0.30, 0.04, 0.10] > print draw(10000, lst) > I would do something like the following (maybe with an additional check that the probabilities do not sum to less than 1), >>> from random import random >>> import operator >>> def draw(n, lst): lst.sort(key=operator.itemgetter(1), reverse=True) cumprobs = [] this_cp = 0 for p in lst: this_cp += p[1] cumprobs.append(this_cp) for _ in xrange(n): rnd = random() for i, cumprob in enumerate(cumprobs): if rnd < cumprob: yield lst[i][0] break >>> lst = [('a', 0.01), ('b', 0.05), ('c', 0.50), ('d', 0.30), ('e', 0.04), ('f', 0.10)] >>> list(draw(8, lst)) ['d', 'd', 'c', 'e', 'c', 'd', 'c', 'f'] >>> The sorting of the list means that iterating over the cumulative probabilities is minimised (for your density function the inner loop will be broken out of after the first iteration 50% of the time). (I've assumed that it doesn't matter to you that the list is sorted.) I'm not sure that this is in any way optimal. Duncan From frank at chagford.com Fri Jun 9 01:35:31 2006 From: frank at chagford.com (Frank Millman) Date: 8 Jun 2006 22:35:31 -0700 Subject: XML, JSON, or what? In-Reply-To: <1149749530.734275.181300@j55g2000cwa.googlegroups.com> References: <1149749530.734275.181300@j55g2000cwa.googlegroups.com> Message-ID: <1149831330.860163.70210@u72g2000cwu.googlegroups.com> Frank Millman wrote: > Hi all > > I am writing a multi-user accounting/business application, which uses > sockets to communicate between server and client. The server contains > all the business logic. It has no direct knowledge of the client. I > have devised a simple message format to exchange information between > the two. > [...] > > I would rather make a decision now, otherwise I will have a lot of > changes to make later on. Does anyone have any recommendations? > > Thanks > > Frank Millman Thanks for the replies, guys. Albert, thank you for the pointer to XMPP. I had not heard of it, but it looks very interesting. I will have to investigate further before deciding whether it is right for my application. If not, JSON it is. Frank From claird at lairds.us Sun Jun 11 23:34:51 2006 From: claird at lairds.us (Cameron Laird) Date: Mon, 12 Jun 2006 03:34:51 +0000 Subject: how to get the length of a number References: Message-ID: In article , Felipe Almeida Lessa wrote: . . . >math.floor(math.log(x, 10)) + 1 > >-- >Felipe. > ... and you're restricting to the positive integers, I take it? I still have rounding problems: >>> def l(x): ... return math.floor(math.log(x, 10)) + 1 ... >>> l(10) 2.0 >>> l(100) 3.0 >>> l(1000) 3.0 >>> l(10000) 5.0 >>> l(100000) 6.0 >>> l(1000000) 6.0 >>> l(10000000) 8.0 While modest mollification improves these results, it's going to be tough to beat len(str(x)). From fredrik at pythonware.com Wed Jun 28 13:28:06 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 28 Jun 2006 19:28:06 +0200 Subject: Immutability In-Reply-To: References: <4Qj*cEjkr@news.chiark.greenend.org.uk> Message-ID: Nick Maclaren wrote: > I wasn't expecting EITHER to be turned INTO a property - I was expecting > both methods to be the same, but one would have non-default properties > attached to it. > |> that's what the documentation > |> says, and that's what your code is doing. > > Er, no, it doesn't. What it says may well be COMPATIBLE with that, but > it is compatible with a good many other interpretations, too. Until and > unless you know what it means, you can't extract its meaning from its > words. well, I completely fail to see how the following is compatible with the interpretation "attaches a non-default property, but doesn't do anything else": property([fget[, fset[, fdel[, doc]]]]) => descriptor Returns a property attribute for new-style classes (classes that derive from object). fget is a function for getting an attribute value, likewise fset is a function for setting, and fdel a function for deleting, an attribute. Typical use is to define a managed attribute x: class C(object): def __init__(self): self.__x = None def getx(self): return self.__x def setx(self, value): self.__x = value def delx(self): del self.__x x = property(getx, setx, delx, "I'm the 'x' property.") From 7abc at sogetthis.com Fri Jun 9 14:28:46 2006 From: 7abc at sogetthis.com (PofN) Date: 9 Jun 2006 11:28:46 -0700 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> Message-ID: <1149877726.498412.294850@y43g2000cwc.googlegroups.com> Xah Lee wrote: [the usual toff-topic trolling stuff] Shit, da troll is back. Abuse reports need to go to abuse [] pacbell.net and abuse [] swbell.net this time. From sleepingsquirrel at yahoo.com Mon Jun 26 20:34:03 2006 From: sleepingsquirrel at yahoo.com (Greg Buchholz) Date: 26 Jun 2006 17:34:03 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> Message-ID: <1151368443.491445.294480@p79g2000cwp.googlegroups.com> Chris F Clark wrote: > Thus, as we traverse a list, the first element might be an integer, > the second a floating point value, the third a sub-list, the fourth > and fifth, two more integers, and so on. If you look statically at > the head of the list, we have a very wide union of types going by. > However, perhaps there is a mapping going on that can be discerned. > For example, perhaps the list has 3 distinct types of elements > (integers, floating points, and sub-lists) and it circles through the > types in the order, first having one of each type, then two of each > type, then four of each type, then eight, and so on. Sounds like an interesting problem. Although not the exact type specified above, here's something pretty similar that I could think of implementing in Haskell. (I don't know what a "sub-list" is, for example). Maybe some Haskell wizard could get rid of the tuples? data Clark a b c = Nil | Cons a (Clark b c (a,a)) deriving Show clark = (Cons 42 (Cons 3.14 (Cons "abc" (Cons (1,2) (Cons (1.2,3.4) (Cons ("foo","bar") (Cons ((9,8),(7,6)) (Cons ((0.1,0.2),(0.3,0.4)) Nil)))))))) main = print clark From webraviteja at gmail.com Thu Jun 1 01:00:08 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 31 May 2006 22:00:08 -0700 Subject: How to access the content of notepad with Python? In-Reply-To: <1149131310.763870.29250@j55g2000cwa.googlegroups.com> References: <1149131310.763870.29250@j55g2000cwa.googlegroups.com> Message-ID: <1149138007.952375.22560@u72g2000cwu.googlegroups.com> > I have a software running on my computer that really looks like notepad > ( same interface, different name). I need to write a script that will > capture the content of this software --> the text written inside. > > Is it possible using win32 libs? any clue? http://www.openqa.org/pywinauto/ The example on their home page is in fact how to automate Notepad. I am sure you can work from there. From will at willNOmcguganSPAM.com Sun Jun 4 14:15:33 2006 From: will at willNOmcguganSPAM.com (Will McGugan) Date: Sun, 04 Jun 2006 19:15:33 +0100 Subject: Python netstring module Message-ID: <44832345$0$23374$db0fefd9@news.zen.co.uk> Hi folks, I have just posted a python 'netstring' module on my blog. Comments welcome! http://www.willmcgugan.com/2006/06/04/python-netstring-module/ Regards, Will McGugan From benji at benjiyork.com Thu Jun 15 16:39:14 2006 From: benji at benjiyork.com (Benji York) Date: Thu, 15 Jun 2006 16:39:14 -0400 Subject: a good programming text editor (not IDE) In-Reply-To: <1150402733.116243.9680@y41g2000cwy.googlegroups.com> References: <_xgkg.2317$No6.48542@news.tufts.edu> <1150402733.116243.9680@y41g2000cwy.googlegroups.com> Message-ID: <4491C572.70703@benjiyork.com> BartlebyScrivener wrote: > Emacs must be dying if this thread could get all the way to 20 with > nobody arguing with the vi folks. heh :) > Will the Windows vim and gvim users vouch for its stability on > Windows? It's very stable on Windows. -- Benji York From Serge.Orlov at gmail.com Mon Jun 5 09:14:55 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 5 Jun 2006 06:14:55 -0700 Subject: Freezing a static executable References: <1149480918.713079.36870@y43g2000cwc.googlegroups.com> Message-ID: <1149513295.128265.57470@h76g2000cwa.googlegroups.com> Will Ware wrote: > I am trying to freeze a static executable. I built a static Python > executable this way: > ./configure --disable-shared --prefix=/usr/local > make > make install > Even that didn't give me a really static executable, though: AFAIK it's not supported because the interpreter won't be able to load C extensions if compiled statically. There is a bootstrap issue, to build a static python executable you need extensions built but to build extensions you need python, so you need unconventional build procedure. After python build is finished you get static library libpython2.4.a. Then you need all extensions you're going to use built as .a files (I'm not even sure there is a standard way to do it). Then you need to write a loader like in py2exe, exemaker, pyinstaller, etc that will initialize python interperter and extensions. Those three pieces (libpython2.4.a, extensions, loader) can be linked as a static executable. > What stupid thing am I doing wrong? You are just trying to do something nobody was really interested to implement. From tundra at tundraware.com Thu Jun 15 18:59:42 2006 From: tundra at tundraware.com (Tim Daneliuk) Date: 15 Jun 2006 18:59:42 EDT Subject: a good programming text editor (not IDE) In-Reply-To: <1150406662.900552.46650@u72g2000cwu.googlegroups.com> References: <_xgkg.2317$No6.48542@news.tufts.edu><44919668$1@nntp0.pdx.net> <1150406662.900552.46650@u72g2000cwu.googlegroups.com> Message-ID: <8j59m3-6hj.ln1@eskimo.tundraware.com> Istvan Albert wrote: > Scott David Daniels wrote: > >> To paraphrase someone else (their identity lost in my mental fog) about >> learning VI: >> "The two weeks you'll spend hating vi (or vim) as you learn it will >> be repaid in another month, ad the rest is pure profit." > > Time and again I hear this (no shortage of Vim fans, same with Emacs), > and I know I should know better but always believe them yet again. > Invariably I download Vim play with it for an hour, get increasingly > frustrated and give up. Most likely I'm greatly spoiled by using This is not a skill or competence issue - it is a mindset issue. Some people are naturally more comfortable with point-n-shoot GUI interfaces. Some of us old retrograde dinosaurs imagine GUIs to be a place to run multiple xterms so we can use the keyboard even more. That said, to the extent you learn to master the keyboard with any tool, you will eventually become far more efficient doing almost everything you do. I find GUI editors/browsers/et al easy to learn or good for casual use, but an interference when I want to do a lot fast. I got so frustrated with it all, I wrote my own pure Python file browser that is *all* about the keyboard and never having to say you're a mouse user (though you can): http://www.tundraware.com/Software/twander/ GUIs are great for two classes of use: 1) For non-specialist or casual users who need to be productive with minimal training or support, and 2) Classes of problems that are inherently graphical - photo editing is such an example. But, I have yet to see a significant advantage to programming under a GUI (beyond the aforementioned ability to run multiple instances of emacs, xterm ...). Yes, a GUI editor is easy to *learn* and use casually, but text intensive work is best done with tools optimized for doing so. BTW, when God created the heavens and earth, the OS was BSD Unix, the config files were edited with emacs, and the doc was written in LaTeX using the dvi2stonetablets backend... -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From arauzo at uco.es Mon Jun 12 13:19:29 2006 From: arauzo at uco.es (Antonio Arauzo Azofra) Date: Mon, 12 Jun 2006 19:19:29 +0200 Subject: Unimporting modules, memory leak? Message-ID: <448DA221.3040607@uco.es> Hello everybody, Probably, this is being too demanding for Python, but it may be useful to unimport modules to work with dynamic code (though not the best, one example is [2]). In fact, it is supposed to be possible[1], but I have detected it usually leaks memory. When unimported in Linux, the simple C module attached (has no functions, just the structure) leaks two memory pages To see the test you can just put the files in a directory and: python setupmod1.py install --install-lib . python testMemory.py Its output follows. First, the memory used before import. Second memory used after the import. Third the number of references to that object is checked before using del. Finally the memory used after unimporting. -- Testing mod1 -- Mem. used: 1242 (gc: 0 ) Mem. used: 1244 (gc: 0 ) Check refs (should be = 2): 2 Mem. used: 1244 (gc: 0 ) -- Testing bigModule -- Mem. used: 1244 (gc: 0 ) Mem. used: 2686 (gc: 0 ) Check refs (should be = 2): 2 Mem. used: 1244 (gc: 0 ) -- Testing random -- Mem. used: 1244 (gc: 0 ) Mem. used: 1256 (gc: 0 ) Check refs (should be = 2): 2 Mem. used: 1256 (gc: 57 ) Unimporting attached "bigmodule.py" there are no memory leaks. Unimporting python's random module it leaks some pages, but garbage collector admit it can not free them. If a module with the same name that the unimported module is imported, the pages are reused. While, if this same module is loaded with another name, they are not freed, and the program grows with each module imported/unimported Is this a Python bug? A Linux bug? Am i missing some way of freeing that memory used by C module? [1] http://mail.python.org/pipermail/python-list/1999-May/002669.html [2] http://ax5.com/antonio/orangesnns -- All the best, Antonio Arauzo Azofra -------------- next part -------------- A non-text attachment was scrubbed... Name: bigModule.py Type: text/x-python Size: 127 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: setupmod1.py Type: text/x-python Size: 270 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: srcmod1.c Type: text/x-csrc Size: 224 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: testMemory.py Type: text/x-python Size: 688 bytes Desc: not available URL: From William.Cellich at lydiandata.com Mon Jun 26 16:01:30 2006 From: William.Cellich at lydiandata.com (William Cellich) Date: Mon, 26 Jun 2006 16:01:30 -0400 Subject: Parsing Digits in Strings, using RE Message-ID: <046B468CDD27AD47B06FD61185F4C3E904A2B7E5@VCMAIL10.ids.Corp.com> Hello, all. I am using a regular expression XXX_re = re.compile( ' \ d { 12 } ' ) # spaces added for clarity that returns the value below from a string similar to this one: XX(00000000) XXXXXXXXX[("XXX_XXX=123456789000","XXXXXX_XXX=1","Xxxxxxx=ABCDE01","Xxxx xxxxxxxx=ABCDEF","XxxxXxxxx=987654321000")] 123456789000 987654321000 I only want "ONE" occurrence, the first one in the RE. The string pieces are 12 digits. I have tried prefacing the pattern with the ' XXX_XXX = ' string segment, then I get XXX_XXX = 123456789000 When I use non-greedy ? or ., I get errors such as unscriptable, or other. Any suggestions??? I am able to do this as two separate progs, but have been unsuccessful at getting it all together as a one-pass code. Thanks! William -------------- next part -------------- An HTML attachment was scrubbed... URL: From gmail_girl at yahoo.co.in Sat Jun 17 01:28:52 2006 From: gmail_girl at yahoo.co.in (gmail_girl at yahoo.co.in) Date: 16 Jun 2006 22:28:52 -0700 Subject: Post Ur Job Requirements/Resumes Free ........ Message-ID: <1150522131.803552.105270@r2g2000cwb.googlegroups.com> Dear Employer/JobConsultant/JobSeeker, NEW GREAT OFFER BY US NOW ITS FREE TO SEARCH RESUME/JOB DATABASE AND CALL FOR INTERVIEW/APPLY INTERVIEW http://www.Net4Professionals.com (HERE YOU WILL GET FIVE TIMES MORE THAN EXPECTATION; FREE ...) FOR EMPLOYERS -------------------------------------------------------------------------------------- 1) EMPLOYERS CAN CREATE/UPDATE YOUR JOB ACCOUNT FREE 2) EMPLOYERS CAN POST UPTO FIVE JOBS FREE FREE FREE 3) EMPLOYERS CAN CALL THRU THRU MONTHLY RESUMES/RESUME SEARCH FOR INTERVIEW FREE 4) EMPLOYERS CAN SEND MESSAGES THRU MONTHLY RESUMES/RESUME SRERCH FREE 5) EMPLOYERS CAN ALSO WIN FREE MONTHLY GIFTS FOR JOB SEEKERS -------------------------------------------------------------------------------------- 1) Create/Manage Your/Your Friend/Relative Resume FREE 2) Search Your Desired Job FREE 3) Apply Online FREE 4) Win FREE Gift every month 5) Send Messages To Employers Free - This website is a combination of state of Art and Technology - Build With Latest DotNET Technology - Data on this website are Safe, Nobody can alter it on his/her system except you REGARDS RITU From fredrik at pythonware.com Thu Jun 8 04:07:21 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 08 Jun 2006 10:07:21 +0200 Subject: language-x-isms In-Reply-To: <1149753206.451066.120960@h76g2000cwa.googlegroups.com> References: <1149753206.451066.120960@h76g2000cwa.googlegroups.com> Message-ID: astyonax wrote: > But it's not the pythonic way. really? I'd say breaking stuff just because you can is remarkably unpythonic. From alf at merlin.fayauffre.org Thu Jun 1 11:50:55 2006 From: alf at merlin.fayauffre.org (Alexandre Fayolle) Date: Thu, 1 Jun 2006 15:50:55 +0000 (UTC) Subject: argmax References: Message-ID: Le 01-06-2006, David nous disait: > 1. Why is there no argmax built-in? > (This would return the index of the largest element in a sequence.) You'll get argmin and argmax in Numeric and its descendants (numarray and numpy). -- Alexandre Fayolle LOGILAB, Paris (France) Formations Python, Zope, Plone, Debian: http://www.logilab.fr/formations D?veloppement logiciel sur mesure: http://www.logilab.fr/services Python et calcul scientifique: http://www.logilab.fr/science From jerry.levan at gmail.com Thu Jun 1 18:40:59 2006 From: jerry.levan at gmail.com (jerry.levan at gmail.com) Date: 1 Jun 2006 15:40:59 -0700 Subject: Solved: Tktable, WinXP and ActiveState Python 2.4.3,x References: <1149047353.883167.18100@i39g2000cwa.googlegroups.com> Message-ID: <1149201659.936164.68960@y43g2000cwc.googlegroups.com> jerry.levan at gmail.com wrote: > Hi, > I have a python app that runs fine on MacOS X and Fedora Core 5. > > This evening I dragged the folder over to my windows partition and > tried to run the rascal. > > The program starts up fine but at the first call to create a Table > object > I get > > Traceback (most recent call last): > File > "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", > line 310, in RunScript > exec codeObject in __main__.__dict__ > File "C:\Documents and > Settings\Jerry\Desktop\PyPgBrowseUni\PyPgExplorer.py", line 7, in ? > obj.main() > File "C:\Documents and > Settings\Jerry\Desktop\PyPgBrowseUni\Resources\PyPgBrowse.py", line 72, > in main > self.build_ui( info) > File "C:\Documents and > Settings\Jerry\Desktop\PyPgBrowseUni\Resources\PyPgBrowse.py", line > 187, in build_ui > rowtagcommand=self.rowproc > File "C:\Documents and > Settings\Jerry\Desktop\PyPgBrowseUni\Resources\Tktable.py", line 64, in > __init__ > master.tk.call('load', '', 'Tktable' ) > TclError: package "Tktable" isn't loaded statically > : > > I get the same error if I try to create a Table object from the command > line > in a console. > > I tried waving a dead chicken at my laptop but it did no good. > > Is there some special magic to get Tktable.py to play nice? > I do have the latest Tcl from Active State loaded on my box and > the Tktable in my Tk programs work well... > > Thanks for any insight.... > > Jerry Thanks to the good folks at Active State here is a way to use tktable from Python. 1) Put the wrapper file Tktable.py into C:\Python24\Lib\lib-tk 2) Copy the whole folder C:\Tcl\lib\Tktable* to C:\Python\tcl Letter Rip.... Thanks Jeff... Jerry From luismgz at gmail.com Mon Jun 5 18:34:09 2006 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 5 Jun 2006 15:34:09 -0700 Subject: C# equivalent to range() In-Reply-To: <1149545140.011616.130610@y43g2000cwc.googlegroups.com> References: <1149468919.951745.163700@g10g2000cwb.googlegroups.com> <1149481675.192638.275140@c74g2000cwc.googlegroups.com> <1149509893.031953.19310@i40g2000cwc.googlegroups.com> <1149545140.011616.130610@y43g2000cwc.googlegroups.com> Message-ID: <1149546849.406638.83870@i39g2000cwa.googlegroups.com> Fuzzyman wrote: > FWIW I agree. If anyone didn't want to answer the question they didn't > need to. > > Why be rude to someone asking a polite question. It's not as if there > isn't much more *worse* noise on this group. I also agree. Although the question may have appeared out of place, it wasn't totally. The poster asked the question very politely, apologizing in advance for what may be consider an off-topyc question. He also said he only knew python, and he probably wasn't able to explain the intended behaviour he wanted in C# without refering to Python. He is also very right when he says that those who were not interested in the question could have simply ignored it. In exchange, he got a couple of slighty rude replies and an ironic comment. What reaction do you expect from him? From marshall.spight at gmail.com Tue Jun 27 01:01:51 2006 From: marshall.spight at gmail.com (Marshall) Date: 26 Jun 2006 22:01:51 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <7zy7vt1mz2.fsf@app-3.diku.dk> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> Message-ID: <1151384511.223582.305760@m73g2000cwd.googlegroups.com> Chris F Clark wrote: > > And to me the question is what kinds of types apply to these dynamic > programs, where in fact you may have to solve the halting problem to > know exactly when some statement is executed. I expect that some > programs have type signatures that exceed the expressibility of any > static system (that is Turing complete). Therefore, we need something > that "computes" the appropriate type at run-time, because we need full > Turing power to compute it. To me such a system is a "dynamic type > system". I think dynamic tags are a good approximation, because they > only compute what type the expression has this time. Yes, an important question (IMHO the *more* important question than the terminology) is what *programs* do we give up if we wish to use static typing? I have never been able to pin this one down at all. Frankly, if the *only* issue between static and dynamic was the static checking of the types, then static typing woud unquestionably be superior. But that's not the only issue. There are also what I call "packaging" issues, such as being able to run partly-wrong programs on purpose so that one would have the opportunity to do runtime analysis without having to, say, implement parts of some interface that one isn't interested in testing yet. These could also be solved in a statically typed language. (Although historically it hasn't been done that way.) The real question is, are there some programs that we can't write *at all* in a statically typed language, because they'll *never* be typable? I think there might be, but I've never been able to find a solid example of one. > Perhaps, there is no such beast. Or, perhaps I just can't formulate > it. Or, perhaps we have static type checkers which can do > computations of unbounded complexity. However, I thought that one of > the characteristics of type systems was that they did not allow > unbounded complexity and weren't Turing Complete. The C++ type system is Turing complete, although in practical terms it limits how much processing power it will spend on types at compile time. > If you allow Turing Complete type systems, then I would say no--every > bug can be reforumlated as a type error. If you require your type > system to be less powerful, then some bugs must escape it. I don't think so. Even with a Turing complete type system, a program's runtime behavior is still something different from its static behavior. (This is the other side of the "types are not tags" issue--not only is it the case that there are things static types can do that tags can't, it is also the case that there are things tags can do that static types can't.) Marshall From ilias at lazaridis.com Wed Jun 7 11:12:04 2006 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Wed, 07 Jun 2006 18:12:04 +0300 Subject: Django Quick Start with Schema Evolution Support In-Reply-To: <1149690890.340282.205710@h76g2000cwa.googlegroups.com> References: <1149446706.085692.174980@h76g2000cwa.googlegroups.com> <1149505316.406428.242450@c74g2000cwc.googlegroups.com> <448429E1.90305@kered.org> <35081.132.60.240.80.1149530454.squirrel@kered.org> <4486D6F2.7000407@lazaridis.com> <1149690890.340282.205710@h76g2000cwa.googlegroups.com> Message-ID: Brian wrote: > Ilias Lazaridis wrote: > >> http://lazaridis.com > > I would agree with you that this is a place to discuss python. > However, your posts primarily deal with your expulsion from another > group. Instead of discussing that, why don't your discuss the python > technicalities of your project and leave the rest alone since we want > to hear about the former and not the later. > > Brian thank you. - *IMPORT* I would like to know, if this construct is valid, or if it can result in problems: 1082 try: 1083 from django.rework.evolve import evolvedb 1084 except ImportError: 1085 def evolvedb(): 1086 "Evolve Command Dummy" 1087 print 'Command evolvedb not imported' 1088 evolvedb.args ='' - *PATCHING* A second problem is, how to make the setup for users (testers) more convenient. Is there e.g. any mechanism to apply a patch in an automated manner (e.g. using a python library)? - *ALIAS_METHOD* The django commands are hard-coded: http://code.djangoproject.com/browser/django/trunk/django/core/management.py#L1180 thus elegant/dynamic additions of commands seem not possible. Another possibility is to enlink (hook?) the functionality into an existent function Is there any way (beside a patch) to alter the behaviour to an existing function. Is ther a python construct similar to the "alias_method" of Ruby: (example from an simple evolution support for a ruby orm) #------------------------------------------------------------------------------ # use "alias_method" to enlink the code #------------------------------------------------------------------------------ class SqliteAdapter alias_method :old_create_table, :create_table def create_table(*args) table_evolve(*args) result = old_create_table(*args) return result end end http://lazaridis.com/case/persist/og-evolve.rb - - - If anyone is interested to verify the results in order to stabelize the simple schema evolution support for django, please review the results here: http://case.lazaridis.com/wiki/DjangoProductEvaluation http://case.lazaridis.com/wiki/DjangoSchemaEvolution http://case.lazaridis.com/browser/django/rework/evolve.py http://case.lazaridis.com/browser/django/rework/add_evolvedb_command.diff . -- http://lazaridis.com From sjmachin at lexicon.net Fri Jun 2 17:58:45 2006 From: sjmachin at lexicon.net (John Machin) Date: Sat, 03 Jun 2006 07:58:45 +1000 Subject: struct.pack('d', ...) -> "frexp() result out of range" (was Re: PyExcelerator) In-Reply-To: <1149269975.981840.286750@j55g2000cwa.googlegroups.com> References: <1149269975.981840.286750@j55g2000cwa.googlegroups.com> Message-ID: <4480B495.6010207@lexicon.net> On 3/06/2006 3:39 AM, tkpmep at hotmail.com wrote: > I write data to Excel files using PyExcelerator 0.6.3.a and have done > so successfully for small files (10-15 cells). I'm experiencing an > error when writing a big chunk of data (10,000 cells) to Excel. By way > of comparison, the same data writes perfectly well to a csv file using > Python's built in csv module. I run the program in PyScripter, and the > traceback shows the following sequence of calls: > > main (my routine) > writeData (my routine) > save Line 563 > get_biff_data Line 548 > get_biff_data Line 1357 > __row_blocks_rec Line 1276 > get_cells_biff_data Line 200 > get_biff_data Line 106 Grumble: When you need to post a traceback, please supply one that shows on each line which *file* the source line is in. In this case there are multiple files, and 9 classes spread over 4 files have a method called get_biff_data. > > SystemError: frexp() result out of range > > The line it stops at in get_biff_data is the line that starts with > packed = > > def get_biff_data(self): > rk_encoded = 0 > > packed = struct.pack(' > Any thoughts on what the problem could be? > It is calling struct.pack (see structmodule.c in the Python source) to encode one of your cell values as an 8-byte little-endian IEEE 754 floating-point number. This task is handed off to _PyFloat_Pack8() (see floatobject.c). Here's the relevant bit: """ if (x < 0) { sign = 1; x = -x; } else sign = 0; f = frexp(x, &e); /* Normalize f to be in the range [1.0, 2.0) */ if (0.5 <= f && f < 1.0) { f *= 2.0; e--; } else if (f == 0.0) e = 0; else { PyErr_SetString(PyExc_SystemError, "frexp() result out of range"); return -1; } """ where x is your cell value as a C double. frexp() is a standard C library routine. The above code is just checking that it has done its job correctly. AFAICT from reading K&R v2 p251, the code is correct. Aside: isn't open source wonderful? Well it is for me. It could be wonderful for you too :-) I'm not an IEEE 754 guru by any means, so I'm guessing your value could be an Inf (infinity) or a NaN (not a number) -- there's no explicit test for those in the code -- or you have stumbled on a value that's a corner case on your platform. Maybe it's -0.0 (zero with the sign bit set). Grumble: When you have a problem like this, you should state what version of Python you are using, on what platform. The line you get when you run Python at the command line is a start e.g. """Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)] on win32""" Please tell us this, plus explicitly what OS and what hardware you are running on. OK, now what's this dodgy number?? Unfortunately, the error is happening right at the end of your process, in the workbook save method. The only info about which row/column is buried deep in pyExcelerator. We don't (yet) want to start poking about there ... Try these steps: 1. Search your alternative CSV output file for the text "Inf" or "NaN" (case insensitive). 2. Put some code in your cell write routine to filter the values you are writing: absval = abs(value) SMALL = 0.000001 # depends on what is reasonable for your app LARGE = 10.0 ** 10 # depends ... if not (value == 0.0 or (SMALL <= absval <= LARGE)): print "strange value %r in row=%d col=%d" % (value, rownum, colnum) Then come back and tell us what if anything you've found. HTH, John From grante at visi.com Mon Jun 5 10:53:01 2006 From: grante at visi.com (Grant Edwards) Date: Mon, 05 Jun 2006 14:53:01 -0000 Subject: How to add few pictures into one References: <1149511692.796038.155930@c74g2000cwc.googlegroups.com> <1149517433.880564.128350@h76g2000cwa.googlegroups.com> Message-ID: <1288hado9if5h7f@corp.supernews.com> On 2006-06-05, Lad wrote: >>> is it possible to add( with PYTHON language) several image >>> files into one? >> >> Google for 'Python Imaging Library'... > > I was thinking about this: to open each image file in binary > mode , read it and write into the result image file? Is that > possible? Yes. -- Grant Edwards grante Yow! I have many CHARTS at and DIAGRAMS... visi.com From ntv1534 at gmail.com Mon Jun 26 16:59:13 2006 From: ntv1534 at gmail.com (MooMaster) Date: 26 Jun 2006 13:59:13 -0700 Subject: Having problems with reading file in Python CGI In-Reply-To: References: Message-ID: <1151355553.085706.313510@i40g2000cwc.googlegroups.com> I haven't tried to use the CGI class for any CGI scripting, so I'm no expert...but I am familiar with file objects. You want to return the next line in the file object? Your loop will run until it hits the EOF, at which point it'll break...once you hit that, there is *no* next line. But it looks to me like you're trying to return the contents of the file in a list...is that the part that's not working? If so, you might wanna try this: def filereader(a_file): contents = [] for line in a_file: contents.append(line.strip()) print line print contents now if you create a file like so: myfile = file("Moo.txt", "r") filereader(myfile) You should see the contents of the file. So in your case, you should be able to change that horrible infinite while 1 loop with a break (which is straight from the python docs too... my programming languages teacher would have a fit!) into something like: for stuff in fileStream.file: Hope this helps! Kiana Toufighi wrote: > Hi, > > I have a simple CGI program that allows that user to upload a file. > However, since accessing the the value of the uploaded file using the > value attribute or the getvalue() method reads the entire file in memory > as a string which is not what I want I'm making use of the file module. > The problem is that all the my checks including "assert fileStream.file > in not None" return true however readline() does not return the next > line of the fileStream.file object! What am I doing wrong? Here's my code: > > Here's my code: > > caller: > dataFile = form['data_file'] > fileproc = redrev.FileStreamProcessor() > dataLines = fileproc.readStream(dataFile) > > callee: > def readStream(self, fileStream): > '''readStream: reads a stream of input returns a list of lines''' > > # list to hold data lines > fileLines = [] > > # make sure that the stream has been provided > try: > assert fileStream.file is not None > except Exception, e: > "No input to process" > > # use filestream object to get uploaded file's lines one by one > if fileStream.file: > while 1: > line = fileStream.file.readline() > if not line: > break > > # process and store the line > line.strip() > fileLines.append(line) > > return fileLines > > > Thanks, > > Kiana From sonal.patankar at 3i-infotech.com Mon Jun 12 02:11:35 2006 From: sonal.patankar at 3i-infotech.com (sonal.patankar at 3i-infotech.com) Date: 11 Jun 2006 23:11:35 -0700 Subject: How to link foreign keys & primary keys using python? References: <1149856668.055162.209650@u72g2000cwu.googlegroups.com> Message-ID: <1150092695.050971.33880@u72g2000cwu.googlegroups.com> Hi Mr. George, Let me try it again... I am not using any relational database to store the required tables with primary keys & foreign keys.... When I say PRIMARY KEY => 1. It means an index is created on the specified fields (Out of various fields given in the comma separated txt file) FileFormat: CODE, FIRST_NAME, last_name, area_of_expertise, country Eg: A1,Harry,George, python, XYZCOUNTRY--------(1st record) 2. The index can be formed on a single field or on multiple fields Eg: a. 'CODE' (single field ) {pk_code} b. 'CODE' & 'NAME' (multiple fields ) {pk_code_fname} Now when I say FOREIGN KEY => 1. If the foreign Key is formed on the field 'CODE' in another text file Format: subsriber_code,CODE,first_name, no_of_posts,active(Y/N) Eg: SUB_001, A1, Harry, 50, Y This means the CODE (A1) given here is checked in the index formed above with primary key: pk_code... 2. If the foreign Key is formed on the fields 'CODE' & 'FIRST_NAME' Format: subsriber_code,CODE,FIRST_NAME, no_of_posts,active(Y/N) Eg: SUB_001, A1, Harry, 50, Y This means the CODE (A1) & FIRST_NAME (Harry) given here are checked in the index formed above with primary key: pk_code_fname... I am done till here..... The problem starts if I have defined an index on multiple fields (composite PK) say: CODE & FIRST_NAME (pk_code_fname) and if I need to define a FK on a single field out of these say: CODE I am unable to do that... Mr. George, I thought i must explain the code i am dealin with, for better understanding.., but i am sorry i confused you all the more (incase, u want to view the code please refer to the code snippets in my first query posted) I hope you atleast get an idea of what i am hunting for.... :( From andrewdalke at gmail.com Tue Jun 20 07:22:44 2006 From: andrewdalke at gmail.com (andrewdalke at gmail.com) Date: 20 Jun 2006 04:22:44 -0700 Subject: Seeking regex optimizer In-Reply-To: <1150781734.524970.272390@u72g2000cwu.googlegroups.com> References: <1150650439.651839.38180@y41g2000cwy.googlegroups.com> <1150750294.232093.304230@p79g2000cwp.googlegroups.com> <1150781734.524970.272390@u72g2000cwu.googlegroups.com> Message-ID: <1150802564.655230.248580@u72g2000cwu.googlegroups.com> Kay Schluehr replied to my question: > > Why do you want to use a regex for this? > > Because it is part of a tokenizer that already uses regexps and I do > not intend to rewrite / replace it. Switching to pytst is not a big change - there will be little impact on the rest of your code. On the other hand, it does change your build and deployment process because of the need for another package. Because you are constraining yourself to regex there isn't much of an improvement you can do. > I found that certain groups of token > might be represented in a more compact mannerr: for matching ['+', > '++'] one might generate '\+|\+\+' or '\+\+?' and I wanted to know if > there is some generic approach to solve the "inverse regexp" problem in > a non-trivial fashion. There are a few questions which come up. Why do you want to have a "more compact" representation? Do you think it will make the result faster? Likely it will because of the reduced need for backtracking but unless you have a lot of strings with the same prefix then the number of backtracks should go as something like the log of the number of words, which scales pretty well. Are you speed limited by the existing implementation? Likely not. In which case the performance isn't an issue. Consider this anecdote from http://www.technicat.com/writing/programming.html I was asked in a phone interview with Google how I would search for a number in an array of ordered numbers. Obviously, the questioner was asking for a CS 101 answer - binary search. But in real life, I would probably do the "wrong" thing - search the array from beginning to end. There's no point in taking twice the time to write twice as much code that has to be maintained and debugged if the application performance is good enough, and in particular if that piece of code is not the bottleneck in the application. (And I seriously doubt you'd have that data laid out linearly in a fixed array like that if it was the bottleneck) As it turns out, the regexp implementation could do the optimization you want. That is, it could recognize that the input sequence is a set of fixed words (no special characters) and implement something like Aho-Corasick, in which case you wouldn't need to change your input. I don't know if Python's regexp implementation does this already. Neither do you. Test the functionality and performance first before going starting other work. I am not the first to give you this advice: John Machin: > Optimised with respect to what? speed? ease of construction? gry at ll.mit.edu: > As others have suggested, you should first try the most naive > implementation before making a hard optimization problem out of this. As for the general question of the existance of a "generic approach to solve the "inverse regexp" problem in a non-trivial fashion." Yes, there is. Kinda of. All (formal/theoretical) regular expressions can be written as a regular expression without need for backtracking. If you look up the theory of regular expressions, backtracking occurs when there are ambiguities in traversing the state machine. These are called nondeterministic finite state machines, or NFAs. It turns out that every NFA can be written as a DFA, which has no need for backtracking. Except. Actually, two excepts. The normal algorithm for converting an NFA to a DFA doesn't support grouping, which you'll need to figure out which group matched. Wikipedia says there is an alternate, slower algorithm which does support groups. The second except is that regexps in Python, Perl, etc. are not regular expressions. Some patterns, like r"([A-Z][a-z]+)\1", which matches "WikiWiki", are not "regular grammars" under the definition used in language theory. It's possible to use regexps to match strings of prime length, for example. So in the general case there is no solution. There are many possible optimizations, but no general solution. For your problem, which is a limited subset of the problem as it involves only constant strings, then the solution is a prefix tree, also called a trie. See http://en.wikipedia.org/wiki/Prefix_tree John Machin in an earlier post suggested you search along these lines when he said > I would have thought the way to approach this would be a simple > character-by-character tree/trie-driven lookup. This would be worst case > O(n) where n is the length of the longest string in your list. There may > well be a Python-callable gadget for this on the net somewhere. Google > "Danny Yoo ahocorasick" for a Python-callable solution to a similar but > more complex problem. For that matter I suggested it when I pointed you to pytst. The tst means "ternary search tree" (some write it "ternary search trie") which is a different implementation of the same idea. Your posts read like you ignored those pointers because they didn't fall into the category "implemented with a regular expression". If that's the case then no, there is no solution. You're letting a sense of purity overwhelm practicality. If you are really interested in this problem, try taking a CS course titled something like "Automata Theory" or "Foundations of Computer Science". The one which covers DFAs, NFAs, CFGs, Turing machines, etc. It's the CS class I enjoyed the most. Andrew dalke at dalkescientific.com From tjreedy at udel.edu Tue Jun 27 22:22:03 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 27 Jun 2006 22:22:03 -0400 Subject: Function to prune dictionary keys not working References: <52244.10.209.4.2.1151460911.squirrel@10.105.1.3> Message-ID: "Girish Sahani" wrote in message news:52244.10.209.4.2.1151460911.squirrel at 10.105.1.3... > hi ppl, > Here is a simple function to remove those keys of a dictionary whose > values are less than some specified value. But it isnt working. Please > help. > > def prune(d,cp): > l = [] > for rule,value in d.iteritems(): > #print value > if value >= cp: > l.append(rule) > return l > > >>>> d = {'be=>c': '1.00', 'c=>da': '0.50', 'ea=>b': '0.33', 'be=>d': > '0.50', 'c=>ba': '0.33', 'bd=>a': '1.00', 'a=>cb': '0.33', 'ea=>c': > '0.67', 'a=>cd': '0.50', 'e=>ac': '0.40', 'e=>ab': '0.20', 'c=>bd': > '0.33', 'e=>cb': '0.40', 'ed=>b': '0.25', 'ed=>c': '0.50'} >>>> cp = 0.5 >>>> if prune(d,cp) == d.keys(): > print "code not working :((" > > code not working :(( You are comparing a float (0.5) to strings ('1.00', etc). The result of that comparison is undefined. Unquote the values and try again. tjr From ishoej at gmail.com Mon Jun 19 05:59:29 2006 From: ishoej at gmail.com (Holger) Date: 19 Jun 2006 02:59:29 -0700 Subject: Noob script needs some input: CVS PatchMaker In-Reply-To: <44934921.7080208@lexicon.net> References: <1150450094.544961.189540@i40g2000cwc.googlegroups.com> <44934921.7080208@lexicon.net> Message-ID: <1150711169.223265.204260@f6g2000cwb.googlegroups.com> John Machin wrote: > > Any feedback on what would be "the pythonic way" to do this would be > > much appreciated! --snip-- > > IMHO that flight of geese heading equatorwards for winter is not Xic for > any language X. Compare with: He he, good point. > 2nd comment: Make a habit of NOT using the names of built-ins like > "file" for your own names. Pretend they are reserved words. Doesn't > matter in this case, but will save you grief some day soon. > Agree. > 3rd comment: Read the section in the re manual that explains the > difference between search and match. Searching for "^foo" will give the > same results as using match() with "foo" or the redundantly anchored > "^foo". However some regex engines when presented with Good point. > 4th comment: what you have called "regx" is a match object. "mobj" might > be a better choice. The term "regex" is applied to a pattern, or > sometimes to the compiled re object. ] > > HTH, > John Thank you for taking the time :-) All points are noted. Holger, From jzgoda at o2.usun.pl Thu Jun 15 12:48:18 2006 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Thu, 15 Jun 2006 18:48:18 +0200 Subject: code folding, a unique problem to python? In-Reply-To: References: <4fdgh7F1hbtteU1@uni-berlin.de> Message-ID: John Salerno napisa?(a): > ::lowers head in embarassment:: I wanted to try out Eric3, but I > couldn't figure out how to install it! Is there a binary file? All I > found was a zipped file with a bunch of stuff I didn't recognize in it. > There was even a file called eric3.py which I thought might be it, but > running it did nothing. You'll need PyQt to run that one. And QScintilla too. -- Jarek Zgoda http://jpa.berlios.de/ From ryanlists at gmail.com Mon Jun 19 09:02:01 2006 From: ryanlists at gmail.com (Ryan Krauss) Date: Mon, 19 Jun 2006 09:02:01 -0400 Subject: interactive multi-file search and replace Message-ID: I need to do some searching and replacing in about 10 latex files. Does anyone have an existing script that does this on an interactive basis? I would like to show each match and ask whether or not it should be replaced. This seems like a fairly common task and I don't want to re-invent the wheel. Ryan From gandalf at designaproduct.biz Fri Jun 9 13:21:12 2006 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Fri, 09 Jun 2006 19:21:12 +0200 Subject: __getattr__ question Message-ID: <4489AE08.2080407@designaproduct.biz> Hello, This is from the Python documentation (fragment): __getattr__( self, name) Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self). name is the attribute name. This method should return the (computed) attribute value or raise an AttributeError exception. How can I determine if an attribute can be found in the usual places? Here is an example program that will enlight the basic problem. class TemplateItem(object): def __init__(self,name): self.name = name self.items = [] # Order of items is important def __getattr__(self,name): """I would like to access the items easily, with their name (if possible)""" for item in self.items: if hasattr(item,'name') and item.name == name: return item raise AttributeError("%s: attribute or item does not exists."%name) def __str__(self): return "TemplateItem('%s')"%self.name class CustomTemplateItem(TemplateItem): pass # I could have been customized this... root = CustomTemplateItem('root') i1 = CustomTemplateItem('item1') i2 = CustomTemplateItem('item2') root.items.append(i1) root.items.append(i2) TemplateItem.item3 = TemplateItem('item3') print root print root.item1 print root.item2 print root.item3 Of course this program will print: TemplateItem('root') TemplateItem('item1') TemplateItem('item2') TemplateItem('item3') So how can I tell if 'root.item3' COULD BE FOUND IN THE USUAL PLACES, or if it is something that was calculated by __getattr__ ? Of course technically, this is possible and I could give a horrible method that tells this... But is there an easy, reliable and thread safe way in the Python language to give the answer? Thanks, Laszlo From ldo at geek-central.gen.new_zealand Sun Jun 25 21:08:13 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 26 Jun 2006 13:08:13 +1200 Subject: popen2 question References: <3026518.PBSJIyfHH0@teancum> Message-ID: In article <3026518.PBSJIyfHH0 at teancum>, David Bear wrote: >I'm using popen2 and getting an extra 1 at the end of my output. I didn't >see where this was explained in the docs so I clearly don't understand the >behavior. My code is simple. > >(input, output) = os.popen2('whackyperlprogram') >results = output.read() >rc = output.close() >print results What if, for comparison, you try running a trivial program that produces no output: (input, output) = os.popen2('/bin/true') results = output.read() rc = output.close() print results Do you still get the "1" at the end? From randhol+valid_for_reply_from_news at pvv.org Sun Jun 18 15:20:21 2006 From: randhol+valid_for_reply_from_news at pvv.org (Preben Randhol) Date: Sun, 18 Jun 2006 21:20:21 +0200 Subject: Extracting values from text file References: <20060617232543.9a0338fb.randhol+valid_for_reply_from_news@pvv.org> <20060618133459.2a56f781.randhol+valid_for_reply_from_news@pvv.org> Message-ID: <20060618212021.0ab49a1b.randhol+valid_for_reply_from_news@pvv.org> On Sun, 18 Jun 2006 17:46:43 +0200 Mirco Wahab wrote: > Thus spoke Preben Randhol (on 2006-06-18 13:34): > > On Sun, 18 Jun 2006 10:54:01 +0200 > > Mirco Wahab wrote: > >> - no DWIM-ism (do what I mean) on 'value' addition > > > > But you don't add two values. you add two strings. If you > > want numbers you must convert the strings. > > Why? At least - if its obvious, what I want. If I say: I want something to eat. Can you know if I want a dessert or a dinner ? ;-) My point is that you don't specify. In your case you show that pyhton is polymorphic, and that can have side-effects... Since in Python you cannot define what type a function should accept you can throw anything to it and it will happily much at it as best it can. Computers are dumb and it is better that one give them enough instructions than to let them second guess you IMHO.... My other language of choice is Ada. Ada is quite the opposite of Python in being a very strictly typed language. It takes some getting used to Python for me ;-) In my opinion Ada95 & Ada2005 got strict typing correct, while Java only partially is strictly typed. C/C++ is not. Anyway Ada and Python has different targets so I can happily play with both static and dynamic typing. I can recommend Ada as it will teach you to a very good programming style that can be used when using other language. From michael at stroeder.com Tue Jun 13 04:48:46 2006 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Tue, 13 Jun 2006 10:48:46 +0200 Subject: [newbie]apache authentication questions In-Reply-To: References: <1150132535.766644.99870@g10g2000cwb.googlegroups.com> <1150173351.116073.316640@u72g2000cwu.googlegroups.com> Message-ID: Steve Holden wrote: > grahamd at dscpl.com.au wrote: > >> It is not impossible though and in cases where you don't have a choice >> but to use a HTTP authentication scheme, use of AJAX may be the >> answer to still allowing use of a form based login scheme. See: >> >> http://www.peej.co.uk/articles/http-auth-with-html-forms.html >> > That's neat! IMHO this makes things more complicated and error-prone. And it requires Javascript. I also can't see why this is more secure than a proper session management (using cookies or URL for passing the session ticket around). Ciao, Michael. From matt.good at gmail.com Fri Jun 9 14:46:59 2006 From: matt.good at gmail.com (Matt Good) Date: 9 Jun 2006 11:46:59 -0700 Subject: Pychecker In-Reply-To: References: Message-ID: <1149878819.556169.270020@u72g2000cwu.googlegroups.com> Anthony Greene wrote: > Howdy, I had the impression that pychecker caught and reported such > dynamic syntactical errors. > > #!/usr/bin/env python > > > def add(i): > i += 10 > > status = 3 > > if 1 == 1: > statuss = 15 > > add(status) > > ======================= > > exalted sysfault$ pychecker foo.py > Processing foo... > > Warnings... > > None > > ======================= > > Hence the mispelling of status (statuss), which was done purposely to test > if pychecker will acknowledge and report the error. Do i need to enable > some type of pychecker option in order for it to pick up the error? I know > that it is syntactically correct in python, however it's likely that > 'status' is meant. Am i wishing that pychecker will replace a statically > typed language mechanism? That's a functional error, not a syntactical one. Analyzing the spelling of variables for similarity would lead to a lot of incorrect warnings since pychecker has no way to tell this apart from intentional similar spellings such as: values = [1, 2, 3] value = values[0] However, when the misspelling is made inside a local scope, rather than at the module level a warning is reported "test.py:8: Local variable (statuss) not used": def add(i): i += 10 def test(): status = 3 if 1 == 1: statuss = 15 add(status) This is why tools like pychecker (or pyflakes, pylint, or even a static code compiler) aren't a substitute for unit tests. They can definitely help catch common mistakes, but they can't ensure your code does what you intended. -- Matt Good From joncle at googlemail.com Thu Jun 1 17:49:53 2006 From: joncle at googlemail.com (Jon Clements) Date: 1 Jun 2006 14:49:53 -0700 Subject: Using print instead of file.write(str) In-Reply-To: <1149197601.238826.151200@f6g2000cwb.googlegroups.com> References: <447f4c9a$0$6174$626a54ce@news.free.fr> <1149197601.238826.151200@f6g2000cwb.googlegroups.com> Message-ID: <1149198592.996237.116760@j55g2000cwa.googlegroups.com> I meant 'trailing': not leading. mea culpa. Jon. Jon Clements wrote: > Didn't know of the >> syntax: lovely to know about it Bruno - thank > you. > > To the OP - I find the print statement useful for something like: > print 'this','is','a','test' > >>> 'this is a test' > (with implicit newline and implicit spacing between parameters) > > If you want more control (more flexibility, perhaps?) over the > formatting of the output: be it spacing between parameters or newline > control, use the methods Bruno describes below. > > I'm not sure if you can suppress the spacing between elements (would > love to be corrected though); to stop the implicit newline use > something like > print 'testing', > >>> 'testing' > (but - with the leading comma, the newline is suppressed) > > I personally find that print is convenient for sentences (or writing > 'lines'). > > Thought it worth pointing this out in case, like some I know, you come > across a cropper with certain output streams. > > All the best, > > Jon. > > > > Bruno Desthuilliers wrote: > > A.M a ?crit : > > > Hi, > > > > > > > > > I found print much more flexible that write method. Can I use print instead > > > of file.write method? > > > > > > > f = open("/path/to/file") > > print >> f, "this is my %s message" % "first" > > f.close() > > > > To print to stderr: > > > > import sys > > print >> sys.stderr, "oops" > > > > FWIW, you and use string formating anywhere, not only in print statements: > > > > s = "some %s and % formating" % ("nice", "cool") > > print s > > > > You can also use "dict formating": > > > > names = {"other": "A.M.", "me" : "bruno"} > > s = "hello %(other)s, my name is %(me)s" % names From aleax at mac.com Thu Jun 1 11:15:21 2006 From: aleax at mac.com (Alex Martelli) Date: Thu, 1 Jun 2006 08:15:21 -0700 Subject: An oddity in list comparison and element assignment References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> Message-ID: <1hg8ug8.m01zhwehpk66N%aleax@mac.com> wrote: ... > operations. I think what must be going on is that the 'b' list > contains replicated references instead of copies of [range(1,3)]*2 . Right. > IMO, python's == operator should detect this difference in list > structure since it leads to different behavior under element > assignments. Wrong; equality does not imply any check on identity. You can consider the definition of "list A equals list B" as: -- len(A) == len(B), AND, -- for each valid index i, A[i] == B[i] This is an extremely natural definition of "equality" for containers: "they have EQUAL items" [[in the same order, for containers for which order is relevant]]. Nowhere in this extremely natural definition does the IDENTITY of the items come into play. Therefore, your expectations about the effects of item alterations (for alterable items) are ill-founded. Try concisely expressing your "should" -- constructively, as pseudocode that one could use to check for your "strengthened equality", not in abstract terms of constraints -- and if (as I strongly suspect) you cannot find a definition that is as simple, concise and natural as the two-liner above, this might help convince you that your desired definition would NOT be the most obvious, natural and fundamental, and therefore would not be appropriate to pick as part of the language's core. Indeed, it's an interesting problem to code up, if one wants any generality (for example, identity of immutable items _whose items or attributes are in turn immutable_ probably should not matter even for your "strengthened" equality... but that's pretty hard to express!-). Alex From news00 at wilec.net Tue Jun 27 12:36:32 2006 From: news00 at wilec.net (Al) Date: Tue, 27 Jun 2006 18:36:32 +0200 Subject: Exchanging data with a C program using shared memory (sysV IPC) Message-ID: Hello, I want my python application to communicate with an legacy C program which read/write data in a shared memory (Unix Sys V IPC). It seems that there are no official shm nor sysV ipc module, and that non-official ones are dead. I can't modify the C code to change its communication method. How would you solve this problem using python ? Is there any reason there is no official shm for python ? I could write a C code which communicates with my python application using mmap or something else and with the old C code using shmat(), but this is a rather ugly solution. Thanks in advance. --- Al From fredrik at pythonware.com Sun Jun 11 18:05:49 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 12 Jun 2006 00:05:49 +0200 Subject: direct initialization of class attributes vs. declarations w/in __init__ In-Reply-To: References: <1150041510.139609.171120@f6g2000cwb.googlegroups.com> <4f2thrF1fd4r4U1@uni-berlin.de> <1150043792.136250.99770@u72g2000cwu.googlegroups.com> <1150047314.025241.260750@c74g2000cwc.googlegroups.com> <1150062413.303012.177330@f6g2000cwb.googlegroups.com> Message-ID: Fredrik Lundh wrote: > a missing plus sign. or a misplaced one... (=+ 1 is not the same thing as += 1) From mr.roboto.ny at gmail.com Wed Jun 14 14:30:20 2006 From: mr.roboto.ny at gmail.com (Mr Roboto) Date: 14 Jun 2006 11:30:20 -0700 Subject: Simple Char-I/O Dialogs for Win32 and DOS Message-ID: <1150309820.174088.6960@f6g2000cwb.googlegroups.com> Folks: I've already searched the group and have determined there *are* char I/O based input systems, ala NCURSES, that are Python-compatible (ie. PyNCurses, UrWid, etc.) What I *need* is something that does simple dialogs under char-I/O Win32 and DOS w/ very little fuss or muss. At most, I need one or two dialog boxes to boot my little app/util *AND* hope upon hope I don't need port something (which would take more days than I have *and* would also require a non-trivial support effort from a one-man show: *me*) and can simply grab something (open-source) off-the-shelf. I don't need a dialog/forms designer, no database access, just a basic dialog box to get input from a couple of text boxes, check boxes, etc. Does such an animal exist and can someone offer a link to the kit ? TIA....MR From aleax at mac.com Wed Jun 14 10:59:05 2006 From: aleax at mac.com (Alex Martelli) Date: Wed, 14 Jun 2006 07:59:05 -0700 Subject: "groupby" is brilliant! References: <1150180151.643245.148210@y43g2000cwc.googlegroups.com> Message-ID: <1hgww3q.88ib5jyqo5hcN%aleax@mac.com> James Stroud wrote: ... > def doit(rows, doers, i=0): > for r, alist in groupby(rows, itemgetter(i)): > if len(doers) > 1: > doit(alist, doers[1:], i+1) > doers[0](r) Isn't this making N useless slices (thus copies, for most kinds of sequences) for a doers of length N? Since you're passing i anyway, it seems to me that: def doit(rows, doers, i=0): for r, alist in groupby(rows, itemgetter(i)): if len(doers) > i+1: doit(alist, doers, i+1) doers[i](r) is equivalent to your code, but avoids these slices (thus copies). Alex From fredrik at pythonware.com Thu Jun 8 09:23:00 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 08 Jun 2006 15:23:00 +0200 Subject: Extended zip() for lists In-Reply-To: References: Message-ID: Florian Reiser wrote: > I have 4 lists: a, b, c and d > Out of this 4 lists I want to build a table (e.g. list of lists): > > a|b|c|d > --------------------------- > a1|b1|c1|d1 > a1|b2| |d2 > > You see: the lists are not equally sized. > Is there a command which fills up the shorter lists with blanks? > Like an enhanced zip() command, maybe? like map(None, ...), perhaps ? >>> a = "1234" >>> b = "12" >>> c = "123" >>> d = "1234" >>> zip(a, b, c, d) [('1', '1', '1', '1'), ('2', '2', '2', '2')] >>> map(None, a, b, c, d) [('1', '1', '1', '1'), ('2', '2', '2', '2'), ('3', None, '3', '3'), ('4', None, None, '4')] From arv.nntp at gmail.com Fri Jun 16 13:41:59 2006 From: arv.nntp at gmail.com (Alexis Roda) Date: Fri, 16 Jun 2006 19:41:59 +0200 Subject: add elements to indexed list locations In-Reply-To: <1150478265.122559.283000@f6g2000cwb.googlegroups.com> References: <1150478265.122559.283000@f6g2000cwb.googlegroups.com> Message-ID: En/na leventyilmaz at gmail.com ha escrit: > Hi, > > I have a very simple problem, but do not know an elegant way to > accomplish this. > ### > # I have a list of names: > names = ['clark', 'super', 'peter', 'spider', 'bruce', 'bat'] > > # and another set of names that I want to insert into > # the names list at some indexed locations: > surnames = { 1: 'kent', 3:'parker', 5:'wayne' } > > # The thing I couldn't figure out is, after I insert a > # surname the rest of the indices are not valid. > # That is, the following won't work: > for i, x in surnames.iteritems(): > names.insert(i,surnames[i]) > ### In my previous post I've misunderstood the problem. Here is a valid solution: keys = surnames.keys() keys.sort() count = 0 for i in keys : names.insert(i + count, surnames[i]) count = count + 1 HTH From nomail at nixmail.com Sun Jun 11 03:03:28 2006 From: nomail at nixmail.com (DarkBlue) Date: Sun, 11 Jun 2006 15:03:28 +0800 Subject: Import elfclass32 issue Message-ID: <448bc040@127.0.0.1> Hello Suse10.1 64 new install if I try to import anything into python2.4.2 like : python - c "import kinterbasdb" I get this : wrong ELF class: ELFCLASS32 Before doing anything wrong , what would be the right thing to do to get rid of this error ? Thanks. From maric at aristote.info Mon Jun 12 06:37:02 2006 From: maric at aristote.info (Maric Michaud) Date: Mon, 12 Jun 2006 12:37:02 +0200 Subject: Function to remove elements from a list not working (corrected) In-Reply-To: <36394.10.209.4.1.1150103178.squirrel@10.105.1.3> References: <49543.10.209.4.1.1150100717.squirrel@10.105.1.3> <200606121041.01792.maric@aristote.info> <36394.10.209.4.1.1150103178.squirrel@10.105.1.3> Message-ID: <200606121237.04032.maric@aristote.info> Le Lundi 12 Juin 2006 11:06, Girish Sahani a ?crit?: > Thanks!It worked....i wasted a lot of time trying to find a bug in my > code...what is wrong in iterating over a list and modifying it? > Doesnt python take the modified list every time the loop starts? Python iterates over an iterator, that means calling it.next() method at each step. Is the iteration is consistent or not when you modify your iterable depends on the implementation of the iterator, but in general case it's a bad idea, and absolutely error prone. > Also in this case, i want to add a condition that if none of the pairs are > in pairList, element = []. How can i do that? element ? I guess it's already the case with lst = [ e for e in lst if e in pairs ] In [1]: lst = (1,2,3,4) In [2]: pairs=(5,) In [3]: lst=[e for e in lst if e in pairs] In [4]: lst Out[4]: [] -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From ptmcg at austin.rr._bogus_.com Tue Jun 6 14:48:26 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Tue, 06 Jun 2006 18:48:26 GMT Subject: Newbie: returning dynamicly built lists (using win32com) References: <1149613586.862299.125070@u72g2000cwu.googlegroups.com> Message-ID: <_5khg.18219$0v4.12301@tornado.texas.rr.com> "Ransom" wrote in message news:1149613586.862299.125070 at u72g2000cwu.googlegroups.com... > Very newb here, but my question will hopefully be obvious to someone. > But when I try and put the output from the spreadsheet into > a dynamic list after the TODO section thusly: > > outputlist = [] > outputlist.extend(excel.ActiveSheet.Cells(32,6) > return outputlist > > I get an error like: > [ 0x15450880>] > 1. First of all, this is not the code you are running. I know this because the unbalanced parens wont even compile. It really doesn't help when you ask for help, but post the wrong code. 2. What you are getting is NOT an error. Read it very carefully. What you have added to outputlist is a Range object. Look into the Excel COM documentation (you can open up VB from Excel by pressing Alt-F11, then open the Object Browser to see the object API) for how to access the methods and properties of an Excel Range. I'm guessing one of the properties Value, Value2, Text, or Formula will give you what you want. 3. The reason your print statement appears to work is because print implicitly applies the str method to objects, while applying the repr method to contents of a list. So "print excel.ActiveSheet.Cells(32,6)" will output "42" or whatever - for grins, try "print type(excel.ActiveSheet.Cells(32,6))" (taking care to insert enough parens :) ) All that is gold does not glitter, not all who wander are lost, don't judge a book by its cover, or a variable by its output, etc... -- Paul From orome.the.valar at gmail.com Thu Jun 15 02:58:48 2006 From: orome.the.valar at gmail.com (Sinan Nalkaya) Date: Thu, 15 Jun 2006 09:58:48 +0300 Subject: popen and password entry In-Reply-To: <200604141852.59515.erchamion.beren@gmail.com> References: <200604141852.59515.erchamion.beren@gmail.com> Message-ID: <8c05f79c0606142358n5fbafc3xd859a63909f11e90@mail.gmail.com> hi, i have found expect method for this purpose. i`m trying to use pexpect but following code gives me an something strange as a result. # The CODE import pexpect cmd = '/usr/bin/rsync config root at 10.1.1.2:/tmp/.' #cmd = 'ssh root at 10.1.1.2' child = pexpect.spawn(cmd) passwd = 'qwe123' try: i = child.expect(['Password:','Password: ',pexpect.EOF, pexpect.TIMEOUT]) if i == 0: child.sendline(passwd) elif i == 1: print 1 elif i == 2: print 2 elif i == 3: print 3 except EOF: print 'EOF' except TIMEOUT: print 'TIMEOUT' print 'finished' # The result finished Exception pexpect.ExceptionPexpect: in > ignored -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Mon Jun 19 11:44:19 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 19 Jun 2006 17:44:19 +0200 Subject: [OT] code is data In-Reply-To: References: <44965f53$0$12743$636a55ce@news.free.fr> <4496b29f$0$27412$626a54ce@news.free.fr> Message-ID: Laurent Pointal wrote: >>> The idea is to have a way to transform a Python (.py) module into XML >>> and then do source code manipulations in XML-space using ElementTree. >> >> My my my... I'm not against the idea of dynamic source code >> transformation, but for heaven's sake, *why* would one put XML in the >> mix ??????? because lots of people know how to describe XML transformations, and there are plenty of tools that implement such transformations efficiently ? > Because its "? la mode", and is better for a commercial point of view, > even if inefficient for this problem. why would XML be inefficient ? From cdsmith at twu.net Mon Jun 19 12:31:55 2006 From: cdsmith at twu.net (Chris Smith) Date: Mon, 19 Jun 2006 10:31:55 -0600 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> Message-ID: Rob Thorpe wrote: > A language is latently typed if a value has a property - called it's > type - attached to it, and given it's type it can only represent values > defined by a certain class. I'm assuming you mean "class" in the general sense, rather than in the sense of a specific construct of some subset of OO programming languages. Now I define a class of values called "correct" values. I define these to be those values for which my program will produce acceptable results. Clearly there is a defined class of such values: (1) they are immediately defined by the program's specification for those lines of code that produce output; (2) if they are defined for the values that result from any expression, then they are defined for the values that are used by that expression; and (3) for any value for which correctness is not defined by (1) or (2), we may define its "correct" values as the class of all possible values. Now, by your definition, any language which provides checking of that property of correctness for values is latently typed. Of course, there are no languages that assign this specific class of values; but ANY kind of correctness checking on values that a language does (if it's useful at all) is a subset of the perfect correctness checking system above. Apparently, we should call all such systems "latent type systems". Can you point out a language that is not latently typed? I'm not trying to poke holes in your definition for fun. I am proposing that there is no fundamental distinction between the kinds of problems that are "type problems" and those that are not. Types are not a class of problems; they are a class of solutions. Languages that solve problems in ways that don't assign types to variables are not typed languages, even if those same problems may have been originally solved by type systems. > Untyped and type-free mean something else: they mean no type checking > is done. Hence, they don't exist, and the definitions being used here are rather pointless. -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation From gneuner2/ at comcast.net Mon Jun 26 14:22:40 2006 From: gneuner2/ at comcast.net (George Neuner) Date: Mon, 26 Jun 2006 14:22:40 -0400 Subject: What is Expressiveness in a Computer Language References: <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <34aj92h0g7tqi9amhh7k3ieq5n568t0e6f@4ax.com> Message-ID: On Sun, 25 Jun 2006 14:28:22 -0600, Chris Smith wrote: >George Neuner wrote: >> >Undecidability can always be avoided by adding annotations, but of >> >course that would be gross overkill in the case of index type widening. >> >> Just what sort of type annotation will convince a compiler that a >> narrowing conversion which could produce an illegal value will, in >> fact, never produce an illegal value? > >The annotation doesn't make the narrowing conversion safe; it prevents >the narrowing conversion from happening. That was my point ... you get a program that won't compile. >If, for example, I need to >subtract two numbers and all I know is that they are both between 2 and >40, then I only know that the result is between -38 and 38, which may >contain invalid array indices. However, if the numbers were part of a >pair, and I knew that the type of the pair was through 40, where the first number is greater than the second>, then I >would know that the difference is between 0 and 38, and that may be a >valid index. > >Of course, the restrictions on code that would allow me to retain >knowledge of the form [pair of numbers, 2 through 40, a > b] may be >prohibitive. That is an open question in type theory, as a matter of >fact; whether types of this level of power may be inferred by any >tractable procedure so that safe code like this may be written without >making giving the development process undue difficulty by requiring ten >times as much type annotations as actual code. There are attempts that >have been made, and they don't look too awfully bad. I worked in signal and image processing for many years and those are places where narrowing conversions are used all the time - in the form of floating point calculations reduced to integer to value samples or pixels, or to value or index lookup tables. Often the same calculation needs to be done for several different purposes. I can know that my conversion of floating point to integer is going to produce a value within a certain range ... but, in general, the compiler can't determine what that range will be. All it knows is that a floating point value is being truncated and the stupid programmer wants to stick the result into some type too narrow to represent the range of possible values. Like I said to Ben, I haven't seen any _practical_ static type system that can deal with things like this. Writing a generic function is impossible under the circumstances, and writing a separate function for each narrow type is ridiculous and a maintenance nightmare even if they can share the bulk of the code. George -- for email reply remove "/" from address From python-url at phaseit.net Tue Jun 20 10:22:47 2006 From: python-url at phaseit.net (Cameron Laird) Date: Tue, 20 Jun 2006 14:22:47 +0000 (UTC) Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jun 20) Message-ID: ANNOUNCEMENT: we had an incident with backups of the "Python-URL!" mailing list. It's possible we lost one or two transactions from the last week. If you aren't receiving an e-mailed copy of this weekly news digest that you should, or are receiving one when you shouldn't, please alert me through an e-mail reply. QOTW: "[L]exical closures bind to names, default arguments bind to values." - Fredrik Lundh http://groups.google.com/group/comp.lang.python/msg/8916574e3c60750d has commentary "Programming is not just creating strings of instructions for a computer to execute. It's also 'literary' in that you are trying to communicate a program structure to other humans reading the code." - Paul Rubin Ravi Teja posts a native win32 Yes-No dialogue in two lines: http://groups.google.com/group/comp.lang.python/msg/d2603fd699857fcf ... makes a case that there might be a place in the world for Scala: http://groups.google.com/group/comp.lang.python/msg/0cccf81bf834b103 ... and cleverly enlists decorators to argue in favor of macros on the premise that "[r]epresentational minimalism" is no vice in a DSL (which is, of course, S to its D): http://groups.google.com/group/comp.lang.python/msg/54425e8137612ae4 Spirited rejoinders follow the latter. Alex and Bruno remark on the languages Google uses, among which Python remains of course prominent: http://groups.google.com/group/comp.lang.python/browse_thread/thread/d7ed5b2061c5cc0d/ Roger Upole can capture a Win32 window to a .bmp image: http://groups.google.com/group/comp.lang.python/msg/2619bc119298041a Rather than speculate about semantics or performance, Python makes it easy enough to measure and validate through the byte-code level: http://groups.google.com/group/comp.lang.python/browse_thread/thread/5cacc718af68fe97/ ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. For far, FAR more Python reading than any one mind should absorb, much of it quite interesting, several pages index much of the universe of Pybloggers. http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog http://www.planetpython.org/ http://mechanicalcat.net/pyblagg.html comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html Steve Bethard, Tim Lesher, and Tony Meyer continue the marvelous tradition early borne by Andrew Kuchling, Michael Hudson and Brett Cannon 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/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 http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topic/python/ (requires subscription) http://groups-beta.google.com/groups?q=python-url+group:comp.lang.python*&start=0&scoring=d& http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From gdr at integrable-solutions.net Sun Jun 25 18:32:01 2006 From: gdr at integrable-solutions.net (Gabriel Dos Reis) Date: 26 Jun 2006 00:32:01 +0200 Subject: What is Expressiveness in a Computer Language References: <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150908952.804184.218990@r2g2000cwb.googlegroups.com> <1150991074.705803.211570@m73g2000cwd.googlegroups.com> <1151244628.566060.40500@p79g2000cwp.googlegroups.com> <1151252226.104247.62960@b68g2000cwa.googlegroups.com> <1151257480.183097.165640@b68g2000cwa.googlegroups.com> Message-ID: rossberg at ps.uni-sb.de writes: | think that it is too relevant for the discussion at hand. Moreover, | Harper talks about a relative concept of "C-safety". Then, I believe you missed the entire point. First point: "safety" is a *per-language* property. Each language comes with its own notion of safety. ML is ML-safe; C is C-safe; etc. I'm not being facetious; I think this is the core of the confusion. Safety is an internal consistency check on the formal definition of a language. In a sense it is not interesting that a language is safe, precisely because if it weren't, we'd change the language to make sure it is! I regard safety as a tool for the language designer, rather than a criterion with which we can compare languages. [...] | Or are you trying to suggest that we should indeed consider C safe for | the purpose of this discussion? I'm essentially suggesting "silly arguments" (as noted by someone in another message) be left out for the sake of productive conversation. Apparently, I did not communicate that point well enough. -- Gaby From bdesth.quelquechose at free.quelquepart.fr Sun Jun 4 22:52:51 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 05 Jun 2006 04:52:51 +0200 Subject: Using print instead of file.write(str) In-Reply-To: <44824B01.3040806@lexicon.net> References: <2Iq*Jzbir@news.chiark.greenend.org.uk> <44809e93$0$13657$636a55ce@news.free.fr> <44824B01.3040806@lexicon.net> Message-ID: <44836ce6$0$13039$626a54ce@news.free.fr> John Machin a ?crit : (snip) > ... or was that a rhetorical question? It was. From bucodi at yahoo.fr.invalid Thu Jun 1 06:19:30 2006 From: bucodi at yahoo.fr.invalid (Rony Steelandt) Date: Thu, 01 Jun 2006 12:19:30 +0200 Subject: Best Python Editor References: Message-ID: I have to admit that I'm testing eclipse with pydev at the moment, and it looks realy good Rony > Hi, > > Can anyone tell me a good python editor/IDE? > It would be great if you can provide the download link also. > > Thank You, > -Manoj- > > > "SASKEN RATED Among THE Top 3 BEST COMPANIES TO WORK FOR IN INDIA - SURVEY > 2005 conducted by the BUSINESS TODAY - Mercer - TNS India" > > SASKEN BUSINESS DISCLAIMER > This message may contain confidential, proprietary or legally Privileged > information. In case you are not the original intended Recipient of the > message, you must not, directly or indirectly, use, Disclose, distribute, > print, or copy any part of this message and you are requested to delete it > and inform the sender. Any views expressed in this message are those of the > individual sender unless otherwise stated. Nothing contained in this message > shall be construed as an offer or acceptance of any offer by Sasken > Communication Technologies Limited ("Sasken") unless sent with that express > intent and with due authority of Sasken. Sasken has taken enough precautions > to prevent the spread of viruses. However the company accepts no liability > for any damage caused by any virus transmitted by this email -- --- Rony Steelandt BuCodi rony dot steelandt (at) bucodi dot com Visit the python blog at http://360.yahoo.com/bucodi From cbaoqiu at yahoo.com Sun Jun 4 12:51:03 2006 From: cbaoqiu at yahoo.com (Baoqiu Cui) Date: Sun, 04 Jun 2006 16:51:03 GMT Subject: deleting texts between patterns References: <1147420279.664699.181200@i40g2000cwc.googlegroups.com> <1147421468.912908.271280@i39g2000cwa.googlegroups.com> <44645C03.3070500@lexicon.net> Message-ID: John Machin writes: > Uh-oh. > > Try this: > >>>> pat = re.compile('(?<=abc\n).*?(?=xyz\n)', re.DOTALL) >>>> re.sub(pat, '', linestr) > 'blahfubarabc\nxyz\nxyzzy' This regexp still has a problem. It may remove the lines between two lines like 'aaabc' and 'xxxyz' (and also removes the first two 'x's in 'xxxyz'). The following regexp works better: pattern = re.compile('(?<=^abc\n).*?(?=^xyz\n)', re.DOTALL | re.MULTILINE) >>> lines = '''line1 ... abc ... line2 ... xyz ... line3 ... aaabc ... line4 ... xxxyz ... line5''' >>> pattern = re.compile('(?<=^abc\n).*?(?=^xyz\n)', re.DOTALL | re.MULTILINE) >>> print pattern.sub('', lines) line1 abc xyz line3 aaabc line4 xxxyz line5 >>> - Baoqiu -- Baoqiu Cui From onurb at xiludom.gro Mon Jun 19 12:59:48 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Mon, 19 Jun 2006 18:59:48 +0200 Subject: Formatted string to object In-Reply-To: <1150731552.799052.47320@r2g2000cwb.googlegroups.com> References: <1150731552.799052.47320@r2g2000cwb.googlegroups.com> Message-ID: <4496d806$0$9017$626a54ce@news.free.fr> janama wrote: > Hi, > > can such a thing be done somehow? > > > aaa = self.aaa > bbb = %s.%s % ('parent', 'bbb') Given the first line, I assume this is inside a method body, and parent is a local var. Then the answer is: bbb = getattr(locals()['parent'], 'bbb') read the doc for these two functions to get more infos. > Can you use strings or %s strings like in the above or > > aaa = 'string' > aaa.%s() % 'upper' > > Somehow? Not directly - but here again, getattr() is your friend. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From onurb at xiludom.gro Mon Jun 26 08:50:41 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Mon, 26 Jun 2006 14:50:41 +0200 Subject: About python 2.5 and its try statement. In-Reply-To: <1151325349.040404.77730@i40g2000cwc.googlegroups.com> References: <1151325349.040404.77730@i40g2000cwc.googlegroups.com> Message-ID: <449fd821$0$10282$636a55ce@news.free.fr> defcon8 wrote: > I can't remember the proposal number, http://docs.python.org/dev/whatsnew/pep-341.html but many of you reading will have > probably read the features that will be added to python 2.5. The actual > part I wanted to talk about was the finally part of try. It has been here from the start (well, IIRC, it's since at least 1.5.2) - the only limitation was that you couldn't use both 'except' and 'finally' in the same statement, so you had to wrap'em when needed. > Isn't it > totally defeating a compiler's job by executing the finally part even > if there is an error in the previous statements? I don't see how this relates to the compiler. But anyway, the whole point of the 'finally' clause is (and has ever been) to *ensure* this block gets executed *whatever* happened. FWIW, the canonical use case is resource aquisition/release. > Or have I understood > something wrong? Seems so - unless it's me misunderstading your question. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From rxrx at yamama.com Sun Jun 11 21:53:47 2006 From: rxrx at yamama.com (Butternut Squash) Date: Mon, 12 Jun 2006 01:53:47 GMT Subject: ANN: PyQt v4.0 Released - Python Bindings for Qt v4 References: Message-ID: Phil Thompson wrote: > Riverbank Computing is pleased to announce the release of PyQt v4.0 > available from http://www.riverbankcomputing.co.uk/pyqt/. > > The main change from v4.0beta1 is the inclusion of comprehensive HTML > documentation based on the Qt documentation. > > PyQt is a comprehensive set of Qt bindings for the Python programming > language > and supports the same platforms as Qt (Windows, Linux and MacOS/X). Like > Qt, PyQt is available under the GPL and a commercial license. > > PyQt v4 supports Qt v4 (http://www.trolltech.com/products/qt/index.html). > PyQt v3 is still available to support earlier versions of Qt. > > PyQt v4 is implemented as a set of 8 extension modules containing > approximately 400 classes and 6,000 functions and methods. > > QtCore > The non-GUI infrastructure including event loops, threads, i18n, > Unicode, signals and slots, user and application settings. > > QtGui > A rich collection of GUI widgets. > > QtNetwork > A set of classes to support TCP and UDP socket programming and higher > level protocols (eg. HTTP). > > QtOpenGL > A set of classes that allows PyOpenGL to render onto Qt widgets. > > QtSql > A set of classes that implement SQL data models and interfaces to > industry > standard databases. Includes an implementation of SQLite. > > QtSvg > A set of classes to render SVG files onto Qt widgets. > > QtXML > A set of classes that implement DOM and SAX parsers. > > QtAssistant > A set of classes that enables the Qt Assistant online help browser to > be integrated with an application. > > A Windows installer is provided for the GPL version of PyQt to be used > with the GPL version of Qt v4 > (http://www.trolltech.com/download/qt/windows.html). It enabes a complete > PyQt environment to be installed on Windows without the need for a C++ > compiler. > > PyQt includes the pyuic utility which generates Python code to implement > user interfaces created with Qt Designer in the same way that the uic > utility > generates C++ code. It is also able to load Designer XML files > dynamically. Where is the best place to learn how to use this library??? From greg at cosc.canterbury.ac.nz Sat Jun 10 19:28:45 2006 From: greg at cosc.canterbury.ac.nz (greg) Date: Sun, 11 Jun 2006 11:28:45 +1200 Subject: ANN: PyGUI 1.7.2-1 Message-ID: I have uploaded a new PyGUI 1.7.2 package to correct a couple of errors in the setup.py file. http://www.cosc.canterbury.ac.nz/~greg/python_gui/ ----------------------------------------------------- What is PyGUI? -------------- PyGUI is an experimental highly-Pythonic cross-platform GUI API. Implementations are currently available for MacOSX and Gtk. For a full description of the project goals, see the PyGUI web page at the above address. -- Greg From martin at v.loewis.de Thu Jun 29 16:26:08 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 29 Jun 2006 22:26:08 +0200 Subject: Interprocess communication on multi-user machine In-Reply-To: <44a41cae$0$29145$9b4e6d93@newsread4.arcor-online.net> References: <44a41cae$0$29145$9b4e6d93@newsread4.arcor-online.net> Message-ID: <44A43760.6090304@v.loewis.de> Michael Butscher wrote: > I'm wanting a method for interprocess communication which is OS- > independent (sockets would be the normal way to go), but which works if > multiple users use the machine at the same time so that one user has no > access to the communication of programs of another user. > > Any hints? The conventional solution is to use environment variables or well-known temporary files for that. For example, the file could look like this port=45413 cookie=9f563aeb2e5639cf574 Put the file into a per-user location, and hope that this "good enough" to separate users. If access control is a must, you need platform-specific code to deny read access to the file to anybody but the user. Alternatively, put the port number and the cookie into an environment variable, e.g. FOO_PORT=45413:9f563aeb2e5639cf574 This is technically better protected (practically, environment variables might easier leak, e.g. when somebody types "env"). However, this works well only if you manage to set this up for the entire user session, else you have to ask the user to manually duplicate the environment variable in all shells he cares about. In case this isn't clear yet: the cookie should then be used for authentication. Only trusted clients would know the right cookie. Regards, Martin From robert.kern at gmail.com Thu Jun 22 14:34:50 2006 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 22 Jun 2006 13:34:50 -0500 Subject: Numeric N-dimensional array initialization In-Reply-To: <1151000155.059823.256350@b68g2000cwa.googlegroups.com> References: <1150999204.839644.179940@g10g2000cwb.googlegroups.com> <1151000155.059823.256350@b68g2000cwa.googlegroups.com> Message-ID: TG wrote: > I tried to use Numeric.fromfunction, but there seems to be a problem : > > the function called must have the right number of args (hint : the > number of dimensions, which I don't know). So i tried to use a function > like : > > def myfunc(*args, **kw): > return 0 > > and then i get : > >>> Numeric.fromfunction(myfunc,(5,5)) > 0 > > I'm a bit puzzled here In [24]: def myfunc(*args): ....: print args ....: ....: In [26]: fromfunction(myfunc, (2, 2)) (array([[0, 0], [1, 1]]), array([[0, 1], [0, 1]])) fromfunction() does not iterate over the possible indices and call the function with scalar arguments to get a scalar return value. It generates N arrays with index values in them and calls the function once with those arrays. The return value should be another array. If you actually just want 0s: In [27]: zeros((5, 5)) Out[27]: array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]) If you want 1s: In [28]: ones((5, 5)) Out[28]: array([[1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]]) If you just want an array as fast as possible because you are going to fill in values later: In [29]: empty((5, 5)) Out[29]: array([[ 13691, 0, 0, 2883587, 3], [ 3, 0, 828189706, 6, 0], [ 0, 9, 10, 828202281, 0], [ 7, 0, 0, 0, 0], [ 0, 0, 0, 0, 0]]) If you have more complicated needs, we can talk about them on numpy-discussion. -- 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 From kuwanger at gmail.com Fri Jun 16 02:20:19 2006 From: kuwanger at gmail.com (kuwanger at gmail.com) Date: 15 Jun 2006 23:20:19 -0700 Subject: Need help with apack compression code Message-ID: <1150438819.310815.231620@f6g2000cwb.googlegroups.com> I've been working on some python code to have an open source apack compression (http://www.ibsensoftware.com/products_aPACK.html is a link to the original proprietary version). Just to clarify the legality of all of this, from decompressor source written by Dwedit in arm/thumb assembly I ended up writing unapack.c and then unapack.py (http://kuwanger.malfunct.net/unapack.py). The compressor is based on studying the C/Python versions I wrote. So, I've got a working compressor (one in C and one in Python). But, my Python version is incredibly slow. And my attempts to have better compression in my C version has produced an incredibly messy/slow code, which is why I'd rather focus on making my current Python version faster. So, here is what I have so far, "http://kuwanger.malfunct.net/apack.hash.py". Currently it's setup under profiling and does a lot of printing out. But even without that, the search part of the algorithm is incredibly slow (~60s to compress 80K on my 1.6GHz Athlon) while adding on attempts to optimize the compress slows it down further (~90s to compress 80K on my 1.6GHz Athlon). So, I'd be curious if others could look at the source and perhaps make some suggestions, such as if I'm just going about it horribly wrong. I'd also greatly welcome someone else joining me on this project, as my efforts to optimize haven't produced results nearly as good as the official compressor. Comments are greatly welcome. Kuwanger From diffuser78 at gmail.com Thu Jun 22 15:23:33 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 22 Jun 2006 12:23:33 -0700 Subject: Network Programming in Python In-Reply-To: References: <1151002934.586359.174540@m73g2000cwd.googlegroups.com> Message-ID: <1151004213.415841.296450@u72g2000cwu.googlegroups.com> Thanks...I will read that up...could you give me some more headstart or if you any sample code which I can study. Thanks for your help, every help is appreciated Fredrik Lundh wrote: > diffuser78 at gmail.com wrote: > > > I am a newbie in python. I want to learn and implement a small > > networking concept. Please help me. Every help is appreciated. > > > > I have one Linux Box and one Windows PC. I want to have a daemon > > running on Windows PC which listens on some specicif port number. I > > want to send a TCP/IP or UDP/IP packet from Linux box to Windows PC to > > start some application. As Windows PC recieves such a packet from Linux > > Box it executes a certain .exe file. I want to implement this concept. > > > > In short I want to remotely send command from Linux to Windows PC to > > start a particular application. > > server: > > http://docs.python.org/lib/module-SimpleXMLRPCServer.html > > client: > > http://docs.python.org/lib/module-xmlrpclib.html > > From luismgz at gmail.com Wed Jun 28 13:32:59 2006 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 28 Jun 2006 10:32:59 -0700 Subject: web Develop question In-Reply-To: <1151514841.490454.284770@i40g2000cwc.googlegroups.com> References: <1151514841.490454.284770@i40g2000cwc.googlegroups.com> Message-ID: <1151515979.877494.316720@m73g2000cwd.googlegroups.com> gerkarcher at gmail.com wrote: > hi guys , > > I' m new to python ...and I would like to ask you , wich is the best > template for developing dinamic generated pages using python ? > > I would like to use something easy to install and develop like php ? > tags and with a lots of features . > > thanks in advance and sorry for this silly question . > > regards, > > richard I suppose you're asking about frameworks. There are many to choose from. There are two that are getting a lot of attention lately: Django and Turbogears, but it seems there are as many options as developers out there... If you're running your own server, you can choose anyone. The real problem is finding a shared hosting service with the option of your choice (at an affordable price). I am very comfortable with bare-bones mod_python. Mod_python is a module that embeds the python interpreter into Apache (a la php). It is not a framework (what's more, many frameworks rely on mod_python), but it gives you many facilities for web development. I find specially handy its publisher handle, which lets you match urls to pages. It can be complemented with a template system, like Cheetah (very good) or its own PSP (python server pages implementation) as a template system. It also gives you the best performance (as far as I know, please correct me if I'm wrong). Luis From davidh at ilm.com Tue Jun 20 13:35:41 2006 From: davidh at ilm.com (David Hirschfield) Date: Tue, 20 Jun 2006 10:35:41 -0700 Subject: TEST IGNORE Message-ID: <449831ED.2070600@ilm.com> Having email trouble... -- Presenting: mediocre nebula. From alexreinhart at satx.rr.com Mon Jun 12 22:38:25 2006 From: alexreinhart at satx.rr.com (Alex Reinhart) Date: Tue, 13 Jun 2006 02:38:25 GMT Subject: Python open proxy honeypot Message-ID: Being deluged by spam like nearly all of us (though fortunately I have a very good spam filter), I also hate spam as much as almost everybody. I know basic Python (enough to make a simple IRC bot) and I figured a good project to help learn Python would be to make a simple "proxypot." I've done some research and found one already existing, written in Perl (http://www.proxypot.org/). However, I prefer the syntax and ease of Python (and Proxypot is no longer maintained, as far as I can see), so I decided to write my own. I have just one question: Is running Python's built-in smtpd, pretending to accept and forward all messages, enough to get me noticed by a spammer, or do I have to do something else to "advertise" my script as an open proxy? I'm hoping to make this proxy script "distributed", in that several honeypots are run on different servers, and the results are then collected on a central server that provides statistics and a listing of all spammers caught. So, just out of curiosity, I'd like to know how many people would actually be willing to run a honeypot on their server, and how many are opposed to the idea (just so I know if the concept is even valid). Thanks! From claird at lairds.us Sun Jun 18 11:46:20 2006 From: claird at lairds.us (Cameron Laird) Date: Sun, 18 Jun 2006 15:46:20 +0000 Subject: Date Subtraction References: Message-ID: In article , Marc 'BlackJack' Rintsch wrote: >In , >rsutradhar_python wrote: > >> How to subtract date which is stored in string variable? >> >> Example: >> >> date1="2006-01-10" >> date2="2005-12-15" >> date = date1 - date2 >> should give me 25 but problem is that date1 and date2 datatype is >> string which need to be conerted into date fromat which i am not able >> to do so please help me. > >from datetime import date > >date_str_1 = '2006-01-10' >date_str_2 = '2005-12-15' >date_1 = date(*map(int, date_str_1.split('-'))) >date_2 = date(*map(int, date_str_2.split('-'))) >print (date_1 - date_2).days - 1 . . . Apparently you understand the original poster better than I. What's with the "- 1"? If I read you correctly, you'd calculate that there are zero days between, for example, 2006-01-13 and 2006-01-12 Do I have that right? From sjmachin at lexicon.net Fri Jun 23 22:36:51 2006 From: sjmachin at lexicon.net (John Machin) Date: Sat, 24 Jun 2006 12:36:51 +1000 Subject: Trouble including Python.h In-Reply-To: <449c9ff6$1@news.eftel.com> References: <1151099498.381282.64590@b68g2000cwa.googlegroups.com> <449c9ff6$1@news.eftel.com> Message-ID: <449ca541$1@news.eftel.com> On 24/06/2006 12:14 PM, John Machin wrote: > On 24/06/2006 7:51 AM, Marcelo Gosling wrote: >> I'm having trouble including Python.h in a C file. The following C >> code: >> In file included from ../../Python2.4/include/Python.h:74, >> from example_wrap.c:112: > > 1. You allegedly have a 6-line test program. What is this example_wrap.c > that has 112 lines (or more) in it? If you're trying to use SWIG (which could quite plausibly have created an example_wrap.c from an example.c), wouldn't you be better off with MinGW?????? I suggest you back away from your 1000-error-message train smash and try telling us what you are trying to accomplish and a little bit more of the history of how you got on this path. Cheers, John From m.yanowitz at kearfott.com Tue Jun 27 17:26:14 2006 From: m.yanowitz at kearfott.com (Michael Yanowitz) Date: Tue, 27 Jun 2006 17:26:14 -0400 Subject: SWIG problems with gcc and Cygwin? In-Reply-To: Message-ID: Thanks. It now works for me in Cygwin. I would never have guessed to write it as a dll. Michael Yanowitz -----Original Message----- From: python-list-bounces+m.yanowitz=kearfott.com at python.org [mailto:python-list-bounces+m.yanowitz=kearfott.com at python.org]On Behalf Of Norman Vine Sent: Tuesday, June 27, 2006 4:21 PM To: python-list at python.org Subject: Re: SWIG problems with gcc and Cygwin? "Michael Yanowitz"wrote > > > I am just trying out SWIG, but quickly ran into problems. > Using Cygwin gcc, I tried the following: > > 3)ran in cygwin: swig -i python example.i try 'swig -python example.i' > 4)Attempted to run on cygwin: ld -shared example.o example_wrap.o -o > _example.so try $ gcc -I/usr/include/python2.4 -L/lib/python2.4/config --shared example.c example_wrap.c -lpython2.4 -o _example.dll $ python Python 2.4.1 (#1, May 27 2005, 18:02:40) [GCC 3.3.3 (cygwin special)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> from example import * >>> get_time() 'Tue Jun 27 16:17:41 2006\n' HTH Norman -- http://mail.python.org/mailman/listinfo/python-list From rogue_pedro at yahoo.com Mon Jun 26 15:32:45 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 26 Jun 2006 12:32:45 -0700 Subject: TypeError: Cannot create a consistent method resolution order (MRO) for bases object In-Reply-To: <1151345197.691600.200060@y41g2000cwy.googlegroups.com> References: <1151345197.691600.200060@y41g2000cwy.googlegroups.com> Message-ID: <1151350365.357634.221780@u72g2000cwu.googlegroups.com> digitalorganics at gmail.com wrote: > What are the reason one would get this error: TypeError: Cannot create > a consistent method resolution order (MRO) for bases object ?? > > I can provide the code if needed.... Yes, do that. That's an amazing error. ~Simon From sreeram at tachyontech.net Sat Jun 3 08:35:14 2006 From: sreeram at tachyontech.net (K.S.Sreeram) Date: Sat, 03 Jun 2006 18:05:14 +0530 Subject: image lib & Qt4 In-Reply-To: References: <1149173540.470829.34940@c74g2000cwc.googlegroups.com> <4e8haiF1dp2heU1@uni-berlin.de> <1149180814.585713.209640@i39g2000cwa.googlegroups.com> Message-ID: <44818202.8060607@tachyontech.net> Fredrik Lundh wrote: > Fredrik Lundh wrote: > > I've posted a simple ImageQt interface module for PIL and PyQt4 here: > > http://svn.effbot.python-hosting.com/stuff/sandbox/pil/ImageQt.py > I'm getting an 'unknown raw mode' error on ImageQt.py:59: data = im.tostring( "raw", "BGRX" ) Does this only work with PIL 1.1.6 snapshots? I currently have PIL 1.1.5. Regards Sreeram -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 260 bytes Desc: OpenPGP digital signature URL: From fredrik at pythonware.com Wed Jun 21 08:01:34 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 21 Jun 2006 14:01:34 +0200 Subject: Search substring in a string and get index of all occurances References: <4499034A.9040306@gmail.com> <200606211345.52243.maric@aristote.info> Message-ID: Maric Michaud wrote: > Another variant, I feel this one more natural as it doesn't contain a > C-looking infinite loop doing things in a convoluted way because you think that non-infinite while- loops are not natural? you can get help for that, you know ;-) > Actually it's even more efficient than Lundh's one for smaller strings (less > than 1000 characters on my box) and slow down as strings go wider (slowly, > seems to be a logarithmic progression) due to the split call resulting in > creation of a new list. and a potentially large number of new strings. there's a lot of string copying going on in there... From theaney at gmail.com Thu Jun 22 22:23:39 2006 From: theaney at gmail.com (Tim Heaney) Date: Thu, 22 Jun 2006 22:23:39 -0400 Subject: Using SQLite3 with python 2.5 beta References: Message-ID: Harold Shore writes: > From the release notes I read that > > "If you're compiling the Python source yourself, note that > the source tree doesn't include the SQLite code, only the > wrapper module. You'll need to have the SQLite libraries > and headers installed before compiling Python, and the build > process will compile the module when the necessary headers > are available." > > I do have SQLite3 installed on my system, but after doing a > plain vanilla compilation of the the 2.5 beta and trying > the SQLite code given in the release notes I get the message > "NameError: name 'sqlite3' is not defined". > > I wonder what the requirement means that "when the necessary > headers are available"? How would they need to be made > available? > > Does anyone have any success with this? It seems to work okay for me. $ python2.5 Python 2.5b1 (r25b1:47027, Jun 21 2006, 19:41:51) [GCC 4.0.2 20051125 (Red Hat 4.0.2-8)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sqlite3 >>> sqlite3.sqlite_version '3.1.2' On my system, the header file is /usr/include/sqlite3.h and the library file is /usr/lib64/libsqlite3.so Those are both standard locations, so configure found them on its own. If they are someplace unusual, you'll have to tell configure where they are. It's possible you have SQLite3 installed, but you lack the header. My system uses RPM, so I had to install both sqlite and sqlite-devel before building Python. The sqlite-devel package contains the header. I hope this helps, Tim From mensanator at aol.com Sat Jun 17 12:35:10 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 17 Jun 2006 09:35:10 -0700 Subject: any subway experiences In-Reply-To: <1150533811.911621.112430@y41g2000cwy.googlegroups.com> References: <1150533811.911621.112430@y41g2000cwy.googlegroups.com> Message-ID: <1150562110.126305.21830@h76g2000cwa.googlegroups.com> a wrote: > thanks for reading Their bread is awful. From steven.klass at gmail.com Wed Jun 21 18:54:56 2006 From: steven.klass at gmail.com (rh0dium) Date: 21 Jun 2006 15:54:56 -0700 Subject: Python at compile - possible to add to PYTHONPATH Message-ID: <1150930496.559207.73320@m73g2000cwd.googlegroups.com> Hi all, Can anyone help me out. I would like to have python automatically look in a path for modules similar to editing the PYTHONPATH but do it at compile time so every user doesn't have to do this.. Soo... I want to add /foo/bar to the PYTHONPATH build so I don't have to add it later on. Is there a way to do this? ./configure ?? ./configure --help doesn't help.. Thanks From laurent.pointal at limsi.fr Mon Jun 19 11:12:14 2006 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Mon, 19 Jun 2006 17:12:14 +0200 Subject: [OT] code is data In-Reply-To: <4496b29f$0$27412$626a54ce@news.free.fr> References: <44965f53$0$12743$636a55ce@news.free.fr> <4496b29f$0$27412$626a54ce@news.free.fr> Message-ID: bruno at modulix a ?crit : > Anton Vredegoor wrote: >> bruno at modulix wrote: >> >>> I still don't get the point. >> >> Well, I've got to be careful here, lest I'd be associated with the >> terr.., eh, the childp..., eh the macro-enablers. >> >> The idea is to have a way to transform a Python (.py) module into XML >> and then do source code manipulations in XML-space using ElementTree. > > My my my... I'm not against the idea of dynamic source code > transformation, but for heaven's sake, *why* would one put XML in the > mix ??????? Because its "? la mode", and is better for a commercial point of view, even if inefficient for this problem. From bussieremaillist at gmail.com Wed Jun 21 09:04:00 2006 From: bussieremaillist at gmail.com (bussiere maillist) Date: Wed, 21 Jun 2006 15:04:00 +0200 Subject: very strange bug coercing to Unicode: need string or buffer, int found Message-ID: <8a8f62c80606210604r7746f64dkf82fb97d347e02e0@mail.gmail.com> i truly didn't understand this error : Traceback (most recent call last): File "D:\Programmation\FrancePaquet\FrancePaquet.py", line 77, in ? cabtri = "zz" + chiffrescabtri + clefc TypeError: coercing to Unicode: need string or buffer, int found >>> if someone could help me i will be glad, this program worked yesterday. Regards Bussiere here is my program : import fileinput,string def calculclef(nombre): nombre2 = int(nombre)*10 nombre = str(nombre2) taille = len(nombre) compteur = 0 nombrepair = 0 nombreimpair = 0 compteur = taille - 2 while compteur != -1: print 'nombre :' print nombre[compteur] + '\n' if compteur%2 : nombrepair = nombrepair + int(nombre[compteur]) print 'suite pair %d' % nombrepair else: nombreimpair = nombreimpair + int(nombre[compteur]) print 'suite impair %d' % nombreimpair print compteur = compteur - 1 print nombreimpair print nombrepair clef = nombrepair*3+nombreimpair clef = 10-(clef%10) if clef == 10: clef = 0 return clef compteclient = "8150" souscompteclient = "03" codeaffranc = "080" partielibre = "142391" print("LES CODES POSTAUX DOIVENT ETRE A LA FIN DU FICHIER CSV ! \n") fichA=raw_input("Entrez le nom du fichier d'entree : ") print ("\n") fichC=raw_input("Entrez le nom du fichier de sortie : ") print ("\n") debutplage = raw_input("Entrez le numero du debut de plage : ") print ("\n") finplage = raw_input("Entrez le numero de fin de plage : ") print ("\n") nbredeplage = int(debutplage) - int(finplage) fiA=open(fichA,"r") fiC=open(fichC,"w") print calculclef(debutplage) compteur = 0 debutplage while 1: fileencoding = "latin1" ligneA=fiA.readline() ligneA = ligneA.decode(fileencoding) if ligneA == "": break if ligneA != "": stramettre = ligneA if compteur != 0: taille = len(ligneA) codepostal = ligneA[taille-5] + ligneA[taille-4] + ligneA[taille-3] + ligneA[taille-2]+ ligneA[taille-1] print codepostal clefb = calculclef(debutplage) clefb = str(clefb) print clefb num = str(debutplage) cabsuivis = "8w"+ num + clefb stramettre = stramettre + ";*" + cabsuivis + "*" chiffrescabtri = clefb + codepostal + compteclient + souscompteclient + codeaffranc + partielibre clefc = calculclef(chiffrescabtri) cabtri = "zz" + chiffrescabtri + clefc stramettre = stramettre + ";*" + cabtri + "*" fiC.write(stramettre) compteur += 1 print compteur, "\n" print "FINIT" fiA.close() fiC.close() -------------- next part -------------- An HTML attachment was scrubbed... URL: From per9000 at gmail.com Wed Jun 28 09:29:58 2006 From: per9000 at gmail.com (per9000) Date: 28 Jun 2006 06:29:58 -0700 Subject: compiling python (or ironpython) to .exe or .dll for or not for .NET Message-ID: <1151501398.664329.142920@d56g2000cwd.googlegroups.com> Hi python people, I am working with .NET (in C++/CLI and C#) but since I really love python I'd like to do things for .NET (or whatever) from python. Has anyone tried it? What (costless) compilers are good? Are there any (costless) editors like MS Visual Express you have tried? Is the newest Ironpython really as old as from 2004 July 28 (as stated on http://www.ironpython.com/)? Thanks. /Per Erik Strandberg yet another Fibonaccilover From bbands at gmail.com Wed Jun 28 19:28:54 2006 From: bbands at gmail.com (BBands) Date: 28 Jun 2006 16:28:54 -0700 Subject: locating strings approximately Message-ID: <1151537334.900487.322980@75g2000cwc.googlegroups.com> I'd like to see if a string exists, even approximately, in another. For example if "black" exists in "blakbird" or if "beatles" exists in "beatlemania". The application is to look though a long list of songs and return any approximate matches along with a confidence factor. I have looked at edit distance, but that isn't a good choice for finding a short string in a longer one. I have also explored difflib.SequenceMatcher and .get_close_matches, but what I'd really like is something like: a = FindApprox("beatles", "beatlemania") print a 0.857 Any ideas? jab From jussij at zeusedit.com Thu Jun 29 01:52:53 2006 From: jussij at zeusedit.com (jussij at zeusedit.com) Date: 28 Jun 2006 22:52:53 -0700 Subject: compiling python (or ironpython) to .exe or .dll for or not for .NET References: <1151501398.664329.142920@d56g2000cwd.googlegroups.com> Message-ID: <1151560373.743835.204870@j72g2000cwa.googlegroups.com> per9000 wrote: > Is the newest Ironpython really as old as from 2004 July 28 (as > stated on http://www.ironpython.com/)? I think the site is dead but IronPython is far from dead. In fact the IronPython 1.0 beta has just been release. For more details go to this link: http://www.gotdotnet.com/ and search for: ironpython > Are there any (costless) editors like MS Visual Express > you have tried? Zeus for Windows has support for Python/IronPython: http://www.zeusedit.com It does syntax highlighting, smart indenting, code folding, class browsing etc. Jussi Jumppanen Author: Zeus For Windows From ptmcg at austin.rr._bogus_.com Fri Jun 30 14:59:14 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 30 Jun 2006 18:59:14 GMT Subject: Regular Expression - old regex module vs. re module References: <1151607229.548737.145800@d56g2000cwd.googlegroups.com> <12aaigaohtou291@corp.supernews.com> Message-ID: <6wepg.6349$Bh.1247@tornado.texas.rr.com> "Jim Segrave" wrote in message news:12aaigaohtou291 at corp.supernews.com... > If fails for floats specified as ###. or .###, it outputs an integer > format and the decimal point separately. It also ignores \# which > should prevent the '#' from being included in a format. > Here's a little more study on this (all tests are using Python 2.4.1): If floats are specified as "###.", should we generate "%4.0f" as the result? In fact, to get 3 leading places and a trailing decimal point, when 0 decimal places are desired, should be formatted with "%3.0f." - we have to explicitly put in the trailing '.' character. >>> print ">%1.0f<" % 10.00001 >10< >>> print ">%2.0f<" % 10.00001 >10< >>> print ">%3.0f<" % 10.00001 > 10< >>> print ">%3.0f.<" % 10.00001 > 10.< But as we see below, if the precision field is not zero, the initial width consumes one character for the decimal point. If the precision field *is* zero, then the entire width is used for the integer part of the value, with no trailing decimal point. ".###" almost makes no sense. There is no floating point format that suppresses the leading '0' before the decimal point. >>> print ">%1.2f<" % 0.00001 >0.00< >>> print ">%2.2f<" % 0.00001 >0.00< >>> print ">%3.2f<" % 0.00001 >0.00< >>> print ">%4.2f<" % 0.00001 >0.00< >>> print ">%5.2f<" % 0.00001 > 0.00< Using the %f with a nonzero precision field, will always output at least the number of decimal places, plus the decimal point and leading '0' if number is less than 1. This whole discussion so far has also ignore negative values, again, we should really look more into the spec for this formatting scheme, rather than try to read the OP's mind. -- Paul From robert.kern at gmail.com Tue Jun 13 18:38:22 2006 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 13 Jun 2006 17:38:22 -0500 Subject: "groupby" is brilliant! In-Reply-To: <448F36D3.1070003@islandtraining.com> References: <1150180151.643245.148210@y43g2000cwc.googlegroups.com> <448F351A.7000201@lexicon.net> <448F36D3.1070003@islandtraining.com> Message-ID: Gary Herron wrote: > John Machin wrote: > >>On 13/06/2006 6:28 PM, Paul McGuire wrote: >> >>>(Oh, and I like groupby too! Combine it with sort to quickly create >>>histograms.) >>> >>># tally a histogram of a list of values from 1-10 >>>dataValueRange = range(1,11) >>>data = [random.choice(dataValueRange) for i in xrange(10000)] >>> >>>hist = [ (k,len(list(g))) for k,g in itertools.groupby(sorted(data)) ] >> >>That len(list(g)) looks like it uses O(N) memory just to find out what N >>is :-( > > Not at all! A python list *knows* its length at all times. len() is a > constant time lookup of an internal attribute. The point is that you had to create the list in the first place. g is an iterator. -- 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 From larry.bates at websafe.com Thu Jun 8 11:13:05 2006 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 08 Jun 2006 10:13:05 -0500 Subject: cos: "Integer Required"?!?!?!? In-Reply-To: <1149777499.262577.318070@u72g2000cwu.googlegroups.com> References: <1149777499.262577.318070@u72g2000cwu.googlegroups.com> Message-ID: <2aqdnQ8uYZLpoxXZnZ2dnUVZ_qadnZ2d@comcast.com> First: Always post cut-paste tracebacks so we can see actual error message. Second: print out self.ACphi, XPLMGetDataf(self.ACphi) and math.radians(XPLMGetDataf(self.ACphi)) before this statement and you will find the problem. -Larry Bates moonman wrote: > Hello all, > > I've just jumped into Python trying to develop X-Plane plugins. > > All was chugging along well until I tried to use math.cos() > > snippet: > > import math > > .... > > cos_phi = math.cos(math.radians(XPLMGetDataf(self.ACphi))) # Error > occurs here > > > > Now XPLMGetDataf should be returning float. > > Is there something that I'm completely missing about how Python does > tyonig or something? > > Thanks in advance, > > Moonman > From Marcin.Ciura at NOSPAM.poczta.onet.pl Fri Jun 9 08:10:00 2006 From: Marcin.Ciura at NOSPAM.poczta.onet.pl (Marcin Ciura) Date: Fri, 09 Jun 2006 14:10:00 +0200 Subject: Large Dictionaries In-Reply-To: References: <1147699064.107490@teuthos> Message-ID: Duncan Booth wrote: > Marcin Ciura wrote: >>See Figure 8 in >>http://sun.iinf.polsl.gliwice.pl/~mciura/shellsort.pdf > That isn't what the reference says. It only covers N up to a few thousand. > Practical values of N need to at least go up into the millions. Please look at the performance graph of Tokuda's increment sequence. You can see that it scales pretty well at least up to 100 million. Marcin From johnjsal at NOSPAMgmail.com Tue Jun 6 15:42:18 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 06 Jun 2006 19:42:18 GMT Subject: tkinter: making widgets instance or not? In-Reply-To: References: Message-ID: Fredrik Lundh wrote: > however, if you need to access a widget later on, it might be a good > idea to save a reference to it somewhere... To follow up on that point, I have the following code now. I have two questions about it: 1. Can I somehow make the passing of 'master' to the draw_entry method automatic, so I don't have to type it each time I call the function? 2. Related to your comment, the obvious problem here is that it doesn't save references to the text box names, so I can't access them later. Is there still a way to automate the process like I've done, but have each entry field have a separate name? Thanks. --------------- import Tkinter as tk class App: def __init__(self, master): self.draw_entry(master, 'First Name:') self.draw_entry(master, 'Last Name:') def draw_entry(self, master, label_text): frame = tk.Frame(master, bd=4) frame.pack() self.label = tk.Label(frame, text=label_text, width=10) self.label.pack(side=tk.LEFT) self.entry = tk.Entry(frame) self.entry.pack(side=tk.LEFT) root = tk.Tk() app = App(root) root.resizable(width=False, height=False) root.mainloop() From fredrik at pythonware.com Wed Jun 21 09:47:19 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 21 Jun 2006 15:47:19 +0200 Subject: very strange bug coercing to Unicode: need string or buffer, int found References: <8a8f62c80606210604r7746f64dkf82fb97d347e02e0@mail.gmail.com> Message-ID: "bussiere maillist" wrote: >i truly didn't understand this error : > Traceback (most recent call last): > File "D:\Programmation\FrancePaquet\FrancePaquet.py", line 77, in ? > cabtri = "zz" + chiffrescabtri + clefc > TypeError: coercing to Unicode: need string or buffer, int found >>>> hint: >>> "one" + u"two" + 3 Traceback (most recent call last): File "", line 1, in ? TypeError: coercing to Unicode: need string or buffer, int found From rganesan at myrealbox.com Thu Jun 15 08:43:26 2006 From: rganesan at myrealbox.com (Ganesan Rajagopal) Date: Thu, 15 Jun 2006 18:13:26 +0530 Subject: popen and password entry References: <200604141852.59515.erchamion.beren@gmail.com> <200604151200.06995.erchamion.beren@gmail.com> <200604151515.03206.erchamion.beren@gmail.com> Message-ID: >>>>> sinan nalkaya writes: > child.expect(['Password:','Password: ',pexpect.EOF,pexpect.TIMEOUT]) > if i == 0: child.sendline(passwd) > elif i == 1: print 1 > elif i == 2: print 2 > elif i == 3: print 3 You don't need the second pattern, the first pattern will catch the second case also. You also need to break when i == 2 or i == 3. Ganesan -- Ganesan Rajagopal From Peter.Silva at ec.gc.ca Fri Jun 16 16:53:48 2006 From: Peter.Silva at ec.gc.ca (Peter Silva) Date: 16 Jun 2006 13:53:48 -0700 Subject: transfer rate limiting in socket.py Message-ID: <1150491228.229045.163110@h76g2000cwa.googlegroups.com> Hi folks, I have a need in a network data distribution application to send out data to folks who want it using the protocol of their choice. I?d like it to support a variety of protocols and I don?t want to implement any of them :-) http, ftp (via ftplib) , https (dunno how yet), ssl, ssh, sftp (via paramiko) The thing is... I want rate-limiting so that in the case of a failure of a single client I don?t penalize the other clients, or if my server (which is acting as a client pushing to remote servers.) goes down, it doesn?t saturate the link when it comes back. So I want to have all the protocols limit the number of bytes they send per second. It looks like the easiest way to do this is to dive into socket.py... and look! it says: # Wrapper module for _socket, providing some additional facilities # implemented in Python. note the ?additional facilities implemented in python? ... so we just add logic to: -- add a ?maxrate? argument to the constructor and/or an attribute to modify the setting... -- tally bytes, and time, and know when we are going ?too fast? -- when too fast.. in the ?flush? routine, in the synchronous case, sleep for the correct time to come back under budget. in the async, return without writing. -- do something similar for reading. Anybody think this would be fun? From yan at NsOeSiPnAeMr.com Thu Jun 1 19:32:45 2006 From: yan at NsOeSiPnAeMr.com (Captain Dondo) Date: Thu, 01 Jun 2006 16:32:45 -0700 Subject: Replace one element of a tuple (LONG) In-Reply-To: <1149204445.622897.26390@c74g2000cwc.googlegroups.com> References: <127ulhn6h7hvj22@corp.supernews.com> <1149198946.567904.260480@f6g2000cwb.googlegroups.com> <127upu8k63qnu10@corp.supernews.com> <1149202416.959127.71620@i39g2000cwa.googlegroups.com> <127usq9lrqavm3d@corp.supernews.com> <1149204445.622897.26390@c74g2000cwc.googlegroups.com> Message-ID: <127uu7c9c1s9n8e@corp.supernews.com> BartlebyScrivener wrote: >>>that one column is always the same, the name of the host that >>>the database resides on. > > > Then why are you pulling all of the other stuff out of the db? Why > don't you just > > UPDATE tablename > SET hostname(or colname) = 'localhost' > WHERE search condition = the rows you want to change > Well, there is an interactive dialog where the user picks which records s/he wants to put into the other database. So in the target database, that table may not even exist until the user selects which records go in there. But it does sound like I need to do some work on the database query.... :-) --Yan From usenet.rpdillon at xoxy.net Thu Jun 15 12:01:14 2006 From: usenet.rpdillon at xoxy.net (R. P. Dillon) Date: Thu, 15 Jun 2006 09:01:14 -0700 Subject: Tiddlywiki type project in Python? In-Reply-To: <1150386336_12135@sp6iad.superfeed.net> References: <1150289313.533749.52330@i40g2000cwc.googlegroups.com> <44900ae9$0$8386$626a54ce@news.free.fr> <1150291679.746132.114730@y43g2000cwc.googlegroups.com> <1150386336_12135@sp6iad.superfeed.net> Message-ID: <1150386830_12149@sp6iad.superfeed.net> That should have said "Since Python _isn't_ embedded in browsers"! Rick R. P. Dillon wrote: > I've been doing some work on a didiwiki-like program written in Python. > Since Python is embedded in browsers, the didwiki approach make sense: > write the server in your language of choice (didwiki uses C), and lay > the necessary (simple) wiki code on top of the server. Roll the entire > thing into a single executable, and you have a personal wiki. The catch > is that you must run the executable before you can access your wiki, but > it is a small price to pay IMHO. > > Anyway, I'll either GPL or public-domain my code when I'm finished with > it and I'll post it here. My hope is it will be as fast on a reasonably > modern computer as didiwiki is. > > Rick > > jkn wrote: >> Hi Bruno >> >> [...] >>>> I don't know Javascript (although it looks moderately simple from a >>>> brief peruse, >>> It's not as simple as it may seem at first look. There are some real >>> gotchas. But if you want a more pythonic javascript, you should have a >>> look at mochikit. >> >> OK, thanks for the pointer >> >> [...] >> >>>> and I know enough languages to know I'll be able to pick >>>> it up); however I do know and use Python, although not nuch in a >>>> web-oriented way. Since unlike JS, python is at least pre-compiled, I >>>> have hopes that this would make things quicker. I do appreciate that JS >>>> is built into the browser, which might make my Python approach slower. >>>> I'm not sure of the 'architectural' approach to this; any suggestions, >>>> and maybe pointers to previous work? >>> I don't really understand what you're after here, since TiddlyWikiLikes >>> can *not* work without javascript. >> >> Well, that may be an/the answer, since another form of my question >> would be 'how can I write a TiddlyWikiLike using Python instead of JS' >> ;-). I appreciate that it might involve, for instance, a local server. >> Does the idea of embedding python in a browser instead of Javascript >> make any sense at all? >> >>> Anyway, there's at least a Zope-based TiddlyWikiLike, so you may want to >>> have a look here: >>> http://ziddlywiki.org/ >>> >> >> Thanks again >> >> jon N >> > > ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet > News==---- > http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ > Newsgroups > ----= East and West-Coast Server Farms - Total Privacy via Encryption =---- ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups ----= East and West-Coast Server Farms - Total Privacy via Encryption =---- From rtw at freenet.co.uk Thu Jun 1 15:19:47 2006 From: rtw at freenet.co.uk (Rob Williscroft) Date: Thu, 01 Jun 2006 14:19:47 -0500 Subject: Tkinter: select multiple entries in Listbox widget? References: Message-ID: Bernard Lebel wrote in news:mailman.6413.1149178158.27775.python- list at python.org in comp.lang.python: > Hello, > > Is there an option or a way to allow the selection of multiple entries > in the Listbox widget? I could not find any, and would like to allow > the end user to select multiple entries. > > When configuring use: selectmode = "multiple" e.g.: import Tkinter as tk root = tk.Tk() a = tk.Listbox( root, selectmode = "multiple" ) for i in range(10): a.insert( i, str(i) + " item" ) a.pack() root.mainloop() I found the answer here: http://www.python.org/doc/life-preserver/ClassListbox.html Though I had to guess the `= "multiple"` part. Rob. -- http://www.victim-prime.dsl.pipex.com/ From michele.simionato at gmail.com Tue Jun 27 09:23:17 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 27 Jun 2006 06:23:17 -0700 Subject: How do you use this list ? In-Reply-To: References: Message-ID: <1151414597.932437.71320@u72g2000cwu.googlegroups.com> Bo Yang wrote: > Hi everyone , > I have join this list for about 4 months , and everyday I receive > hundreds of > mails . There is no means to read all of them , so I just read something > interesting > for me . But if so , there are too much mails pile up in my inbox , I > want to ask > how do you use this list , reading every mail come in or just read what > you think > interesting ? > > Thank you ! > > > Best Regard ! I use the newsgroup: http://groups.google.com/group/comp.lang.python Michele Simionato From fairwinds at eastlink.ca Sat Jun 3 08:46:44 2006 From: fairwinds at eastlink.ca (David Pratt) Date: Sat, 03 Jun 2006 09:46:44 -0300 Subject: Initializing an attribute that needs the object In-Reply-To: <4480CC87.8050006@lexicon.net> References: <4480be5b$0$27367$626a54ce@news.free.fr> <4480CC87.8050006@lexicon.net> Message-ID: <448184B4.7090107@eastlink.ca> Hi John. Thank you for the tips and the link. This is helpful. Many thanks. Regards David > A new-style class is one which inherits ultimately from the type that is > called "object". > > class NewStyleClass(object): > pass > > class OldStyleClass(): > pass > > Docs are a bit ummmm ... > See this: http://www.python.org/doc/newstyle/ > > HTH, > John > From kernel1983 at gmail.com Wed Jun 14 02:38:53 2006 From: kernel1983 at gmail.com (kernel1983) Date: 13 Jun 2006 23:38:53 -0700 Subject: curses module bug in windows python? Message-ID: <1150267132.986057.226690@i40g2000cwc.googlegroups.com> when I type command below in windows python: import curses it gives the error msg! It can't find _curses.pyd Is this a bug? From bignose+hates-spam at benfinney.id.au Fri Jun 16 07:29:25 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 16 Jun 2006 21:29:25 +1000 Subject: BeautifulSoup error References: <871wtpdbas.fsf@www.williamxu.com> <874pylllqn.fsf@benfinney.id.au> <20060616101031.CCD6.SLAWOMIR.NOWACZYK.847@student.lu.se> Message-ID: <87wtbhjq3u.fsf@benfinney.id.au> Slawomir Nowaczyk writes: > >>> soup.feed( unicode(port,"iso-8859-1") ) Sure, once you have the encoding name. Visit a different URL, you may get a different encoding which should be used. -- \ "I believe in making the world safe for our children, but not | `\ our children's children, because I don't think children should | _o__) be having sex." -- Jack Handey | Ben Finney From axwack at gmail.com Wed Jun 7 12:01:19 2006 From: axwack at gmail.com (axwack at gmail.com) Date: 7 Jun 2006 09:01:19 -0700 Subject: 10GB XML Blows out Memory, Suggestions? In-Reply-To: <1149694031.712812.304940@u72g2000cwu.googlegroups.com> References: <1149594519.098115.8980@u72g2000cwu.googlegroups.com> <4eleh3F1eguosU1@uni-berlin.de> <1149648187.891942.258300@i40g2000cwc.googlegroups.com> <1149694031.712812.304940@u72g2000cwu.googlegroups.com> Message-ID: <1149696078.984114.51880@h76g2000cwa.googlegroups.com> Thanks guys for all your posts... So I am a bit confused....Fuzzy, the code I saw looks like it decompresses as a stream (i.e. per byte). Is this the case or are you just compressing for file storage but the actual data set has to be exploded in memory? fuzzylollipop wrote: > Fredrik Lundh wrote: > > fuzzylollipop wrote: > > > > > you got no idea what you are talking about, anyone knows that something > > > like this is IO bound. > > > > which of course explains why some XML parsers for Python are a 100 times > > faster than other XML parsers for Python... > > > > dependes on the CODE and the SIZE of the file, in this case > > processing 10GB of file, unless that file is heavly encrypted or > compressed will, the process will be IO bound PERIOD! > > And in the case of XML unless the PARSER is extremely inefficient, and > I assume, that would be an edge case, the parser is NOT the bottle neck > in this case. > > The relativel performance of Python XML parsers is irrelvant in > relationship to this being an IO bound process, even the slowest parser > could only process the data as fast as it can be read off the disk. > > Anyone saying that using C instead of Python will be faster when 99% of > the time in this case is just waiting on the disk to feed a buffer, has > no idea what they are talking about. > > I work with TeraBytes of files, and all our Python code is just as fast > as equivelent C code for IO bound processes. From girish at cse.iitb.ac.in Fri Jun 9 04:51:22 2006 From: girish at cse.iitb.ac.in (Girish Sahani) Date: Fri, 9 Jun 2006 14:21:22 +0530 (IST) Subject: Error in Chain of Function calls (Code Attached) In-Reply-To: <448930f1$0$10302$636a55ce@news.free.fr> References: <448930f1$0$10302$636a55ce@news.free.fr> Message-ID: <38733.10.209.4.2.1149843082.squirrel@10.105.1.3> > Girish Sahani wrote: >> Hi, >> >> There is a code in my main function which is something like: >> >> while prunedFinal != []: >> prunedNew = genColocations(prunedK) *** >> tableInstancesNew = >> genTableInstances(prunedNew,tableInstancesK) >> tiCountDict = tiCount(tableInstancesNew) >> tiDict = findPI(tableInstancesNew) >> prunedFinal = pruneTI(tiDict,pi) >> rulesDict = genRules(prunedFinal) >> cpDict = findCP(rulesDict) >> prunedRulesList = pruneCP(cpDict,cp) >> prunedK = prunedFinal >> tableInstancesK = tableInstancesNew >> else: >> return prunedRulesList >> >> prunedK and tableInstancesK are defined in the main function. > > defined as what ? functions, strings, lists, classes, ... ? PrunedK is a list that contains 2 length strings and tableInstancesK is a dictionary,its keys are 2 length strings and values are lists of lists > >> Before the >> main function, i have defined the other functions such as >> genColocations,genTableInstances,etc. Output of genColocations is to be >> given to the next function genTableInstances,output of this function to >> tiCount and findPI, and so on. >> However i am getting an error at the line marked with ***. > > Which error ? How do you hope us to be of any help here if you don't *at > least* provide the full traceback ? FWIW, the canonical way to do things > is to: > - provide minimal *runnable* code exposing the problem > - explain what you hoped to get > - explain what you got instead (including full traceback) > > As a matter of fact, it's often the case that one solves the problem > when working on the first point !-) > > (snip) Ohh...I was thinking that posting the whole code would not be a good idea. The error i get above is: line 266, in colocationMiner prunedNew = genColocations(prunedK) Anyways, i've attached the file colocations.py. The expected output is a List of rules (prunedRulesList).These rules are themselves lists.e.g ['ab','c'] denotes the rule ab=>c. Please do have a look if you have time :). > > -- > bruno desthuilliers > python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for > p in 'onurb at xiludom.gro'.split('@')])" > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: colocation.py URL: From struggleyb at gmail.com Wed Jun 7 02:50:05 2006 From: struggleyb at gmail.com (struggleyb struggleyb) Date: Wed, 7 Jun 2006 02:50:05 -0400 Subject: Any good module for chart creation ? Message-ID: <4d75aaf70606062350p6c3d6abapeeb6c15deecf8526@mail.gmail.com> Hi , I am just doing a trivial job , which generate a bar chart from a collection of data , for example : I have a file like below , Tom:23 John:12 Marry:56 Jack:34 ... What I want to do is to read the data from the file and display it as a bar chart or some other chart and then put the chart in my web page ! I know it is something very easy but I got blocked in installing reportlab package . It failed to generate any picture and told that it can't find the 'Times-Roman' .pfd file . And the traceback is at below : Warn: Can't find .pfb for face 'Times-Roman' Traceback (most recent call last): File "./test1.py", line 21, in ? renderPM.draw(d,c,0,0,showBoundary=rl_config._unset_) File "/usr/lib/python2.4/site-packages/reportlab/graphics/renderPM.py", line 49, in draw R.draw(drawing, canvas, x, y, showBoundary=showBoundary) File "/usr/lib/python2.4/site-packages/reportlab/graphics/renderbase.py", line 188, in draw self.initState(x,y) File "/usr/lib/python2.4/site-packages/reportlab/graphics/renderPM.py", line 86, in initState self.applyState() File "/usr/lib/python2.4/site-packages/reportlab/graphics/renderPM.py", line 80, in applyState self._canvas.setFont(s['fontName'], s['fontSize']) File "/usr/lib/python2.4/site-packages/reportlab/graphics/renderPM.py", line 327, in setFont _setFont(self._gs,fontName,fontSize) File "/usr/lib/python2.4/site-packages/reportlab/graphics/renderPM.py", line 207, in _setFont raise RenderPMError, "Can't setFont(%s) missing the T1 files?\nOriginally %s: %s" % (fontName,s1,s2) reportlab.graphics.renderPM.RenderPMError: Can't setFont(Times-Roman) missing the T1 files? Originally exceptions.TypeError: makeT1Font() argument 2 must be string, not None I get bored to do that , can anyone give me some help or is there any other python package to accomplish the task more simply and fast ? Thanks in advance ! Best Regards ! -------------- next part -------------- An HTML attachment was scrubbed... URL: From bearophileHUGS at lycos.com Tue Jun 6 03:56:12 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 6 Jun 2006 00:56:12 -0700 Subject: How to add few pictures into one In-Reply-To: <1149573892.526072.6770@i39g2000cwa.googlegroups.com> References: <1149511692.796038.155930@c74g2000cwc.googlegroups.com> <1149517433.880564.128350@h76g2000cwa.googlegroups.com> <1149529269.228019.120480@u72g2000cwu.googlegroups.com> <1149573892.526072.6770@i39g2000cwa.googlegroups.com> Message-ID: <1149580572.739202.110940@y43g2000cwc.googlegroups.com> Lad wrote: > I want to to do that as easy as possible. But not even more easy. > I think the easest way could be add( append) an image to another > into an image file so that I can use an image browser and see all > pictures in one file. Is that possible? Well, you can do it with PIL, creating a very big white image and putting on it all the images, as tiles. But probably you want to do something different. Maybe you can use PyUNO to create a PowerPoint-like (Presentation) file with an image on each page. If you are on Win another easy way is to create an Html page that shows all the pics, open it with Explorer and save it as a single HMT file. Probably there are other solutions. Bye, bearophile From george.sakkis at gmail.com Sat Jun 10 19:53:07 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 10 Jun 2006 16:53:07 -0700 Subject: Allowing zero-dimensional subscripts References: <1149801040.936452.26270@i40g2000cwc.googlegroups.com> <1149908197.118535.199910@j55g2000cwa.googlegroups.com> <1149969605.765077.166740@y43g2000cwc.googlegroups.com> Message-ID: <1149983587.198721.46960@f6g2000cwb.googlegroups.com> spam.noam at gmail.com wrote: > George Sakkis wrote: > > spam.noam at gmail.com wrote: > > > > > However, I'm designing another library for > > > managing multi-dimensional arrays of data. Its purpose is similiar to > > > that of a spreadsheet - analyze data and preserve the relations between > > > a source of a calculation and its destination. > > > > Sounds interesting. Will it be related at all to OLAP or the > > Multi-Dimensional eXpressions language > > (http://msdn2.microsoft.com/en-us/library/ms145506.aspx) ? > > > Thanks for the reference! I didn't know about any of these. It will > probably be interesting to learn from them. From a brief look at OLAP > in wikipedia, it may have similarities to OLAP. I don't think it will > be related to Microsoft's language, because the language will simply by > Python, hopefully making it very easy to do whatever you like with the > data. Glad it helped, I thought you were already familiar withe these. As for MDX, I didn't mean you should use it instead of python or implement it at the syntax level, but whether you consider an API with similar concepts. Given your description below, I think you should by all means take a look at MDX focusing on the concepts (datacubes, dimensions, hierarchies, levels, measures, etc.) and the functions, not its syntax. Here's a decent manual I found online http://support.sas.com/documentation/onlinedoc/91pdf/sasdoc_91/olap_mdx_7002.pdf. Regards, George From frank at chagford.com Thu Jun 22 02:01:52 2006 From: frank at chagford.com (Frank Millman) Date: 21 Jun 2006 23:01:52 -0700 Subject: wx.Yield() during socket timeout In-Reply-To: <1150923629.735462.83370@b68g2000cwa.googlegroups.com> References: <1150923629.735462.83370@b68g2000cwa.googlegroups.com> Message-ID: <1150956111.953622.204030@b68g2000cwa.googlegroups.com> Kiran wrote: > Hello All, > I am creating a socket connection in order to read and write to a > location. My problem is,the gui becomes unresponsive if the socket > times out. > I know that a good solution is to have the socket read and write with > a thread. However, I have tried this and have a problem where ONLY on > linux does the program crash, it DOES NOT crash on windows xp. I have > been trying to figure out why for about a week and have just given up. You must have a bug in your threading code. I am doing something similar to what you describe, and it works perfectly, on Windows and on Linux. Threading *is* the correct approach for what you are attempting. Don't give up. Try to isolate where the crash happens, and post the relevant section of code here. If I can't spot the error, there is a good chance someone else will. Frank Millman From marc.t.davies at gmail.com Tue Jun 20 18:38:36 2006 From: marc.t.davies at gmail.com (MTD) Date: 20 Jun 2006 15:38:36 -0700 Subject: Iteration over recursion? In-Reply-To: References: <1150808045.539887.291180@i40g2000cwc.googlegroups.com> Message-ID: <1150843116.595587.46550@b68g2000cwa.googlegroups.com> Thanks a lot! More food for thought! From david.nospam.hopwood at blueyonder.co.uk Tue Jun 27 19:29:07 2006 From: david.nospam.hopwood at blueyonder.co.uk (David Hopwood) Date: Tue, 27 Jun 2006 23:29:07 GMT Subject: What is Expressiveness in a Computer Language [correction] In-Reply-To: References: <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <1151384511.223582.305760@m73g2000cwd.googlegroups.com> <1151425350.679754.278820@i40g2000cwc.googlegroups.com> Message-ID: <7bjog.229500$8W1.29971@fe1.news.blueyonder.co.uk> David Hopwood wrote: > Joe Marshall wrote: > >>(defun blackhole (argument) >> (declare (ignore argument)) >> #'blackhole) > > This is typeable in any system with universally quantified types (including > most practical systems with parametric polymorphism); it has type > "forall a . a -> #'blackhole". Ignore this answer; I misinterpreted the code. I believe this example requires recursive types. It can also be expressed in a gradual typing system, but possibly only using an unknown ('?') type. ISTR that O'Caml at one point (before version 1.06) supported general recursive types, although I don't know whether it would have supported this particular example. -- David Hopwood From dav.phillips at ntlworld.com Tue Jun 6 04:48:20 2006 From: dav.phillips at ntlworld.com (dav.phillips at ntlworld.com) Date: 6 Jun 2006 01:48:20 -0700 Subject: Checking var is a number? Message-ID: <1149583700.145737.170720@j55g2000cwa.googlegroups.com> Hi, I am very new to all this and need to know how to check a variable to see if it is a number or not. Also can anyone recommend a reference book apart from dive into python preferably a reference with good examples of how to impliment code. The project i have been given to work in is all CGI written in Python. Many Thanks David Phillips From reply.in.the.newsgroup at my.address.is.invalid Wed Jun 7 11:32:31 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Wed, 07 Jun 2006 17:32:31 +0200 Subject: CENSORSHIP - Django Project (Schema Evolution Support) References: <4486B9FB.9030804@lazaridis.com> <4ent10F1f9d3gU1@uni-berlin.de> Message-ID: <6asd825u537kpp2aurhaeo1i41f61akbd6@4ax.com> Ilias Lazaridis: >What is the credibility and value of the provided "wikipedia" entry? Wikipedia always tells the Absolute Truth, because if it doesn't, we can edit it and fix it right away. From meyer at mesw.de Mon Jun 19 11:54:32 2006 From: meyer at mesw.de (meyer at mesw.de) Date: 19 Jun 2006 08:54:32 -0700 Subject: Which compiler will Python 2.5 / Windows (Intel) be built with? In-Reply-To: References: <1150367139.495114.148550@g10g2000cwb.googlegroups.com> <44917535$1@nntp0.pdx.net> <1150391891.130185.4640@f6g2000cwb.googlegroups.com> <4492414C.10505@v.loewis.de> <1150444191.618761.22810@c74g2000cwc.googlegroups.com> Message-ID: <1150732472.933138.81170@y41g2000cwy.googlegroups.com> Roel Schroeven wrote: > meyer at mesw.de schreef: > > * The code created by the Windows GCC is not as good as the one created > > by the Microsoft compiler > > Isn't Python for other platforms built with GCC? Seems to me that if it > GCC is good enough for other platforms, it's good enough for Windows. Actually, GCC on Linux does provide worse machine code than say, the Intel compiler for Linux. This is not a "bug" of GCC, but a feature, because GCC was created for maximum portability and flexibility, not for maximum performance on one single platform like the Intel compiler. But GCC is truly free and can be distributed easily (because it's GPL), so it is the default compiler for most (if not all) distros at the moment. Also, there are many free software programs that use special features of GCC and cannot be compiled using another compiler. Of course I do acknowledge that often in the real world the IO forms the bottleneck of a system and the efficiency of the machine code is somewhat neglegible (other posters pointed that out already). Markus From steve at REMOVETHIScyber.com.au Sat Jun 24 21:10:08 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 25 Jun 2006 11:10:08 +1000 Subject: String negative indices? References: <1151054259.765401.252230@b68g2000cwa.googlegroups.com> <1151152577.661130.5690@g10g2000cwb.googlegroups.com> Message-ID: On Sat, 24 Jun 2006 05:36:17 -0700, Filip Wasilewski wrote: > Steven D'Aprano wrote: >> On Fri, 23 Jun 2006 02:17:39 -0700, Filip Wasilewski wrote: >> >> > drtimhill at comcast.net wrote: >> > >> >> Logically, I should be able to enter x[-2:-0] to get the last and next to last characters. However, since Python doesn't distinguish between positive and negative zero, this doesn't work. Instead, I have to enter x[-2:]. >> > >> > Hooray! Logically there is no such thing as positive or negative zero, >> > or did I miss something in the primary? >> >> No, not in the primary, or even in the secondary, but possibly in the >> tertiary. >> >> For many purposes, it doesn't make sense to distinguish +0 from -0. But >> for other purposes, it does. > > I believe you will agree that this is mostly a matter of notation of > some fact rather than really trying to sign zero. No. In floating point, +0 *really is* different from -0 -- the two floats have different bit patterns. Floating point libraries must be specifically programmed to ignore that difference, making zero treated differently than other floats. That's -- usually -- a good thing. In mathematics, well, maybe... certainly in the Real number system, there is no difference, and +0 and -0 are just two ways of writing the same thing. In the hyperreals, +0 and -0 are the same, but there are infinitesimals which are different, and signed. I don't know enough about the surreals to comment. In matrix maths, there are an infinite number of different matrices where all the elements are zero -- they are all distinct, different, zeroes. And in "the real world", all numbers are an abstraction anyway, so I'm not too worried about correspondence to reality. If mathematicians find a use for distinguishing +0 from -0 (as the statistical physicists have done) they will treat them as "really" different. If they don't, they won't. -- Steven. From a at tempinbox.com Wed Jun 28 23:58:05 2006 From: a at tempinbox.com (a) Date: 28 Jun 2006 20:58:05 -0700 Subject: how do i make an array global In-Reply-To: References: <1151472238.400461.42350@p79g2000cwp.googlegroups.com> Message-ID: <1151553485.378000.203760@p79g2000cwp.googlegroups.com> hi bruno georg and erik you are right i m a newbie, i just want to do some stuff read out some stuff from a feed and display it in a page, so my py code, builds this list and when it goes to cheetah it gives me an error and hence i posted global has fixed the error but i keep getting this again and again and i dont know why? but if i refresh the page error goes away and the correct content comes up please help me out Traceback (most recent call last): File "C:\Python24\lib\site-packages\web.py", line 2054, in run_wsgi_app result = self.server.app(env, self.wsgi_start_response) File "C:\Python24\lib\site-packages\web.py", line 1894, in wsgifunc result = func() File "C:\Python24\lib\site-packages\web.py", line 1872, in func = lambda: handle(getattr(mod, name), mod) File "C:\Python24\lib\site-packages\web.py", line 1051, in handle return tocall(*([urllib.unquote(x) for x in args] + fna)) File "c:\mark\web1\code.py", line 64, in GET l_code.append( len(d_list_code[i]['entries']) ) IndexError: list index out of range it goes off when page is refreshed I m getting the following error, infrequently and if I refresh the page, it just displays the page properly I am unable to find the problem. How is this out of range and what does the error message mean? Solution: Remove all .pyc files from you Zope tree and try again: find -name "*.pyc" | xargs rm How can we do this when code is running? ---------------------------------------------------------------- Traceback (most recent call last): File "C:\Python24\lib\site-packages\web.py", line 2054, in run_wsgi_app result = self.server.app(env, self.wsgi_start_response) File "C:\Python24\lib\site-packages\web.py", line 1894, in wsgifunc result = func() File "C:\Python24\lib\site-packages\web.py", line 1872, in func = lambda: handle(getattr(mod, name), mod) File "C:\Python24\lib\site-packages\web.py", line 1051, in handle return tocall(*([urllib.unquote(x) for x in args] + fna)) File "c:\usr\code.py", line 64, in GET l_code.append( len(d_list_code[i]['entries']) ) IndexError: list index out of range Erik Max Francis wrote: > Georg Brandl wrote: > > > No need for "global" here. > > Yes, that's true. I was just following the original poster's lead, but > I tend to use a `global` statement whenever I'm mutating a global in a > local block. That works as self-documentation and means you don't have > to be concerned about the precise case in which it's required, reducing > bugs when you change a block so that it would have been required if you > hadn't included it. > > -- > Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ > San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis > Seriousness is the only refuge of the shallow. > -- Oscar Wilde From miki.tebeka at gmail.com Mon Jun 19 06:30:52 2006 From: miki.tebeka at gmail.com (Miki) Date: 19 Jun 2006 03:30:52 -0700 Subject: Yet Another Python Blog Message-ID: <1150713052.423005.123820@h76g2000cwa.googlegroups.com> Hello All, Decided that there are not enough blogs out there so http://pythonwise.blogspot.com/ is up :) This blog will feature a weekly (or about) Python code examples. I'll be glad to hear your comments. Miki, http://pythonwise.blogspot.com/ From sreeram at tachyontech.net Mon Jun 12 23:39:26 2006 From: sreeram at tachyontech.net (K.S.Sreeram) Date: Tue, 13 Jun 2006 09:09:26 +0530 Subject: ANN: PyQt v4.0 Released - Python Bindings for Qt v4 In-Reply-To: References: Message-ID: <448E336E.3060106@tachyontech.net> Butternut Squash wrote: > Where is the best place to learn how to use this library??? There dont seem to any tutorials on the web for PyQt4 yet. So you'll have to make do with reading pyqt3 tutorials, and reading the bundled example code. If you are comfortable with C++, then check out the Qt tutorial that comes with the trolltech distribution. PyQt4 has python versions of most samples provided with Qt. Regards Sreeram -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 260 bytes Desc: OpenPGP digital signature URL: From anton at appsolutions.com Sat Jun 24 12:54:36 2006 From: anton at appsolutions.com (Anton van Straaten) Date: Sat, 24 Jun 2006 16:54:36 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> Message-ID: Chris Smith wrote: > Dr.Ruud wrote: ... >>The 'dynamic type' is just another type. > > > That's essentially equivalent to giving up. I doubt many people would > be happy with the conclusion that dynamically typed languages are typed, > but have only one type which is appropriate for all possible operations. I'm not sure if this is what you're getting at, but what you've written is precisely the position that type theorists take. Having "only one type which is appropriate for all possible operations" is exactly what the term "untyped" implies. > That type system would not be implemented, since it's trivial and > behaves identically to the lack of a type system, and then we're back > where we started. This is why I've suggested that "untyped" can be a misleading term, when applied to dynamically-typed languages. Anton From fredrik at pythonware.com Mon Jun 12 12:05:19 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 12 Jun 2006 18:05:19 +0200 Subject: Function to remove elements from a list not working (corrected) In-Reply-To: <36394.10.209.4.1.1150103178.squirrel@10.105.1.3> References: <49543.10.209.4.1.1150100717.squirrel@10.105.1.3> <200606121041.01792.maric@aristote.info> <36394.10.209.4.1.1150103178.squirrel@10.105.1.3> Message-ID: Girish Sahani wrote: > Thanks!It worked....i wasted a lot of time trying to find a bug in my > code...what is wrong in iterating over a list and modifying it? > Doesnt python take the modified list every time the loop starts? this is explained in the tutorial, under "the for statement": The for loop maintains an internal loop variable, and you may get unexpected results if you try to modify the sequence being iterated over in the loop (this can only happen for mutable sequence types, such as lists). To safely modify the list you are iterating over (for example, to duplicate selected items), you must iterate over a copy. The slice notation makes this particularly convenient: >>> for x in a[:]: # make a slice copy of the entire list ... if len(x) > 6: a.insert(0, x) ... >>> a ['defenestrate', 'cat', 'window', 'defenestrate'] (see http://pytut.infogami.com/node6.html ) From grflanagan at yahoo.co.uk Wed Jun 28 07:24:52 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 28 Jun 2006 04:24:52 -0700 Subject: Immutability In-Reply-To: References: Message-ID: <1151493892.192120.113760@p79g2000cwp.googlegroups.com> Nick Maclaren wrote: > In article , > Georg Brandl writes: > |> > > |> > Thanks very much. And, what's more, I have even found its documentation! > |> > Whatsnew2.2. The 2.4.2 reference is, er, unhelpful. > |> > |> Is it? > |> > |> http://docs.python.org/lib/built-in-funcs.html > |> > |> documents "property" quite well. > > Sigh. No. It's terrible. What it documents is the use of the property > FUNCTION. It does not document what properties ARE, and how they interact > with the rest of the language. Until you know that, it is so ambiguous > as to be almost totally useless - and it is THAT information that needs to > be in the reference manual, but is only in whatsnew2.2. > > There are (unofficial) documentation wikis here: pytut.infogami.com pyref.infogami.com pyfaq.infogami.com You might like to consider adding the information you perceive to be lacking. All the best. Gerard From scott.daniels at acm.org Sat Jun 17 20:11:07 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Sat, 17 Jun 2006 17:11:07 -0700 Subject: Which compiler will Python 2.5 / Windows (Intel) be built with? In-Reply-To: References: <1150367139.495114.148550@g10g2000cwb.googlegroups.com> <44917535$1@nntp0.pdx.net> <1150391891.130185.4640@f6g2000cwb.googlegroups.com> <4492414C.10505@v.loewis.de> <1150444191.618761.22810@c74g2000cwc.googlegroups.com> <4494424f$1@nntp0.pdx.net> Message-ID: <4494953f$1@nntp0.pdx.net> Roel Schroeven wrote: > ... But what I meant was not related to interface compatibilities, but to > the performance of the generated code: many people say that the code > generated by gcc is not as well optimized as code generated by > Microsoft's compilers. Yet I never hear complaints about that from > people who use Python on e.g. Linux, where Python is compiled with gcc. > So, while there might be valid reasons not to use mingw, as far as I can > see the optimization capabilities of the compiler are not a compelling > reason. I musunderstood you. I thought you were advocating that Python itself be built on gcc, obviating many compiler access issues. That wouldn't work because gcc cannot, by itself (as I understand it) get to all the nooks and crannies a windows developer may need to traverse. I know I just repeated my argument here against a strawman, but that was really for other readers, not for you. --Scott David Daniels scott.daniels at acm.org From grflanagan at yahoo.co.uk Fri Jun 23 16:28:25 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 23 Jun 2006 13:28:25 -0700 Subject: hard to explain for a french ;-) In-Reply-To: References: <007b01c696c9$dc8c1a40$33067a37@d11610100.cpamalencon.cnamts.fr> Message-ID: <1151094505.233523.287830@i40g2000cwc.googlegroups.com> Daniel Nogradi wrote: > > hi everybody, > > > > i have a problem with a script. > > after a research with my directory, i want to do a popup of a person's > > photo but i don't know the syntax (i'm a newbie) : > > > > > src="user.gif"> it's good but, it's open the photo in a large > > window, not in a popup. > > what happens if you put the target into the tal:attributes? ie. Gerard (after googling for 'tal:attributes') ps. http://groups.google.com/group/fr.comp.lang.python is a French-speaking newsgroup From martin at v.loewis.de Mon Jun 5 04:29:37 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 05 Jun 2006 10:29:37 +0200 Subject: Where is the ucs-32 codec? In-Reply-To: <1149459785.331497.203920@c74g2000cwc.googlegroups.com> References: <1149459785.331497.203920@c74g2000cwc.googlegroups.com> Message-ID: <4483EB71.9090509@v.loewis.de> beni.cherniavsky at gmail.com wrote: > Python seems to be missing a UCS-32 codec, even in wide builds (not > that it the build should matter). > Is there some deep reason or should I just contribute a patch? The only reason is that nobody has needed one so far, and because it is quite some work to do if done correctly. Why do you need it? > There should be '-le' and '-be' variats, I suppose. Should there be a > variant without explicit endianity, using a BOM to decide (like > 'utf-16')? Right. > And it should combine surrogates into valid characters (on all builds), > like the 'utf-8' codec does, right? Right. Also, it should support the incremental interface (as any multi-byte codec should). If you want it complete, it should also support line-oriented input. Notice that .readline/.readlines is particularly difficult to implement, as you can't rely on the underlying stream's .readline implementation to provide meaningful results. While we are discussing problems: there also is the issue whether .readline/.readlines should take the additional Unicode linebreak characters into account (e.g. U+2028, U+2029), and if so, whether that should be restricted to "universal newlines" mode. Regards, Martin From rogue_pedro at yahoo.com Fri Jun 23 12:05:54 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 23 Jun 2006 09:05:54 -0700 Subject: Help req: Problems with MySQLdb References: <1150968147.565850.156870@u72g2000cwu.googlegroups.com> <1150969803.984843.111950@y41g2000cwy.googlegroups.com> <1150995682.162673.238130@u72g2000cwu.googlegroups.com> <449bb21e$0$11019$626a54ce@news.free.fr> Message-ID: <1151078754.679537.148270@m73g2000cwd.googlegroups.com> Bruno Desthuilliers wrote: > Simon Forman wrote: > > rodmc wrote: ... > > except: > > print "A database connection error has occurred" > > How can you assert it is a database connection error ? assert "database connection" in error (just kidding) I was really just leaving as much of the OP's code unchanged as seemed useful. Maybe they *want* to print that (possibly inaccurate) message and return False (from what appears to be module-level code at that!) FWIW, if I wanted the code to keep going but still report the exception I would use the logging module's exception() method. But that seemed a lot to explain. > > > traceback.print_exc() > > return False > > else: > > pass > > > > #The rest of the program > > You get the same result - with a more accurate error message - by not > handling the exception at all. > You'd get the same traceback printed out either way, but the generic except statement with the possibly inaccurate message does seem naive to me. However, it's entirely possible that the OP *would* like the code to keep running despite any exceptions while trying to connect to the db. In that case, using traceback (or logging) is (IMHO) a reasonable way to do that but still find out what went wrong. Ciao, ~Simon From nmm1 at cus.cam.ac.uk Wed Jun 28 13:54:55 2006 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 28 Jun 2006 17:54:55 GMT Subject: Immutability References: <4Qj*cEjkr@news.chiark.greenend.org.uk> Message-ID: In article , Fredrik Lundh writes: |> |> well, I completely fail to see how the following is compatible with the |> interpretation "attaches a non-default property, but doesn't do anything |> else": Because I was using a decorator and defining an attribute directly. But no matter - it is clear I had completely misunderstood the intent. Regards, Nick Maclaren. From diffuser78 at gmail.com Wed Jun 21 09:34:42 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 21 Jun 2006 06:34:42 -0700 Subject: OS specific command in Python In-Reply-To: <4498dcd5$0$25503$626a54ce@news.free.fr> References: <1150781429.090359.148560@c74g2000cwc.googlegroups.com> <1150783324.258644.65770@u72g2000cwu.googlegroups.com> <4498dcd5$0$25503$626a54ce@news.free.fr> Message-ID: <1150896882.746722.95200@u72g2000cwu.googlegroups.com> I have a question on getpass. Since I am a newbie you might find it a little dumb. By using the getpass, are u trying to retrieve the username and password of remote mahcine or local ? Avell Diroll wrote: > stephanearnold at yahoo.fr wrote: > > When you connect (via ssh or telnet) to a remote machine, you need to > > type (manually) > > your username and your password. Programming that is never easy. > > > > This is really eased by the module getpass (std library) : > > ### > > import getpass > > login = getpass.getuser() > password = getpass.getpass() > > ### > > If the username is different from your system login this can be changed to : > > ### > > import getpass > > login = raw_input('login: ') > password = getpass.getpass() > > ### > > > Python definitely comes with batteries included ! From sambo at void.com Mon Jun 12 04:03:46 2006 From: sambo at void.com (Sambo) Date: Mon, 12 Jun 2006 04:03:46 -0400 Subject: mutable member, bug or ... In-Reply-To: <4483641f$0$31935$626a54ce@news.free.fr> References: <4483641f$0$31935$626a54ce@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > Sambo a ?crit : > >> By accident I assigned int to a class member 'count' which was >> initialized to (empty) string and had no error till I tried to use it >> as string, obviously. Why was there no error on assignment( near the >> end ). > > > Python is dynamically typed - which means that it's not the name that > holds type info, but the object itself. names are just, well, names... > Hmm.. so I could have one instance with (int)count and (string)count? (yay DBase flashback, BRRR) I was going to initialize the vars in __init__() but somehow it didn't make sense to me( but left couple of them there). > BTW, I failed to see where you assigned an int to the class attribute > 'count'. I just saw a try to call a string - which should raise a > TypeError. > I must have fixed it before posting. gr_info.count = gr_info.first = gr_info.last = 0 ??? except ValueError: gr_info.count(0) ??? not sure what I was thinking there (maybe I was trying to triple fault the CPU hehe) >> class Cgroup_info: > > > Do yourself (and anyone having to work on or with your code) a favour: > use new-style classes (ie : inherit from 'object'). And FWIW, the > convention for class names is CamelCase - preferably without MS-like > hungarian annotation. > Those damn hungarians with their calculators and notations, only later did it occur to me to paste the "class ServerInfo():" statement above. > this creates a local variable 'group_name', bound to an empty string. > Using the reference to the current instance (usually named 'self', and > always passed in as first param) is *not* optional. > >> count = "0" #last time checked and processed/retrieved In __init__() it was an oversight but after the class className()... I may have thought it unnecessary, otherwise class consists only of a group of functions if as you say any vars should be created/initialized in __init__() hmmm. > the string module is mostly deprecated. Use str object methods instead - > or if you just want to create an int from it's representation as a > string, int(self.count). > Are string object methods among others, things like: words = sentence.split() This no longer works for me is it because I imported 'string' , didn't import something or didn't use "from string import *" instead. ( must be a year since I last played with python.) > >> gr_info.group_name = grp > > > Tthis create a new instance attribute "group_name" on the gr_info > object. This instance attribute will shadow the class attribute of the > same name. > Hmmm . so what is a class attribute good for? > Also, FWIW, if you always know the value for group_name when > instanciating a Cgroup_info object, you might as well pass it to the > initializer. > Good point. >> try: >> ind = self.group_list.index( grp ) > > > The common convention for indices in each and every language is 'i'. If > you really want a meaningful name, then group_index would be better. > lol, well like in a book and increasingly on the net index in used to refer to a list. So... I guess subscribed_group_list_index(_pointer) might be workable. > Also, for this kind of lookups, dicts are really faster than lists. > I am storing group count first last, although I am considering moving the numeric data elsewhere, for about 100 items .. I'll leave dictionaries for future learning. >> return ( gr_info ) > > > parenthesis here are useless (and FWIW, they would be just as useless in > C++). > A habit, true in python , in C, I think I remember reading about return function and statement. I was important at some point in C or perhaps way back in Pascal. >> print ind >> if len( self.group_list[ind].split() ) == 4: >> gr_info.count = self.group_list[ind].split()[1] >> gr_info.first = self.group_list[ind].split()[2] >> gr_info.last = self.group_list[ind].split()[3] > > > group_list[ind] is the same as grp, isn't it ? if so, using grp directly > might be much more efficient *and* much more readable. > no grp is the (string) group name that was used earlier to find the right item in the list. > Also, you're calling 4 times the same method. This is highly > inefficient. Try this instead: > parts = grp.split() > if len(parts) == 4: > gr_info.count, gr_info.first, gr_info.last = parts[1:] > > yes I realized that in another function but forgot about the unpacking assignment of a slice. >> else: >> gr_info.count = gr_info.first = gr_info.last = "0" > > > This style of "chained assignment" can be a real gotcha in Python. In > this case, it is safe since "0" is immutable. But using a mutable object > instead would lead to probably unexpected results. Try this: > > a = b = [] > a.append(1) > print b I rarely do that even in C particularly when working with struct members, but now with shorter names it is affordable. barely remembered reading about it. > > You have to understand that Python "variables" (the correct name is > "bindings") are just the association (in a given namespace) of a name > and a *reference* (kind of a smart pointer) to an object. > >> return( gr_info ) > > > Here's a possible rewrite of your code. It's certainly not how it should > be done, but (apart from going into wild guesses) it's difficult to come > up with anything better without knowing the specs. Anyway, it should > help you grasp a more pythonic way to do things: > > class GroupInfo(object): > > def __init__(self, group_name, count="0", first="0", last=""): > self.group_name = group_name > self.count = count #last time checked and processed/retrieved > self.first = first > self.last = last > > self.retrieval_type = "" # always , ask( if more than some > limit), none > self.date_checked = "" > self.time_checked = "" > self.new_count = "" > self.new_first = "" > self.new_last = "" > > # local storage maintanance vars > self.pointer_file = "" > self.message_file = "" > > #maintanance vars > self.cur_mess_num = 0 > self.cur_mess_id = "" > > # if you want to store count as string > # but retrieve it as an int. The setter will > # be used by the initializer, and will then create > # the implementation attribute _count > def _get_count(self): > return int(self._count) > > def _set_count(self, value): > self._count = str(value) > > count = property(_get_count, _set_count) > > > class ServerInfo(object): > def __init__(self, ???) > self._groups = {} # dict lookup is faster > # ... > def has_group(self, group_name): > return self._groups.has_key(group_name) > > def get_group_stat(self, group_name): > if not self.has_group(group_name): > return GroupInfo(group_name, "0") > > parts = group_name.split() > if len(parts) != 4: > parts = [None, "0", "0", "0"] > return GroupInfo(group_name, *(parts[1:4])) > > > As a last point, I'd second Fredrik : don't try to write C++ in Python. > Learn to write Python instead. The (freely available) "Dive into Python" > book should be a good place to get started. > > HTH New class style eh, I haven't got a grasp of the old style and exceptions only out of necessity. Either the Python exception docs were easier to understand or simply since I had to, to use those Inet classes , I finally broke down. I may have to go to C with this, for the GUI and I don't think building list of 100,000 messages is realistic . Well Thank You for all the good pointers. From webraviteja at gmail.com Fri Jun 9 17:11:07 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 9 Jun 2006 14:11:07 -0700 Subject: Python or Ajax? In-Reply-To: References: Message-ID: <1149887467.281050.173820@y43g2000cwc.googlegroups.com> > I've been hearing a ot about AJAX lately. I may have to build a web > application in the near future, and I was curoius: > > How does a web application that uses Python compare with one that uses AJAX? > > I've done some basic web page design with HTML and CSS, but never any > web applications. I don't want to learn a new language if I can use > Python. Would AJAX offer me any significant advantages? AJAX is *NOT* a programming language. It is a certain way of building web applications. Any Python (or any other language) web framework may be used, though some (TurboGears / LivePage etc) have explicit support for it. I bit of googling does not hurt. From sonja.coussell at gmail.com Thu Jun 15 01:25:12 2006 From: sonja.coussell at gmail.com (sonjaa) Date: 14 Jun 2006 22:25:12 -0700 Subject: memory leak problem with arrays In-Reply-To: <1150327127.904461.84740@h76g2000cwa.googlegroups.com> References: <1150317325.614389.14770@i40g2000cwc.googlegroups.com> <1150322504.136131.139350@i40g2000cwc.googlegroups.com> <1150324059.063981.70450@u72g2000cwu.googlegroups.com> <1150327127.904461.84740@h76g2000cwa.googlegroups.com> Message-ID: <1150349112.780025.289480@i40g2000cwc.googlegroups.com> Serge Orlov wrote: > sonjaa wrote: > > Serge Orlov wrote: > > > sonjaa wrote: > > > > Hi > > > > > > > > I'm new to programming in python and I hope that this is the problem. > > > > > > > > I've created a cellular automata program in python with the numpy array > > > > extensions. After each cycle/iteration the memory used to examine and > > > > change the array as determined by the transition rules is never freed. > > > > I've tried using "del" on every variable possible, but that hasn't > > > > worked. > > > > > > Python keeps track of number of references to every object if the > > > object has more that one reference by the time you use "del" the object > > > is not freed, only number of references is decremented. > > > > > > Print the number of references for all the objects you think should be > > > freed after each cycle/iteration, if is not equal 2 that means you are > > > holding extra references to those objects. You can get the number of > > > references to any object by calling sys.getrefcount(obj) > > > > thanks for the info. I used this several variables/objects and > > discovered that little counters i.e. k = k +1 have many references to > > them, up tp 10000+. > > Is there a way to free them? > > Although it's looks suspicious, even if you manage to free it you will > gain only 12 bytes. I think you should concentrate on more fat > objects ;) Sent message to the NumPy forum as per Roberts suggestion. An update after implimenting the suggestions: After doing this I see that iterative counters used to collect occurrences and nested loop counters (ii & jj) as seen in the code example below are the culprits with the worst ones over 1M: for ii in xrange(0,40): for jj in xrange(0,20): try: nc = y[a+ii,b+jj] except IndexError: nc = 0 if nc == "1" or nc == "5": news = news +1 if news == 100: break else: pass y[a+ii,b+jj] = 4 else: pass The version of python I'm using is 2.4.3 and the version of NumPy is 0.9.8 thanks again for all the help Sonja From iny+news at iki.fi Sun Jun 4 01:37:38 2006 From: iny+news at iki.fi (Ilpo =?iso-8859-1?Q?Nyyss=F6nen?=) Date: Sun, 04 Jun 2006 08:37:38 +0300 Subject: Python less error-prone than Java References: Message-ID: Christoph Zwerschke writes: > What's better about the Python version? First, it will operate on > *any* sorted array, no matter which type the values have. > > But second, there is a hidden error in the Java version that the > Python version does not have. While I can see your point, I'd say you are totally in the wrong level here. With Java generics you can sort a list and still keeping the type of the contents defined. This is makes the code less error-prone. But why would you implement binary search as the standard library already has it for both arrays and lists? This is one big thing that makes code less error-prone: using existing well made libraries. You can find binary search from python standard library too (but actually the API in Java is a bit better, see the return values). Well, you can say that the binary search is a good example and in real code you would use the stuff from the libraries. I'd say it is not good example: How often will you write such algorithms? Very rarely. Integer overflows generally are not those errors you run into in programs. The errors happening most often are from my point of view: 1. null pointer errors 2. wrong type (class cast in Java, some weird missing attribute in python) 3. array/list index out of bounds First and third ones are the same in about every language. The second one is one where the typing can make a difference. If in the code level you know the type all the way, there is much less changes of it being wrong. (The sad thing in the Java generics is that it is a compile time only thing and that causes some really weird stuff, but that is too off topic to here.) In python passing sequences for a function and also from a function is very easy. You can very easily pass a sequence as argument list. You can also very easily return a sequence from the function and even split it to variables directly. This is very powerful tool, but it has a problem too: How can you change what you return without breaking the callers? There are many cases where passing an object instead of a sequence makes the code much easier to develop further. What's the point? The point is that neither with Java or Python you want to be doing things in the low level. You really want to be doing stuff with objects and using existing libraries as much as possible. And in that level Java might be less error-prone as it does restrict the ways you can shoot yourself more. -- Ilpo Nyyss?nen # biny # /* :-) */ From pc at p-cos.net Thu Jun 22 06:02:02 2006 From: pc at p-cos.net (Pascal Costanza) Date: Thu, 22 Jun 2006 12:02:02 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: <1150967543.947096.72840@g10g2000cwb.googlegroups.com> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150902275.129780.50260@p79g2000cwp.googlegroups.com> <1150918629.818145.143220@y41g2000cwy.googlegroups.com> <4fv081F1jh4ifU1@individual.net> <1150967543.947096.72840@g10g2000cwb.googlegroups.com> Message-ID: <4fv84rF1kp06kU1@individual.net> ilitzroth at gmail.com wrote: > > A statically type language requires you to think about two models of > >> your program at the same time: the static type model and the dynamic >> behavioral model. A static type system ensures that these two >> _different_ (that's important!) perspectives are always in sync. > > I have trouble understanding your use of the wording "Model of a > program". > If it is a system that behaves according to the rules of your program > then > statements about your program should consider *all* possible models. > If it is a formal system that makes statements about properties of your > program > than the static type system is a simplified model that is suitable for > automatic > analysis and your runtime model is in most cases nonexistent. > Can you give a definition of a "model of a program"? Can you explain > why > Lisp doesn't have two (SBCL does do a lot of typechecking and gives > type errors)? I wasn't talking about models that the language implementation may or may not have, but the models that I as a programmer must have in order to convince the compiler to let me program run. Consider a simple expression like 'a + b': In a dynamically typed language, all I need to have in mind is that the program will attempt to add two numbers. In a statically typed language, I additionally need to know that there must a guarantee that a and b will always hold numbers. In a trivial example like this, this doesn't hurt a lot, but can be problematic as soon as the program size grows. >> This is >> especially valuable in settings where you know your domain well and want >> to rely on feedback by your compiler that you haven't made any mistakes >> in encoding your knowledge. (A static type system based on type >> inferencing doesn't essentially change the requirement to think in two >> models at the same time.) > > It is also valuable when you don't know your domain very well and you > want to rely on feedback by your compiler that you haven't made any > mistakes in encoding your limited knowledge I have more or less used exactly the same words in the paragraph that followed the one you cited from my previous posting, and I have already given a reply there. >> A dynamically typed language is especially well suited when you don't >> (yet) have a good idea about your domain and you want to use programming >> especially to explore that domain. our domain). > > In the sense that you can start writing code without the compiler > pointing out > all but the most glaring holes in your program, I agree. I don't know what language environments you are used to, but the Common Lisp compilers I use always point out the most glaring holes in my programs. But maybe I just have trouble understanding your use of the wording "most glaring holes". Can you give a definition of "most glaring holes"? ;) > Most of your > arguments > aren't very convincing and the thruth is that I have seem lisp > programmers using > the debugger to find out that you can't add a number and a hastable. > The static view > was not there and the dynamic view must have been too complicated so > they had > nothing to think about. We have all seen less-than-average programmers who would fail in all kinds of languages. What they do is typically not very illuminating. My goal is not to convince anyone, my goal is to illustrate for those who are interested in getting a possibly different perspective. Pascal -- 3rd European Lisp Workshop July 3 - Nantes, France - co-located with ECOOP 2006 http://lisp-ecoop06.bknr.net/ From ldo at geek-central.gen.new_zealand Mon Jun 26 03:21:37 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 26 Jun 2006 19:21:37 +1200 Subject: Python taught in schools? References: <1151220913.406987.162420@u72g2000cwu.googlegroups.com> Message-ID: In article , Mirco Wahab wrote: >C++ programming requires you to massively invest your thinking >first into the setup of your build environment ... I don't understand why. It's easy enough to build small programs with a single g++ command. From steve at holdenweb.com Wed Jun 28 03:04:35 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 28 Jun 2006 08:04:35 +0100 Subject: Python database access In-Reply-To: <44a15ede$0$15784$14726298@news.sunsite.dk> References: <1151295558.067744.91470@b68g2000cwa.googlegroups.com> <1151331311.172035.178060@y41g2000cwy.googlegroups.com> <1151335288.099526.207890@m73g2000cwd.googlegroups.com> <44a15ede$0$15784$14726298@news.sunsite.dk> Message-ID: Damjan wrote: >>The odbc module is part of the Python Standard Library. > > > Since when? > > Nope, it's a standard part of Mark Hammond's win32all extensions. As such it probably comes with ActivePython for Windows, which many people use as their standard distro. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From saint.infidel at gmail.com Thu Jun 1 11:01:06 2006 From: saint.infidel at gmail.com (infidel) Date: 1 Jun 2006 08:01:06 -0700 Subject: New to Python: Do we have the concept of Hash in Python? In-Reply-To: References: Message-ID: <1149174066.510963.83060@c74g2000cwc.googlegroups.com> > Is there any built-in Hash implementation in Python? I am looking for a > container that I can access to it's items by name. Something like this: > > Print container["memeberName"] You obviously haven't read the tutorial, they're called "dictionaries" in Python > I am asking this because I learned that DB-API in Python doesn't offer > access to cursor columns by name. The only option is access by index. I hope > that I've got it wrong! That's because the DB-API uses tuples to represent records. > I learned Ruby perfectly supports that. Yay for Ruby. From cito at online.de Sun Jun 4 14:25:31 2006 From: cito at online.de (Christoph Zwerschke) Date: Sun, 04 Jun 2006 20:25:31 +0200 Subject: Python less error-prone than Java In-Reply-To: <1149424883.529756.13700@j55g2000cwa.googlegroups.com> References: <1149424883.529756.13700@j55g2000cwa.googlegroups.com> Message-ID: nikie wrote: > Let's look at two different examples: Consider the following C# code: > > static decimal test() { > decimal x = 10001; > x /= 100; > x -= 100; > return x; > > It returns "0.01", as you would expect it. Yes, I would expect that because I have defined x as decimal, not int. > Now, consider the python equivalent: > > def test(): > x = 10001 > x /= 100 > x -= 100 > return x No, that's not the Python equivalent. The equivalent of the line decimal x = 10001 in Python would be x = 10001.0 or even: from decimal import Decimal x = Decimal(10001) Setting x = 10001 would be equivalent to the C# code int x = 10001 > It returns "0". Clearly an error! That's not clearly an error. If you set int x = 10001 in C#, then you also get a "0". By setting x to be an integer, you are implicitely telling Python that you are not interested in fractions, and Python does what you want. Granted, this is arguable and will be changed in the __future__, but I would not call that an error. By the way, the equivalent Python code to your C# program gives on my machine the very same result: >>> x = 10001.0; x /= 100; x -= 100; print x 0.01 > Even if you used "from __future__ import division", it would actually > return "0.010000000000005116", which, depending on the context, may > still be an intolerable error. With from __future__ import division, I also get 0.01 printed. Anyway, if there are small discrepancies then these have nothing to do with Python but rather with the underlying floating-point hardware and C library, the way how you print the value and the fact that 0.01 can principally not be stored exactly as a float (nor as a C# decimal), only as a Python Decimal. > I can even think of an example where C's (and Java's) bounded ints are > the right choice, while Python's arbitraty-precision math isn't: > Assume you get two 32-bit integers containing two time values (or > values from an incremental encoder, or counter values). How do you > find out how many timer ticks (or increments, or counts) have occured > between those two values, and which one was earlier? In C, you can > just write: > > long Distance(long t1, long t0) { return t1-t0; } > > And all the wraparound cases will be handled correctly (assuming there > have been less than 2^31 timer ticks between these two time values). > "Distance" will return a positive value if t1 was measured after t0, a > negative value otherwise, even if there's been a wraparound in > between. Try the same in Python and tell me which version is simpler! First of all, the whole problem only arises because you are using a statically typed counter ;-) And it only is easy in C when your counter has 32 bits. But what about a 24 bit counter? Anyway, in Python, you would first define: def wrap(x, at=1<<31): if x < -at: x += at*2 elif x >= at: x -= at*2 return x Then, the Python program would be as simple: Distance = lambda t1,t0: wrap(t1-t0) -- Christoph From aleax at mac.com Sat Jun 3 14:12:19 2006 From: aleax at mac.com (Alex Martelli) Date: Sat, 3 Jun 2006 11:12:19 -0700 Subject: carshing the interpreter in two lines References: <1149343823.789918.210110@h76g2000cwa.googlegroups.com> <1149350854.072412.263920@f6g2000cwb.googlegroups.com> Message-ID: <1hgcsal.x6phhi1i5nx0qN%aleax@mac.com> sam wrote: > tomer: > > It is my opinion that you would loose performance if the Python > interpreter had the additional task of verifying byte code. It might be > more appropriate to have a preprocessor that did the verifying as it > compiled the byte code. But in this case, there is no "compiled" -- just the code type's constructor: > > from types import CodeType as code > > exec code(0, 5, 8, 0, "hello moshe", (), (), (), "", "", 0, "") Yes, code() itself could do some sanity checking. But so could 'exec' -- it's never a particularly fast operation anyway... and most definitely NOT on the critical path of normal operations. I'd rather have "defense in depth", in this case. Alex From defcon8 at gmail.com Fri Jun 23 16:02:43 2006 From: defcon8 at gmail.com (defcon8) Date: 23 Jun 2006 13:02:43 -0700 Subject: PIL problems Message-ID: <1151092963.150515.153540@c74g2000cwc.googlegroups.com> Hello. I have been trying to use PIL's .putdata() method and I have been having some problems. The error I get is: Traceback (most recent call last): File "realautomata.py", line 72, in ? nim.putdata(y) File "C:\Python24\Lib\site-packages\PIL\Image.py", line 1120, in putdata self.im.putdata(data, scale, offset) TypeError: too many data entries The code is: import Image # Contract: # To simulate simple cellular automata. class calculations: def __init__(self): self.against = self.array_maker_2()[110] print self.against self.check = self.array_maker_1() self.array = self.array_maker_3(31) self.calculator() def binary(self, n, size): ## This is the Int -> str(BINARY) converter assert n >= 0 bits = [] while n: bits.append('01'[n&1]) n >>= 1 bits.reverse() result = ''.join(bits) or '0' for iteration in range(len(result),size): result = "0" + result return result def array_maker_1(self): # This makes the array that represents the 8 different permutations of 3 cells. Itself, its left and its right. return [self.binary(n, 3) for n in range(8)] def array_maker_2(self): # This makes the array that represents every single different rule. If for instance the second element in one # of these rules is 1, then the corresponding permutation that may be found in the result array (array_maker_3), will be 1 (black). return [self.binary(n, 8) for n in range(256)] def array_maker_3(self, y): # This is the array for all the results. The automaton starts from the middle of the first row x = [["0" for x in range(2*y+1)] for n in range(y)] x[0][(2*y-1)/2] = "1" return x def calculator(self): # This cycles over all of the cells, and scans one row at a time, and changes the next row according to the current cell. self.buff_result = ["0","0","0"] # This is the current permutation buffer to be checked against the corresponding arrays. for i in range(len(self.array)-1): for j in range(1, len(self.array[0])-1): self.step1(j,i) self.step2(j,i) self.step3(j,i) y = self.check.index(''.join(self.buff_result)) self.array[i+1][j] = self.against[y] # The steps update the result buffer. def step1(self, step, y): self.buff_result[0] = self.array[y][step-1] def step2(self, step, y): self.buff_result[1] = self.array[y][step] def step3(self, step, y): self.buff_result[2] = self.array[y][step+1] objo = calculations() x = objo.array y = [] for num,zo in enumerate(x): for com,wo in enumerate(zo): x[num][com] = int(wo) nim = Image.new("1", (62,31)) for n in x: #converting the array of arrays into a single array so putdata can take it. for p in n: y.append(p) print y nim.putdata(y) nim.resize((620,310)).save("output.png") can someone tell me why I get the error? From digitalorganics at gmail.com Mon Jun 26 23:47:56 2006 From: digitalorganics at gmail.com (digitalorganics at gmail.com) Date: 26 Jun 2006 20:47:56 -0700 Subject: Traversing Inheritance Model Message-ID: <1151380076.454803.93680@i40g2000cwc.googlegroups.com> What's the best way to traverse the web of inheritance? I want to take a class and traverse its bases and then the bases' bases etc.... looking for a particular class. What first came to mind was nested for loops. However, I want to know if there's some pre-existing method for doing this or if this isn't even possible (might send me in circles perhaps?).Thanks all. From grante at visi.com Fri Jun 9 12:34:52 2006 From: grante at visi.com (Grant Edwards) Date: Fri, 09 Jun 2006 16:34:52 -0000 Subject: About sizers.. References: Message-ID: <128j8pcf73im1bb@corp.supernews.com> On 2006-06-09, Mario Lacunza wrote: > Hi, > > Im build a cross platform application develop with Python and wxPython > and I ask for your opinions about if is a good choice use sizers for my > frames design? or not? Yes. Using hardwired pixel-count locations is evil, Evil, EVIL! > Other techniques? I've seen "constraints" mentioned as another way to layout things, but they don't seem to be recommended. -- Grant Edwards grante Yow! If I am elected no at one will ever have to do visi.com their laundry again! From rpdooling at gmail.com Thu Jun 15 16:18:53 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 15 Jun 2006 13:18:53 -0700 Subject: a good programming text editor (not IDE) References: <_xgkg.2317$No6.48542@news.tufts.edu> Message-ID: <1150402733.116243.9680@y41g2000cwy.googlegroups.com> Emacs must be dying if this thread could get all the way to 20 with nobody arguing with the vi folks. Will the Windows vim and gvim users vouch for its stability on Windows? rd From jdhunter at ace.bsd.uchicago.edu Wed Jun 7 08:54:22 2006 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 07 Jun 2006 07:54:22 -0500 Subject: how not to run out of memory in cursor.execute References: <1149447895.037396.81550@j55g2000cwa.googlegroups.com> <1149667287.092087.111270@c74g2000cwc.googlegroups.com> Message-ID: <874pyxi0sh.fsf@peds-pc311.bsd.uchicago.edu> >>>>> "yairchu at gmail" == yairchu at gmail com writes: yairchu at gmail> whenever you are using a package that leaks memory. yairchu at gmail> it can be appropriate to use Rpyc yairchu at gmail> (http://rpyc.wikispaces.com/) to run the leaking yairchu at gmail> code in a different process, and restart it from yairchu at gmail> time to time. I've been using this method to avoid yairchu at gmail> the leaks of matplotlib. The only known leak in matplotlib is in the tkagg backend which we believe comes from tkinter and is not in matplotlib proper. There are a variety of ways to make it look like matplotlib is leaking memory, eg overplotting when you want to first clear the plot, or failing to close figures properly. We have unit tests to check for leaks, and they are passing. Perhaps you can post some code which exposes the problem. JDH From sjmachin at lexicon.net Fri Jun 9 08:59:45 2006 From: sjmachin at lexicon.net (John Machin) Date: Fri, 09 Jun 2006 22:59:45 +1000 Subject: Short questions wrt Python & Unicode In-Reply-To: <1149854676.717074.309260@f6g2000cwb.googlegroups.com> References: <1149854676.717074.309260@f6g2000cwb.googlegroups.com> Message-ID: <448970C1.6020005@lexicon.net> On 9/06/2006 10:04 PM, KvS wrote: > 2) How do I get a representation of a unic. object in terms of Unicode > code points? repr() doesn't do that, it sometimes parses or encodes the > code points right: > >|>>> s=u"\u0040\u0166\u00e6" >|>>> s > u'@\u0166\xe6' |>>> ' '.join('U+%04X % ord(c) for c in s) 'U+0040 U+0166 U+00E6' If you'd prefer it more Pythonic than unicode.orgic, adjust the format string and separator to suit your taste. > (does this latter \xe6 have to do with the internal representation of > unic. objects, maybe with this UCS-2 encoding?) |>>> u'\xe6' == u'\u00e6' == unichr(0xe6) True |>>> hex(ord(u'\u00e6')) '0xe6' U+nnnnnn is represented internally as the integer 0xnnnnnn -- except if it won't fit, but you can pretend that surrogate pairs don't exist, for the moment :-) Cheers, John From python at hope.cz Sat Jun 10 11:48:36 2006 From: python at hope.cz (Lad) Date: 10 Jun 2006 08:48:36 -0700 Subject: PIL problem after installation Message-ID: <1149954516.785869.160700@i40g2000cwc.googlegroups.com> I installed PIL under Linux but now when I try it I get the error: decoder jpeg not available How can I correct that problem? Thank you for help L. From cdsmith at twu.net Fri Jun 23 16:13:07 2006 From: cdsmith at twu.net (Chris Smith) Date: Fri, 23 Jun 2006 14:13:07 -0600 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> Message-ID: Dr.Ruud wrote: > Chris Smith schreef: > > > Static types are not fuzzy > > Static types can be fuzzy as well. For example: a language can define > that extra accuracy and bits may be used for the implementation of > calculations: d = a * b / c > Often some minimum is guaranteed. Who cares how many bits are declared by the type? Some specific implementation may tie that kind of representation information to the type for convenience, but the type itself is not affected by how many bits are used by the representation. The only thing affected by the representation is the evaluation semantics and the performance of the language, both of which only come into play after it's been shown that the program is well-typed. > The 'dynamic type' is just another type. That's essentially equivalent to giving up. I doubt many people would be happy with the conclusion that dynamically typed languages are typed, but have only one type which is appropriate for all possible operations. That type system would not be implemented, since it's trivial and behaves identically to the lack of a type system, and then we're back where we started. -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation From sonaldgr8 at gmail.com Tue Jun 13 02:29:19 2006 From: sonaldgr8 at gmail.com (sonal) Date: 12 Jun 2006 23:29:19 -0700 Subject: How to link foreign keys & primary keys using python? References: <1149856668.055162.209650@u72g2000cwu.googlegroups.com> <1150092695.050971.33880@u72g2000cwu.googlegroups.com> Message-ID: <1150180158.987206.183490@u72g2000cwu.googlegroups.com> Hi Mr. Steve, The *indexes* i am using are lists... The code for creation of the PartionedPK is given below... ******************************************************************************* class PartitionedPK(object): def __init__(self, name, save_to, fields): self.name = name self.idx_name = save_to self.part_name = save_to + PARTITION_SUFFIX self.fields = fields self.digester = sha.new def setup(self, schema): self.partitions = [[] for i in range(256)] self.flush_pos = [[] for i in range(256)] self.flush_count = 0 self.index = {} self.offsets = field_offsets(self.fields, schema) if not self.offsets: raise ValueError('One or more index field names are invalid') self.idx_file = open(self.idx_name, 'wb+') self.part_file = open(self.part_name, 'wb+') def save(self): pickle.dump(self.flush_count, self.part_file, -1) pickle.dump(self.flush_pos, self.part_file, -1) self.idx_file.close() self.part_file.close() def flush(self): self.flush_count += 1 for i in range(256): self.flush_pos[i].append(self.idx_file.tell()) pickle.dump(self.partitions[i], self.idx_file, -1) self.partitions[i] = [] def valid(self, record, data): key = self.digester(''.join( [data[i] for i in self.offsets] )).digest() self.partitions[ ord(key[0]) ].append( (key, record) ) # defer checking till later return True def finalize(self): self.flush() errors = [] for bin in range(256): #show('Checking %s, bin %d/256 ... ' % (self.name, bin)) seen = {} has = seen.has_key for flush in range(self.flush_count): self.idx_file.seek( self.flush_pos[bin][flush] ) records = pickle.load(self.idx_file) for key, value in records: if has(key): errors.append(value) else: seen[key] = value return errors ******************************************************************************* the PK definition is as follows: vol_pk = PartitionedPK( name = 'VOL_PK', save_to = '../Index/vol.idx', fields = ['ID','Type','Curr_Code','Tenor']) The code for the Foreign Key declaration (referencing to the indexes) is as given below... ******************************************************************************* class HashedFK(object): def __init__(self, name, load_from, fields): self.name = name self.filename = load_from self.fields = fields self.digester = sha.new def setup(self, schema): self.index = {} self.offsets = field_offsets(self.fields, schema) if not self.offsets: raise ValueError('One or more index field names are invalid') file = open(self.filename, 'rb+') self.index = pickle.load(file) file.close() def valid(self, record, fields): key = self.digester(''.join( [fields[i] for i in self.offsets] )).digest() return self.index.has_key(key) def flush(self): pass def finalize(self): return None ******************************************************************************* the FK definition is as follows: vol_fk = HashedFK( name = ' VOL_FK, load_from = '../Index/vol.idx', fields= ['ID','Type','Curr_Code','Tenor']) The code is working fine when the foreign key is referenced to the complete primary key But if the FK were to be on only 'ID' the FK defn would have been like => vol_fk = HashedFK( name = ' VOL_FK, load_from = '../Index/vol.idx', fields = ['ID'] ) This is were the problem lies... it shows AttributeError: 'list' object has no attribute 'has_key' I have also tried defining another PK with a single field as follows => Tvol_pk = PartitionedPK( name = 'TVOL_PK', save_to = '../Index/tvol.idx', fields = ['ID'] ) The index ''tvol.idx'' is being created at the given location(path specified) but referencing to this index(i.e., tvol.idx) with the vol_fk given above also gives the same error. From tommy04 at gmail.com Tue Jun 6 17:46:54 2006 From: tommy04 at gmail.com (Tommy B) Date: 6 Jun 2006 14:46:54 -0700 Subject: Writing to a certain line? In-Reply-To: <44854184$0$29904$636a55ce@news.free.fr> References: <1149576072.168354.14470@f6g2000cwb.googlegroups.com> <44854184$0$29904$636a55ce@news.free.fr> Message-ID: <1149630414.246008.270720@f6g2000cwb.googlegroups.com> bruno at modulix wrote: > Tommy B wrote: > > I was wondering if there was a way to take a txt file and, while > > keeping most of it, replace only one line. > > > This is a FAQ (while I don't know if it's in the FAQ !-), and is in no > way a Python problem. FWIW, this is also CS101... > > > You can't do this in place with a text file (would be possible with a > fixed-length binary format). > > The canonical way to do so - whatever the language, is to write the > modified version in a new file, then replace the old one. > > import os > old = open("/path/to/file.txt", "r") > new = open("/path/to/new.txt", "w") > for line in old: > if line.strip() == "Bob 62" > line = line.replace("62", "66") > new.write(line) > old.close() > new.close() > os.rename("/path/to/new.txt", "/path/to/file.txt") > > If you have to do this kind of operation frequently and don't care about > files being human-readable, you may be better using some lightweight > database system (berkeley, sqlite,...) or any other existing lib that'll > take care of gory details. > > Else - if you want/need to stick to human readable flat text files - at > least write a solid librairy handling this, so you can keep client code > free of technical cruft. > > HTH > -- > bruno desthuilliers > python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for > p in 'onurb at xiludom.gro'.split('@')])" Umm... I tried using this method and it froze. Infiinite loop, I'm guessing. From uval at rz.uni-karlsruhe.de Fri Jun 23 09:23:57 2006 From: uval at rz.uni-karlsruhe.de (Daniel Schüle) Date: Fri, 23 Jun 2006 15:23:57 +0200 Subject: re question Message-ID: Hello re gurus, I wrote this pattern trying to get the "name" and the "content" of VHDL package I know that the file is a valid VHDL code, so actually there is no need to perform validation after 'end' token is found, but since it works fine I don't want to touch it. this is the pattern pattern = re.compile(r'^\s*package\s+(?P\w+)\s+is\s+(?P.*?)\s+end(\s+package)?(\s+(?P=name))?\s*;', re.DOTALL | re.MULTILINE | re.IGNORECASE) and the problem is that package TEST is xyz end; works but package TEST123 is xyz end; fails \w is supposed to match [a-zA-Z0-9_] so I don't understand why numbers and undescore let the pattern fail? (there is a slight suspicion that it may be a re bug) I also tried this pattern with the same results pattern = re.compile(r'^\s*package\s+(?P.+?)\s+is\s+(?P.*?)\s+end(\s+package)?(\s+(?P=name))?\s*;', re.DOTALL | re.MULTILINE | re.IGNORECASE) something must be wrong with (?P\w+) inside the main pattern thanks in advance -- Daniel From Bulkan at gmail.com Sat Jun 24 03:27:53 2006 From: Bulkan at gmail.com (placid) Date: 24 Jun 2006 00:27:53 -0700 Subject: HTTP server Message-ID: <1151134073.393065.187500@c74g2000cwc.googlegroups.com> Hi all, Ive been reading about creating a HTTP server like the one pydoc creates (and studying pydoc source code). What i want to know, is it possible to create server that creates a webpage with hyperlinks that communicate back to the HTTP server, where each link accessed tells the server to execute some arbitrary command on local machine its running on? Cheers From wahab at chemie.uni-halle.de Sat Jun 17 21:12:23 2006 From: wahab at chemie.uni-halle.de (Mirco Wahab) Date: Sun, 18 Jun 2006 03:12:23 +0200 Subject: Extracting values from text file In-Reply-To: <20060617232543.9a0338fb.randhol+valid_for_reply_from_news@pvv.org> References: <20060617232543.9a0338fb.randhol+valid_for_reply_from_news@pvv.org> Message-ID: Thus spoke Preben Randhol (on 2006-06-17 23:25): > The code is a very good starting point for me! I already > managed to change it and I see I need to make it a bit more robust. I think, the only thing you have to look at - is the congruence of the regex-based filter rule and the text. suppose you have a text: Apples 34 23 Apples, 234 Lemons 4 Eggs (note the comma!) and some rules: ... '(apples) Apples', 'Apples (apples)', ... the former program would handle that alright after changing the variable assignment from: if k.group(1): varname[k.group(1)] = to if k.group(1): varname[k.group(1)] += (note the +=) and the result would be: 'apples = 57'. It would add up all values corresponding to one variable. aehhm ... would be so in Perl, but Python throws another stone at you: - you have to explicitly instantiate a dictionary value (with 0) if/before you want in-place add to it (why is that?) - you can't have a return value from a regex object auto-converted to a number even if it _is_ a number and smells like a number (???) with these two nasty surprises, out extractor-loop looks like this: for rule in filter: k = re.search(r'\((.+)\)', rule) # pull out variable names ->k if k.group(1): # pull their values from text if not varname.has_key(k.group(1)): varname[k.group(1)] = 0; varname[k.group(1)] += float( \ re.search( re.sub(r'\((.+)\)', varscanner, rule), \ example ).group(1) ) # use regex in modified 'rule' whereas the in Perl-loop, only + to += would change for (@filter) { $v = $1 if s/\((.+)\)/$varscanner/; # pull out variable names ->$1 $varname{$v} += $1 if $example =~ /$_/; # pull their values from text } I'll add the complete python program which handles all cases you mentioned. Regards Mirco ==> DATA = ''' An example text file: ----------- Some text that can span some lines. Apples 34 23 Apples, 234 Lemons 4 Eggs 56 Ducks Some more text. 0.5 g butter ----------------------------------''' # data must show up before usage filter = [ # define filter table '(apples) Apples', 'Apples (apples)', '(ducks) Ducks', '(lemons) Lemons', '(eggs) Eggs', '(butter) g butter', ] varname = {} # variable names to be found in filter varscanner = r'\\b(\S+?)\\b' # expression used to extract values example = DATA # read the appended example text, import re for rule in filter: # iterate over filter rules, rules will be in 'rule' k = re.search(r'\((.+)\)', rule) # pull out variable names ->k if k.group(1): # pull their values from text if not varname.has_key(k.group(1)): varname[k.group(1)] = 0; varname[k.group(1)] += float( \ re.search( re.sub(r'\((.+)\)', varscanner, rule), \ example ).group(1) ) # use regex in modified 'rule' for key, val in varname.items(): print key, "\t= ", val # print what's found <== From claudio.grondi at freenet.de Mon Jun 26 11:25:28 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Mon, 26 Jun 2006 17:25:28 +0200 Subject: style question In-Reply-To: References: Message-ID: Hari Sekhon wrote: > Is it better to do: > > message = """This is line1. > This is line2 > This is line3\n""" > > or > > message = "This is line1.\n > message = message + "This is line2\n" > message = message + "This is line3\n" > > > Since the first method does not follow python's clean and easy looking > indentation structure but the second just looks crude and ugly anyway. > > If I indent the first version so the text is lined up to match code > indentation then this comes out in the input and isn't aligned there. > What about message = """ This is line 1 This is line 2 This is line 3 """ When it is necessary to skip first empty line): message = """ This is line 1 This is line 2 This is line 3 """[1:] When necessary to skip first line _and_ indentation: message = """ This is line 1 This is line 2 This is line 3 """.replace('\n ', '\n')[1:] # adjust here '\n ' to indentation # ^-- gives 'This is line 1\nThis is line 2\nThis is line 3\n' ? Claudio From duncan.booth at invalid.invalid Tue Jun 20 03:51:57 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 20 Jun 2006 07:51:57 GMT Subject: Function definition References: <1150758338.302466.102040@r2g2000cwb.googlegroups.com> Message-ID: aarondesk wrote: > I have a little .py file that has the format: > > > def fxn(a): > do stuff > > other stuff > ... > r = fxn(a) > .... > > > Now I've tried putting the function declaration after the call but the > program wouldn't work. Is there anyway to put function declarations at > the end of the program, rather than putting them at the beginning, > which is rather clunky? > How about putting your main program code inside another function called something like 'main'? Then it can appear wherever you like. All you need at the end of the file then is: if __name__=='__main__': main() This also means you can reuse the functions with different main code simply by importing them from another file. From esj at harvee.org Wed Jun 21 13:00:25 2006 From: esj at harvee.org (Eric S. Johansson) Date: Wed, 21 Jun 2006 13:00:25 -0400 Subject: need all python dialog equivalent In-Reply-To: References: Message-ID: <44997B29.7080607@harvee.org> Fredrik Lundh wrote: > Eric S. Johansson wrote: > http://excess.org/urwid/ ? I just found that about an hour ago. the demos work on the target system so I'm comfortable enough to go down that path. thank you all. ---eric From robert.thorpe at antenova.com Wed Jun 21 11:59:26 2006 From: robert.thorpe at antenova.com (Rob Thorpe) Date: 21 Jun 2006 08:59:26 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <1150809118.677124.142230@u72g2000cwu.googlegroups.com> <1150815461.210286.53120@r2g2000cwb.googlegroups.com> <1150822150.701434.296460@u72g2000cwu.googlegroups.com> <1150883442.498308.226730@b68g2000cwa.googlegroups.com> <1150899429.801658.16120@r2g2000cwb.googlegroups.com> Message-ID: <1150905566.142680.246550@u72g2000cwu.googlegroups.com> Matthias Blume wrote: > "Rob Thorpe" writes: > > >> >> > No it doesn't. Casting reinterprets a value of one type as a value of > >> >> > another type. > >> >> > There is a difference. If I cast an unsigned integer 2000000000 to a > >> >> > signed integer in C on the machine I'm using then the result I will get > >> >> > will not make any sense. > >> >> > >> >> Which result are you getting? What does it mean to "make sense"? > >> > > >> > Well the right one actually, bad example. > >> > > >> > But, if I cast an unsigned int 2500000000 to signed I get -1794967296. > >> > >> So, why do you think this "does not make sense"? > > > > Well, it makes sense in terms of the C spec certainly. > > It does not make sense in that it does not emit an error. > > Why not? Well it's really a matter of perspective isn't it. In some cases it may even be what the programmer intends. >From my perspective I don't expect a large positive number to turn into a negative one just because I've requested that it be signed. The behaviour I would expect is that either the variable being set gets the right number, or an error occurs. I don't care if the reporting is at runtime or compile time, so long as it can be seen. -- Anyway, this is a small point. Does the fact that you only disagreed with me on this point indicate that you agreed with everything else? ... Only joking :) I think you and I have irreconcilable views on this subject. I think we can agree that value mostly have some sort of type in a statically typed language. You may say that they have directly have types, but I can't see how that can be, as far as I can see they have types only indirectly. This is only a minor point though. The issue of typing of values vs variables is not practically meaningless though. The main problem I find with statically typed programs is that much of the world outside the program is not statically typed. Library and API writers in-particular seem to treat static typing carelessly. As a result it's not generally possible to write a program meaningfully inside the static type system, as the type systems designers intended. You're force to break it all over the place with casts etc anyway. And at every place you break it the possibility of error occurs and flow from that place into the rest of the program. So, you end up actually checking the values of variables rather than relying on their types anyway. And this can be difficult because their values have no associated information telling you their types. It's different writing a function deep inside a large program, in this case data can be cleaned up beforehand. And in this case the static typing works are intended and becomes more useful. Anyway, I don't think it would help either of us to continue this sub-thread any more. Feel free to reply to this post, but I might not reply back. Static typing is rather off topic on most of the newsgroups this thread is in anyway, and I suspect the people in them are getting rather sick of it. From steve at holdenweb.com Mon Jun 12 04:59:41 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 12 Jun 2006 09:59:41 +0100 Subject: An error ? In-Reply-To: <200606121018.44943.maric@aristote.info> References: <448D06AB.3070104@gmail.com> <200606121018.44943.maric@aristote.info> Message-ID: Maric Michaud wrote: > Le Lundi 12 Juin 2006 09:07, Steve Holden a ?crit : > >>print "Content-Type: text\plain\n" > > a typo I guess, > print "Content-Type: text/plain\n" > Good eye! regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From fredrik at pythonware.com Wed Jun 7 14:19:05 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 07 Jun 2006 20:19:05 +0200 Subject: 10GB XML Blows out Memory, Suggestions? In-Reply-To: <9ehjl3-4um.ln1@prcm.tecont.de> References: <1149594519.098115.8980@u72g2000cwu.googlegroups.com> <2Qfhg.18186$0v4.787@tornado.texas.rr.com> <9ehjl3-4um.ln1@prcm.tecont.de> Message-ID: Ralf Muschall wrote: > In the DOM, it contracts to 3 integers and a few pointers - > essentially the same as needed in a reasonably written > data structure. what kind of magic DWIM DOM is this? From diffuser78 at gmail.com Fri Jun 30 14:16:34 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 30 Jun 2006 11:16:34 -0700 Subject: efficiency question In-Reply-To: References: <6AD91BEE-08AF-446D-AE17-B2FB5532E7FE@math.harvard.edu> Message-ID: <1151691394.556619.284330@m73g2000cwd.googlegroups.com> So nice to know this that you can compare your own code using this methodology. I was completely unaware of this. Thank you so much. Fredrik Lundh wrote: > David Harvey wrote: > > > Suppose I write > > > > if x in ("abc", "def", "xyz"): > > doStuff() > > > > elif x in ("pqr", "tuv", "123"): > > doOtherStuff() > > > > elif ... > > When is python building the tuples? Does it need to build the tuple > > every time it comes through this code? Or does it somehow recognise > > that they are constant and cache them? > > when in doubt, ask the compiler: > > def code(x): > if x in ("abc", "def", "xyz"): > doStuff() > elif x in ("pqr", "tuv", "123"): > doOtherStuff() > > import dis > dis.dis(code) > > prints: > > 2 0 LOAD_FAST 0 (x) > 3 LOAD_CONST 7 (('abc', 'def', 'xyz')) > 6 COMPARE_OP 6 (in) > 9 JUMP_IF_FALSE 11 (to 23) > 12 POP_TOP > > 3 13 LOAD_GLOBAL 1 (doStuff) > 16 CALL_FUNCTION 0 > 19 POP_TOP > 20 JUMP_FORWARD 25 (to 48) > >> 23 POP_TOP > > 4 24 LOAD_FAST 0 (x) > 27 LOAD_CONST 8 (('pqr', 'tuv', '123')) > 30 COMPARE_OP 6 (in) > 33 JUMP_IF_FALSE 11 (to 47) > 36 POP_TOP > > 5 37 LOAD_GLOBAL 2 (doOtherStuff) > 40 CALL_FUNCTION 0 > 43 POP_TOP > 44 JUMP_FORWARD 1 (to 48) > >> 47 POP_TOP > >> 48 LOAD_CONST 0 (None) > 51 RETURN_VALUE > > so the answer is "yes, in this specific case". > > > (The tuples I have in mind are of course much longer than three > > elements) > > in that case, you should probably use pre-calculated sets instead of tuples. > > From iainking at gmail.com Thu Jun 1 16:08:41 2006 From: iainking at gmail.com (Iain King) Date: 1 Jun 2006 13:08:41 -0700 Subject: Trying to get FreeImagePy to work. In-Reply-To: References: <1148651668.578852.3160@i40g2000cwc.googlegroups.com> <7fEdg.13375$cX1.201311@twister2.libero.it> <1148655611.990937.322350@j73g2000cwa.googlegroups.com> <1149166096.176405.22780@i40g2000cwc.googlegroups.com> <3PCfg.20835$cX1.315781@twister2.libero.it> <1149174938.337973.85950@g10g2000cwb.googlegroups.com> Message-ID: <1149192520.959302.250840@j55g2000cwa.googlegroups.com> Michele Petrazzo wrote: > Iain King wrote: > > However, when I'm do the > > fipy.convertToPil(), it inverts the image? > > No, it not invert the image... It only return the image as is. > > > I've inserted a > > fipy.invert() before the conversion as a temporary fix, but is there a > > reason for this? > > If you are have a min-is-white image (fax ?) that isn't the standard, > you will have an "inverted" image, because PIl expect a min-is-black > image! > This is probably what is happening. I'll upload one of the images tomorrow, and you can check it out to make sure. > > relevant code: > > > > def getHeaders(files): > > thumbs = [] > > for f in files: > > print "Adding %s" % f > > fi = FIPY.Image(f) > > fi.setCurrentPage(0) > > fi.invert() #temp fix > > thumb = fi.convertToPil() > > thumb.thumbnail(THUMBNAIL_SIZE, Image.ANTIALIAS) > > thumbs.append((os.path.basename(f), pilToBitmap(thumb))) > > thumbs.sort() > > return thumbs > > Just a question, why "thumbs.sort" ? Inside this list you have only > images! Ah, look closer! It's a list of tuples: (filename, image) I'll try out FIPY's resizing tomorrow too. OTOH, I have functions to convert between PIL and wxPython, and functions to convert betweem PIL and FIPY, but I don't see a function to convert FIPY to wxPython? Iain From jo at durchholz.org Sun Jun 25 14:00:09 2006 From: jo at durchholz.org (Joachim Durchholz) Date: Sun, 25 Jun 2006 20:00:09 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: <4g7k1mF1ma4ghU1@individual.net> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150908952.804184.218990@r2g2000cwb.googlegroups.com> <1150991074.705803.211570@m73g2000cwd.googlegroups.com> <4g7k1mF1ma4ghU1@individual.net> Message-ID: Pascal Costanza schrieb: >> Another observation: type safeness is more of a spectrum than a >> clearcut distinction. Even ML and Pascal have ways to circumvent the >> type system, and even C is typesafe unless you use unsafe constructs. >> IOW from a type-theoretic point of view, there is no real difference >> between their typesafe and not typesafe languages in the "statically >> typed" column; the difference is in the amount of unsafe construct >> usage in practial programs. > > It's also relevant how straightforward it is to distinguish between safe > and unsafe code, how explicit you have to be when you use unsafe code, > how likely it is that you accidentally use unsafe code without being > aware of it, what the generally accepted conventions in a language > community are, etc. pp. Fully agreed. From ldo at geek-central.gen.new_zealand Mon Jun 5 05:27:57 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 05 Jun 2006 21:27:57 +1200 Subject: Large Dictionaries References: <1147699064.107490@teuthos> <1147772420.405097@teuthos> <1147818548.532882.94180@i39g2000cwa.googlegroups.com> <1147874585.728471@teuthos> <1148514158.790760.205630@i40g2000cwc.googlegroups.com> <447af556$1@nntp0.pdx.net> Message-ID: In article <447af556$1 at nntp0.pdx.net>, Scott David Daniels wrote: >For example, time timsort (Python's internal sort) on pre-sorted >data; you'll find it is handled faster than random data. But isn't that how a reasonable sorting algorithm should behave? Less work to do if the data is already sorted? From find at my.address.elsewhere Tue Jun 27 16:54:02 2006 From: find at my.address.elsewhere (Matthias Blume) Date: Tue, 27 Jun 2006 15:54:02 -0500 Subject: languages with full unicode support References: <1151251736.590910.36050@u72g2000cwu.googlegroups.com> <1151276031.641318@elch.in-berlin.de> <4gd3iiF1md4lcU1@individual.net> Message-ID: Tin Gherdanarra writes: > Oliver Bandel wrote: >> ????? Xah-Lee san ;-) > > Uhm, I'd guess that Xah is Chinese. Be careful > with such things in real life; Koreans might > beat you up for this. Stay alive! And the Japanese might beat him up, too. For butchering their language. :-) From bayazee at gmail.com Fri Jun 23 04:38:12 2006 From: bayazee at gmail.com (Bayazee) Date: 23 Jun 2006 01:38:12 -0700 Subject: reaching to the notification area Message-ID: <1151051892.796863.76570@b68g2000cwa.googlegroups.com> Hi i want to make an icon in the notification area by python . how can I make a notification area button likewise windows system tray and show custem menu on right click or ... (i want to use pyqt ...) ThanX From fredrik at pythonware.com Sat Jun 10 03:16:29 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 10 Jun 2006 09:16:29 +0200 Subject: Error in Chain of Function calls (Code Attached) In-Reply-To: <60248.10.209.4.2.1149897069.squirrel@10.105.1.3> References: <448930f1$0$10302$636a55ce@news.free.fr> <448994e6$1_3@news.bluewin.ch> <60248.10.209.4.2.1149897069.squirrel@10.105.1.3> Message-ID: Girish Sahani wrote: > Thanks for the help boris....i'll try using sets instead of lists > But i dont understand the point below...full traceback means what :-? see: http://tinyurl.com/qwpsf From jal at machinefx.co.uk Fri Jun 23 14:28:59 2006 From: jal at machinefx.co.uk (John Lockwood) Date: Fri, 23 Jun 2006 19:28:59 +0100 Subject: Python on intel osx In-Reply-To: <1151086320.564736.272500@y41g2000cwy.googlegroups.com> Message-ID: Can some one please suggest the most suitable python for mac osx 10.4.6 Finding the right the installs doesn?t seem quite as cut and dried as it is for linux or windows. I?m also looking for numeric and pyopengl. Cheers -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at holdenweb.com Fri Jun 9 03:16:17 2006 From: steve at holdenweb.com (Steve Holden) Date: Fri, 09 Jun 2006 08:16:17 +0100 Subject: Allowing zero-dimensional subscripts In-Reply-To: <1149832139.948242.64160@f6g2000cwb.googlegroups.com> References: <1149801040.936452.26270@i40g2000cwc.googlegroups.com> <1149807149.516004.48590@f6g2000cwb.googlegroups.com> <1149832139.948242.64160@f6g2000cwb.googlegroups.com> Message-ID: spam.noam at gmail.com wrote: > Hello, > > Terry Reedy wrote: > >>So I do not see any point or usefulness in saying that a tuple subcript is >>not what it is. > > > I know that a tuple is *constructed*. The question is, is this, > conceptually, the feature that allows you to ommit the parentheses of a > tuple in some cases. If we see this as the same feature, it's > reasonable that "nothing" won't be seen as an empty tuple, just like "a > = " doesn't mean "a = ()". > > However, if we see this as a different feature, which allows > multidimensional subscript by constructing a tuple behind the scenes, > constructing an empty tuple for x[] seems very reasonable to me. Since > in some cases you can't have the parentheses at all, I think that x[] > makes sense. > Hey, I have an idea, why don't we look at the language reference manual instead of imagining how we think it might work! In section 3.2 we find: """ Tuples The items of a tuple are arbitrary Python objects. Tuples of two or more items are formed by comma-separated lists of expressions. A tuple of one item (a `singleton') can be formed by affixing a comma to an expression (an expression by itself does not create a tuple, since parentheses must be usable for grouping of expressions). An empty tuple can be formed by an empty pair of parentheses. """ So it seems that your speculation is false. Section 2.6 specifically defines "[" and "]" as delimiters. Section 5.3.2 defines a subscription (a term I've not really grown to love, but what the heck) as subscription ::= primary "[" expression_list "]" and section 5.12, which defines expression_list, explicitly says """An expression list containing at least one comma yields a tuple.""". So it would appear that while your change might be very convenient to allow you to refer to scalar values as zero-dimensional arrays, it doesn't really fit into Python's conceptual framework. Sorry. One further point: if you really do conceptualize scalars as zero-dimensional arrays, where is the value conceptually stored? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From dnew at san.rr.com Tue Jun 20 14:19:40 2006 From: dnew at san.rr.com (Darren New) Date: Tue, 20 Jun 2006 18:19:40 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: <4498356b$0$659$bed64819@news.gradwell.net> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> Message-ID: <0%Wlg.3521$MF6.947@tornado.socal.rr.com> Chris Uppal wrote: > Personally, I would be quite happy to go there -- I dislike the idea that a > value has a specific inherent type. Interestingly, Ada defines a type as a collection of values. It works quite well, when one consistantly applies the definition. For example, it makes very clear the difference between a value of (type T) and a value of (type T or one of its subtypes). -- Darren New / San Diego, CA, USA (PST) My Bath Fu is strong, as I have studied under the Showerin' Monks. From girish at cse.iitb.ac.in Tue Jun 6 00:10:48 2006 From: girish at cse.iitb.ac.in (Girish Sahani) Date: Tue, 6 Jun 2006 09:40:48 +0530 (IST) Subject: Reading from a file and converting it into a list of lines: code not working In-Reply-To: <1149535195.763340.220010@y43g2000cwc.googlegroups.com> References: <1149534126.129714.131860@f6g2000cwb.googlegroups.com> <1149535195.763340.220010@y43g2000cwc.googlegroups.com> Message-ID: <54688.10.209.4.1.1149567048.squirrel@10.105.1.3> I have a text file in the following format: 1,'a',2,'b' 3,'a',5,'c' 3,'a',6,'c' 3,'a',7,'b' 8,'a',7,'b' . . . Now i need to generate 2 things by reading the file: 1) A dictionary with the numbers as keys and the letters as values. e.g the above would give me a dictionary like {1:'a', 2:'b', 3:'a', 5:'c', 6:'c' ........} 2) A list containing pairs of numbers from each line. The above formmat would give me the list as [[1,2],[3,5],[3,6][3,7][8,7]......] I wrote the following codes for both of these but the problem is that lines returns a list like ["1,'a',2,'b'","3,'a',5,'c","3,'a',6,'c'".....] Now due to the "" around each line,it is treated like one object and i cannot access the elements of a line. [code] #code to generate the dictionary def get_colocations(filename): lines = open(filename).read().split("\n") colocnDict = {} i = 0 for line in lines: if i <= 2: colocnDict[line[i]] = line[i+1] i+=2 continue return colocnDict [/code] [code] def genPairs(filename): lines = open(filename).read().split("\n") pairList = [] for line in lines: pair = [line[0],line[2]] pairList.append(pair) i+=2 continue return pairList [/code] Please help :(( From max at alcyone.com Mon Jun 5 18:27:59 2006 From: max at alcyone.com (Erik Max Francis) Date: Mon, 05 Jun 2006 15:27:59 -0700 Subject: C# equivalent to range() In-Reply-To: <1149509893.031953.19310@i40g2000cwc.googlegroups.com> References: <1149468919.951745.163700@g10g2000cwb.googlegroups.com> <1149481675.192638.275140@c74g2000cwc.googlegroups.com> <1149509893.031953.19310@i40g2000cwc.googlegroups.com> Message-ID: Neuruss wrote: > The other zilion persons who were not interested (other than the four I > mentioned above) silently and peacefully ignored the question on went > on with their happy lifes. That's because many of them have killfiled you. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Society attacks early when the individual is helpless. -- B.F. Skinner From pc at p-cos.net Fri Jun 16 05:47:09 2006 From: pc at p-cos.net (Pascal Costanza) Date: Fri, 16 Jun 2006 11:47:09 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: <7zy7vxqxni.fsf@app-1.diku.dk> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <2006061410510511272-raffaelcavallaro@pasdespamsilvousplaitmaccom> <878xnzv5i3.fsf@thalassa.informatimago.com> <2006061501582450878-raffaelcavallaro@pasdespamsilvousplaitmaccom> <7zy7vxqxni.fsf@app-1.diku.dk> Message-ID: <4ffd0tF1iprnnU1@individual.net> Torben ?gidius Mogensen wrote: > Raffael Cavallaro writes: > >> On 2006-06-14 16:36:52 -0400, Pascal Bourguignon said: >> >>> In lisp, all lists are homogenous: lists of T. >> CL-USER 123 > (loop for elt in (list #\c 1 2.0d0 (/ 2 3)) collect >> (type-of elt)) >> (CHARACTER FIXNUM DOUBLE-FLOAT RATIO) >> >> i.e., "heterogenous" in the common lisp sense: having different >> dynamic types, not in the H-M sense in which all lisp values are of >> the single union type T. > > What's the difference? Dynamically types values _are_ all members of > a single tagged union type. Yes, but that's mostly a meaningless statement in a dynamically typed language. In a dynamically typed language, you typically don't care about the static types. > The main difference is that the tages > aren't always visible and that there are only a fixed, predefined > number of them. Depending on the language, the number of "tags" is not fixed. Pascal -- 3rd European Lisp Workshop July 3 - Nantes, France - co-located with ECOOP 2006 http://lisp-ecoop06.bknr.net/ From aurora00 at gmail.com Wed Jun 28 19:21:04 2006 From: aurora00 at gmail.com (aurora00 at gmail.com) Date: 28 Jun 2006 16:21:04 -0700 Subject: Generator naming convention? References: <1151520720.749818.131460@i40g2000cwc.googlegroups.com> <1151533692.535262.258690@y41g2000cwy.googlegroups.com> Message-ID: <1151536864.660620.164170@i40g2000cwc.googlegroups.com> iter- clicks for me, thanks :) wy infidel wrote: > > Any idea? Do you have a naming convention for generators? > > Sometimes I use the prefix 'iter', like dictionaries have .items() and > .iteritems(). sometimes I use 'x', like range() vs. xrange(). You > could simply use 'i' like some of the functions in the iteritems module > (imap(), izip(), etc). I guess it depends on the project, what you're > doing, your mood at the moment, and the alignment of Jupiter and > Mercury in Aquarius. From td_01 at att.net.invalid Mon Jun 19 22:19:51 2006 From: td_01 at att.net.invalid (Tom Del Rosso) Date: Tue, 20 Jun 2006 02:19:51 GMT Subject: Active Python versions References: <2hElg.41514$mF2.19600@bgtnsc04-news.ops.worldnet.att.net> <1150769349.111390.280450@y41g2000cwy.googlegroups.com> Message-ID: jmdeschamps at gmail.com typed in news://1150769349.111390.280450 at y41g2000cwy.googlegroups.com, > Maybe the OP is refering to PythonWin editor (as compared to IDLE) > which is in ActiveState's release but not in the Python.org release... > makes for a very different subject, and hopefully for very different > answer direction. Yes. I just wanted to know which programming environment is prefered by regular users, maybe even one that I haven't heard of yet. -- Reply in group, but if emailing add another zero, and remove the last word. From bigodines at gmail.com Mon Jun 5 09:38:54 2006 From: bigodines at gmail.com (bigodines) Date: 5 Jun 2006 06:38:54 -0700 Subject: Simple question Message-ID: <1149514734.312783.122520@i40g2000cwc.googlegroups.com> Hi guys! I'm a complete newbie in Python and I'm trying to make a small software to watch my network. It will be a simple snmpget report for a specific machine. I would like to make a small program in python to be runed with crontrab that will store the whole output in a txt file. I know its not a big deal, but i've no background in python :) basically i would like to know how to: 1 - execute a command in the server 2 - write the whole output into a file. best regards, Matheus From slawomir.nowaczyk.847 at student.lu.se Fri Jun 2 08:11:58 2006 From: slawomir.nowaczyk.847 at student.lu.se (Slawomir Nowaczyk) Date: Fri, 02 Jun 2006 14:11:58 +0200 Subject: An oddity in list comparison and element assignment In-Reply-To: <1hg9pbo.1oem3vh1ryksipN%aleax@mac.com> References: <1hg9pbo.1oem3vh1ryksipN%aleax@mac.com> Message-ID: <20060602140630.FC41.SLAWOMIR.NOWACZYK.847@student.lu.se> On Thu, 01 Jun 2006 19:16:16 -0700 aleax at mac.com (Alex Martelli) wrote: #> > What does "parallel mutations" mean? In particular, what should be the #> > results of each of the following three comparisons: #> > #> > x, y, z = [1],[1],[1] #> > a, b = [x,y], [y,z] #> > c, d = [[1],[1]], [[1],[1]] #> > a == b #> > c == d #> > a[0].remove(1) #> > b[0].remove(1) #> > a == b #> > #> > So, do I understand correctly that you would like first comparison #> > (a==b) to return "False" and second comparison (c==d) to return #> > "True"? #> #> I sure hope not, So do I, but that's how I understood Michaels' words... #> In fact, I'm starting to wonder if by Michaels' requirement ANY #> non-*IDENTICAL* containers (with non-identical mutable items) could #> EVER be deemed "equal". If he's arguing that "==" should mean #> exactly the same as "is", that's even crazier than I had gauged so #> far. I think he explicitly said that "is" doesn't fulfill his requirements either... but then, I am not sure as I do not understand what his requirements actually are (they seem to make some sense for immutable objects, but how should they generalise to mutable stuff I have no idea). PS. Thanks for explanation about Bank of America: I had no clue how it works in realty, it just had a good name ;) -- Best wishes, Slawomir Nowaczyk ( Slawomir.Nowaczyk at cs.lth.se ) Java is clearly an example of a MOP (money-oriented programming) -- Alexander Stepanov From faik at pardus.org.tr Fri Jun 16 06:24:57 2006 From: faik at pardus.org.tr (Faik Uygur) Date: Fri, 16 Jun 2006 13:24:57 +0300 Subject: getting umask without changing it In-Reply-To: References: <200606161207.56008.faik@pardus.org.tr> Message-ID: <200606161324.57359.faik@pardus.org.tr> Cuma 16 Haziran 2006 12:48 tarihinde, Fredrik Lundh ?unlar? yazm??t?: > Faik Uygur wrote: > > Is there a python way of getting the current umask without changing it? > > os.umask changes it, and i dont want to use os.system("umask") > > just call os.umask twice: > current_mask = os.umask(0) This is not atomic. At this point i changed all the running python threads' umask and i don't want to change current umask. I just want to get it. > os.umask(current_mask) - Faik From samaloth at gmail.com Mon Jun 19 17:38:05 2006 From: samaloth at gmail.com (Saint Malo) Date: 19 Jun 2006 14:38:05 -0700 Subject: Newbie Question In-Reply-To: <129e55eahc35f00@corp.supernews.com> References: <1150750938.973049.114780@y41g2000cwy.googlegroups.com> <129e55eahc35f00@corp.supernews.com> Message-ID: <1150753085.332654.283270@f6g2000cwb.googlegroups.com> Thanks! That helped a lot! Now, lets say that I just want to display one or just a few of the items and not the whole line. For example, the text file contains the following: red blue yello green purple brown If the program searches for blue, i just want it to print blue, not the whole line. If i ask it to find blue and brown, i just want it to return those two values. Andrew Robert wrote: > Saint Malo wrote: > > I am new to programming, and I've chosen python to start with. I wrote > > a simple program that asks several questions and assings each one of > > them a variable via raw_input command. I then combined all the > > variables into one like this a = b + c + d. After this I wrote these > > values to a file. What I want to do now is be able to search through > > the file for any data in there. Is this possible? > > > Most certainly. > > It depends on how you want to treat the read data. > > for example > > > # Open a file for read > file=open(r'test.txt','r') > > # Read each line in file > for line in file > > #Search each line > if "A" in line: > > print "I found A" > > file.close() From simon at xiano.co.uk Wed Jun 28 09:15:14 2006 From: simon at xiano.co.uk (Bowen) Date: 28 Jun 2006 06:15:14 -0700 Subject: MySQLdb not updating rows Message-ID: <1151500514.817456.65510@d56g2000cwd.googlegroups.com> import md5 import string import MySQLdb tc = raw_input("Teacher Code: ") p = raw_input("New Password: ") print tc hash = md5.new() hash.update(p) print p print hash.hexdigest() h = hash.hexdigest() boo = raw_input("Sure you want to update password with above details? Y or N: ") if boo == 'y': db = MySQLdb.connect("copweb2", "******", "******", "*******") cursor = db.cursor() if cursor.execute("UPDATE teachers SET password = '%s' WHERE teacher_code = '%s'" % (h, tc)): print "Done" else: print "Error" else: print "cancelled" cursor.close() db.close() This code doesn't seem to update my database, anyone any idea why? Is it me being stupid? It doesn't kick out an error at all. From fredrik at pythonware.com Sat Jun 24 11:09:12 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 24 Jun 2006 17:09:12 +0200 Subject: PIL problems In-Reply-To: <1151092963.150515.153540@c74g2000cwc.googlegroups.com> References: <1151092963.150515.153540@c74g2000cwc.googlegroups.com> Message-ID: defcon8 wrote: > The error I get is: > > Traceback (most recent call last): > File "realautomata.py", line 72, in ? > nim.putdata(y) > File "C:\Python24\Lib\site-packages\PIL\Image.py", line 1120, in > putdata > self.im.putdata(data, scale, offset) > TypeError: too many data entries the error means that you're passing in more items than there are pixels in the target image. adding print nim.size, len(y) before the putdata line should help you figure out what's wrong. From mail at microcorp.co.za Sun Jun 11 01:37:04 2006 From: mail at microcorp.co.za (H J van Rooyen) Date: Sun, 11 Jun 2006 07:37:04 +0200 Subject: Intermittent Failure on Serial Port References: <1149934488.780566.265600@j55g2000cwa.googlegroups.com> Message-ID: <005b01c68d19$150cd860$03000080@hendrik> Serge Orloff wrote: | H J van Rooyen wrote: | > Traceback (most recent call last): | > File "portofile.py", line 232, in ? | > ret_val = main_routine(port, pollstruct, pfifo) | > File "portofile.py", line 108, in main_routine | > send_nak(port, timeout) # so bad luck - comms error | > File "/home/hvr/Polling/lib/readerpoll.py", line 125, in send_nak | > port.flush() | > IOError: [Errno 29] Illegal seek | > close failed: [Errno 29] Illegal seek | > | | | > Where can I find out what the Errno 29 really means? | > Is this Python, the OS or maybe hardware? | | It is from kernel: grep -w 29 `locate errno` | /usr/include/asm-generic/errno-base.h: #define ESPIPE 29 | /* Illegal seek */ | | man lseek: | | ERRORS: | ESPIPE fildes is associated with a pipe, socket, or FIFO. | | RESTRICTIONS: | Linux specific restrictions: using lseek on a tty device | returns ESPIPE. Thanks for the info - so the Kernel sometimes bombs me out - does anybody know why the python flush sometimes calls lseek? - Hendrik From k.retheesh at gmail.com Thu Jun 8 19:49:12 2006 From: k.retheesh at gmail.com (k.retheesh at gmail.com) Date: 8 Jun 2006 16:49:12 -0700 Subject: ValueError: too many values to unpack In-Reply-To: <1149807288.129274.269000@i39g2000cwa.googlegroups.com> References: <1149803076.552465.137150@j55g2000cwa.googlegroups.com> <1149807288.129274.269000@i39g2000cwa.googlegroups.com> Message-ID: <1149810552.526698.157640@y43g2000cwc.googlegroups.com> Thank you, that solved my problem. Thanks Retheesh alisonken1 wrote: > k.retheesh at gmail.com wrote: > > > 56 records were different > > Type, FileType, > > Item, > > Hash, > > > > Path, Size, CullCd, Ext, DtCr, > > DtLMd, DtLAc > > Traceback (most recent call last): > > File > > "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", > > line 310, in RunScript > > exec codeObject in __main__.__dict__ > > File "Q:\PythonScripts\InventoryCompareCase.py", line 234, in ? > > main() > > File "Q:\PythonScripts\InventoryCompareCase.py", line 117, in main > > for (Type,FileType,Item,Hash,Path,Size,CullCd,Ext,DtCr,DtLMd,DtLAc) > > in infoDiffs : > > ValueError: too many values to unpack > > > > Thanks > > Retheesh > > The "too many values to unpack" indicates you don't have enough > variables in the [for (...) in infoDiffs: ] construct. > > You also may want to change some of the names; although "Type" > (variable name) and "type" (python function) should be different, it's > good practice to not use names that are similar to functions. From tim.golden at viacom-outdoor.co.uk Thu Jun 1 04:23:06 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 1 Jun 2006 09:23:06 +0100 Subject: Is device Connected Windows? Message-ID: [placid] | Just wondering is there a way (not brute force) to check if a usb | storage device is connected? Hmmm. How do you identify "a usb storage device" to know that it is or isn't connected? You can certainly do something useful with wmi. eg, import wmi c = wmi.WMI () for usb_disk in c.Win32_DiskDrive (InterfaceType="USB"): print usb_disk.Caption print usb_disk.PNPDeviceID Now, assuming that the PNPDeviceID is unique enough for your purpose, you could probably do something with it to keep hold of it and then check later whether the same device is still inserted. One possibility is to use a WMI watcher to spot when devices are removed: import wmi c = wmi.WMI () usb_watcher = c.watch_for ( notification_type="Deletion", wmi_class="Win32_DiskDrive", delay_secs=2, InterfaceType="USB" ) while True: usb_removed = usb_watcher () # can optionally timeout print usb_removed.PNPDeviceID Lots of other possibilities, a polling loop, two watchers, one for creation one for deletion etc. Depends exactly what your requirements are. 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 ________________________________________________________________________ From rossberg at ps.uni-sb.de Sun Jun 25 10:10:28 2006 From: rossberg at ps.uni-sb.de (rossberg at ps.uni-sb.de) Date: 25 Jun 2006 07:10:28 -0700 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150908952.804184.218990@r2g2000cwb.googlegroups.com> <1150991074.705803.211570@m73g2000cwd.googlegroups.com> Message-ID: <1151244628.566060.40500@p79g2000cwp.googlegroups.com> Joachim Durchholz write: > > Another observation: type safeness is more of a spectrum than a clearcut > distinction. Even ML and Pascal have ways to circumvent the type system, No. I'm not sure about Pascal, but (Standard) ML surely has none. Same with Haskell as defined by its spec. OCaml has a couple of clearly marked unsafe library functions, but no unsafe feature in the language semantics itself. > and even C is typesafe unless you use unsafe constructs. Tautology. Every language is "safe unless you use unsafe constructs". (Unfortunately, you can hardly write interesting programs in any safe subset of C.) > IOW from a type-theoretic point of view, there is no real difference > between their typesafe and not typesafe languages in the "statically > typed" column; the difference is in the amount of unsafe construct usage > in practial programs. Huh? There is a huge, fundamental difference: namely whether a type system is sound or not. A soundness proof is obligatory for any serious type theory, and failure to establish it simply is a bug in the theory. - Andreas From digitalorganics at gmail.com Sun Jun 11 13:35:14 2006 From: digitalorganics at gmail.com (digitalorganics at gmail.com) Date: 11 Jun 2006 10:35:14 -0700 Subject: direct initialization of class attributes vs. declarations w/in __init__ In-Reply-To: <1150043792.136250.99770@u72g2000cwu.googlegroups.com> References: <1150041510.139609.171120@f6g2000cwb.googlegroups.com> <4f2thrF1fd4r4U1@uni-berlin.de> <1150043792.136250.99770@u72g2000cwu.googlegroups.com> Message-ID: <1150047314.025241.260750@c74g2000cwc.googlegroups.com> Wait a minute! It doesn't explain my bugs. I've got "class variables" acting like instance variables. What's weirder is that this behavior occurs on my computer (in both of my installed WinXP copies) but not on my laptop (WinXP Pro). See the following test: class Boo: jerk = "yes" def killjerk(self): self.jerk = self.jerk + "no" print self.jerk print self.__class__.jerk bing = Boo() bing.killjerk() outputs: yesno yes At first, I thought that self.jerk was resolving to the class attribute instead of creating a new variable (w/ a differing scope). But we can see that there are actually two variables because a direct reference to self.__class__.jerk returns "yes", not yesno (what we would get if self.jerk pointed to the same data/object as self.__class__.jerk). Yet, it's treating self.jerk as a combination of the two (it always add the class attribute to the instance attribute). Is this normal behavior?? It doesn't work this way on my laptop... Perhaps you can see why I'd be confused! Thanks. digitalorganics at gmail.com wrote: > Ah, you've brought me much clarity Diez, thank you. That would explain > some "bugs" I've been having... > > > Diez B. Roggisch wrote: > > digitalorganics at gmail.com schrieb: > > > What's the difference between initializing class variables within the > > > class definition directly versus initializing them within the class's > > > __init__ method? Is there a reason, perhaps in certain situations, to > > > choose one over the other? > > > > You are confusing class variables with instance variables. The former > > are what you can initialize inside the class-statement. However, they > > are shared amongst _all_ instances. Consider this little example: > > > > class Foo(object): > > FOO = 1 > > BAR = [] > > > > def __init__(self, FOO): > > self.FOO = FOO > > self.BAR.append(FOO) > > > > def __repr__(self): > > return "FOO: %r\nBAR: %r\n" % (self.FOO, self.BAR) > > > > > > f1 = Foo(1) > > print f1 > > f2 = Foo(2) > > print f2 > > print f1 > > > > > > ------ > > meskal:~/Projects/CameraCalibrator deets$ python2.4 /tmp/test.py > > FOO: 1 > > BAR: [1] > > > > FOO: 2 > > BAR: [1, 2] > > > > FOO: 1 > > BAR: [1, 2] > > > > > > ----- > > > > As you can see, the list BAR is shared. And you can also see that > > _assigning_ to something like this: > > > > self.FOO > > > > will create an instance-variable. Even if a variable of the same name > > existed on the class before! > > > > Which is precisely the difference between using variable initialization > > in __init__ and inside the class-statement. > > > > BTW, > > > > self.__class__.FOO = value > > > > will set class-variables inside a method. Just if you wondered. > > > > Diez From wojciech_mula at poczta.null.onet.pl.invalid Sun Jun 11 14:30:58 2006 From: wojciech_mula at poczta.null.onet.pl.invalid (Wojciech =?iso-8859-2?Q?Mu=B3a?=) Date: Sun, 11 Jun 2006 18:30:58 +0000 (UTC) Subject: math.pow(x,y) References: <1150049976.916474.186580@j55g2000cwa.googlegroups.com> Message-ID: fl1p-fl0p wrote: > import math > math.pow(34564323, 456356) > > will give math range error. > > how can i force python to process huge integers without math range > error? Any modules i can use possibly? You have to use operator **, i.e. 34564323**456356 From webraviteja at gmail.com Thu Jun 29 13:40:12 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 29 Jun 2006 10:40:12 -0700 Subject: what do you guys prefer for ajax? In-Reply-To: <1151600034.678929.90210@y41g2000cwy.googlegroups.com> References: <1151600034.678929.90210@y41g2000cwy.googlegroups.com> Message-ID: <1151602812.704908.163290@j72g2000cwa.googlegroups.com> a wrote: > what do you guys prefer for ajax? > dojo > mochikit > prototype > or somehting else/ I am using OpenLaszlo for a project with a Karrigell (Python) ReST backend. Now strictly speaking, this is not AJAX at the moment. It uses Flash but has the same "asynchronous updates from the server" model. I am waiting for their DHTML engine to mature to switch to it (they just released a preview). The DHTML engine is AJAX and is based on Dojo toolkit. Pro:. 1.) Declarative UI development. 2.) Good look and feel for free. 3.) Comprehensive API for data binding. 4.) Excellent documentation. Cons: 1.) Only Flash available now. You might want to take a look at TurboGears 1.0 preview as well. They have made quite a bit of progress integrating MochiKit. From marshall.spight at gmail.com Wed Jun 21 11:35:34 2006 From: marshall.spight at gmail.com (Marshall) Date: 21 Jun 2006 08:35:34 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> Message-ID: <1150904134.520639.71070@b68g2000cwa.googlegroups.com> Nice post! One question: Anton van Straaten wrote: > > 3. A really natural term to refer to types which programmers reason > about, even if they are not statically checked, is "latent types". It > captures the situation very well intuitively, and it has plenty of > precedent -- e.g. it's mentioned in the Scheme reports, R5RS and its > predecessors, going back at least a decade or so (haven't dug to check > when it first appeared). Can you be more explicit about what "latent types" means? I'm sorry to say it's not at all natural or intuitive to me. Are you referring to the types in the programmers head, or the ones at runtime, or what? Marshall From nmm1 at cus.cam.ac.uk Wed Jun 28 12:40:32 2006 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 28 Jun 2006 16:40:32 GMT Subject: Immutability References: <4Qj*cEjkr@news.chiark.greenend.org.uk> Message-ID: In article , "Fredrik Lundh" writes: |> |> identical? you only applied @property to one of the methods, and then you're |> surprised that only one of the methods were turned into a property? I wasn't expecting EITHER to be turned INTO a property - I was expecting both methods to be the same, but one would have non-default properties attached to it. |> @property turns your "joe" method into a getter method for the (virtual) attribute |> "joe". when you access the attribute, the getter method will be called. whatever |> that method returns will be the attribute's value. Ah! That clarifies a lot. |> that's what the documentation |> says, and that's what your code is doing. Er, no, it doesn't. What it says may well be COMPATIBLE with that, but it is compatible with a good many other interpretations, too. Until and unless you know what it means, you can't extract its meaning from its words. Regards, Nick Maclaren. From david.huard at gmail.com Wed Jun 21 14:06:00 2006 From: david.huard at gmail.com (David Huard) Date: Wed, 21 Jun 2006 14:06:00 -0400 Subject: How to override the doc of an object instance. References: <200606211927.48167.maric@aristote.info> Message-ID: It works ! Wow. Thanks a lot. If you don't mind, I'll post your code to the ipython list so it can be reused. David From sjmachin at lexicon.net Thu Jun 1 08:40:37 2006 From: sjmachin at lexicon.net (John Machin) Date: 1 Jun 2006 05:40:37 -0700 Subject: Tkinter - changing existing Dialog? In-Reply-To: References: <447ED790.20101@lexicon.net> Message-ID: <1149165637.162492.139380@j55g2000cwa.googlegroups.com> Michael Yanowitz wrote: > Hello: > > > I have a Tkinter GUI Dialog with many buttons and labels and text > widgets. > So start a *new* thread. From steve at holdenweb.com Sat Jun 10 08:43:43 2006 From: steve at holdenweb.com (Steve Holden) Date: Sat, 10 Jun 2006 13:43:43 +0100 Subject: Most elegant way to generate 3-char sequence In-Reply-To: <4489F30A.9000006@ucla.edu> References: <1149889784.391965.271570@h76g2000cwa.googlegroups.com> <4489F30A.9000006@ucla.edu> Message-ID: James Stroud wrote: > Rob Cowie wrote: > >>Hi all, >> >>I wish to generate a sequence of the form 'aaa', 'aab', aac'.... 'aba', >>'abb', 'abc' etc. all the way to 'zzz'. >> >>How would you construct a generator to acheive this? >> >>A simple, working but somewhat inelegant solution is... >> >>alpha = ['a','b','c','d'] #shortened for brevity >>alpha2 = ['a','b','c','d'] >>alpha3 = ['a','b','c','d'] >> >>def generator(): >> for char in alpha: >> for char2 in alpha2: >> for char3 in alpha3: >> yield char + char2 + char3 >> >>x = generate() >>x.next() # etc, etc, etc, >> > > > A touch more efficient: > > import string > alpha = string.lowercase > > def generator(choices, length): > length -= 1 > for a in choices: > if length: > for g in generator(choices, length): > yield a + g > else: > yield a > > for a in generator(alpha, 3): > print a > Frankly, this doesn't seem more elegant than the original, particularly once it uses a single string. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From john at castleamber.com Thu Jun 8 18:42:33 2006 From: john at castleamber.com (John Bokma) Date: 8 Jun 2006 22:42:33 GMT Subject: Importing again and again References: <1149796920.757115.290840@h76g2000cwa.googlegroups.com> Message-ID: "Terry Reedy" wrote: > > "John Bokma" wrote in message > news:Xns97DCA4EEBEBEEcastleamber at 130.133.1.4... >>> def foo(): >>> import bar >>> bar.printStuff() >> I am new to Python so this might be a weird question, but it there a >> reason why you import bar inside foo? > > Two possible reasons: > 1) delay import until actually needed, if ever. > 2) put 'bar' into the function local namespace instead of the module > global namespace OK clear and thanks. I was guessing the later, and the first one I overlooked (Perl works different, you have to do the delay yourself). -- John MexIT: http://johnbokma.com/mexit/ personal page: http://johnbokma.com/ Experienced programmer available: http://castleamber.com/ Happy Customers: http://castleamber.com/testimonials.html From ptmcg at austin.rr._bogus_.com Wed Jun 7 19:22:03 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 07 Jun 2006 23:22:03 GMT Subject: Regular Expression question References: <1149714949.542234.148800@y43g2000cwc.googlegroups.com> Message-ID: wrote in message news:1149714949.542234.148800 at y43g2000cwc.googlegroups.com... > Hi, > I am new to python regular expression, I would like to use it to get an > attribute of an html element from an html file? > > for example, I was able to read the html file using this: > req = urllib2.Request(url=acaURL) > f = urllib2.urlopen(req) > > data = f.read() > > my question is how can I just get the src attribute value of an img > tag? > something like this: > (.*)(.*) > > I need to get the href of the image source. > > Thanks. > As Fredrik pointed out, re's are not the only tool out there. Here's a pyparsing solution. -- Paul import pyparsing import urllib # define HTML tag format using makeHTMLTags helper # (we don't really care about the ending tag, # even though makeHTMLTags returns definitions for both # starting and ending tag patterns) imgStartTag, dummy = pyparsing.makeHTMLTags("img") # get HTML source from some web site htmlPage = urllib.urlopen("http://www.yahoo.com") htmlSource = htmlPage.read() htmlPage.close() # scan HTML source, printing SRC attribute from each tag for tokens,start,end in imgStartTag.scanString(htmlSource): print tokens.src Prints: http://us.i1.yimg.com/us.yimg.com/i/ww/beta/edit_plink.gif http://us.i1.yimg.com/us.yimg.com/i/ww/bt1/125.gif http://us.i1.yimg.com/us.yimg.com/i/ww/bt1/13441.gif http://us.i1.yimg.com/us.yimg.com/i/ww/bt1/136.gif http://us.i1.yimg.com/us.yimg.com/i/ww/beta/y3.gif http://us.i1.yimg.com/us.yimg.com/i/ww/bt1/ml.gif http://us.i1.yimg.com/us.yimg.com/i/ww/bt1/my.gif http://us.i1.yimg.com/us.yimg.com/i/ww/bt1/msgn.gif http://us.i1.yimg.com/us.yimg.com/i/ww/v5_mail_t2.gif http://us.i1.yimg.com/us.yimg.com/i/mntl/aut/06q2/hea_0411.gif http://us.i1.yimg.com/us.yimg.com/i/mntl/aut/06q2/img_0607.jpg http://us.i1.yimg.com/us.yimg.com/i/ww/news/2006/06/07/0607notorious_big.jpg http://us.i1.yimg.com/us.yimg.com/i/ww/beta/news/video.gif http://us.i1.yimg.com/us.yimg.com/i/buzz/2006/06/wholefoodssmall.jpg http://us.i1.yimg.com/us.yimg.com/i/mntl/msg/06q2/img_im.jpg http://us.i1.yimg.com/us.yimg.com/i/ww/trfc_bckt.gif http://us.i1.yimg.com/us.yimg.com/i/mntl/sh/04q2/camera.gif From jstroud at ucla.edu Tue Jun 20 22:09:10 2006 From: jstroud at ucla.edu (James Stroud) Date: Tue, 20 Jun 2006 19:09:10 -0700 Subject: Absolute noob to Linux programming needs language choice help In-Reply-To: <1150854682.904891.274480@c74g2000cwc.googlegroups.com> References: <1150854682.904891.274480@c74g2000cwc.googlegroups.com> Message-ID: stylecomputers at gmail.com wrote: > Hey guys, > > I am absolutely new to Linux programming, with no w######s programming > experience except a small amount of C++ console apps. > Reasonably new to Linux, BSD etc, got good sound networking base of > knowledge and dont have any problem working the command line etc. > > I want to learn a language that I can use in my networking duties that > is most likely to be of use to me. I have a few choices I can think of > being: > > Python > Perl > C > > Any other Langs out there that would be better suited? > > I want to be able to use the app's I write in OpenBSD and RH versions > of Linux > > What would you reccomend (Unbiased opinion please, I'm after the > functionality I'll love it later :) ) > > Cheers > > Ty > Yes python will be good for this. I'm not so sure C is better suited. Definitely resist "shell scripting". Several chapters in Mark Lutz's _Programming Python_ will help with networking (after you have read through _Learning Python_ or equivalent). NewRiders publishes _Python Web Programming_ authored by Steve Holden, who visits this list on occasion. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From pythor at gmail.com Fri Jun 23 15:47:49 2006 From: pythor at gmail.com (Pythor) Date: 23 Jun 2006 12:47:49 -0700 Subject: Getting Python scripts to execute in RedHat In-Reply-To: References: <1151081154.003234.299170@r2g2000cwb.googlegroups.com> Message-ID: <1151092069.458957.300610@g10g2000cwb.googlegroups.com> Dennis Lee Bieber wrote: > Now, if you mean you store all your python programs in > "~/pyscripts/" but you want them to run from any directory, you need to > add "~/pyscripts/" to your login PATH definition. If you want to always > make the local directory valid, add the "./". Thank You. Between your explanation and the previous poster's instruction, I've got it. From girish at cse.iitb.ac.in Sun Jun 4 23:49:39 2006 From: girish at cse.iitb.ac.in (Girish Sahani) Date: Mon, 5 Jun 2006 09:19:39 +0530 (IST) Subject: Concatenating dictionary values and keys, and further operations Message-ID: <55123.10.209.4.1.1149479379.squirrel@10.105.1.3> I wrote the following code to concatenate every 2 keys of a dictionary and their corresponding values. e.g if i have tiDict1 = tiDict1 = {'a':[1,2],'b':[3,4,5]} i should get tiDict2={'ab':[1,2][3,4,5]} and similarly for dicts with larger no. of features. Now i want to check each pair to see if they are connected...element of this pair will be one from the first list and one from the second....e.g for 'ab' i want to check if 1 and 3 are connected,then 1 and 4,then 1 and 5,then 2 and 3,then 2 and 4,then 2 and 5. The information of this connected thing is in a text file as follows: 1,'a',2,'b' 3,'a',5,'a' 3,'a',6,'a' 3,'a',7,'b' 8,'a',7,'b' . . This means 1(type 'a') and 2(type 'b') are connected,3 and 5 are connected and so on. I am not able to figure out how to do this.Any pointers would be helpful Here is the code i have written till now: [code] def genTI(tiDict): tiDict1 = {} tiList = [tiDict1.keys(),tiDict1.values()] length =len(tiDict1.keys())-1 for i in range(0,length,1): for j in range(0,length,1): for k in range(1,length+1,1): if j+k <= length: key = tiList[i][j] + tiList[i][j+k] value = [tiList[i+1][j],tiList[i+1][j+k]] tiDict2[key] = value continue continue continue return tiDict2 [/code] Thanks in advance, girish From Serge.Orlov at gmail.com Thu Jun 1 14:02:44 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 1 Jun 2006 11:02:44 -0700 Subject: py2exe & qt4/qimage References: <1149163754.826678.95920@h76g2000cwa.googlegroups.com> Message-ID: <1149184964.329575.292450@y43g2000cwc.googlegroups.com> aljosa wrote: > i'm trying to convert python (image resizer script using PyQt4) script > to exe but support for jpeg and tiff image formats is located in > Qt4.1\plugins\imageformats (dll files) and when script is converted > exe file doesn't support jpeg and tiff. > > i tryed using all file formats in > script: > tmp1 = QImage('images/type.bmp') > tmp2 = QImage('images/type.gif') > tmp3 = QImage('images/type.jpg') > tmp4 = QImage('images/type.png') > tmp5 = QImage('images/type.tif') > > but it doesn't work when i convert script to exe. > any tips on howto include jpeg and tiff image formats support in exe? You need bundle the plugins as data files: http://docs.python.org/dist/node12.html From ptmcg at austin.rr._bogus_.com Thu Jun 15 13:16:00 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Thu, 15 Jun 2006 17:16:00 GMT Subject: code folding, a unique problem to python? References: Message-ID: "John Salerno" wrote in message news:jxfkg.2314$No6.48555 at news.tufts.edu... > Specifically, I'm using UltraEdit and perhaps there's no way perfect way > to implement code folding with it, given how it uses its syntax > highlighting file to do so (i.e., you have to specify an "Opening" and > "Closing" character in which to enfold code, such as braces). > > But my question is more general: is it possible to implement code > folding with Python given that it has no real block delimiters? Or is > this still a matter of which particular editor/IDE you use? For my part > I've tried (as was suggested elsewhere) to use 'def' as an opening and > closing keyword, but this of course will enfold everything between two > defs, even if you have more code between your function definitons (such > as a new class definition). > > So maybe I'm stuck in UE, but I'm curious if there is some general way > to do this, or is Python just too simple and concise for its own good? :) From syl_stand at yahoo.es Wed Jun 14 08:23:41 2006 From: syl_stand at yahoo.es (Davor) Date: 14 Jun 2006 05:23:41 -0700 Subject: convert .pdf files to .txt files References: <1149945556.411580.143850@j55g2000cwa.googlegroups.com> Message-ID: <1150287821.308768.265080@c74g2000cwc.googlegroups.com> Thanks for all you wrote, It will be very usefull to me, at the end I use that code and the file I introduce is converted to .txt on the directory where the file is placed, and in documents written in spanish this do not gives problems on "acentos" in words like "cami?n" or "introducci?n" that was very important to me. Thanks! import os os.system("pdftotext -layout my_pdf_file.pdf") #This will create 'my_pdf_file.txt' file. From michael.f.ellis at gmail.com Thu Jun 1 18:12:23 2006 From: michael.f.ellis at gmail.com (michael.f.ellis at gmail.com) Date: 1 Jun 2006 15:12:23 -0700 Subject: An oddity in list comparison and element assignment References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> Message-ID: <1149199942.955228.281950@u72g2000cwu.googlegroups.com> I believe that 'is' tests equality of reference, such that >>> a = range(1,3) >>> b = range(1,3) >>> a is b False The 'is' operator tells you whether a and b refer to the same object. What I've been discussing is whether == should test for "structural" equality so that a and b remain equivalent under parallel mutations (and also under single mutations to common references) Cheers, Mike Maric Michaud wrote: > Le Jeudi 01 Juin 2006 18:00, michael.f.ellis at gmail.com a ?crit : > > Perhaps the most fundamental notion is mathematics is that the left and > > right sides of an equation remain identical after any operation applied > > to both sides. > > IMHO, you are not aware that the '=' symbol of mathematics exists in python, > it's the 'is' assertion. > > a is b > and then, do what you want with a (or b), a is b remains True. > > THIS is the meaning of expr1 = expr2, but in computer science, this is not as > important as it is in pure logic (most languages do not even provide the 'is' > assertion). > > -- > _____________ > > Maric Michaud > _____________ > > Aristote - www.aristote.info > 3 place des tapis > 69004 Lyon > Tel: +33 426 880 097 From fyleow at gmail.com Tue Jun 13 19:24:59 2006 From: fyleow at gmail.com (fyleow) Date: 13 Jun 2006 16:24:59 -0700 Subject: How do I ignore the errors thrown by the DB api? Message-ID: <1150241099.578287.116400@i40g2000cwc.googlegroups.com> Here's the code I have in place right now. cursor.execute("SELECT link FROM feeds_feed WHERE link=%s", (self.link,)) db.commit() if cursor.rowcount == 0: cursor.execute("INSERT INTO feeds_feed (release_group, title, link, category, pub_date) VALUES (%s, %s, %s, %s, now())", (self.group, self.title, self.link, self.category,)) db.commit() print "Inserting" else: print "Already Exists" Basically the uniqueness of the link attribute is enforced in the database so if I try to insert a value that already exists I get an error that breaks the program. Right now I do a SELECT query first to check if the value already exists. The insert is only executed only if the value doesn't already exist. This is a really bad way of doing things because I'm accessing the DB way more than I need to. It would be great if I could just insert values into the DB and let the uniqueness check at the DB level to either add or refuse the duplicate value. I'm not really interested if a particular value is rejected or added, I just want the most efficient way to insert values. I would really appreciate any suggestions or tips. Thanks. From steven.bethard at gmail.com Wed Jun 21 12:52:54 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 21 Jun 2006 10:52:54 -0600 Subject: returning index of minimum in a list of lists In-Reply-To: <1150905017.886816.81750@m73g2000cwd.googlegroups.com> References: <1150901648.832039.165590@b68g2000cwa.googlegroups.com> <1150905017.886816.81750@m73g2000cwd.googlegroups.com> Message-ID: forman.simon at gmail.com wrote: > JJLaRocque at gmail.com wrote: >> Is there a simple python function to return the list index of the >> minimum entry in a list of lists? >> ie, for [[3,3,3,3], [3,3,3,1], [3,3,3,3]] to return 2,4. >> Or, same question but just for a list of numbers, not a list of lists. > > One way to do this is to generate (value, index-in-main-list, > index-in-secondary-list) tuples and then just take the minimum. > > def f(L): > '''Return indices of the first minimum value in a list of lists.''' > return min( > (n, i, j) > for i, L2 in enumerate(L) > for j, n in enumerate(L2) > )[1:] > > L = [[3, 3, 3, 3], [3, 3, 3, 1], [3, 3, 3, 3]] > > print f(L) # prints (1, 3) I think this is probably the nicest solution. Probably doesn't matter, but it may be worth noting that if you have more than one minimum value, this will return the one with the lowest indices (where indices are ordered lexicographically):: >>> L = [[3, 2, 1], [1, 2, 3], [2, 1, 3]] >>> min((n, i, j) ... for i, L2 in enumerate(L) ... for j, n in enumerate(L2))[1:] (0, 2) STeVe From agr at fq.uniovi.es Wed Jun 28 07:45:48 2006 From: agr at fq.uniovi.es (=?UTF-8?B?w4FuZ2VsIEd1dGnDqXJyZXogUm9kcsOtZ3Vleg==?=) Date: Wed, 28 Jun 2006 13:45:48 +0200 Subject: Beginner question? Classes, variables, ... References: <4getagF1mpqksU1@uni-berlin.de> <4gev94F1mo2p2U1@uni-berlin.de> Message-ID: That wa sneat! Thanks! -- ?ngel Guti?rrez Rodr?guez - agr at fq.uniovi.es Instituto de Ciencia de los Materiales de Madrid - CSIC SpLine - European Syncrothorn Radiation Facility - Grenoble - France Postal adress: Departamento de Qu?mica F?sica y Anal?tica Universidad de Oviedo - c/Juli?n Claver?a 8 33006 - Oviedo Asturias - Spain E-mail: agr at fq.uniovi.es Telf.: +34-985103687 From sreeram at tachyontech.net Thu Jun 8 23:44:23 2006 From: sreeram at tachyontech.net (K.S.Sreeram) Date: Fri, 09 Jun 2006 09:14:23 +0530 Subject: what does %u mean? In-Reply-To: <1149823453.947116.200500@y43g2000cwc.googlegroups.com> References: <1149823453.947116.200500@y43g2000cwc.googlegroups.com> Message-ID: <4488EE97.1020700@tachyontech.net> yaru22 wrote: > In the exercise in my book, it asks me to try print "%u" % (-5) > I'm wondering what this %u mean? Looks like there is *no* difference between '%u' and '%d' in Python. Python 2.4.3 source code: from stringobject.c, formatint function.... if (x < 0 && type == 'u') { type = 'd'; } -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 260 bytes Desc: OpenPGP digital signature URL: From pc at p-cos.net Fri Jun 30 14:03:01 2006 From: pc at p-cos.net (Pascal Costanza) Date: Fri, 30 Jun 2006 20:03:01 +0200 Subject: Reddit broke - should have remained on Lisp? In-Reply-To: <1151684803.210502.68450@d56g2000cwd.googlegroups.com> References: <1151626961.232761.255550@d56g2000cwd.googlegroups.com> <1151662301.891275.166300@d56g2000cwd.googlegroups.com> <1151662812.571023.205500@d56g2000cwd.googlegroups.com> <1151684803.210502.68450@d56g2000cwd.googlegroups.com> Message-ID: <4gl7amF1ntjp8U1@individual.net> olsongt at verizon.net wrote: > Kay Schluehr wrote: >> Please, since this is a Python+Lisp cross-thread and you seem to have >> background info: can you explain why Lisp hackers have turned >> themselves into Python newbies for Reddit impl. and finally complain >> about the language switch? What was cause for their decision to use >> Python in the first place? > > Basically, it was the same complaint everyone else has about common > lisp. It's an awesome language, but there are no reliable standard > crossplatform (and free) libraries for threading and sockets. They > were using FreeBSD as a server, and (trying to) use powerbooks as a dev > platform, and that seriously restricted viable CL implemenations. > > http://redditblog.blogspot.com/2005/12/night-of-living-python.html > http://redditblog.blogspot.com/2005/12/on-lisp.html Compare this to that report: http://groups.google.com/group/comp.lang.lisp/msg/33fec2394f38546b Pascal -- 3rd European Lisp Workshop July 3 - Nantes, France - co-located with ECOOP 2006 http://lisp-ecoop06.bknr.net/ From austuff at gmail.com Wed Jun 14 18:58:02 2006 From: austuff at gmail.com (janama) Date: 14 Jun 2006 15:58:02 -0700 Subject: Newbie wxpython staticbitmap help please Message-ID: <1150325882.038508.122780@g10g2000cwb.googlegroups.com> Hi, how do i go about having my little gui (boa) app updating (changing) the bitmap used in a StaticBitmap automatically. In the example below when i click the button the app check checks to see if a file exists and if so it swaps the StaticBitmap in the gui to another bitmap. Can somewhone add a wx.Timer example to this to make it check if the file exists every minute or so , instead of clicking the button to check and update this? Or is there a better way of auto updating my little gui apps StaticBitmap if a file exists? Thanks for any help with this Regards ################################################ Frame1 # Frame 1 #Boa:Frame:Frame1 import wx import os def create(parent): return Frame1(parent) [wxID_FRAME1, wxID_FRAME1BUTTON1, wxID_FRAME1PANEL1, wxID_FRAME1STATICBITMAP1, ] = [wx.NewId() for _init_ctrls in range(4)] class Frame1(wx.Frame): def _init_ctrls(self, prnt): # generated method, don't edit wx.Frame.__init__(self, id=wxID_FRAME1, name='', parent=prnt, pos=wx.Point(535, 346), size=wx.Size(175, 109), style=wx.DEFAULT_FRAME_STYLE, title='Frame1') self.SetClientSize(wx.Size(167, 75)) self.panel1 = wx.Panel(id=wxID_FRAME1PANEL1, name='panel1', parent=self, pos=wx.Point(0, 0), size=wx.Size(167, 75), style=wx.TAB_TRAVERSAL) self.staticBitmap1 = wx.StaticBitmap(bitmap=wx.Bitmap('Z:/Dan/scripting/python/gui/up1.png', wx.BITMAP_TYPE_PNG), id=wxID_FRAME1STATICBITMAP1, name='staticBitmap1', parent=self.panel1, pos=wx.Point(16, 24), size=wx.Size(32, 32), style=0) self.button1 = wx.Button(id=wxID_FRAME1BUTTON1, label='button1', name='button1', parent=self.panel1, pos=wx.Point(64, 24), size=wx.Size(88, 32), style=0) self.button1.Bind(wx.EVT_BUTTON, self.OnButton1Button, id=wxID_FRAME1BUTTON1) def __init__(self, parent): self._init_ctrls(parent) def OnButton1Button(self, event): if os.path.isfile('Z:/Dan/scripting/python/gui/p1.txt'): i = wx.Image('Z:/Dan/scripting/python/gui/up2.png', wx.BITMAP_TYPE_PNG) b1 = wx.BitmapFromImage(i) self.staticBitmap1.SetBitmap(b1) event.Skip() ################################################ App1 #!/usr/bin/env python #Boa:App:BoaApp import wx import Frame1 modules ={'Frame1': [1, 'Main frame of Application', 'Frame1.py']} class BoaApp(wx.App): def OnInit(self): wx.InitAllImageHandlers() self.main = Frame1.create(None) self.main.Show() self.SetTopWindow(self.main) return True def main(): application = BoaApp(0) application.MainLoop() if __name__ == '__main__': main() From gerkarcher at gmail.com Wed Jun 28 13:14:01 2006 From: gerkarcher at gmail.com (gerkarcher at gmail.com) Date: 28 Jun 2006 10:14:01 -0700 Subject: web Develop question Message-ID: <1151514841.490454.284770@i40g2000cwc.googlegroups.com> hi guys , I' m new to python ...and I would like to ask you , wich is the best template for developing dinamic generated pages using python ? I would like to use something easy to install and develop like php tags and with a lots of features . thanks in advance and sorry for this silly question . regards, richard From cvanarsdall at mvista.com Thu Jun 29 14:58:40 2006 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Thu, 29 Jun 2006 11:58:40 -0700 Subject: to py or not to py ? In-Reply-To: References: Message-ID: <44A422E0.40904@mvista.com> Tom Plunket wrote: > Carl J. Van Arsdall wrote: > > >> Because of the GIL only one thread can actually run at a time. >> > > I've recently been wondering about this, since in the work I do, a lot > of time is spent doing disk I/O. So if I want the UI to remain > responsive, I could spawn an IO thread to handle requests, and do a > pretty simple "just whack new requests onto the queue" without locks > since I'm guaranteed to not have the IO thread read at the same time > as the requestor thread? > > ...what exactly constitutes an atomic operation in Python, anyway? > > Well, although only one thread can run at a time due to the GIL you can't accurately predict when the GIL is going to be released and therefore you don't know when another thread is going to pick up and start going (GIL is released on every so many byte instructs - correct me if i'm wrong, certain operations that have a bit to do with IO, and modules you wrote yourself where you manually release the GIL using macros provided in the C API). If you have your own data structure that is shared among threads you can use the threading modules synchronization constructs to get the job done, using locks, conditions, and events. Queue.Queue is also a good way to go about communicating with threads. > e.g. > > class IoThread: > # ... > > # called from the other thread... > def RequestFile(self, name): > self.fileQueue.append(name) > > # called during the IO thread > def GetNextFile(self); > next = self.fileQueue[0] > self.fileQueue.pop(0) > return next > > ? > -tom! > -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From timr at probo.com Sat Jun 3 19:06:12 2006 From: timr at probo.com (Tim Roberts) Date: Sat, 03 Jun 2006 23:06:12 GMT Subject: Using print instead of file.write(str) References: <2Iq*Jzbir@news.chiark.greenend.org.uk> <44809e93$0$13657$636a55ce@news.free.fr> Message-ID: <1d5482dibl4b4or8d4fkd90pd17ml3st2p@4ax.com> Bruno Desthuilliers wrote: >Sion Arrowsmith a ?crit : >> A.M wrote: >> >>>I found print much more flexible that write method. >> >> "more flexible"? More convenient, yes. More powerful, maybe. But I >> don't see more flexible. Everything print can to stdout.write() can >> do. The reverse isn't true. eg (this appears to be a FAQ on this >> group, although I can't find it in the FAQ): >> >> for x in range(10): >> sys.stdout.write(str(x)) >> >> to print: >> >> 0123456789 > >The reverse isn't true ??? > > print "".join(str(x) for x in range(10)) What he meant it that it is impossible to produce "0123456789" using 10 separate print statements, while it IS possible with 10 separate writes. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From spiralx at gmail.com Sat Jun 3 12:08:09 2006 From: spiralx at gmail.com (James) Date: Sat, 3 Jun 2006 17:08:09 +0100 Subject: How do you practice Python? In-Reply-To: References: <1149150517.034409.292530@g10g2000cwb.googlegroups.com> <1149271920.917381.112910@u72g2000cwu.googlegroups.com> Message-ID: <7ee3dcd80606030908nbd09943j8cf34c217e4cac07@mail.gmail.com> Thirded here. Perhaps better for me is that although I program client-side Java for my job, as much of the backend as possible I code in Python, which makes it easier to do a lot of data processing stuff much simpler than Java would. And it's let me use and understand all of the new features of the language... last time I did it for a job was in the days of Python 1.5.2. Being non-critical utilities on the backend means whenever new features are introduced I can upgrade my code to take advantage of them without worrying about things going wrong as well ;) James On 02/06/06, Jarek Zgoda wrote: > I second that. I moved from Python to J2EE in my job, but I didn't stop > writing Python code for my spare-time projects. Now, when tight schedule > made my project's manager to shift paradigm from buzz to productivity, I > am happy I can write programs in Python again. On AS/400, but still > better than Java... :D > > -- > Jarek Zgoda > http://jpa.berlios.de/ > -- > http://mail.python.org/mailman/listinfo/python-list > From bogus@does.not.exist.com Thu Jun 8 13:52:36 2006 From: bogus@does.not.exist.com (Morpheus) Date: Thu, 8 Jun 2006 19:52:36 +0200 Subject: wxpython: where is the demo? References: Message-ID: <448863e4$0$12642$3b214f66@aconews.univie.ac.at> That's a separate download. Morpheus "John Salerno" wrote in message news:lIYhg.2265$No6.47594 at news.tufts.edu... > I just realized that after installing wxPython, it did not add the usual > menu item to my Start menu (Windows), where I can access the docs and > demo. I searched through the wxPython folder in the site-packages > directory, but I can't seem to find it. > > Anyone know how I can get this back? > > Thanks. From bdesth.quelquechose at free.quelquepart.fr Wed Jun 28 22:23:41 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 29 Jun 2006 04:23:41 +0200 Subject: Immutability In-Reply-To: <44a307a5$0$23554$626a54ce@news.free.fr> References: <4Qj*cEjkr@news.chiark.greenend.org.uk> <44a307a5$0$23554$626a54ce@news.free.fr> Message-ID: <44a3095a$0$23554$626a54ce@news.free.fr> Bruno Desthuilliers a ?crit : > Georg Brandl a ?crit : (snip) >> >> That's another sign that property isn't intended to be used as a >> decorator. >> Normally, decorators wrap functions with other functions. > > > Normally, decorators take a function and return anything appropriate. > >> property doesn't >> return a function but a descriptor object. So do classmethod. >>> classmethod(fun).__get__ >>> >>> classmethod(fun)() Traceback (most recent call last): File "", line 1, in ? TypeError: 'classmethod' object is not callable From eric_brunel at despammed.com Tue Jun 27 09:40:20 2006 From: eric_brunel at despammed.com (Eric Brunel) Date: Tue, 27 Jun 2006 15:40:20 +0200 Subject: Tkinter - Button Overrelief References: <1151409965.666818.179750@y41g2000cwy.googlegroups.com> Message-ID: On Tue, 27 Jun 2006 14:06:05 +0200, Fuzzyman wrote: > Hello all, > > I have some Tkinter buttons that display images. I would like to change > these to 'active' images when the mouse is over the button. > > I see that the button widget can take an 'overrelief' argument in the > constructor. What values can this take ? The same as the 'relief' option, i.e the ones described here: http://www.tcl.tk/man/tcl8.4/TkCmd/options.htm#M-relief Note that Tkinter contains symbolic constants for these values: 'raised' is Tkinter.RAISED, 'flat' is Tkinter.FLAT, and so on. > Also - can anyone provide an example of using the equivalent of a > 'mouseover' event to change the image used by a button in Tkinter ? I'm > afraid google has not helped me much here. The events you're after are '' and ''; see here: http://www.tcl.tk/man/tcl8.3/TkCmd/bind.htm#M7 Here is an example showing how to change the button text (changing the image is similar): -------------------------------- from Tkinter import * root = Tk() b = Button(root, width=8, text='foo') b.pack() def enterB(event): b.configure(text='bar') def leaveB(event): b.configure(text='foo') b.bind('', enterB) b.bind('', leaveB) root.mainloop() -------------------------------- HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From rintaro_m at nifty.com Sun Jun 18 08:14:32 2006 From: rintaro_m at nifty.com (Rintaro Masuda) Date: Sun, 18 Jun 2006 21:14:32 +0900 Subject: Do you know good source codes to study? Message-ID: <001501c692d0$c1fffdb0$020ba8c0@seattleflower> Hi guys, I am about to finish reading the book "Learning Python" which is published by O'reilly. This is a good book and I get basic knowledge of Python from it. I think it's time to read good source codes for the next step. It might be great to join some open source projects. So, do you guys know any good code I can get free? I am thinking of Zope, but It seems to be big for me. Thanks, Rintaro Masuda -------------- next part -------------- An HTML attachment was scrubbed... URL: From rogue_pedro at yahoo.com Mon Jun 26 15:48:32 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 26 Jun 2006 12:48:32 -0700 Subject: break the loop in one object and then return References: <1151343860.239200.179270@c74g2000cwc.googlegroups.com> Message-ID: <1151351312.333699.6300@r2g2000cwb.googlegroups.com> Alex Pavluck wrote: > I am trying to write the following code to block up evaluation and > prompting for entering new information. However, when I break the loop > in one object and then return it does not start at the beginning again > but rather at the point where it exited. Can someone look at the > following code and give me some feedback. > > > > > > yournum = input("I am thinking of a number between 1 and 100.\n Guess > which number: ") > mynum = (yournum-5) > > def eval(): > if yournum == mynum: > print "Wow! You got it!" > elif yournum < mynum: > print "Nope. Too low" > again() > elif yournum > mynum: > print "Oh, your too high" > again() > > def again(): > global yournum > yournum = input("guess again: ") > eval() > > eval() Your code works fine for me. What's the problem exactly? Be aware, 'eval' is a built-in function, you might want to use a different name. And instead of "your" use "you're" the contraction of "you are"-- but that's not a code problem. FWIW, here's another way to structure your program without the recursion you're using. yournum = input("I am thinking of a number between 1 and 100.\n Guess which number: ") mynum = (yournum-5) def loop(): global yournum, mynum while yournum != mynum: if yournum < mynum: print "Nope. Too low" elif yournum > mynum: print "Oh, you're too high" again() print "Wow! You got it!" def again(): global yournum yournum = input("guess again: ") loop() HTH, ~Simon From onurb at xiludom.gro Mon Jun 26 14:31:00 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Mon, 26 Jun 2006 20:31:00 +0200 Subject: Replace Whole Object Through Object Method In-Reply-To: <1151342339.985517.104000@b68g2000cwa.googlegroups.com> References: <1151337453.804750.293180@b68g2000cwa.googlegroups.com> <1151342339.985517.104000@b68g2000cwa.googlegroups.com> Message-ID: <44a027e5$0$29887$636a55ce@news.free.fr> digitalorganics at gmail.com wrote: > Maric Michaud wrote: > (snip) >>This doesn't work in most cases (with new style classes), better recreat a >>type which inherit from Class and Mixin, or Class.__dict__ with >>Mixin.__dict__. > > > What doesn't work exactly? The whole purpose of the mixin is to add > functionality to the class and hence to all its instances on the fly. very na?ve solution: def mixin(obj): def someFunc(self, ...) # code here def someOtherFunc(self, ...) # code here cls = obj.__class__ cls.someFunc = someFunc cls.someOtherFunc = someOtherFunc Just a bit less n?ave solution: def mixin(func): func._mixin = True return func def mixable(func): return getattr(attr, '_mixin', False): class Mixin(object): @mixin def someFunc(self, ...): # code here @mixin def someOtherFunc(self, ...) # code here def mix(cls, mixincls): for name in dir(mixincls): attr = getattr(mixincls, name) if callable(attr) and mixable(attr): setattr(cls, name, attr) Of course, one can do much better... -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From frank at niessink.com Mon Jun 5 05:01:43 2006 From: frank at niessink.com (Frank Niessink) Date: Mon, 05 Jun 2006 11:01:43 +0200 Subject: TreeCtrl to TreeListCtrl In-Reply-To: <20060527124212.23272.qmail@web33101.mail.mud.yahoo.com> References: <20060527124212.23272.qmail@web33101.mail.mud.yahoo.com> Message-ID: <4483F2F7.9080300@niessink.com> sendhil kumar: > Hi all, > whwn working with xml connectvity to python, i have a > sash window, in which first window has a Tree Control > that has 'n' parent fields preceded by + sign and on > leftdown all the childs got from external xml file. > > when the particular parent field is selected and > dragged, it must get posted to the other sash window > which should in TreeList Control, bcoz iam displaying > numerous xml attributes of the parent and following > 'n' number of childs from xml. > > Now, iam facing a problem in implementing with > TreeListCtrl, but it works fne with ListCtrl... And what exactly is your problem? Cheers, Frank From john.thingstad at chello.no Mon Jun 26 02:06:04 2006 From: john.thingstad at chello.no (John Thingstad) Date: Mon, 26 Jun 2006 08:06:04 +0200 Subject: What is Expressiveness in a Computer Language References: <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150904134.520639.71070@b68g2000cwa.googlegroups.com> <1151056505.908723.162580@u72g2000cwu.googlegroups.com> <1151171007.230666.235430@r2g2000cwb.googlegroups.com> <1151224844.569347.167420@r2g2000cwb.googlegroups.com> Message-ID: On Sun, 25 Jun 2006 20:11:22 +0200, Anton van Straaten wrote: > rossberg at ps.uni-sb.de wrote: >>>> In this context, the term "latently-typed language" refers to the >>>> language that a programmer experiences, not to the subset of that >>>> language which is all that we're typically able to formally define. >> That language is not a subset, if at all, it's the other way round, >> but >> I'd say they are rather incomparable. That is, they are different >> languages. > > The "subset" characterization is not important for what I'm saying. The > fact that they are different languages is what's important. If you > agree about that, then you can at least understand which language I'm > referring to when I say "latently-typed language". > > Besides, many dynamically-typed languages have no formal models, in > which case the untyped formal model I've referred to is just a > speculative construct. The language I'm referring to with > "latently-typed language" is the language that programmers are familiar > with, and work with. > >>> That is starting to get a bit too mystical for my tastes. >> I have to agree. >> \sarcasm One step further, and somebody starts calling C a "latently >> memory-safe language", because a real programmer "knows" that his code >> is in a safe subset... And where he is wrong, dynamic memory page >> protection checks will guide him. > > That's a pretty apt comparison, and it probably explains how it is that > the software we all use, which relies so heavily on C, works as well as > it does. > > But the comparison critiques the practice of operating without static > guarantees, it's not a critique of the terminology. > > Anton Actually I have never developed a C/C++ program without a bounds checker the last 15 years. It checks all memory references and on program shutdown checks for memory leaks. What is it about you guys that make you blind to these fact's. Allocation problem's haven't really bugged me at all since forever. Now debugging fluky templates on the other hands.. But then debugging Lisp macro's isn't much better. -- Using Opera's revolutionary e-mail client: http://www.opera.com/mail/ From beni.cherniavsky at gmail.com Fri Jun 9 09:20:30 2006 From: beni.cherniavsky at gmail.com (cben@users.sf.net) Date: 9 Jun 2006 06:20:30 -0700 Subject: Where is the ucs-32 codec? In-Reply-To: <4483649e$0$18311$ba4acef3@news.orange.fr> References: <1149459785.331497.203920@c74g2000cwc.googlegroups.com> <4483649e$0$18311$ba4acef3@news.orange.fr> Message-ID: <1149859229.962904.48480@f6g2000cwb.googlegroups.com> M?ta-MCI wrote: > Hi! > > Look at: http://cjkpython.berlios.de (iconvcodec) > > (Serge Orlov has built a version for Python 2.4 "special for me"; thanks to > him). > Thanks for the pointer. iconvcodec should do the job, but I still want a native implementation to be included with any python. From chris.lasher at gmail.com Thu Jun 15 17:52:35 2006 From: chris.lasher at gmail.com (Chris Lasher) Date: 15 Jun 2006 14:52:35 -0700 Subject: Regular expression for not-group References: <1150405899.027971.256160@r2g2000cwb.googlegroups.com> <1150406322.094263.239930@g10g2000cwb.googlegroups.com> Message-ID: <1150408354.973625.204360@p79g2000cwp.googlegroups.com> Man, that's a headslap-worthy overlooking of the obvious. Ha! =-) I was using the redemo.py that comes standard with Python but that Kodos app looks even neater! Thanks for the tip. Thanks Paddy. Chris From peace.is.our.profession at gmx.de Tue Jun 20 09:05:38 2006 From: peace.is.our.profession at gmx.de (Mirco Wahab) Date: Tue, 20 Jun 2006 15:05:38 +0200 Subject: Seeking regex optimizer In-Reply-To: <1150760365.168277.171940@p79g2000cwp.googlegroups.com> References: <1150650439.651839.38180@y41g2000cwy.googlegroups.com> <1150750294.232093.304230@p79g2000cwp.googlegroups.com> <1150760365.168277.171940@p79g2000cwp.googlegroups.com> Message-ID: Thus spoke andrewdalke at gmail.com (on 2006-06-20 01:39): Hi, are you the A.Dalke from the Schulten group (VMD) as listed here: http://www.ks.uiuc.edu/Overview/People/former.cgi > Replying to me Mirco Wahab wrote: >> If you pull the strings into (?>( ... )) (atomic groups), >> this would't happen. > > Given that Python's re engine doesn't support this feature > it doesn't really help the original poster's problem. Yeah, right. I misunderstood the problem - where it was meant to be 'literally' a problem of capture group id's. I took it metaphorical, which meant to me 'problems by backtracking' (which was wrong). > Even if some future Python did support it, the limit > to 100 named groups is unaffected by backtracking. Right for that one, what I had in mind was something like the following: # naive regex '\d+9' # find some number only if it ends by 9 my $str="1009900000000000000000000000000000000000"; print "non-atomic backtracks: $1\n" if $str =~ / ( \d+9 )/x; print "atomic: matches $1\n" if $str =~ / ( (?>\d+)9 )/x; Second line would not backtrack and not find the 9 behind \d+ because atomic grouping prevents that, so line 1 matches 10099 and line 2 nothing (but very fast, which is the point). >>>> import re >>>> re.compile("(.)"*100) > Traceback (most recent call last): > ... > ... > AssertionError: sorry, but this version only supports 100 named groups >>>> I tried: my $re = '(\d+)\D' x 10000; my $text = join ' ', 0..10000; print $+ if $text =~ /$re/; print "\n", $1001; which prints: 9999 1000 Why is there a named group count restriction in Python? Any reasons one should know? Regards & thanks Mirco From mail at tuxipuxi.org Mon Jun 26 13:48:27 2006 From: mail at tuxipuxi.org (Michael Goettsche) Date: Mon, 26 Jun 2006 19:48:27 +0200 Subject: Beginner Programmer Question In-Reply-To: <1151342733.742416.180370@r2g2000cwb.googlegroups.com> References: <1151342733.742416.180370@r2g2000cwb.googlegroups.com> Message-ID: <44A01DEB.8010100@tuxipuxi.org> kydavis77 at gmail.com wrote: > I am doing alot of reading and trying to teach myself how to program. > I can not figure out how to make "Write a program that continually > reads in numbers from the user and adds them together until the sum > reaches 100." this work. If someone could show me the correct code so i > can learn from that it would be much appreciated. Thanks > sum = 0 while sum <= 100: number = int(raw_input("Enter a number\n")) sum = sum + number print "Finally there" As long as the sum is <= 100 the program asks for a number and adds it to the sum variable. If the variable is >= 100, it exits and outputs the string. From mario.lacunza at gmail.com Fri Jun 9 11:23:28 2006 From: mario.lacunza at gmail.com (Mario Lacunza) Date: Fri, 09 Jun 2006 10:23:28 -0500 Subject: About sizers.. Message-ID: <1149866609.7689.11.camel@localhost.localdomain> Hi, Im build a cross platform application develop with Python and wxPython and I ask for your opinions about if is a good choice use sizers for my frames design? or not? Other techniques? Thanks in advance! Mi configuracion/My config: Ubuntu Dapper 6.06 Linux Kernel 2.6.15.23.386 Python 2.4.3 wxPython 2.6.1.2Pre -- Saludos / Best regards Mario Lacunza V?squez Desarrollador de Software - Webmaster Desarrollador 2 Estrellas VS2005 Website : http://mlacunzav.cogia.net Email : mlacunza[AT]gmail[DOT]com Email : mario_lacunza[AT]yahoo[DOT]es Blog : http://mlacunza.blogspot.com Lima - Peru From larry.bates at websafe.com Fri Jun 2 18:24:01 2006 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 02 Jun 2006 17:24:01 -0500 Subject: Open Source Charting Tool In-Reply-To: <4480ae6c$1@nntp0.pdx.net> References: <1L0gg.1841$Su3.159041@news20.bellglobal.com> <4480ae6c$1@nntp0.pdx.net> Message-ID: <3aCdnbRzDu3gJx3ZnZ2dnUVZ_r-dnZ2d@comcast.com> Ouch. I had a typo. -Larry Scott David Daniels wrote: > Felipe Almeida Lessa wrote: >> Em Sex, 2006-06-02 ?s 16:56 -0400, A.M escreveu: >>> I can't browse to www.reporlab.org, but I found >>> http://www.reportlab.com/ which has a commercial charting product. >>> Is that what you referring to? >> >> ReportLab (the commercial bussiness thing on .com) is where the main >> developers of ReportLab (a library freely available on www.reporlab.org) >> work. So what you want really is .org, but apparently it's having >> problems right now. > Or, you could look for: > http://www.reportlab.org/ > ------------------------^ > > --Scott David Daniels > scott.daniels at acm.org From madpython at gmail.com Mon Jun 26 14:02:06 2006 From: madpython at gmail.com (madpython) Date: 26 Jun 2006 11:02:06 -0700 Subject: Python database access References: <1151295558.067744.91470@b68g2000cwa.googlegroups.com> Message-ID: <1151344926.535968.66450@r2g2000cwb.googlegroups.com> arvind wrote: > Hi all, > I am going to work on Python 2.4.3 and MSSQL database server on > Windows platform. > But I don't know how to make the connectivity or rather which module to > import. > I searched for the modules in the Python library, but I couldn't find > which module to go for. > Please help me out! i suggest pymssql. It doesnt throw runtime error while executing a query where prepackaged odbc module does. From steve at holdenweb.com Wed Jun 7 10:39:33 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 07 Jun 2006 15:39:33 +0100 Subject: THE IMPORTANCE OF MAKING THE GOOGLE INDEX DOWNLOADABLE In-Reply-To: <1149689482.372450.13210@i39g2000cwa.googlegroups.com> References: <1149689482.372450.13210@i39g2000cwa.googlegroups.com> Message-ID: gen_tricomi wrote: > THE IMPORTANCE OF MAKING THE GOOGLE INDEX DOWNLOADABLE > > > > I write here to make a request on behalf of all the programmers on > earth who have been or are intending to use the Google web search API > for either research purposes or for the development of real world > applications, that Google make their indexes downloadable. > Frankly I doubt whether the average programmer possesses sufficient storage or has access to sufficient bandwidth to make downloading the Google indexes a practical proposition - let alone the cached page contents too. There's also the tiny factoid that Google might regard their index structure, not to mention its contents, as proprietary. Finally, how frequently would you propose to update your local copy? Google is adding the results of new spidering to their indices all the time. A nice idea, perhaps, but surely completely impractical. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From gneuner2/ at comcast.net Tue Jun 27 11:42:07 2006 From: gneuner2/ at comcast.net (George Neuner) Date: Tue, 27 Jun 2006 11:42:07 -0400 Subject: What is Expressiveness in a Computer Language References: <34aj92h0g7tqi9amhh7k3ieq5n568t0e6f@4ax.com> Message-ID: On Mon, 26 Jun 2006 13:02:33 -0600, Chris Smith wrote: >George Neuner wrote: > >> I worked in signal and image processing for many years and those are >> places where narrowing conversions are used all the time - in the form >> of floating point calculations reduced to integer to value samples or >> pixels, or to value or index lookup tables. Often the same >> calculation needs to be done for several different purposes. > >These are value conversions, not type conversions. Basically, when you >convert a floating point number to an integer, you are not simply >promising the compiler something about the type; you are actually asking >the compiler to convert one value to another -- i.e., see to it that >whatever this is now, it /becomes/ an integer by the time we're done. >This also results in a type conversion, but you've just converted the >value to the appropriate form. There is a narrowing value conversion, >but the type conversion is perfectly safe. We're talking at cross purposes. I'm questioning whether a strong type system can be completely static as some people here seem to think. I maintain that it is simply not possible to make compile time guarantees about *all* runtime behavior and that, in particular, narrowing conversions will _always_ require runtime checking. >> I can know that my conversion of floating point to integer is going to >> produce a value within a certain range ... but, in general, the >> compiler can't determine what that range will be. > >If you mean "my compiler can't", then this is probably the case. If you >mean "no possible compiler could", then I'm not sure this is really very >likely at all. Again, the discussion is about narrowing the result. It doesn't matter how much the compiler knows about the ranges. When the computation mixes types, the range of the result can only widen as the compiler determines the types involved. George -- for email reply remove "/" from address From rabkinDELETE at mweb.co.za Tue Jun 6 16:35:36 2006 From: rabkinDELETE at mweb.co.za (Max) Date: Tue, 06 Jun 2006 22:35:36 +0200 Subject: newbie: python application on a web page In-Reply-To: <1149624046.762779.225240@h76g2000cwa.googlegroups.com> References: <1149615269.695229.88820@j55g2000cwa.googlegroups.com> <1149624046.762779.225240@h76g2000cwa.googlegroups.com> Message-ID: <9PSdnTgkR_-HehjZnZ2dnUVZ_qidnZ2d@is.co.za> puzz wrote: > sorry about the missunderstanding... > > but my question is "how" and not "where" to put it online > and that's where the "newbie" comes from > > P M If you just want to make it available for download, that's easy. If you want to make it open source, you could upload it to planet-source-code.com (I used to put a lot there; don't know if they have a python section) or SourceForge depending on your "market". But what I think you want is a web interface (where a user goes to your site and uses it in the browser window). This is more tricky, but you're almost certainly going to have to abandon Tkinter. You could try doing an applet in Jython (which compiles Python to Java bytecode so you could in theory do a Java-style applet). The alternative is to have the curve drawn server-side, so you would have an HTML form on the page, and on clicking a button, load the graph (into an "iframe" or something perhaps [I have a feeling iframes have been deprecated - check first]). In which case you'd want to look up CGI, AJAX, etc. --Max From jzgoda at o2.usun.pl Thu Jun 15 12:29:10 2006 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Thu, 15 Jun 2006 18:29:10 +0200 Subject: Which compiler will Python 2.5 / Windows (Intel) be built with? In-Reply-To: <1150388468.149672.30810@i40g2000cwc.googlegroups.com> References: <1150367139.495114.148550@g10g2000cwb.googlegroups.com> <1150388468.149672.30810@i40g2000cwc.googlegroups.com> Message-ID: nikie napisa?(a): > If you want to *buy* VS 2003, you could still purchase a 1-year MSDN > Pro Subscription. The price difference isn't *that* big compared to a > single-user license of VS, and it automatically includes past VS > versions (everything from VC++ 6.0 and upwards, IIRC). This doesn't make building Python exension libraries any easier. In some cases, you can still build Python extension with MinGW. I didn't try this with anything more complicated than linking to libxml2, but still, it's some workaround. Not sure about the performace of such build, though. -- Jarek Zgoda http://jpa.berlios.de/ From ilias at lazaridis.com Fri Jun 9 14:49:15 2006 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Fri, 09 Jun 2006 21:49:15 +0300 Subject: CONSTRUCT - Python's way of Ruby's "alias_method" In-Reply-To: References: Message-ID: Slawomir Nowaczyk wrote: > On Thu, 08 Jun 2006 15:28:39 +0300 > Ilias Lazaridis wrote: > > #> *IMPORT* > #> > #> I would like to know, if this construct is valid, or if it can > #> result in problems (that I do not see as a newcomer): > > The intricacies of import are far beyond me, but FWIW I do not see > anything wrong in this code. > > #> Is there any way (beside a patch) to alter the behaviour to an > #> existing function. > > You can just assign new function to the old name. There are a few > loops to hop through if you want to alter the behaviour of an existing > *method*... There is an example -- I do not know if a good one -- here: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52192 This looks intresting, especially the comment, although I do not understand what is meant by "creates a cycle in the object". " There is a Better Way to Add Methods To Classes, Moshe Zadka, 2001/03/15 This method creates a cycle in the object for no reason at all. The following function will add any function to an instance in a cycle free way: def add_method(self, method, name=None): if name is None: name = method.func_name class new(self.__class__): pass setattr(new, name, method) self.__class__ = new Use as follows: def pretty_str(self): pass add_method(C(), pretty_str, '__str__') " -- http://lazaridis.com From antroy at gmail.com Wed Jun 21 08:29:02 2006 From: antroy at gmail.com (Ant) Date: 21 Jun 2006 05:29:02 -0700 Subject: urllib2 OpenerDirector question on usage. Message-ID: <1150892942.290474.185890@p79g2000cwp.googlegroups.com> Hello all, I am using urllib2 as a part of a web testing tool. One of the things I am testing is the effect of two different people perforing the same actions on the website - do they interfer with each other or not. So to emulate this, I essentially have the following function: def get_opener(): policy = cookielib.DefaultCookiePolicy(rfc2965=True) cj = cookielib.CookieJar(policy) return urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) Now am I right in thinking that since I am creating a separate CookieJar for each opener, then creating two openers and using one for each hypothetical user will achieve this effect - i.e. sessions will be separate from each other in the app, since the openers will return different session cookies back to the server. Cheers, Ant... From maric at aristote.info Thu Jun 1 07:46:16 2006 From: maric at aristote.info (Maric Michaud) Date: Thu, 1 Jun 2006 13:46:16 +0200 Subject: Function mistaken for a method In-Reply-To: References: Message-ID: <200606011346.17442.maric@aristote.info> Le Jeudi 01 Juin 2006 13:34, Peter Otten a ?crit?: > A python-coded function has a __get__ attribute, a C-function doesn't. > Therefore C1.f performs just the normal attribute lookup while C2.f also > triggers the f.__get__(C2(), C2) call via the descriptor protocol which > happens to return a bound method. I don't think it's about c-coded versus python-coded stuff, C1.f is a type, C2.f is a method. In [14]: class t : pass ....: In [15]: class u : ....: f = t ....: ....: In [16]: u().f() Out[16]: <__main__.t instance at 0xa795a9ec> -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From luismgz at gmail.com Fri Jun 2 01:44:44 2006 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 1 Jun 2006 22:44:44 -0700 Subject: Are there something like "Effective Python"? References: <1149224468.481470.74580@i39g2000cwa.googlegroups.com> Message-ID: <1149227084.592329.262420@i39g2000cwa.googlegroups.com> Mike Meng wrote: > Hi all, > I just finished reading Learning Python 3rd ed, and am doing my > first Python application, which retrieves and process text and XML > documents from Web. Python helped me to write the application in a few > hours, I'm very happy with its productivity. But the performance is not > satisfactory. I decide to optimized it in Python before trying C/C++ > extensions. But I don't know Python much and have no clu to tune my > program. Also, I don't know what Pythonist's preferred styles. Are > there any books/documents which play the similar role for Python as > 'Effective C++' does for C++? > > For example, one of my friends read my program and suggest me to > move the re.compile() out of a for-loop, since the regular pattern is > fixed, and re.compile() is slow. I want to find more such advice, where > can I find them? > > Thank you. > > Mike http://wiki.python.org/moin/PythonSpeed/PerformanceTips Also, I suggest checking Psyco ( http://psyco.sourceforge.net/ ), which can easily improve your program's speed with no change in your code. Hope this helps... Luis From deets at nospam.web.de Tue Jun 13 09:50:12 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 13 Jun 2006 15:50:12 +0200 Subject: What's wrong in this HTML Source file of a Bank References: <1150196896.819711.154640@c74g2000cwc.googlegroups.com> <1150204559.415713.288600@h76g2000cwa.googlegroups.com> <1150205478.055121.60300@u72g2000cwu.googlegroups.com> <4f7t7dF1f0g44U1@uni-berlin.de> <1150206298.560467.18420@g10g2000cwb.googlegroups.com> Message-ID: <4f7u6bF1gumngU1@uni-berlin.de> Thaqalainnaqvi at gmail.com wrote: > > I have posted the same question in alt.html but no one yet replied. No wonder. From skip at pobox.com Wed Jun 7 07:07:40 2006 From: skip at pobox.com (skip at pobox.com) Date: Wed, 7 Jun 2006 06:07:40 -0500 Subject: Need pixie dust for building Python 2.4 curses module on Solaris 8 In-Reply-To: <87vereq9ua.fsf@reportlab.com> References: <87vereq9ua.fsf@reportlab.com> Message-ID: <17542.45948.628860.824854@montanaro.dyndns.org> John> Was libncurses.a compiled with -fpic (or -fPIC, if necessary)? John> http://mail.python.org/pipermail/python-dev/2001-March/013510.html When built shared the source was compiled with -fPIC. -fPIC is not used when not built shared. I forced that in a non-shared build. It still gave me the undefined acs32map error. I tried adding either termlib or termcap to the link libraries, as they both provide that symbol: bash-2.03$ nm -p /usr/lib/libtermcap. libtermcap.a libtermcap.so libtermcap.so.1 bash-2.03$ nm -p /usr/lib/libtermcap.so | egrep acs32map 0000245332 B acs32map bash-2.03$ nm -p /usr/lib/libtermcap.a | egrep acs32map 0000000004 D acs32map 0000000000 U acs32map 0000000000 U acs32map 0000000000 U acs32map 0000000000 U acs32map 0000000000 U acs32map I got all sorts of warnings about various symbols having differing sizes: ld: warning: symbol `acs_map' has differing sizes: (file /opt/app/nonc++/ncurses-5.5/lib/libncurses.a(lib_acs.o) value=0x200; file /usr/ccs/lib/libtermcap.so value=0x4); /opt/app/nonc++/ncurses-5.5/lib/libncurses.a(lib_acs.o) definition taken ld: warning: symbol `numnames' has differing sizes: (file /opt/app/nonc++/ncurses-5.5/lib/libncurses.a(names.o) value=0xa0; file /usr/ccs/lib/libtermcap.so value=0x88); /opt/app/nonc++/ncurses-5.5/lib/libncurses.a(names.o) definition taken ... The link succeeded when I added termcap and the generated _curses and _curses_panel modules import successfully. The fact that both modules appear to refer to /usr/lib/libcurses.so.1 now: $ ldd build/lib.solaris-2.8-i86pc-2.4/_curses.so libcurses.so.1 => /usr/lib/libcurses.so.1 libgcc_s.so.1 => /opt/app/nonc++/lib/libgcc_s.so.1 libc.so.1 => /usr/lib/libc.so.1 libdl.so.1 => /usr/lib/libdl.so.1 $ ldd build/lib.solaris-2.8-i86pc-2.4/_curses_panel.so libcurses.so.1 => /usr/lib/libcurses.so.1 libgcc_s.so.1 => /opt/app/nonc++/lib/libgcc_s.so.1 libc.so.1 => /usr/lib/libc.so.1 libdl.so.1 => /usr/lib/libdl.so.1 bothers me since I explicitly asked to get the version I had installed and (based on the warnings above) it appears to have retrieved many symbols from that version. Also, running the unit test seems to hang. It certainly ties up the xterm. Skip From bignose+hates-spam at benfinney.id.au Fri Jun 9 20:13:59 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 10 Jun 2006 10:13:59 +1000 Subject: __getattr__ question References: <4489AE08.2080407@designaproduct.biz> Message-ID: <87fyidyiig.fsf@benfinney.id.au> Laszlo Nagy writes: > This is from the Python documentation (fragment): > > __getattr__( self, name) > Called when an attribute lookup has not found the attribute in the > usual places (i.e. it is not an instance attribute nor is it found in > the class tree for self). name is the attribute name. This method should > return the (computed) attribute value or raise an AttributeError exception. > > > How can I determine if an attribute can be found in the usual places? When the attribute is not found in the usual places, the object's __getattr__ method (if it has one) is called. Thus, when you write your __getattr__ method, you should assume that the attribute has not been found in the usual places. -- \ "If nature has made any one thing less susceptible than all | `\ others of exclusive property, it is the action of the thinking | _o__) power called an idea" -- Thomas Jefferson | Ben Finney From ptmcg at austin.rr._bogus_.com Tue Jun 27 08:48:57 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Tue, 27 Jun 2006 12:48:57 GMT Subject: classes and interfaces References: <1151401318.703216.288850@x69g2000cwx.googlegroups.com> Message-ID: wrote in message news:1151401318.703216.288850 at x69g2000cwx.googlegroups.com... > hi > i come from a non OO environment. now i am learning about classes. can > i ask, in JAva, there are things like interface. eg > public interface someinterface { > public somemethod (); > .... > ... > } > > In python , how to implement interface like the above? is it just > define a class?? > > class someinterface: > def somemethod: blah.... > > thanks > This question crops up every week or two on this list. (This is a healthy indicator of people looking to map their Java learnings to Python. Some of the best programming knowledge I've gained has come from comparing features among different languages, and understanding their respective purposes/strengths/shortcomings. In this case, presence of interfaces in Java) Here are some recent threads that cover this topic: http://groups.google.com/group/comp.lang.python/browse_frm/thread/d5da229b0050725d/47411c8c9322821c?q=java+interface&rnum=20#47411c8c9322821c http://groups.google.com/group/comp.lang.python/browse_frm/thread/d5da229b0050725d/47411c8c9322821c?q=java+interface&rnum=20#47411c8c9322821c Is this in the FAQ? Hmm, these two FAQ's may be related to your question (although you have to know what you're looking for to recognize them): http://www.python.org/doc/faq/general/#how-do-you-specify-and-enforce-an-interface-spec-in-python http://www.python.org/doc/faq/programming/#is-there-a-tool-to-help-find-bugs-or-perform-static-analysis Lastly, you should look into From uval at rz.uni-karlsruhe.de Fri Jun 30 18:06:38 2006 From: uval at rz.uni-karlsruhe.de (=?ISO-8859-1?Q?Sch=FCle_Daniel?=) Date: Sat, 01 Jul 2006 00:06:38 +0200 Subject: How to control permission of file? In-Reply-To: <12ab7bgti9us73@corp.supernews.com> References: <12aavvb7vc58b48@corp.supernews.com> <12ab7bgti9us73@corp.supernews.com> Message-ID: > True, but I don't see what it has to do with my question. my mistake, I misunderstood your question as Sreeram said, os.open can be used help(os.open) Help on built-in function open: open(...) open(filename, flag [, mode=0777]) -> fd Open a file (for low level IO). >>> import os >>> fd=os.open("secret", os.O_WRONLY|os.O_CREAT, 0400) >>> os.write(fd,"not for everybody") 17 >>> os.close(fd) ls -l secret -r-------- 1 root root 17 2006-07-01 00:05 secret Regards, Daniel From spam.noam at gmail.com Thu Jun 8 18:52:29 2006 From: spam.noam at gmail.com (spam.noam at gmail.com) Date: 8 Jun 2006 15:52:29 -0700 Subject: Allowing zero-dimensional subscripts References: <1149801040.936452.26270@i40g2000cwc.googlegroups.com> Message-ID: <1149807149.516004.48590@f6g2000cwb.googlegroups.com> Hello, Terry Reedy wrote: > > In a few more words: Currently, an object can be subscripted by a few > > elements, separated by commas. It is evaluated as if the object was > > subscripted by a tuple containing those elements. > > It is not 'as if'. 'a,b' *is* a tuple and the object *is* subcripted by a > tuple. > Adding () around the non-empty tuple adds nothing except a bit of noise. > It doesn't necessarily matter, but technically, it is not "a tuple". The "1, 2" in "x[1, 2]" isn't evaluated according to the same rules as in "x = 1, 2" - for example, you can have "x[1, 2:3:4, ..., 5]", which isn't a legal tuple outside of square braces - in fact, it even isn't legal inside parens: "x[(1, 2:3:4, ..., 5)]" isn't legal syntax. Noam From skip at pobox.com Wed Jun 28 15:05:08 2006 From: skip at pobox.com (skip at pobox.com) Date: Wed, 28 Jun 2006 14:05:08 -0500 Subject: How to parse timestamps containing milliseconds In-Reply-To: References: Message-ID: <17570.53988.702405.732116@montanaro.dyndns.org> Chris> I'm trying to read a file containing timestamps with milliseconds Chris> ("2006/3/18 8:20:34.050").... When I try to parse I get an error Chris> about the trailing ".050". Chris> How should I approach this? Here's the bad hack I use... def timeparse(t, format): """Parse a time string that might contain fractions of a second. Fractional seconds are supported using a fragile, miserable hack. Given a time string like '02:03:04.234234' and a format string of '%H:%M:%S', time.strptime() will raise a ValueError with this message: 'unconverted data remains: .234234'. If %S is in the format string and the ValueError matches as above, a datetime object will be created from the part that matches and the microseconds in the time string. """ try: return datetime.datetime(*time.strptime(t, format)[0:6]).time() except ValueError, msg: if "%S" in format: msg = str(msg) mat = re.match(r"unconverted data remains:" " \.([0-9]{1,6})$", msg) if mat is not None: # fractional seconds are present - this is the style # used by datetime's isoformat() method frac = "." + mat.group(1) t = t[:-len(frac)] t = datetime.datetime(*time.strptime(t, format)[0:6]) microsecond = int(float(frac)*1e6) return t.replace(microsecond=microsecond) else: mat = re.match(r"unconverted data remains:" " \,([0-9]{3,3})$", msg) if mat is not None: # fractional seconds are present - this is the style # used by the logging module frac = "." + mat.group(1) t = t[:-len(frac)] t = datetime.datetime(*time.strptime(t, format)[0:6]) microsecond = int(float(frac)*1e6) return t.replace(microsecond=microsecond) raise Skip From userprogoogle-139 at yahoo.co.uk Tue Jun 20 05:51:26 2006 From: userprogoogle-139 at yahoo.co.uk (rodmc) Date: 20 Jun 2006 02:51:26 -0700 Subject: USB support References: <1150222139.721785.268830@f14g2000cwb.googlegroups.com> <1150664445.317749.305880@u72g2000cwu.googlegroups.com> Message-ID: <1150797086.130209.74240@i40g2000cwc.googlegroups.com> Thanks, well if what you say is true then it would make sense. Cheers, rod Tim Roberts wrote: > "rodmc" wrote: > > > >Thanks for this, I have managed to build PyUSB and install it in the > >relevant directory. However I get bus errors when I try the PlugUSB.py > >example. Does anyone know why this is likely to be the case? > > > >I am using Macpython 2.4, Libusb 0.1.12 and PyUSB 0.3.3 on an Intel > >based mac. > > It is my understanding that OS/X does not support the /proc filesystem. > Without /proc, libusb cannot operate. > -- > - Tim Roberts, timr at probo.com > Providenza & Boekelheide, Inc. From bapolis at gmail.com Mon Jun 12 05:35:25 2006 From: bapolis at gmail.com (Tgone) Date: 12 Jun 2006 02:35:25 -0700 Subject: Using PHP in Python Message-ID: <1150104925.811155.3550@y43g2000cwc.googlegroups.com> Hello, I've come across sites that discuss embedding Python in PHP, but is it possible to access PHP functions in Python? From onurb at xiludom.gro Wed Jun 14 05:00:36 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 14 Jun 2006 11:00:36 +0200 Subject: Test functions and test discovery In-Reply-To: References: <1150218398.443615.304880@p79g2000cwp.googlegroups.com> Message-ID: <448fd035$0$1806$636a55ce@news.free.fr> Ben Finney wrote: (snip) > if __name__ == "__main__": > test_funcs = [x for name, x in globals() > if name.startswith("test") and hasattr(x, "__call__") > ] Any reason not to use callable(x) here ? (instead of hasattr(x, "__call__")) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From find at my.address.elsewhere Tue Jun 20 11:45:42 2006 From: find at my.address.elsewhere (Matthias Blume) Date: Tue, 20 Jun 2006 10:45:42 -0500 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <4fpvbvF1keed1U1@individual.net> Message-ID: Pascal Costanza writes: > - In a dynamically typed language, you can run programs successfully > that are not acceptable by static type systems. This statement is false. For every program that can run successfully to completion there exists a static type system which accepts that program. Moreover, there is at least one static type system that accepts all such programs. What you mean is that for static type systems that are restrictive enough to be useful in practice there always exist programs which (after type erasure in an untyped setting, i.e., by switching to a different language) would run to completion, but which are rejected by the static type system. By the way, the parenthetical remark is important: If a language's definition is based on a static type system, then there are *no* programs in that language which are rejected by its type checker. That's trivially so because strings that do not type-check are simply not considered programs. > Here is an example in Common Lisp: > > ; A class "person" with no superclasses and with the only field "name": > (defclass person () > (name)) > > ; A test program: > (defun test () > (let ((p (make-instance 'person))) > (eval (read)) > (slot-value p 'address))) > > (slot-value p 'address) is an attempt to access the field 'address in > the object p. In many languages, the notation for this is p.address. > > Although the class definition for person doesn't mention the field > address, the call to (eval (read)) allows the user to change the > definition of the class person and update its existing > instances. Therefore at runtime, the call to (slot-value p 'adress) > has a chance to succeed. I am quite comfortable with the thought that this sort of evil would get rejected by a statically typed language. :-) From python.list at tim.thechases.com Mon Jun 19 14:39:24 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 19 Jun 2006 13:39:24 -0500 Subject: Need Help comparing dates In-Reply-To: <1150741480.160371.234000@g10g2000cwb.googlegroups.com> References: <1150419503.224684.320550@c74g2000cwc.googlegroups.com> <1150741480.160371.234000@g10g2000cwb.googlegroups.com> Message-ID: <4496EF5C.507@tim.thechases.com> > I kept getting a Python error for the following line: > > month = m[webMonth] > > I changed it to month = month_numbers[webMonth] > > and that did the trick. Sorry for the confusion. Often when I'm testing these things, I'll be lazy and create an alias to save me the typing. In this case, I had aliased the month_numbers mapping to "m": >>> m = month_numbers and it slipped into my pasted answer email. You correctly fixed the problem. The purpose of the mapping is simply to resolve the month name to the month number so that the month number can be used. Depending on how predictable the website's date string will be, you can use month_numbers = dict([(date(2006, m, 1).strftime("%b").upper(), m) for m in range(1,13)]) and then use month = month_numbers[webMonth.upper()] or month = month_numbers[webMonth[0:3].upper()] depending on whether the website might return full month names or not. -tkc From diffuser78 at gmail.com Fri Jun 23 09:02:38 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 23 Jun 2006 06:02:38 -0700 Subject: Network Programming in Python In-Reply-To: References: <1151002934.586359.174540@m73g2000cwd.googlegroups.com> Message-ID: <1151067757.353199.238420@g10g2000cwb.googlegroups.com> How will Pyon help my cause ? Bill Maxwell wrote: > On 22 Jun 2006 12:02:14 -0700, diffuser78 at gmail.com wrote: > > >I am a newbie in python. I want to learn and implement a small > >networking concept. Please help me. Every help is appreciated. > > > >I have one Linux Box and one Windows PC. I want to have a daemon > >running on Windows PC which listens on some specicif port number. I > >want to send a TCP/IP or UDP/IP packet from Linux box to Windows PC to > >start some application. As Windows PC recieves such a packet from Linux > >Box it executes a certain .exe file. I want to implement this concept. > > > >In short I want to remotely send command from Linux to Windows PC to > >start a particular application. > > > Have you checked out Pyro (Python Remote Objects)? > > http://pyro.sourceforge.net/ > > Bill From george.sakkis at gmail.com Sun Jun 11 10:16:40 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 11 Jun 2006 07:16:40 -0700 Subject: Very newbie programming References: <448ae8ce_1@news.tm.net.my> <448bb2c7_1@news.tm.net.my> Message-ID: <1150035400.493116.319830@j55g2000cwa.googlegroups.com> TheSaint wrote: > Maric Michaud wrote: > > > Le Samedi 10 Juin 2006 17:44, TheSaint a ?crit : > > >> > > begin using more explicit variable names. > > Frankly it's a very rooted way of programming, since C64 basic :-) If by 'rooted' you mean old enough, so is 'goto'... Except perhaps for iteration variables ("for i in xrange(10)"), always use names that mean something; you (and anyone else that might have to read your code) will thank yourself for doing so if you have to go back at this code a few months later. > > this will do exactly the same > > > > for icon_file in (open(dskt + e) for e in os.listdir(dskt) if '.desktop' > > in e) : > > for line in icon_file : > > if 'URL=/media' in line : > > icon = icon.name > > dvc = line[11:-1] > > break > > > A simple question, how do I'll get out of all loops, once found the right > result? You can set a boolean "found" flag to False, make it True in the if block, check it in the outer loop and break if it is True. For this case though I'd use the fileinput module to iterate over the lines of all files directly (http://docs.python.org/lib/module-fileinput.html): from fileinput import FileInput instram = FileInput([dskt+e for e in os.listdir(dskt) if 'desktop' in e]) for line in instream: if 'URL=/media' in line : icon = instream.filename() dvc = line[11:-1] break Btw, you can delete a file or directory with os.unlink and os.rmdir, respectively; no need for os.system. George From fredrik at pythonware.com Sat Jun 3 05:16:39 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 03 Jun 2006 11:16:39 +0200 Subject: Missing unicode data? In-Reply-To: References: Message-ID: Klaus Alexander Seistrup wrote: > When checking unicodedata.name() against each uchar in the file > /usr/share/unidata/UnicodeData-4.0.1d1b.txt that came with the > console-data package on my Ubuntu Linux installation a total of > 1226 unicode characters seems to be missing from the unicodedata > module (2477 missing characters when checking against the latest > database from unicode.org?). Is this a deliberate omission? I'm pretty sure unicodename.name() doesn't look in the UnicodeData file on your machine, nor in the latest file from unicode.org. in other words, you get whatever version that was used to create the Unicode data set in your Python distribution. this is usually the version that was current when that Python version was originally released (i.e. in your case, when 2.4 was released). iirc, 2.4 uses Unicode 3.2, and 2.5 uses Unicode 4.1. to update, use the tools under Tools/unicode. From nogradi at gmail.com Fri Jun 23 13:54:10 2006 From: nogradi at gmail.com (Daniel Nogradi) Date: Fri, 23 Jun 2006 19:54:10 +0200 Subject: hard to explain for a french ;-) In-Reply-To: <007b01c696c9$dc8c1a40$33067a37@d11610100.cpamalencon.cnamts.fr> References: <007b01c696c9$dc8c1a40$33067a37@d11610100.cpamalencon.cnamts.fr> Message-ID: <5f56302b0606231054u10743a95ke6768492519fa225@mail.gmail.com> > hi everybody, > > i have a problem with a script. > after a research with my directory, i want to do a popup of a person's > photo but i don't know the syntax (i'm a newbie) : > > with a javascript : "">Popup don't work > > with the function window.open : tal:attributes="python:onClick string:javascript:window.open(/Popup > > intranet/nom_agents/'+result.fullname+'/photo)">Popup don't work > > i try that : > > src="user.gif"> it's good but, it's open the photo in a large > window, not in a popup. > > do you understand my problem ? (it's not easy to explain that in english > for me) > thank you for all and have a good day. > Bruce As explained in this thread http://mail.python.org/pipermail/python-list/2006-June/348241.html what you try to do will never work because your attempts are at using python on the client side and only javascript works for that purpose. But for this popup thing javascript is just fine so if all you want to do is this then you don't need python at the first place. HTH, Daniel From jarrod.roberson at gmail.com Wed Jun 7 11:27:11 2006 From: jarrod.roberson at gmail.com (fuzzylollipop) Date: 7 Jun 2006 08:27:11 -0700 Subject: 10GB XML Blows out Memory, Suggestions? In-Reply-To: References: <1149594519.098115.8980@u72g2000cwu.googlegroups.com> <4eleh3F1eguosU1@uni-berlin.de> <1149648187.891942.258300@i40g2000cwc.googlegroups.com> Message-ID: <1149694031.712812.304940@u72g2000cwu.googlegroups.com> Fredrik Lundh wrote: > fuzzylollipop wrote: > > > you got no idea what you are talking about, anyone knows that something > > like this is IO bound. > > which of course explains why some XML parsers for Python are a 100 times > faster than other XML parsers for Python... > dependes on the CODE and the SIZE of the file, in this case processing 10GB of file, unless that file is heavly encrypted or compressed will, the process will be IO bound PERIOD! And in the case of XML unless the PARSER is extremely inefficient, and I assume, that would be an edge case, the parser is NOT the bottle neck in this case. The relativel performance of Python XML parsers is irrelvant in relationship to this being an IO bound process, even the slowest parser could only process the data as fast as it can be read off the disk. Anyone saying that using C instead of Python will be faster when 99% of the time in this case is just waiting on the disk to feed a buffer, has no idea what they are talking about. I work with TeraBytes of files, and all our Python code is just as fast as equivelent C code for IO bound processes. From michele.petrazzo at TOGLIunipex.it Fri Jun 16 14:11:53 2006 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Fri, 16 Jun 2006 18:11:53 GMT Subject: Problem on win xp and run time error Message-ID: Hi list, just found in this moment that my applications stop to work with win xp and receive this error: """ This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information. """ (Note that the same application [python source code + py2exe] with python 2.3.x work well!) With a little google search I found that this is a win xp sp2 problem *without* apparently solution :( http://support.microsoft.com/kb/884538/en-us I see that the page says: """ This problem may occur when you use the /GR and the /MD compiler switches """ so my question are: python are compiled with that switches? If yes, can someone try to compile it without that switches, if it can of course, and publish the new installer? I'm can't work until microsoft solve that issue! :( Thanks, Michele From python at hope.cz Tue Jun 6 02:04:52 2006 From: python at hope.cz (Lad) Date: 5 Jun 2006 23:04:52 -0700 Subject: How to add few pictures into one In-Reply-To: References: <1149511692.796038.155930@c74g2000cwc.googlegroups.com> <1149517433.880564.128350@h76g2000cwa.googlegroups.com> <1149529269.228019.120480@u72g2000cwu.googlegroups.com> Message-ID: <1149573892.526072.6770@i39g2000cwa.googlegroups.com> > > All that I want is this: > > I download ( via Python) some pictures from internet and I want to add > > all these pictures into one =one file/ > > So far, I managed to download pictures but I do not know how to add i > > them nto one file. > > How can I do that? > > Thank you for reply and help > > L. > > > Zip file? Image file? "Add all these pictures into one file" isn't (fro > me) a sufficient specification. I want to to do that as easy as possible. I think the easest way could be add( append) an image to another into an image file so that I can use an image browser and see all pictures in one file. Is that possible? Thank you for reply L. From andyrsmith at googlemail.com Thu Jun 1 04:14:28 2006 From: andyrsmith at googlemail.com (andyrsmith at googlemail.com) Date: 1 Jun 2006 01:14:28 -0700 Subject: Best Python Editor References: Message-ID: <1149149668.113003.142940@j55g2000cwa.googlegroups.com> If we could go back to emacs again for a second... I'm still using emacs but have been playing with a few other ide's (wing, komodo + pydev) are the ones i've given a go recently. However I still end up coming back to emacs for what I consider to be emacs mode's piece of 'killer functionality', (well, killer for me anyway :-) ) which is the C-c C-c shortcut to send the contents of the current buffer to a running interpreter. (i.e. one long-running interpreter that behaves as if the entire buffer had been retyped). Not very useful on first glance, but compared with what I've found to be the 'standard' run-this-script-in-a-new-interpreter function the other ides seem to have it has the following advantages. 1/ No wait for another interpreter to start up 2/ It lets you do the following in a script which lends itself to a much tighter edit-run loop ... try: runOnce except: doSomePainfulDataGathering() runOnce = 1 doSomeLessPainfulDataProcessing() i.e. the painful part will only get executed once, so its cost can be amortized over multiple runs of the script. Of course care has to be taken to ensure the script doesn't violate causality (i.e. code can creep in that depends on variables that haven't yet been initialized) , but in practice I haven't found it to be much of a problem. (And can be checked quickly by simply killing the running interpreter and starting a fresh one). Anyway, the question is whether or not any of the other IDE's support this style of working, (I say I'd *played* with some of them but can't swear I'd dug through every nook and cranny of all of their menu options) Cheers, A. From skip at pobox.com Thu Jun 1 15:37:51 2006 From: skip at pobox.com (skip at pobox.com) Date: Thu, 1 Jun 2006 14:37:51 -0500 Subject: How to format datetime values In-Reply-To: References: Message-ID: <17535.16911.954640.438870@montanaro.dyndns.org> Alan> I have a datetime value and want to format it to "June 1, 2006" Alan> shape. How can I do that? Again, Python's introspection capabilities to the rescue: % pydoct datetime Help on module datetime: NAME datetime - Fast implementation of the datetime type. ... class datetime(date) | datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]]) ... | strftime(...) | format -> strftime() style string. Skip From wegein at gmail.com Wed Jun 21 23:14:37 2006 From: wegein at gmail.com (damacy) Date: 21 Jun 2006 20:14:37 -0700 Subject: python + postgres psql + os.popen Message-ID: <1150946077.931411.170930@u72g2000cwu.googlegroups.com> hello, everyone. i am trying to write a program which executes SQL commands stored in .sql files. i wrote a function called psql() whose contents look like the following. ... os.popen(command) file = os.popen(command, 'w') file.write(password) file.close() ... where command looks like psql -h [host] -d [dbname] -U [username] -W -f "[filename]" this works well. however, it does not show me any warning nor error messages if there is one. for example, i am trying to create a table which already exists in the database, it should show me a warning/error message saying there already is one present in the database, or something like that. can anyone help me? From fuzzyman at gmail.com Mon Jun 5 18:32:16 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 5 Jun 2006 15:32:16 -0700 Subject: C# equivalent to range() In-Reply-To: References: <1149468919.951745.163700@g10g2000cwb.googlegroups.com> <1149481675.192638.275140@c74g2000cwc.googlegroups.com> <1149509893.031953.19310@i40g2000cwc.googlegroups.com> <1149545140.011616.130610@y43g2000cwc.googlegroups.com> Message-ID: <1149546736.728440.74700@i39g2000cwa.googlegroups.com> Erik Max Francis wrote: > Fuzzyman wrote: > > > FWIW I agree. If anyone didn't want to answer the question they didn't > > need to. > > > > Why be rude to someone asking a polite question. It's not as if there > > isn't much more *worse* noise on this group. > > Here were the "harsh" and "whining" responses to his question he's > complaining about: > Fair enough. Maybe they weren't "harsh" and "whining", just patronising and abrupt. Fuzzyman http://www.voidspace.org.uk/python/index.shtml > | Bad guess. Ask questions about language X on comp.lang.X > > | Really, it isn't. Post in a C# discussion forum, describing the > | behaviour you want from your program. > > | *Very* strong suggestion - read the following link: > | > | http://www.catb.org/~esr/faqs/smart-questions.html > > Sorry, if you think those are unacceptable tones for responses to > off-topic questions, the real world is going to be something of an > unpleasant shock. > > He asked a question. He was told how to get the answer. No one was > rude until _he_ started being rude. > > -- > Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ > San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis > Society attacks early when the individual is helpless. > -- B.F. Skinner From spam.noam at gmail.com Fri Jun 9 09:11:05 2006 From: spam.noam at gmail.com (spam.noam at gmail.com) Date: 9 Jun 2006 06:11:05 -0700 Subject: Allowing zero-dimensional subscripts In-Reply-To: References: <1149801040.936452.26270@i40g2000cwc.googlegroups.com> Message-ID: <1149858665.282059.206940@h76g2000cwa.googlegroups.com> Hello, Fredrik Lundh wrote: > (but should it really result in an empty tuple? wouldn't None be a bit > more Pythonic?) I don't think it would. First of all, x[()] already has the desired meaning in numpy. But I think it's the right thing - if you think of what's inside the brackets as a list of subscripts, one for each dimension, which is translated to a call to __getitem__ or __setitem__ with a tuple of objects representing the subscripts, then an empty tuple is what you want to represent no subscripts. Of course, one item without a comma doesn't make a tuple, but I see this as the special case - just like parentheses with any number of commas are interpreted as tuples, except for parentheses with one item without a comma. (By the way, thanks for the tips for posting a PEP - I'll try to do it quickly.) Noam From scott.daniels at acm.org Thu Jun 29 18:31:53 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Thu, 29 Jun 2006 15:31:53 -0700 Subject: style question In-Reply-To: References: <1151314163.701348.195370@u72g2000cwu.googlegroups.com> <1151314474.696043.201250@b68g2000cwa.googlegroups.com> Message-ID: <44a44fa9$1@nntp0.pdx.net> Jorgen Grahn wrote: > On Mon, 26 Jun 2006 11:47:21 +0200, Fredrik Lundh wrote: > ... >> assuming fixed-pitch fonts isn't very Pythonic, though; to get reliable indentation >> no matter what font you're using, you can write [...] > > Since when? I've always coded, in all languages I've ever used[1], under the > assumption that the reader will view it with a fixed-pitch ... font. I assumed > everyone else did, too.... > I like well-typeset code in print though. Bjarne Stroustrup uses an elegant > system for C++ code, .... See Knuth on Literate Programming and the "Web" systems (e.g. CWeb). His goal is to look good typeset with explanation, and extract-to-compile. --Scott David Daniels scott.daniels at acm.org From maric at aristote.info Fri Jun 2 05:26:13 2006 From: maric at aristote.info (Maric Michaud) Date: Fri, 2 Jun 2006 11:26:13 +0200 Subject: how to define a static field of a given class In-Reply-To: <1149239221.045268.6170@g10g2000cwb.googlegroups.com> References: <1149239221.045268.6170@g10g2000cwb.googlegroups.com> Message-ID: <200606021126.14068.maric@aristote.info> Le Vendredi 02 Juin 2006 11:07, feel_energetic a ?crit?: > Hi, > > I already knew how to define a static method of a class( using > staticmethod() ),but I find there isn't a built-in func to build a > static field ( something like staticfield() ) > can anyone help me on this? > thanks very much for your help :) I guess you come from a c++ background, and what you mean by static field is a variable shared by all instance of the class, right ? then, class toto : VAL=5 but, you can't assign directly via instances of the class as it will override VAL in the instance : In [2]: t=toto() In [3]: t.VAL=4 In [4]: toto.VAL Out[4]: 5 In [5]: t.__dict__ Out[5]: {'VAL': 4} You must explicitly modify t.__class__.VAL or toto.VAL : In [8]: t1, t2 = toto(), toto() In [9]: t1.__class__.VAL = 4 In [10]: t2.VAL Out[10]: 4 -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From grflanagan at yahoo.co.uk Sat Jun 3 15:27:41 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 3 Jun 2006 12:27:41 -0700 Subject: grouping a flat list of number by range In-Reply-To: <1149196642.001466.53990@c74g2000cwc.googlegroups.com> References: <1149196642.001466.53990@c74g2000cwc.googlegroups.com> Message-ID: <1149362861.558049.172100@j55g2000cwa.googlegroups.com> joh12005 at yahoo.fr wrote: > hello, > > i'm looking for a way to have a list of number grouped by consecutive > interval, after a search, for example : > > [3, 6, 7, 8, 12, 13, 15] > > => > > [[3, 4], [6,9], [12, 14], [15, 16]] > > (6, not following 3, so 3 => [3:4] ; 7, 8 following 6 so 6, 7, 8 => > [6:9], and so on) Just another 'itertools.groupby' variation. It considers the whole range of numbers spanned by the dataset - eg. in your example, range(3,17) - so possibly not very efficient if the range is large and the data sparse within the range. def get_intervals(data): intervals = [ [], [] ] for k,g in groupby(range(data[0],data[-1]+2), lambda x:x in data): intervals[k].append( list(g)[0] ) #k is 0 or 1 return zip(intervals[1],intervals[0]) a = [3, 6, 7, 8, 12, 13, 15] assert get_intervals(a) == [(3,4),(6, 9),(12,14),(15,16)] Gerard From sjmachin at lexicon.net Thu Jun 15 21:07:47 2006 From: sjmachin at lexicon.net (John Machin) Date: Fri, 16 Jun 2006 11:07:47 +1000 Subject: API functions not working as expected In-Reply-To: <4491edc3$1@nntp0.pdx.net> References: <4491edc3$1@nntp0.pdx.net> Message-ID: <44920463.1000501@lexicon.net> On 16/06/2006 9:51 AM, Kirk McDonald wrote: > ... for reasons that are obvious in retrospect. Specifically, I am > talking about the PyNumber_InPlace* family of functions. For example, > the docs for InPlaceAdd say: > > PyObject* PyNumber_InPlaceAdd(PyObject *o1, PyObject *o2) > Return value: New reference. > Returns the result of adding o1 and o2, or NULL on failure. The > operation is done in-place when o1 supports it. This is the equivalent > of the Python statement "o1 += o2". > > But, of course, numbers are immutable. None of them support in-place > addition. This is not the same as o1 += o2, as o1 is not actually > changed when using this function. > > Am I missing something here? Is there, in fact, no point to these > InPlace* functions? > Well, I guess it all depends on your expectations ... I've never used any of those functions, but after a quick perusal of the manual, here's my expectation: Looking at the heading of the manual section ("Number protocol"), I take that to mean that the contents relate to operations on objects which support some of the (mostly) binary operators usually associated with numbers. I expect that PyNumber_Add will work with numbers, strings, lists, and more. I expect that PyNumber_InPlaceAdd will work like PyNumber_Add for numbers and strings, and do o1.extend(o2) for lists. I expect a similar story with PyNumber_(InPlace)?Or and sets. By the way, I also have an expectation that the core devs don't waste their time and talents writing, testing and documenting pointless functions. Any suspicions that I may have had to the contrary over the time since I was first pointed at Python 1.5.1 have proved to be wrong and founded on my own ignorance. HTH, John From stephanearnold at yahoo.fr Tue Jun 20 02:02:04 2006 From: stephanearnold at yahoo.fr (stephanearnold at yahoo.fr) Date: 19 Jun 2006 23:02:04 -0700 Subject: OS specific command in Python References: <1150781429.090359.148560@c74g2000cwc.googlegroups.com> Message-ID: <1150783324.258644.65770@u72g2000cwu.googlegroups.com> diffuser78 at gmail.com a ?crit : > So basically, instead of typing in on the command line argument I want > to have it in a python program and let it do the action. Try exec() and execfile() from the standard library (IIRC) > > for example. in my program I would want to call the ssh feature like > one does on the command line > > ssh Admin at 192.168.2.10 .....etc > When you connect (via ssh or telnet) to a remote machine, you need to type (manually) your username and your password. Programming that is never easy. If what you need is simulating console interaction, you will need to get Expect. Expect allows you to program/emulate user interaction in a text console, based on the Tool Command Language (a.k.a. Tcl). But there are alternatives : start a SSH daemon written as a shell script. (you just have to enter your login/pass once, then call the daemon to execute some commands) IMHO, Expect is by far the cleanest way. Regards, St?phane From webmaster at garymgordon.com Wed Jun 14 15:22:34 2006 From: webmaster at garymgordon.com (Gary M. Gordon) Date: Wed, 14 Jun 2006 14:22:34 -0500 Subject: python-list@python.org Removed Message-ID: We are sorry to see you leaving Gary M. Gordon, LLC! You will not receive news and information about Gary M. Gordon, LLC anymore. ------------------------------------------------------------------ If you ever want to join Gary M. Gordon, LLC again, simply visit: http://www.garymgordon.com/easylist/easylist.cgi?action=subscribe&submitemail=python-list at python.org and you will be automatically subscribed again. Thanks, Gary M. Gordon, LLC Staff From jcrocholl at googlemail.com Fri Jun 9 17:49:38 2006 From: jcrocholl at googlemail.com (Johann C. Rocholl) Date: 9 Jun 2006 14:49:38 -0700 Subject: Writing PNG with pure Python References: <1149853401.521169.112530@i39g2000cwa.googlegroups.com> Message-ID: <1149889778.182865.181600@f6g2000cwb.googlegroups.com> Alan Isaac schrieb: > It's your code, so you get to license it. > But if you wish to solicit patches, > a more Pythonic license is IMHO more likely > to prove fruitful. What license would you suggest? After some reading at [1] and [2] and [3], I found that the Academic Free License (version 2.1) and the Apache License (version 2.0) are considered helpful for contributions to the Python Software Foundation. So far, I haven't used either of these licenses for my own code, and after a little reading the AFL seems okay for me. I would perhaps consider the LGPL [4] as an alternative because it is less restrictive than the GPL. Thoughts or links, anybody? Cheers, Johann [1] http://www.python.org/moin/PythonSoftwareFoundationLicenseFaq [2] http://www.python.org/psf/records/board/minutes/2004-11-09/ [3] http://www.python.org/psf/contrib/ [4] http://www.gnu.org/licenses/lgpl.html From duncan.booth at invalid.invalid Fri Jun 9 07:35:48 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 9 Jun 2006 11:35:48 GMT Subject: Large Dictionaries References: <1147699064.107490@teuthos> Message-ID: Marcin Ciura wrote: > Tim Peters wrote: >> shellsort is much more a refinement of insertion-sort than of >> bubblesort, but is not an O(N log N) algorithm regardlesss. > > With a judiciously chosen increment sequence, > the number of comparisons made by shellsort > *is* of the order N log N for practical values of N. > See Figure 8 in > http://sun.iinf.polsl.gliwice.pl/~mciura/shellsort.pdf That isn't what the reference says. It only covers N up to a few thousand. Practical values of N need to at least go up into the millions. Read the summary: > Using sequential analysis, the search for optimal increment sequences > for Shellsort was accelerated enough to find them for arrays up to > several thousand elements. ... > However, the sequences obtained so far are too short to draw a > reliable conclusion whether an appropriate sequence of increments can > make Shellsort a O(N logN) sorting method on the average. Some > hypotheses may be possible when the sequences are prolonged to sort > arrays of about 10^5 elements. From girish at cse.iitb.ac.in Mon Jun 5 03:22:29 2006 From: girish at cse.iitb.ac.in (Girish Sahani) Date: Mon, 5 Jun 2006 12:52:29 +0530 (IST) Subject: How to search for substrings of a string in a list? Message-ID: <50436.10.209.4.1.1149492149.squirrel@10.105.1.3> Given a length k string,i want to search for 2 substrings (overlap possible) in a list consisting of length k-1 strings. These 2 substrings when 'united' give the original string. e.g given 'abc' i want to search in the list of 2-length strings ['ab',ac','cd','bc','bd'] to extract either 1) 'ab and 'ac' OR ('a' common) 2) 'ab' and 'bc' OR ('b' common) 3) 'ac' and 'bc' ('c' common) In all these cases, one of the letter is common in the 2 strings. Out of the k-1 letters in each length k-1 string,k-2 will be common. Another e.g is: Given 'abcd' and list ['abc,'abd','bcd'],i must extract 1)abc and abd OR ('ab' common) 2)abc and bcd OR 3)abd and bcd OR Here 2 letters are common in all the solutions. I havent been able to figure out a method. Pleeez help!! Thanks in advance, girish From robert.kern at gmail.com Fri Jun 30 23:38:19 2006 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 30 Jun 2006 22:38:19 -0500 Subject: Concatenating strings In-Reply-To: <1151724830.900116.225960@m79g2000cwm.googlegroups.com> References: <1151724830.900116.225960@m79g2000cwm.googlegroups.com> Message-ID: John Henry wrote: > Sorry if this is a dumb question. > > I have a list of strings (some 10,000+) and I need to concatenate them > together into one very long string. The obvious method would be, for > example: > > alist=["ab","cd","ef",.....,"zzz"] > blist = "" > for x in alist: > blist += x > > But is there a cleaner and faster way of doing this? blist = ''.join(alist) -- 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 From Mike.S.Duffy at gmail.com Sat Jun 17 03:49:51 2006 From: Mike.S.Duffy at gmail.com (Mike Duffy) Date: 17 Jun 2006 00:49:51 -0700 Subject: Legitimate use of the "is" comparison operator? Message-ID: <1150530591.422197.304300@p79g2000cwp.googlegroups.com> I just recently realized that the comparison operator "is" actually works for comparing numeric values. Now, I know that its intended use is for testing object identity, but I have used it for a few other things, such as type checking, and I was just wondering whether or not it is considered bad practice in the Python Community to use it for numerics as well. Example: a = range(5) b = range(5) if len(a) is len(b): print "They're the same size!" else: print "They're not the same size!" From jcarlson at uci.edu Wed Jun 28 18:37:06 2006 From: jcarlson at uci.edu (Josiah Carlson) Date: Wed, 28 Jun 2006 15:37:06 -0700 Subject: sys.settrace() and Python 2.3 Message-ID: <20060628152910.109E.JCARLSON@uci.edu> According to my reading of Python 2.3 docs, the call to goo() at the end should exit with a KeyboardInterrupt... import sys def goo(): while 1: pass count = [100] def foo(frame, event, arg): count[0] -= 1 if not count[0]: raise KeyboardInterrupt return foo sys.settrace(foo) goo() In Python 2.3, the above call to goo() doesn't seem to ever return. It exits with a KeyboardInterrupt in 2.4, as expected. Does anyone have an idea why this is the case? I've checked the release notes for both 2.3 and 2.4 and found no discussion of trace functions in them or sourceforge (I could be entering in the wrong terms, of course). Any pointers as to why there is a difference would be appreciated. Thank you, - Josiah (I'm not subscribed, but I'll be checking for replies, and ccing me on any replies would be appreciated) From tundra at tundraware.com Mon Jun 12 19:03:37 2006 From: tundra at tundraware.com (Tim Daneliuk) Date: 12 Jun 2006 19:03:37 EDT Subject: Combining The Best Of Python, Ruby, & Java?????? Message-ID: So it is claimed: http://www.infoq.com/news/Scala--combing-the-best-of-Ruby-;jsessionid=CC7C8366455E67B04EE5864B7319F5EC Has anyone taken a look at this that can provide a meaningful contrast with Python? -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From marshall.spight at gmail.com Wed Jun 21 14:58:47 2006 From: marshall.spight at gmail.com (Marshall) Date: 21 Jun 2006 11:58:47 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <0%Wlg.3521$MF6.947@tornado.socal.rr.com> <44992e6c$0$664$bed64819@news.gradwell.net> Message-ID: <1150916327.332627.124400@g10g2000cwb.googlegroups.com> Andreas Rossberg wrote: > Chris Uppal wrote: > > > > I have never been very happy with relating type to sets of values (objects, > > whatever). > > Indeed, this view is much too narrow. In particular, it cannot explain > abstract types, which is *the* central aspect of decent type systems. What prohibits us from describing an abstract type as a set of values? > There were papers observing this as early as 1970. References? > (There are also theoretic problems with the types-as-sets view, because > sufficiently rich type systems can no longer be given direct models in > standard set theory. For example, first-class polymorphism would run > afoul the axiom of foundation.) There is no reason why we must limit ourselves to "standard set theory" any more than we have to limit ourselves to standard type theory. Both are progressing, and set theory seems to me to be a good choice for a foundation. What else would you use? (Agree with the rest.) Marshall From micklee74 at hotmail.com Fri Jun 2 21:30:30 2006 From: micklee74 at hotmail.com (micklee74 at hotmail.com) Date: 2 Jun 2006 18:30:30 -0700 Subject: check for dictionary keys Message-ID: <1149298230.864123.8320@u72g2000cwu.googlegroups.com> hi in my code, i use dict(a) to make to "a" into a dictionary , "a" comes from user input, so my program does not know in the first place. Then say , it becomes a = { '-A' : 'value1' , '-B' : "value2" , "-C" : "value3" , '-D' : 'value4' } somewhere next in my code, i will check for these..: 1) -A and -B cannot exist together 2) -A and -C cannot exist together 3) -A and -B and -D cannot exist together 4) and lots of other combinations to check for.... how can i efficiently check for the above? At first as i do simple checks , i use if and else. But as i began to check for more combinatoiuns, it gets messy.... thanks. From jstroud at ucla.edu Mon Jun 26 18:24:03 2006 From: jstroud at ucla.edu (James Stroud) Date: Mon, 26 Jun 2006 15:24:03 -0700 Subject: Having problems with strings in HTML In-Reply-To: References: Message-ID: Kiana Toufighi wrote: > Hi, > > I get a very odd error: > ValueError: unsupported format character 't' (0x74) at index 237 > > Here's my code: > HI_LITE_FILE_NAME = '/var/tmp/out.txt' > > print ''' > href="http://bbc.botany.utoronto.ca/ntools/cgi-bin/ntools_treeview_word.cgi?input=&max=2&values_off=no&remove_bracket=no&show_line_nr=yes&show_link_out=yes&decimal_places=10&show_classification=yes&db=arabidopsis&selection=any%20term&mode=&mode_nos=&yellow_blue=yes&local_file_name=%(OUT_FILE_NAME)s&show_instructions=no&expt_link=NASCArrays&max_adjust=2&view_size=large&highlight=%(HI_LITE_FILE_NAME)s">GraphicalOutput > > ''' % {'OUT_FILE_NAME': OUT_FILE_NAME, 'HI_LITE_FILE_NAME': > HI_LITE_FILE_NAME} > > I wonder if this has something to do with HTML's % character. > > KT > Yes it does. Have a look at urllib.quote and unquote. These may help. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From apgwoz at gmail.com Tue Jun 13 09:39:12 2006 From: apgwoz at gmail.com (Andrew Gwozdziewycz) Date: Tue, 13 Jun 2006 09:39:12 -0400 Subject: .py and running in Windows: In-Reply-To: References: Message-ID: You'll have better results posting this to it's own thread. On Jun 13, 2006, at 9:29 AM, Michael Yanowitz wrote: > Hello: > > Presently in my Windows 2000 system, when I double-click on a > .py file (open it) it automatically runs it in Python. I would > like to change that behavour. That is fine for .pyc file, but > for .py files, I would either like to have it run in Python but > return to the Python shell prompt when finished rather than > exit the shell. How do I do that? > Or would it cause a problem (so that Python no longer works) if > I change the default .py extension to open in an editor rather > than execute it if I open it? > > Thanks: > Michael Yanowitz > > -- > http://mail.python.org/mailman/listinfo/python-list --- Andrew Gwozdziewycz apgwoz at gmail.com http://23excuses.com | http://ihadagreatview.org | http://and.rovir.us From subscriber100 at rjs.org Sat Jun 10 20:20:27 2006 From: subscriber100 at rjs.org (Ray Schumacher) Date: Sat, 10 Jun 2006 17:20:27 -0700 Subject: "parent" in a class __init__ def? Message-ID: <6.2.3.4.2.20060610171649.02d58eb0@rjs.org> Thanks Larry, My depth really only gets to ~3: package module module error_module and usually not that. It is shallow, with >hundred methods (mainly serial protocol defs for LX* telescopes), but it could grow modules, I suppose. I mainly see its use as an import for other, large apps. Speed is not an issue here, just clutter, as you'd said. I also have not seen a written consensus on the "proper" usage of class variables, if any. I define module vars (some constants), which I think is reasonable, although these modules are the type with only one class: port = LXSerial.LXSerial(...) My rationale of putting one class in its own module is to minimize giant module files with lots of long classes; I see only a remote possibility that someone would want call a class without most of the others as well. Ray Ray Schumacher wrote: > > What is the feeling on using "parent" in a class definition that class > > methods can refer to, vs. some other organization ? > > Should all relevant objects/vars just be passed into the method as needed? > > It seems like including "parent" in the class def is just like a class > > variable, which most do not recommend. > Passing parent instance into a class is perfectly legal and is > used extensively in modules like wxPython GUI. It isn't really > anything like a class variable as the instance is normally > passed not the class itself. Each instance can have different > attributes. So if you have many parents with many children this > can be an effective way to structure them. > > I think it depends on how deeply nested things get and how many > parameters need to be passed. I've used it when I want to > nest my objects more than 2 deep and I must pass around lots of > attributes. I find it is easier to just look "upwards" into the > parent to get the attribute than to clutter up my argument list > passing arguments deeper and deeper into the class hierarchy. > It can simplify the argument lists quite a bit. Maybe others can > comment with their thoughts as well. From steve at holdenweb.com Thu Jun 29 08:46:24 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 29 Jun 2006 13:46:24 +0100 Subject: to py or not to py ? In-Reply-To: References: Message-ID: Tom Plunket wrote: > Carl J. Van Arsdall wrote: > > >>Because of the GIL only one thread can actually run at a time. > > > I've recently been wondering about this, since in the work I do, a lot > of time is spent doing disk I/O. So if I want the UI to remain > responsive, I could spawn an IO thread to handle requests, and do a > pretty simple "just whack new requests onto the queue" without locks > since I'm guaranteed to not have the IO thread read at the same time > as the requestor thread? > > ...what exactly constitutes an atomic operation in Python, anyway? > Standard (and excellent) advice to those new to Python: use threading, not thread, and have threads communicate using Queue.Queue(s). regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From vasudevram at gmail.com Mon Jun 26 11:21:28 2006 From: vasudevram at gmail.com (vasudevram) Date: 26 Jun 2006 08:21:28 -0700 Subject: Python database access In-Reply-To: <1151331311.172035.178060@y41g2000cwy.googlegroups.com> References: <1151295558.067744.91470@b68g2000cwa.googlegroups.com> <1151331311.172035.178060@y41g2000cwy.googlegroups.com> Message-ID: <1151335288.099526.207890@m73g2000cwd.googlegroups.com> The odbc module is part of the Python Standard Library. So you can search for docs on using it in the Python2x.chm help file (or the HTML version of the same docs) that comes with the Windows Python disttribution. Its quite easy to use ODBC from Python, at least for simple tasks like "select * from tablename". Vasudev Ram http://www.geocities.com/vasudevram PDF conversion toolkt: http://sourceforge.net/projects/xtopdf BartlebyScrivener wrote: > > But I don't know how to make the connectivity or rather which module to > > import. > > Try mxODBC > > http://www.egenix.com/files/python/mxODBC.html From shejo284 at gmail.com Fri Jun 30 05:46:14 2006 From: shejo284 at gmail.com (Sheldon) Date: 30 Jun 2006 02:46:14 -0700 Subject: Numeric help! References: <1151510615.139278.167520@j72g2000cwa.googlegroups.com> <1151540468.434688.242530@75g2000cwc.googlegroups.com> <1151573125.651727.322660@i40g2000cwc.googlegroups.com> <1151591837.540485.80860@j72g2000cwa.googlegroups.com> Message-ID: <1151660774.576559.298730@h44g2000cwa.googlegroups.com> Carl Banks wrote: > Sheldon wrote: > >Carl Banks wrote: > >> I'm not sufficiently sure this isn't a homework problem, so here's a > >> partial answer. > [snip] > > > > My days as a student is over for the most part. I am learning python on > > my own and Numeric is not properly documented so I am learning by doing > > and copying from others. > > Are you aware of this guide? > > http://numeric.scipy.org/numpydoc/numdoc.htm > > I've seen better documents but it's fairly complete--I wouldn't call it > improper. > > > > I thought about the problem and a solution > > another problem given to me earlier using "putmask" is the solution but > > there is a bug that I cannot figure out: > > ************************ > > index = 0 > > for z in range_va: > > wk = msgva # working arrary > > sattmp = sat_id # working array > > This appears to be doing something you don't expect. In Python all > names are references; assignments don't create new objects but rather > new names for the same object. In the above, wk and msvga are the same > array: any changes in wk also appear in msvga. So wk[1,1] = 4 also > causes msgva[1,1] to be 4. > > Numeric arrays even share data when slicing. If you were to take a > slice of wk, for example, a = wk[0:10,0:10], then modifying a would > also show up in wk (and msvga). (However, slicing most other objects > copies rather than shares the data.) > > It's completely different from Matlab, which always copies data. > > Here's what you should do: > > wk = array(msgva) # this creates a new array for wk > sattmp = array(sat_id) > > > mask = where(equal(wk,z),1,0) # creating a mask of > > valid data pixs > > Note that the "where" is unnecessary here. equal creates an array of > ones and zeros. > > > putmask(sattmp,mask==0,-999) # since zero is valid > > data, -999 is used instead > > This would overwrite sat_id unless you copy the array as I've shown > above. > > > rdata = > > compress(ravel(not_equal(sattmp,-999)),ravel(sattmp)) > > I believe you could avoid the above putmask above step and just use > ravel(mask) as the first argument of compress here, or even just > equal(wk,z). > > "equal(wx,z)", "mask", and "not_equal(sattmp,-999)" are all equal > arrays. > > > if sum(sum(rdata)) == 0: > > av = 0 > > rdata is one-dimensional, so you only need one sum call; but why do > this? average will still work if the sum is zero. > > > else: > > av = average(rdata,axis=None) > > axis argument isn't necessary here since rdata is one-dimesional. > > > tmparray[0,index] = av > > tmparray[1,index] = z > > index += 1 > > print tmparray > > *********************************** > > But the tmparray is returning zeros as averages. When I try just one > > value for z everything works. I can't see where I going wrong. I am not > > using the original arrays, only the copies and when a new z is chosen > > then these are recreated. > > Care to help out with this? > > /Sheldon > > Other than the array sharing mistake, it looks like it should work. > > Also, note that this group disdains top-posting; replies should go > below the quoted text because in these sorts of discussions it's best > to keep things in conversational order, especially for the sake of > other interested readers. > > Good luck. > > > Carl Banks Thanks for the tips about the array and how it is copied. I figured this out late yesterday and wrote a dirty solution to this problem but your is more elegant and concise. Yes, where statement is not needed and I removed it. The replacement is the following: average(compress(ravel(equal(wk,z)),ravel(sattmp)),axis=None) This is much more compact and elegant. Thanks for pointing this out. I don't know why average() returned a divide by zero error and to avoid this I inserted this if statement. Now it works much better ! Much obliged, Sheldon From rschroev_nospam_ml at fastmail.fm Tue Jun 13 05:55:09 2006 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Tue, 13 Jun 2006 09:55:09 GMT Subject: Python 411. In-Reply-To: <1150188399.809316.172840@f14g2000cwb.googlegroups.com> References: <1150152755.474292.39010@j55g2000cwa.googlegroups.com> <1150188399.809316.172840@f14g2000cwb.googlegroups.com> Message-ID: <1Yvjg.479774$tY4.12454945@phobos.telenet-ops.be> Mike T schreef: > What exactly is 411 in this context? A reference to higher education > perhaps? Or perhaps part of the American constitution? What exactly? > Also for that matter what is 101? I don't know about 411, but 101 refers to basic or entry-level courses at universities in the United States. I gathered something like that from context after seeing many references to it; then I finally decided to look it up to be sure about it: http://en.wikipedia.org/wiki/101_%28number%29 under "In other fields". -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From fredrik at pythonware.com Thu Jun 15 13:48:49 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 15 Jun 2006 19:48:49 +0200 Subject: memory leak problem with arrays In-Reply-To: <1150389750.360090.123430@c74g2000cwc.googlegroups.com> References: <1150317325.614389.14770@i40g2000cwc.googlegroups.com> <1150349112.780025.289480@i40g2000cwc.googlegroups.com> <1150389750.360090.123430@c74g2000cwc.googlegroups.com> Message-ID: sonjaa wrote: > "y" is a 500x500 array. a 500x500 array of what ? how did you create the array ? From bearophileHUGS at lycos.com Sat Jun 24 12:49:32 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 24 Jun 2006 09:49:32 -0700 Subject: Python and cellular automata (It works this time!) In-Reply-To: <1151158859.422817.239810@y41g2000cwy.googlegroups.com> References: <1151158859.422817.239810@y41g2000cwy.googlegroups.com> Message-ID: <1151167772.881199.11020@u72g2000cwu.googlegroups.com> Few coding suggestions: - Don't mix spaces and tabs; - Don't write line (comments) too much long; - Don't post too much code here; - For this program maybe Pygame is more fit (to show the images in real time) instead of PIL; - Maybe Psyco can help speed up this program; - Maybe ShedSkin will support part of the cimg library, such kind of programs is fit for it :-) Bye, bearophile From sekhon.hari at googlemail.com Thu Jun 22 07:33:17 2006 From: sekhon.hari at googlemail.com (Hari Sekhon) Date: Thu, 22 Jun 2006 12:33:17 +0100 Subject: What's the best way to wrap a whole script in try..except? In-Reply-To: <4499209c$0$9929$636a55ce@news.free.fr> References: <4499209c$0$9929$636a55ce@news.free.fr> Message-ID: On 21/06/06, Bruno Desthuilliers wrote: > > Hari Sekhon wrote: > > I want to wrap a whole script in try ... except. What is the best way of > > doing this? > > > > Consider the following: - > > > > try: > > import > > > > > > > > def notifyme(traceback): > > code to tell me there is a problem > > > > except Exception, traceback: > > notifyme(traceback) > > > > > > Would this code not work because if any part of encounters an > > exception then it won't reach the notifyme() function definition and > > therefore the whole thing won't work and I won't get notified when a > > traceback occurs, in fact the call to notifyme() under except will > > itself probably trace back as well! > > Yes. > > > Do I have to instead do: > > > > import > > def notifyme(): > > code to tell me there is a problem > > > > try: > > > > > > except Exception, traceback: > > notifyme(traceback) > > > > Would work, but... > > > How you you handle this? > > I don't put the main logic at the top level - I use a main() function. > > import > def notifyme(e): > # code here... > > def main(*args): > try: > # code here > return 0 > > except Exception, e: > notifyme(e) > return > > if __name__ == '__main__': > import sys > sys.exit(main(*sys.argv)) > > -- > bruno desthuilliers > python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for > p in 'onurb at xiludom.gro'.split('@')])" > -- > http://mail.python.org/mailman/listinfo/python-list > Why bother passing the args in def main(*args): and main(*sys.argv)? Couldn't you just use sys.argv straight off inside main, no passing args around.... I can see you are probably a C programmer as well? -h -------------- next part -------------- An HTML attachment was scrubbed... URL: From cowie.rob at gmail.com Sat Jun 10 05:01:24 2006 From: cowie.rob at gmail.com (Rob Cowie) Date: 10 Jun 2006 02:01:24 -0700 Subject: Most elegant way to generate 3-char sequence In-Reply-To: <4489F72C.7010101@lexicon.net> References: <1149889784.391965.271570@h76g2000cwa.googlegroups.com> <4489F72C.7010101@lexicon.net> Message-ID: <1149930084.768576.315300@f6g2000cwb.googlegroups.com> John Machin wrote: > On 10/06/2006 7:49 AM, Rob Cowie wrote: > > Hi all, > > > > I wish to generate a sequence of the form 'aaa', 'aab', aac'.... 'aba', > > 'abb', 'abc' etc. all the way to 'zzz'. > > > > How would you construct a generator to acheive this? > > > > A simple, working but somewhat inelegant solution is... > > You're not wrong. > > > > > alpha = ['a','b','c','d'] #shortened for brevity > > Hope you remember the alphabet correctly. Not sure I understand your point. Why would I forget the alphabet? > Why type all that punctuation? What punctuation? > Any reason this cruft is global (i.e. not local to the generator)? No > > > alpha2 = ['a','b','c','d'] > > alpha3 = ['a','b','c','d'] > > Hope you get the redundant copy/paste right. Again, I don't understand what you mean > > > > > def generator(): > > for char in alpha: > > Why stop at two spaces? One-space indentation is syntactically correct :-) As are 3, 4 and 5 space indentation. Yet again, what is your point? > > > for char2 in alpha2: > > for char3 in alpha3: > > yield char + char2 + char3 > > > > x = generate() > > Did you meant "generator"? Yes, made a mistake > > > x.next() # etc, etc, etc, > > > > |>> def generator(): > ... import string > ... alpha = string.ascii_lowercase > ... for char in alpha: > ... for char2 in alpha: > ... for char3 in alpha: > ... yield char + char2 + char3 > ... > |>> x = generator() > |>> the_lot = list(x) > |>> len(the_lot) == 26 ** 3 > True > |>> [the_lot[i] for i in (0, 1, 25, 26, -27, -26, -1)] > ['aaa', 'aab', 'aaz', 'aba', 'zyz', 'zza', 'zzz'] > > Cheers, > John I'm aware the code I posted is not great - it isn't code I would consider using. It was only intended to serve as an illustration of the task at hand in case my explanation wasn't sufficient. I'm grateful to you for using list(generator) in your example. I was not aware this could be done (I haven't yet fully read the generator documentation). Rob C From fredrik at pythonware.com Sun Jun 11 17:52:32 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 11 Jun 2006 23:52:32 +0200 Subject: direct initialization of class attributes vs. declarations w/in __init__ In-Reply-To: <1150062413.303012.177330@f6g2000cwb.googlegroups.com> References: <1150041510.139609.171120@f6g2000cwb.googlegroups.com> <4f2thrF1fd4r4U1@uni-berlin.de> <1150043792.136250.99770@u72g2000cwu.googlegroups.com> <1150047314.025241.260750@c74g2000cwc.googlegroups.com> <1150062413.303012.177330@f6g2000cwb.googlegroups.com> Message-ID: digitalorganics at gmail.com wrote: > Any clue what's behind this behavior? a missing plus sign. From bucodi at yahoo.fr.invalid Tue Jun 20 06:29:08 2006 From: bucodi at yahoo.fr.invalid (Rony Steelandt) Date: Tue, 20 Jun 2006 12:29:08 +0200 Subject: Specifing arguments type for a function References: <4fq09iF1k0h0eU1@uni-berlin.de> Message-ID: > Paolo Pantaleo wrote: > >> I have a function >> >> def f(the_arg): >> ... >> >> and I want to state that the_arg must be only of a certain type >> (actually a list). Is there a way to do that? > > Yes and no. You can ensure that the passed object is a list, by calling e.g. > > def f(arg): > if not isinstance(arg, list): > raise "Not a list!" > > > Alternatively, you can just use it as an iterable - and the exception will > come from arg not being iterable. > > But what you can't do is make python complain about this: > > def f(arg): > for e in arg: > print e > > > f(100) > > before actually calling f. It will always fail at runtime. > > Diez What about def f(arg): if type(arg)=='list': #do something -- --- Rony Steelandt BuCodi rony dot steelandt (at) bucodi dot com Visit the python blog at http://360.yahoo.com/bucodi From wahab at chemie.uni-halle.de Thu Jun 22 13:48:57 2006 From: wahab at chemie.uni-halle.de (Mirco Wahab) Date: Thu, 22 Jun 2006 19:48:57 +0200 Subject: Absolute noob to Linux programming needs language choice help In-Reply-To: <1150854682.904891.274480@c74g2000cwc.googlegroups.com> References: <1150854682.904891.274480@c74g2000cwc.googlegroups.com> Message-ID: Thus spoke stylecomputers at gmail.com (on 2006-06-21 03:51): > I want to learn a language that I can use in my networking duties that > is most likely to be of use to me. I have a few choices I can think of > being: > > Python > Perl > C C is not really a choice in the perimeter of Perl and Python. Perl was created to do "networking duties" in the Unix environment and had a phenomenal impact, was (then) also a long time the number #1 scripting language for web apps ('CGI' was almost synonymously used w/Perl). Then came Python, which was (iirc) also intended for solving problems around "networking duties" by the GvR, who didn't like the appearance of Perl-Programs (couldn't stand sigils and braces, I guess;-). So it's today just a matter of 1) personal taste, what do think is fancier for you, 2) choice of the community you want to be in. BTW. I don't really think its a "choice" at all, I'd use each language where it applies best. > Any other Langs out there that would be better suited? Never ever ;-) Regards Mirco From kay.schluehr at gmx.net Fri Jun 9 02:59:22 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 8 Jun 2006 23:59:22 -0700 Subject: dynamic inheritance In-Reply-To: <_IidnWMwvOnfRBXZnZ2dneKdnZydnZ2d@comcast.com> References: <_IidnWMwvOnfRBXZnZ2dneKdnZydnZ2d@comcast.com> Message-ID: <1149836362.271889.162580@j55g2000cwa.googlegroups.com> alf wrote: > is there any way to tell the class the base class during runtime? > > a. Example: >>> class A(object):pass >>> class B(A):pass >>> B.mro() [, , ] See also Micheles nice article about the semantics of the "mro" ( method resolution order). http://www.python.org/download/releases/2.3/mro/ Regards, Kay From petr at tpc.cz Wed Jun 14 17:02:24 2006 From: petr at tpc.cz (Petr Jakes) Date: 14 Jun 2006 14:02:24 -0700 Subject: Simple Char-I/O Dialogs for Win32 and DOS In-Reply-To: <1150309820.174088.6960@f6g2000cwb.googlegroups.com> References: <1150309820.174088.6960@f6g2000cwb.googlegroups.com> Message-ID: <1150318944.566439.186810@g10g2000cwb.googlegroups.com> Mr Roboto wrote: > Folks: > > I've already searched the group and have determined there *are* > char I/O based input systems, ala NCURSES, that are > Python-compatible (ie. PyNCurses, UrWid, etc.) What I *need* is > something that does simple dialogs under char-I/O Win32 and DOS > w/ very little fuss or muss. At most, I need one or two dialog > boxes to boot my little app/util *AND* hope upon hope I don't > need port something (which would take more days than I have > *and* would also require a non-trivial support effort from a > one-man show: *me*) and can simply grab something (open-source) > off-the-shelf. I don't need a dialog/forms designer, no > database access, just a basic dialog box to get input from a > couple of text boxes, check boxes, etc. > > Does such an animal exist and can someone offer a link to the > kit ? TIA....MR You can try: Dialog http://invisible-island.net/dialog/ HTH Petr Jakes From robin at NOSPAMreportlab.com Sat Jun 24 10:49:10 2006 From: robin at NOSPAMreportlab.com (Robin Becker) Date: Sat, 24 Jun 2006 14:49:10 +0000 Subject: Kamaelia 0.4.0 RELEASED - Faster! More Tools! More Examples! More Docs! ;-) In-Reply-To: <449D4E3C.8080508@jessikat.plus.net> References: <4499c9de$0$69378$ed2619ec@ptn-nntp-reader01.plus.net> <449D4E3C.8080508@jessikat.plus.net> Message-ID: <449D50E6.4040103@jessikat.plus.net> Robin Becker wrote: > Michael wrote: >> Hi! >> >> >> (OK, slightly silly subject line :) >> >> I'm extremely pleased to say - Kamaelia 0.4.0 has been released! >> . whoops, forgot to say thanks as I think this is very nice work -- Robin Becker From martin.witte at gmail.com Mon Jun 12 04:51:20 2006 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 12 Jun 2006 01:51:20 -0700 Subject: Function to remove elements from a list not working (corrected) In-Reply-To: References: Message-ID: <1150102280.505268.174420@u72g2000cwu.googlegroups.com> Girish Sahani wrote: > Hi, > I am trying to modify a list of pairs (l4) by removing those > pairs which are not present in a third list called pairList. > The following is a simplified part of the routine i have written. However > it does not give the correct output. Please help! > Its possible i have made a trivial mistke since i am a newbie. > > def getl5(): > l5 = [] > pairList = [[1,2],[3,4],[3,5],[3,6],[9,7],[8,9],[8,7],[7,9],[11,10]] > l4 = [[4,2],[4,7],[4,10],[4,12],[9,2],[9,7],[9,10],[9,12],[11,2],[11,7]] > for pair in l4: > if pair not in pairList: > l4.remove(pair) > print "l4 is",l4 > > The output given is: > l4 is [[4, 7], [4, 12], [9, 7], [9, 12], [11, 7]] It is better to iterate over a copy, e.g. like this: pairList = [[1,2],[3,4],[3,5],[3,6],[9,7],[8,9],[8,7],[7,9],[11,10]] l4 = [[4,2],[4,7],[4,10],[4,12],[9,2],[9,7],[9,10],[9,12],[11,2],[11,7]] for pair in l4[:]: if pair not in pairList: l4.remove(pair) print "l4 is",l4 From sjmachin at lexicon.net Mon Jun 26 21:32:02 2006 From: sjmachin at lexicon.net (John Machin) Date: Tue, 27 Jun 2006 11:32:02 +1000 Subject: Extracting 3-byte integers In-Reply-To: <44a074f5$1@news.eftel.com> References: <44a074f5$1@news.eftel.com> Message-ID: <44a08a91$1@news.eftel.com> On 27/06/2006 9:59 AM, John Machin wrote: > On 27/06/2006 9:36 AM, Bob Greschke wrote: >> I have some binary data read from a file that is arranged like >> >> <3-byte int> <3-byte int> <3-byte int> etc. >> >> The "ints" are big-endian and there are 169 of them. Is there any >> clever way to convert these to regular Python ints other than (struct) >> unpack'ing them one at a time and doing the math? >> > > I'd call that "arithmetic", not "math" :-) > > Here's another way, not touted as "clever": > > |>> guff = "\x00\x00\x01\x00\x02\x01\x03\x00\x00\x00\x00\xFF" > |>> import array > |>> b = array.array('B', guff) > |>> actual = [b[x]*65536 + b[x+1]*256 + b[x+2] for x in range(0, len(b), > 3)] Two further points: (1) If using struct.unpack, it's not necessary to unpack 3 bytes at a time; one could substitute b = struct.unpack('507B', guff) in the above. (2) The OP didn't specify whether the ints were signed or unsigned. The above is for unsigned. To convert an unsigned X to signed, here's the "math": if X >= 0x800000: X -= 0x1000000 Cheers, John From webraviteja at gmail.com Sat Jun 17 15:35:23 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 17 Jun 2006 12:35:23 -0700 Subject: code is data In-Reply-To: <1150566924.066371.323110@c74g2000cwc.googlegroups.com> References: <1150566924.066371.323110@c74g2000cwc.googlegroups.com> Message-ID: <1150572923.369099.288220@h76g2000cwa.googlegroups.com> Paddy wrote: > Anton Vredegoor wrote: > > With the inclusion of ElementTree (an XML-parser) in Python25 and recent > > developments concerning JSON (a very Pythonesque but somewhat limited > > XML notation scheme, let's call it statically typed XML) > > > > Your thoughts please. > > > > Anton > > Hi Anton. > If you mean this JSON: http://www.json.org/example.html > then I'd just point out that JSON isn't XML-like at all. In fact the > examples look like valid Python nested dictionaries. It is the same JSON. JSON is typically seen as a human friendly replacement for some of the functions that XML is otherwise used for, where the full blown XML spec is an overkill and JSON does not need complicated parsers in some common languages because it can express hierarchical data just like XML. From grante at visi.com Fri Jun 23 11:39:13 2006 From: grante at visi.com (Grant Edwards) Date: Fri, 23 Jun 2006 15:39:13 -0000 Subject: Network Programming in Python References: <1151002934.586359.174540@m73g2000cwd.googlegroups.com> <1151067757.353199.238420@g10g2000cwb.googlegroups.com> Message-ID: <129o2p1l3149579@corp.supernews.com> On 2006-06-23, diffuser78 at gmail.com wrote: > How will Pyon help my cause ? What's Pyon? -- Grant Edwards grante Yow! We are now enjoying at total mutual interaction in visi.com an imaginary hot tub... From onurb at xiludom.gro Tue Jun 27 11:32:02 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Tue, 27 Jun 2006 17:32:02 +0200 Subject: Unbound Local error? How? In-Reply-To: References: Message-ID: <44a14f72$0$16244$636a55ce@news.free.fr> Hari Sekhon wrote: > I've got some code as follows: > > import re > re_regexname = re.compile('abc') > > ..... > ..... various function defs > ..... > > def func1(): > ... > func2() > ... > > def func2(): > if re_regexname.match('abc'): > > > if __name__ == '__main__': > func1() > > > but this returns the Traceback: > > UnboundLocalError: local variable 're_regexname' referenced before > assignment this is *not* the traceback. This is only the error message. The traceback contains all needed informations (or at least all possible information at this point) to know what happened. But you did not post the traceback. Nor did you post the minimal runnable code snippet producing this error. > > How? How could we know ? -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From meng.yan at gmail.com Mon Jun 5 12:24:57 2006 From: meng.yan at gmail.com (Mike Meng) Date: 5 Jun 2006 09:24:57 -0700 Subject: [twisted] PyOpenSSL and PyCrypto are outdated! Message-ID: <1149524697.220261.73510@c74g2000cwc.googlegroups.com> Hi all, I'm learning Twisted and downloaded pyOpenSSL and pycrypto win32 installer on http://twisted.sourceforge.net/contrib/ . But I find the lastest version are for Python 2.3. I try to rebuild pyOpenSSL from source, but get lots of compile errors. Are these two packages obsolated? Where can I find updated version? Thank you in advance. From gandalf at designaproduct.biz Fri Jun 30 05:54:33 2006 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Fri, 30 Jun 2006 11:54:33 +0200 Subject: No error while sending via TCP Socket In-Reply-To: <1151659739.850068.287190@d56g2000cwd.googlegroups.com> References: <1151659739.850068.287190@d56g2000cwd.googlegroups.com> Message-ID: <44A4F4D9.6060606@designaproduct.biz> Ben Sizer ?rta: > Martin B?rkle wrote: > >> I have writen a programm using TCP sockets. After i get the connection >> to another socket I cut the Ethernet cable. Then I send a message. >> The program doesnt raise any exception. Can somebody tell me why and >> give me a hint how to get an exception >> > > Have you tried waiting 30 seconds or so? The connection may just take a > while to time out. > I'm not sure if this will help him. He told that the program doesn't raise an exception. I suppose this also means that socket.send() was successful. If his program does not want to send or receive anything else, then he will not get an exception. Otherwise if socket.send() blocks his program, then you are right - he needs to wait. But I think he would have seen that his program is still running, and he would not have written what he wrote. If his program is still running, than he shouldn't have told "it did not raise an exception". :-) Laszlo From larry.bates at websafe.com Fri Jun 9 19:30:19 2006 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 09 Jun 2006 18:30:19 -0500 Subject: First question on extending Python... In-Reply-To: References: Message-ID: <448A048B.7000007@websafe.com> Redefined Horizons wrote: > I still new to Python, and I've only dabbled in C, but I've got my > first project I need to tackle that involves both languages. I was > hoping to get some advice on how to proceed. > > There is a third-party application that I need to work with. It is > closed-source, but it exposes a C API. I want to wrap this C API so > that it is available from Python. I have no ability to modify the C > API of the third part application. > > Do I the C functions that I wrap in an extensions module for Python > need to be in a certian format? If so, I will have to write an > intermediate DLL in C that wraps the third-party application and > exports the functions in a form that Python can use. > > Or can an extension module for Python wrap any C function? If this is > the case I think I can skip the intermediate C DLL. > > Are there any advantages to using the intermediate DLL written in C in > this particular case where I will not have ability to manipulate the C > API of the third party application directly? (For example, if the > third-party application developers are willing to call a "call-back" > function that must be written in C, but not Python. Could the same > extension module export both C functions and serve as a Python > module?) > > Thanks, > > Scott Huey John Machin has answered most of your questions in a separate post. All you need is to take a look at ctypes module for Python. You can call virtually any C based API that is stored in a .DLL using ctypes. I've called .DLL APIs for Castelle's Faxpress, Expervision's OCR toolkit and Softrak's ADS.DLL with no problems. The trick is creating some functions/classes that help with the C structures that need to be passed back and forth. For that you will probably also need to take a look at the Python struct module, but ctypes has some built-in helper functions also. ctypes can be located here: http://starship.python.net/crew/theller/ctypes/ -Larry Bates From scott.daniels at acm.org Tue Jun 20 13:41:03 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Tue, 20 Jun 2006 10:41:03 -0700 Subject: comparing two arrays In-Reply-To: <4fq4d0F1jvgbrU1@uni-berlin.de> References: <1150721380.948808.231760@h76g2000cwa.googlegroups.com> <1150795424.752973.303420@g10g2000cwb.googlegroups.com> <4fpvr0F1k8dauU1@uni-berlin.de> <4fq4d0F1jvgbrU1@uni-berlin.de> Message-ID: <44982e40$1@nntp0.pdx.net> Diez B. Roggisch wrote: > Maric Michaud wrote: > >> Le Mardi 20 Juin 2006 12:09, Diez B. Roggisch a ?crit : >>> [i for i, equals in enumerate((x == y for x, y in zip(a, b))) if equals] >> No needs to nest comprehensions, should be : >> [ i for i, v in enumerate(zip(a, b)) if v[0] == v[1] ] > > You're right, that design stemmed from my first broken version. Or even deconstruct to avoid the (very mildly confusing) v[0], v[1]: [i for i, (left, right) in enumerate(zip(a, b)) if left == right] -- --Scott David Daniels scott.daniels at acm.org From rvtol+news at isolution.nl Fri Jun 16 08:16:07 2006 From: rvtol+news at isolution.nl (Dr.Ruud) Date: Fri, 16 Jun 2006 14:16:07 +0200 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> Message-ID: Torben ?gidius Mogensen schreef: > Bugs that in dynamically typed languages would > require testing to find are found by the compiler in a statically > typed language. So whil[e ]it may take [l]onger to get a program that[ ] > gets past the compiler, it takes less time to get a program that works. If it were that simple, I would say: compile time type inference is the only way to go. -- Affijn, Ruud "Gewoon is een tijger." From bborcic at gmail.com Fri Jun 23 14:16:14 2006 From: bborcic at gmail.com (Boris Borcic) Date: Fri, 23 Jun 2006 20:16:14 +0200 Subject: How to generate all permutations of a string? In-Reply-To: References: Message-ID: <449c3002$1_5@news.bluewin.ch> Another generator solution, based on computing a permutation from its rank according to some natural order. Written for strings. def perms(s) : def nth(n,L,k=1) : if k>len(L) : if n : raise StopIteration return '' return nth(n/k,L,k+1)+L.pop(n%k) for n in xrange(1<<30) : yield nth(n,list(s)) From gene.tani at gmail.com Sun Jun 11 05:40:07 2006 From: gene.tani at gmail.com (gene tani) Date: 11 Jun 2006 02:40:07 -0700 Subject: learning python idioms In-Reply-To: <1150016172.064188.264790@m38g2000cwc.googlegroups.com> References: <1149998884.261678.299860@u72g2000cwu.googlegroups.com> <1150006411.269862.117680@j55g2000cwa.googlegroups.com> <1150016172.064188.264790@m38g2000cwc.googlegroups.com> Message-ID: <1150018807.945016.3100@y43g2000cwc.googlegroups.com> bayerj wrote: > Hi, > > If you switched from java to python the best point to start is > http://dirtsimple.org/2004/12/python-is-not-java.html. > > Greets, > -Justin yup, you could spend weeks reading the Language Wars: http://www.google.com/search?hl=en&q=site%3Aartima.com+java+python&btnG=Google+Search http://del.icio.us/tag/python+java From jcrocholl at googlemail.com Thu Jun 1 16:14:41 2006 From: jcrocholl at googlemail.com (Johann C. Rocholl) Date: 1 Jun 2006 13:14:41 -0700 Subject: XML-RPC server with xmlrpclib and mod_python Message-ID: <1149192881.683913.308240@g10g2000cwb.googlegroups.com> Hi all, I'm wondering what would be the best way to write an XML-RPC server using mod_python with Apache 2.0. I want the mod_python environment because the rest of my project is web-based, and Apache gives me multi-threading and everything. My first attempt implements XML-RPC introspection. Please have a look at the following files and give me a rigorous critique. All comments are welcome, even about coding style and module design. My handler for incoming mod_python requests: http://trac.browsershots.org/browser/trunk/shotserver/lib/xmlrpc/__init__.py The introspection module (I plan to have more modules in that folder): http://trac.browsershots.org/browser/trunk/shotserver/lib/xmlrpc/system.py A simple standalone test client: http://trac.browsershots.org/browser/trunk/shotserver/scripts/xmlrpc_help.py Are there any existing interfaces to use xmlrpclib with mod_python? Are there any security issues that I should be aware of when implementing XML-RPC? Thanks in advance, Johann From fredrik at pythonware.com Fri Jun 16 15:28:08 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 16 Jun 2006 21:28:08 +0200 Subject: Which compiler will Python 2.5 / Windows (Intel) be built with? In-Reply-To: References: <1150367139.495114.148550@g10g2000cwb.googlegroups.com> <44917535$1@nntp0.pdx.net> <1150391891.130185.4640@f6g2000cwb.googlegroups.com> <4491b9e1$1@nntp0.pdx.net> <1150406005.948538.188950@h76g2000cwa.googlegroups.com> <4491d3c0$1@nntp0.pdx.net> <1150410921.201231.277880@c74g2000cwc.googlegroups.com> <1150414509.020482.249110@g10g2000cwb.googlegroups.com> Message-ID: Philip Austin wrote: > Presuming I succeed in setting up vc7 correctly, is it as simple > as 'python setup.py install' from here? yup (for a suitable definition of "correctly"; afaik, all you need is a couple of registry settings; for a normal VC install, the easiest way to get them in place is to start the visual studio application once). From steve at holdenweb.com Thu Jun 29 08:36:37 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 29 Jun 2006 13:36:37 +0100 Subject: New to Python: Do we have the concept of Hash in Python? In-Reply-To: <200606290958.42417.runlevelten@gmail.com> References: <200606290958.42417.runlevelten@gmail.com> Message-ID: Ten wrote: > On Friday 02 June 2006 13:07, Piet van Oostrum wrote: > >>>>>>>"A.M" (AM) wrote: >>> >>>AM> This is my 1st day that I am seriously diving into Python and I have >>>AM> to finish this application by the end of today. >> >>Are you serious? >>-- >>Piet van Oostrum >>URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] >>Private email: piet at vanoostrum.org > > > It's not that unfeasible - I can think of a few instances off the top of my head where > management have read something in a magazine or heard something in conversation, then > come in full of vim and vigour the next day - telling people to create item X using buzzword > technology Y by the end of the day, the week or whatever, despite the devs having never seen it, > despite the timescale being insufficient, and despite there being *real* work to do. > [obYorkshireman] You were lucky. Mine used to come in like this *every bloody Monday morning*. British readers familiar with Kenneth Grahame's "The Wind in the Willows" will recognise a technological Mr. Toad here. The guy wanted to hit every available technology with a technical staff of two people, and seriously appeared to believe that he could just keep doing this until he came upon one that made money. Until it did he had the pleasure of bitching about how much of his money the company was swallowing. The last words I ever uttered to that man were a physiological impossibility. [Feels better]. > Even if it's just because they want to see it, or to impress other management types with their > use of the latest "trend", I believe the best response is to just get on with it. > Self-preservation and all that. > Clearly it's good press for Python if it *could* pass this test of usability. Don't see Perl users doing that (though, to be fair, I'm very little involved with Perl now). And since the boss signs the cheques, one should mollify them when ethically possible. > Even so, the idea of using python across the company is actually a very sensible one, so I expect > it's programmer's enthusiasm fuelling things in this case. > That's right, blame the poor technical staff ... regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From girish at cse.iitb.ac.in Wed Jun 28 04:01:22 2006 From: girish at cse.iitb.ac.in (Girish Sahani) Date: Wed, 28 Jun 2006 13:31:22 +0530 (IST) Subject: How to measure execution time of a program In-Reply-To: <54032.10.209.4.1.1151481158.squirrel@10.105.1.3> References: <54032.10.209.4.1.1151481158.squirrel@10.105.1.3> Message-ID: <57589.10.209.4.1.1151481682.squirrel@10.105.1.3> Sorry for spamming again, but please also enlighten me with some way to time a function i.e. to find out how much time each function takes for execution in a big program. > Hi all, > > Can anyone tell me the simplest way to do it (some code snippet that > could be included in the program's main function) ?? > > Thanks, > girish > -- > http://mail.python.org/mailman/listinfo/python-list > From ksheka at gmail.com Sun Jun 18 15:51:06 2006 From: ksheka at gmail.com (K P S) Date: 18 Jun 2006 12:51:06 -0700 Subject: Simple script to make .png thumbnails from .zip archive... Message-ID: <1150660266.413889.217280@c74g2000cwc.googlegroups.com> Hi. I'm looking for a small script that will take a .zip archive and pull the first .jpg from the archive and convert it to a .png. The reason for this is I want to have tuhmbnails for these archives in nautilus under gnome. I would like something similar to the following code, which will pull a thumbnail from an openoffice.org (oasis) document. What I want is a little more involved, I guess, since I don't know the name of the file (for the zip.read command), and I need to convert the file from .jpg to .png once I get it. Any help would be appreciated. Including a pointer to a web page of a manual with examples. :-) #!/usr/bin/python import zipfile import sys import gnomevfs inURL=gnomevfs.get_local_path_from_uri(sys.argv[1]) outURL=sys.argv[2] zip=zipfile.ZipFile(inURL,mode="r") picture=zip.read("Thumbnails/thumbnail.png") thumbnail=open(outURL,"w") thumbnail.write(picture) thumbnail.write("/n") zip.close() thumbnail.close() From johnjsal at NOSPAMgmail.com Thu Jun 15 11:21:50 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 15 Jun 2006 15:21:50 GMT Subject: Python is fun (useless social thread) ;-) In-Reply-To: <1150380401.422325.119360@h76g2000cwa.googlegroups.com> References: <1150380401.422325.119360@h76g2000cwa.googlegroups.com> Message-ID: Michele Simionato wrote: > John Salerno wrote: >> So out of curiosity, I'm just wondering how everyone else came to learn >> it. > > I have already reported my first experiences with Python here: > http://groups.google.com/group/comp.lang.python/browse_frm/thread/2afa89689e897039/3d77eba36a97751d?q=simionato+my+first+python&rnum=3#3d77eba36a97751d > > Michele Simionato > Very interesting post. And I definitely agree with you that, as much as everyone seems to suggest the tutorial, I find it very difficult to actually learn from. It helps to provide a review for the language, but as a newbie, I really wouldn't have learned Python from it. I do, however, think the docs are pretty good, although I sometimes find myself just wishing that a function definition was simply laid out in an easy to read format that included all of its parameters, so I would know exactly what to pass to it (I guess help() is good for this though). From jstroud at ucla.edu Wed Jun 14 15:29:49 2006 From: jstroud at ucla.edu (James Stroud) Date: Wed, 14 Jun 2006 12:29:49 -0700 Subject: "groupby" is brilliant! In-Reply-To: <1hgww3q.88ib5jyqo5hcN%aleax@mac.com> References: <1150180151.643245.148210@y43g2000cwc.googlegroups.com> <1hgww3q.88ib5jyqo5hcN%aleax@mac.com> Message-ID: Alex Martelli wrote: > James Stroud wrote: > ... > >>def doit(rows, doers, i=0): >> for r, alist in groupby(rows, itemgetter(i)): >> if len(doers) > 1: >> doit(alist, doers[1:], i+1) >> doers[0](r) > > > Isn't this making N useless slices (thus copies, for most kinds of > sequences) for a doers of length N? Since you're passing i anyway, it > seems to me that: > > def doit(rows, doers, i=0): > for r, alist in groupby(rows, itemgetter(i)): > if len(doers) > i+1: > doit(alist, doers, i+1) > doers[i](r) > > is equivalent to your code, but avoids these slices (thus copies). > > > Alex Yes, it does seem the copies are useless. Thank you. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From bearophileHUGS at lycos.com Mon Jun 12 20:04:45 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 12 Jun 2006 17:04:45 -0700 Subject: Combining The Best Of Python, Ruby, & Java?????? In-Reply-To: References: Message-ID: <1150157085.887359.318760@f14g2000cwb.googlegroups.com> Scala seems terse and fast enough, few examples: http://shootout.alioth.debian.org/gp4sandbox/benchmark.php?test=all&lang=psyco&lang2=scala Bye, bearophile From kay.schluehr at gmx.net Tue Jun 6 11:44:06 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 6 Jun 2006 08:44:06 -0700 Subject: what are you using python language for? References: Message-ID: <1149608646.683116.264380@y43g2000cwc.googlegroups.com> hacker1017 wrote: > im just asking out of curiosity. To get an impression you might have a look at the Europython 2006 schedule: http://indico.cern.ch/conferenceTimeTable.py?confId=44 Personally I'm playing with the language itself at the moment and extend it through it: http://www.fiber-space.de/EasyExtend/doc/EE.html Regards, Kay From diffuser78 at gmail.com Fri Jun 30 14:35:17 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 30 Jun 2006 11:35:17 -0700 Subject: Py2exe make wxPython window looks bad In-Reply-To: <1151653241.416599.6450@i40g2000cwc.googlegroups.com> References: <1151653241.416599.6450@i40g2000cwc.googlegroups.com> Message-ID: <1151692517.120733.37920@d56g2000cwd.googlegroups.com> My question is not exactly related. In windows you create exe using py2exe. What is the Linux equivalent of it ? I am assuming you just make your .py file executable by doint this. Please correct me if I am wrong. *********************************** chmoad a+c file_name.py *********************************** I recently wrote a small app using wxPython. It is meant to be run on Windows and Linux both. In Windows I have created the exe as given in py2exe.org. What do I need to do in Linux if I need to distribute to people using Linux who don't have all the dependent libraries installed in their Linux distro ?? Every help is appreciated. Thanks zdp wrote: > Dear all: > > I made a window program by wxPython. Split windows, treectrl, listctrl > and textctrl are used. When I program in python, the look & feel of the > window controls are like the windos XP look & feel, with thin and flat > border (My os is window XP). It's natural because, as I know, wxPython > use native look and feel. > > But when I convert the program to EXE file by Py2exe, and run it, the > look & feel is bad. It's just like the windows 9x. All controls has a > thick and emboss border. However, the scrollbars look good, same as the > window XP. > > So I'm puzzled. What's the problem and how can I get a XP look & feel > window program? Should I add some code in my program to set the look > and feel, or, set some options in py2exe script to force the generated > exe has specified look and feel? > > The setup.py is very simple as following: > > -------------setup.py--------------------- > import sys, os > from distutils.core import setup > import py2exe > import glob > > setup( name = "mainframe", > windows = ["mainframe.py"] > ) From Serge.Orlov at gmail.com Fri Jun 2 03:44:30 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 2 Jun 2006 00:44:30 -0700 Subject: struct: type registration? References: <447e4b98$1@news.eftel.com> <1149185926.636174.48970@y43g2000cwc.googlegroups.com> <447F6F64.400@lexicon.net> Message-ID: <1149234270.300072.316880@c74g2000cwc.googlegroups.com> John Machin wrote: > On 2/06/2006 4:18 AM, Serge Orlov wrote: > > If you want to parse binary data use pyconstruct > > > > > > Looks promising on the legibility and functionality fronts. Can you make > any comment on the speed? I don't know really. I used it for small data parsing, its performance was acceptable. As I understand it is implemented right now as pure python code using struct under the hood. The biggest concern is the lack of comprehensive documentation, if that scares you, it's not for you. > Reason for asking is that Microsoft Excel > files have this weird "RK" format for expressing common float values in > 32 bits (refer http://sc.openoffice.org, see under "Documentation" > heading). I wrote and support the xlrd module (see > http://cheeseshop.python.org/pypi/xlrd) for reading those files in > portable pure Python. Below is a function that would plug straight in as > an example of Giovanni's custom unpacker functions. Some of the files > can be very large, and reading rather slow. I *guess* that the *current* implementation of pyconstruct will make parsing slightly slower. But you have to try to find out. > from struct import unpack > > def unpack_RK(rk_str): # arg is 4 bytes > flags = ord(rk_str[0]) > if flags & 2: > # There's a SIGNED 30-bit integer in there! > i, = unpack(' i >>= 2 # div by 4 to drop the 2 flag bits > if flags & 1: > return i / 100.0 > return float(i) > else: > # It's the most significant 30 bits > # of an IEEE 754 64-bit FP number > d, = unpack(' if flags & 1: > return d / 100.0 > return d I had to lookup what < means :) Since nobody except this function cares about internals of RK number, you don't need to use pyconstruct to parse at bit level. The code will be almost like you wrote except you replace unpack(' <1150402733.116243.9680@y41g2000cwy.googlegroups.com><4492ae6c$0$19179$626a54ce@news.free.fr> <4492C307.704@tim.thechases.com> Message-ID: <032601c691f0$6e818b80$03000080@hendrik> Tim Chase wrote: | > No need to argue. I started with vim, and finally switched to | > emacs less than one year later. | | Both are very-much-so good editors. I made the opposite switch | from emacs to vim in less than a year. Both are good^Wgreat | editors, so one's decision to use one over the other is more a | matter of working style. I don't grok LISP, and just never felt | at home in emacs, despite all the power I could see that was | there. I grok vim (and its similar power/extensibility), so I | migrated to it. I have to laugh at the whole holy-war thing, as | it's somewhat like arguing about a favorite color. "But blue is | so better than green! The sky is blue!" "Nuh, uh! Green is far | better than blue! Grass is green!" (okay, here in Texas, that | doesn't always hold as true...maybe personality #2 should be | arguing for brown instead). | | My best friend is an emacs user, and I'm a vimmer...it doesn't | come between us. :) You guys are not gonna believe this - I keep a low grade PC specially so that I can do my programming with Brief (yes the one by Underware) - and yes I know Emacs has a so called *crisp* emulator - but IMNSHO it sucks! I like the macros, I do some stuff with the macro language, and as a mostly assembler programmer, I adore the way it copies and pastes columns with minimal keystrokes.... And I switch between buffers (different files - "modules" in Python ) - with an alt n or alt - ..... and worse - like the confirmed Vi or Emacs user - the problem is that you get used to it, and ya dont wanna change... - Hendrik I wish I could run this on my Linux box.... From tjreedy at udel.edu Thu Jun 29 14:24:24 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 29 Jun 2006 14:24:24 -0400 Subject: Python docs bug References: <1151593209.084822.207460@j72g2000cwa.googlegroups.com> <17571.60845.33044.994034@montanaro.dyndns.org> Message-ID: wrote in message news:17571.60845.33044.994034 at montanaro.dyndns.org... > > >> One long-standing irritation I have with the table of contents for > >> the Python Library Reference , > >> is that there is one very important section, "String Methods" > >> , which does not > >> appear there. That's because it is section 2.3.6.1, and the table > of > >> contents only goes to 3 levels. > > John> I've found that to be quite irritating as well. Me too > Maybe someone should submit a bug report on SF... done www.python.org/sf/1514540 Terry Jan Reedy From marshall.spight at gmail.com Fri Jun 23 17:12:26 2006 From: marshall.spight at gmail.com (Marshall) Date: 23 Jun 2006 14:12:26 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <7zpshbsvjy.fsf@app-1.diku.dk><4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <0%Wlg.3521$MF6.947@tornado.socal.rr.com> <44992e6c$0$664$bed64819@news.gradwell.net> <449aaea0$0$656$bed64819@news.gradwell.net> <449bde5e$1$663$bed64819@news.gradwell.net> Message-ID: <1151097146.910247.56170@g10g2000cwb.googlegroups.com> Andreas Rossberg wrote: > > ... And the reason is that "type" has a > well-established use in theory. It is not just my "assumption", it is > established practice since 80 or so years. Wouldn't it be fair to say it goes back a least to Principia Mathematica, 1910? > So far, this discussion has > not revealed the existence of any formal work that would provide a > theory of "dynamic types" in the sense it is used to characterise > "dynamically typed" languages. Indeed, the idea I am starting to get is that much of what is going on in the dynamic/latent/untyped/whatever world is simply informal, conceptual-level static analysis. The use of the runtime system is a formal assistant to this informal analysis. In other words, formal existential quantification is used as hint to help do informal universal quantification. Now, given that explanation, the formal analysis looks better. But that's not the whole story. We also have the fact that the informal analysis gets to run on the human brain, while the static analysis has to run on a lousy microprocessor with many orders of magnitude less processing power. We have the fact that the formal static analysis is of limited power. We have the fact that historically, static languages have forbidden the use of the formal existential method preferred by the DT crowd until *after* the static analysis has passed, thus defeating their purpose. And probably still more things that I don't appreciate yet. So I'll now throw around some terms (in an attempt to look smart :-) and say, late binding, impredicativity. Marshal From antroy at gmail.com Tue Jun 6 04:21:44 2006 From: antroy at gmail.com (Ant) Date: 6 Jun 2006 01:21:44 -0700 Subject: C# equivalent to range() In-Reply-To: References: <1149468919.951745.163700@g10g2000cwb.googlegroups.com> <1149481675.192638.275140@c74g2000cwc.googlegroups.com> <1149509893.031953.19310@i40g2000cwc.googlegroups.com> Message-ID: <1149582104.349641.252000@g10g2000cwb.googlegroups.com> > That's because many of them have killfiled you. I actually wonder whether anyone does use killfiles. I just can''t imagine the sort of person who writes "plonk" or "welcome to my killfile" etc could bear to miss out on a reply to such a post in case there's more to get angry about! And people who are not riled enough by a post to comment on it probably would'nt be fired up enough to bother killfiling either... From onurb at xiludom.gro Mon Jun 26 05:04:36 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Mon, 26 Jun 2006 11:04:36 +0200 Subject: error with string (beginner) In-Reply-To: <1151248415.626494.38710@p79g2000cwp.googlegroups.com> References: <1151240297.725336.305960@i40g2000cwc.googlegroups.com> <1151248415.626494.38710@p79g2000cwp.googlegroups.com> Message-ID: <449fa325$0$10298$636a55ce@news.free.fr> Jason wrote: > I believe what you are trying to do is something like the following. > > [code] > def isIntLike(x): > try: int(x) > except: return False *Never* ever use a bare except clause. *Always* specify wich exceptions you are expecting. (NB : here, TypeError and ValueError). (NB : of course, like for all and any do's-and-don't rules, there are actually a very few cases where using a bare except may be ok.) > else: return True > > something = raw_input("Enter something and I will tell you the type: ") > > if isIntLike(something): print "I am an int" Nope. At this stage, 'something' is *not* an int - it's a string that can be turned into an int. > elif isinstance(something, type('')): print "I am a string" You don't need the "type('')" stuff - use isinstance(something, basestring) instead. > else: print "I am an impostor!" > [/code] (snip) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From python.list at tim.thechases.com Mon Jun 26 11:25:50 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 26 Jun 2006 10:25:50 -0500 Subject: Get List of Classes In-Reply-To: <1151332257.564563.139040@u72g2000cwu.googlegroups.com> References: <1151332257.564563.139040@u72g2000cwu.googlegroups.com> Message-ID: <449FFC7E.2010600@tim.thechases.com> > Is there a method or attribute I can use to get a list of > classes defined or in-use within my python program? I tried > using pyclbr and readmodule but for reason that is dogslow. Well, given that so much in python is considered a class, the somewhat crude code below walks an object/module and emits details regarding what's going on. I couldn't find any nice method for determining if a variable referenced a module other than checking to see if that item had both a "__file__" and a "__name__" attribute. Likewise, the check for whether something is an object is a bit crude. >>> def inspect(thing, name = '', indent=0): ... if hasattr(thing, "__file__") and hasattr(thing, "__name__"): ... #assume it's a module ... print "%sModule %s" % ("\t" * indent, thing.__name__) ... for subthing in dir(thing): ... objname = ".".join([name, subthing]).lstrip(".") ... inspect(eval(objname), ... objname, indent+1) ... elif isinstance(thing, object): ... print "%s%s is an object" % ("\t" * indent, name) ... >>> import m1 >>> # m1 is a junk module that references module "m2" and has >>> # some junk classes in it >>> inspect(m1, "m1") Module m1 m1.M1Class is an object m1.M1ObjectClass is an object m1.__builtins__ is an object m1.__doc__ is an object m1.__file__ is an object m1.__name__ is an object Module m2 m1.m2.M2Class is an object m1.m2.M2ObjectClass is an object m1.m2.__builtins__ is an object m1.m2.__doc__ is an object m1.m2.__file__ is an object m1.m2.__name__ is an object You could also filter out builtin object properties by wrapping that last print statement in something like if not name.startswith("_"): print ... which might cut down on some of the noise. Just a few ideas. -tkc From rpdooling at gmail.com Thu Jun 1 17:55:46 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 1 Jun 2006 14:55:46 -0700 Subject: Replace one element of a tuple In-Reply-To: <127ulhn6h7hvj22@corp.supernews.com> References: <127ulhn6h7hvj22@corp.supernews.com> Message-ID: <1149198946.567904.260480@f6g2000cwb.googlegroups.com> >> I've looked at various search-and-replace snippets but none that address >> what I am trying to do.... I think you need to tell more about what you're trying to do. You say it's in a database? Is that why you can't just put the whole blob in your text editor and do search-and-replace? And is that also why you can't turn it into a giant string and do giantstring.replace('unwanted','wanted') rd From onurb at xiludom.gro Tue Jun 6 04:55:37 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 06 Jun 2006 10:55:37 +0200 Subject: the most efficient method of adding elements to the list In-Reply-To: References: Message-ID: <4485430a$0$20879$636a55ce@news.free.fr> alf wrote: > Hi, > > Would it be .append()? Does it reallocate te list with each apend? > > l=[] > for i in xrange(n): > l.append(i) > FWIW, you'd have the same result with: l = range(n) More seriously (and in addition to other anwsers): you can also construct a list in one path: l = [i for i in xrange(n)] or if you want operations and conditionals : l = [trasform(i) for i in xrange(n) if match_some_cond(i)] HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From diffuser78 at gmail.com Tue Jun 13 10:30:56 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 13 Jun 2006 07:30:56 -0700 Subject: Customized Boot Manager in Python Message-ID: <1150209056.507195.81430@y43g2000cwc.googlegroups.com> I have to create a small visual interface program called as Boot Manager which is customized accoring to the needs. I have around 8 pc's and 2 linux boxes. One Linux box is always on and all other are closed in sleep state. I have to perform the following things: 1. Boot up all of them. I used Wake on LAN and wrote a small python script for that. It works fine. 2. To shutdown all pc's when the work is done. For this I installed an OpenSSH server for Windows in PC. When I send a command using ssh it shuts it down. Now, I have to create a visual interface for such kind of small program. I have 2 questions (i) How can we use operating system specific commands like ssh within the python program (ii) Which grphics library (wxPython or any other) would be the fastest with least learning curve to get this thing done. Thanks From mdudley at king-cart.com Sun Jun 4 13:31:12 2006 From: mdudley at king-cart.com (Marshall Dudley) Date: Sun, 04 Jun 2006 13:31:12 -0400 Subject: Installation Problem References: <44830900.155C7297@king-cart.com> Message-ID: <448318DF.82D337BF@king-cart.com> Fredrik Lundh wrote: > Marshall Dudley wrote: > > I am trying to install python, but am having problems. I did what the > > README file said, and it created an executible code in the current > > directory as it said it would when I typed "make". > > "make" doesn't install the interpreter by itself; you're supposed to use > "make install" (or "make altinstall") to do that. > > just copying the interpreter binary around won't give you a complete > install. > > > It seemed to say to copy the executable over to the /usr/local > > directory, which I did. > > the README says: > > To start building right away (on UNIX): type "./configure" in the > current directory and when it finishes, type "make". This creates an > executable "./python"; to install in /usr/local, first do "su root" > and then "make install". Yes, that is what I did. Since I ended up with no executable in /usr/local, or /usr/local/bin and it said " This creates an executable "./python" (which it did); to install in /usr/local" I copied the one it created over to /usr/local, then later /usr/local/bin > > > the detailed installation section says: > > To install the Python binary, library modules, shared library modules > (see below), include files, configuration files, and the manual page, > just type > > make install > > /.../ > > Yes, I typed "make install". But nothing gets put into /usr/local or /usr/local/bin without me copying it over. And if I run python it in the directory I unpacked it in, it works, but if I run the copy in /usr/local or /usr/local/bin it does not. I also tried the instuctions on their web site: "python setup.py install" But get the same result, but it copies and puts the following 3 files in the /usr/local/bin dir. -rwxr-xr-x 1 root wheel 96 May 31 07:50 idle -rwxr-xr-x 1 root wheel 81 May 31 07:50 pydoc -rwxr-xr-x 1 root wheel 18017 May 31 07:50 smtpd.py Marshall From michele.petrazzo at TOGLIunipex.it Mon Jun 5 05:16:03 2006 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Mon, 05 Jun 2006 09:16:03 GMT Subject: Trying to get FreeImagePy to work. In-Reply-To: References: <1148651668.578852.3160@i40g2000cwc.googlegroups.com> <7fEdg.13375$cX1.201311@twister2.libero.it> <1148655611.990937.322350@j73g2000cwa.googlegroups.com> <1149166096.176405.22780@i40g2000cwc.googlegroups.com> <3PCfg.20835$cX1.315781@twister2.libero.it> <1149174938.337973.85950@g10g2000cwb.googlegroups.com> <1149192520.959302.250840@j55g2000cwa.googlegroups.com> <1149235836.646855.164110@i40g2000cwc.googlegroups.com> Message-ID: Fredrik Lundh wrote: >> So you *need* to invert it to work correctly with PIL! > > PIL has no problem reading "min-is-white" TIFF images. > > it would be nice if you stopped posting bogus "support" information > for other libraries. Sorry if my posts make to seem that other libraries has problems! Sure that *my* wrap has problems, like I have problem with something that I don't know so well, like Image world (like I always said). I'm only suggesting some, bad, trick for do the work that "Iain" wants. I tried, but without success, to make the "convertToPil" function work with 1, 8, 16 bpp... Seem that only 24/32 work, but I don't know why. I know that PIL doesn't have problems! > > > Hope that this can explain better the situation. Bye, Michele From bignose+hates-spam at benfinney.id.au Wed Jun 14 20:31:12 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 15 Jun 2006 10:31:12 +1000 Subject: Negative hex to int References: <1150326597.327669.222640@r2g2000cwb.googlegroups.com> Message-ID: <873be7mf8v.fsf@benfinney.id.au> andreas.lydersen at gmail.com writes: > The problem is negative values. If the unit returns the hex value > 'e7', it means -25, but python says it's 231: Python is right. There is no "negative bit" in Python numbers, now that unification of 'long' and 'int' is complete; numbers can grow indefinitely large. If you want a special interpretation of the value, you'll have to calculate it. Example assuming you want a one's-complement interpretation:: def value_from_reading(num): """ Gets the integer value from the reading string. num is a positive hexadecimal number as a string. Numbers greater than 0x7F are interpreted as negative, with magnitude greater than 0x7F being the negative value. Only the lowest 15 bits are used for the magnitude. >>> value_from_reading('00') 0 >>> value_from_reading('05') 5 >>> value_from_reading('7f') 127 >>> value_from_reading('80') -128 >>> value_from_reading('e7') -25 >>> value_from_reading('ff') -1 >>> value_from_reading('100') -128 >>> value_from_reading('fff') -1 """ num_base = 16 negative_threshold = 0x7F int_val = int(num, num_base) if int_val > negative_threshold: magnitude = (int_val & negative_threshold) int_val = -(1 + negative_threshold - magnitude) return int_val Adjust for whatever algorithm you want to use. Consult a book of algorithms if you want a better implementation than my off-the-cuff brute-force approach. -- \ "Remorse: Regret that one waited so long to do it." -- Henry | `\ L. Mencken | _o__) | Ben Finney From juergen.huber at kirchnersoft.com Fri Jun 30 10:53:05 2006 From: juergen.huber at kirchnersoft.com (Juergen Huber) Date: Fri, 30 Jun 2006 16:53:05 +0200 Subject: print shell output in a file References: <44a52fdb$0$3892$91cee783@newsreader01.highway.telekom.at> <44a53851$0$3882$91cee783@newsreader01.highway.telekom.at> Message-ID: <44a53ac5$0$12933$91cee783@newsreader02.highway.telekom.at> hello, if i would type in your code, i became the following output in the "output.txt" - file BOOL | 4 | 50463 |201852 but why?! he wouldn?t do that for all the entrys in the csv file! but only for the first one in the file! Stephan Wassipaul wrote: > f = file('output.txt','w') > print >>f, '%-30s | %-12d | %-12d |%-12d ' % (typename, > size / count, > count, > size) > f.close() >> hello, >> >> one more question i will have! >> >> now i have written a little programm, which delivers me an output on >> the shell! >> >> >> here is the print command, which delivers me the following output >> (see below) on the shell: >> >> >> print '%-30s | %-12d | %-12d |%-12d ' % (typename, >> size / count, >> count, >> size) >> >> >> >> --------------NAME-------------|Groesse(Byte)-|----Anzahl----|-Gesamtgroe sse >> (Byte)-| >> ------------------------------------------------------------------------- --- >> ---------- >> ADD_REAL_N6 | 4 | 1 |4 >> AND_BOOL_N10 | 4 | 1 |4 >> AND_BOOL_N12 | 4 | 1 |4 >> >> >> >> Is there a way to put this output in an file?!?! i searched about 2h >> for this, but i couldn`t find an answer! >> >> thnks, juergen From duncan.booth at invalid.invalid Mon Jun 12 04:06:22 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 12 Jun 2006 08:06:22 GMT Subject: printing all variables References: <1150098291.647296.86340@f6g2000cwb.googlegroups.com> Message-ID: Sheldon wrote: > Good day, > > I would like to know if there is a way to print all the variables set > in a python program with having to write > "print variable" on all? > Not all the variables in a program (that would be rather more than you want), but you can print all the variables in a specific namespace easily enough: >>> from pprint import pprint >>> def f(x): pprint(locals()) >>> f(2) {'x': 2} >>> pprint(globals()) {'__builtins__': , '__doc__': None, '__name__': '__main__', 'f': , 'pprint': } >>> class C: classvar = [] def __init__(self, n): self.n = n >>> c = C(3) >>> pprint(vars(c)) {'n': 3} >>> pprint(vars(C)) {'__doc__': None, '__init__': , '__module__': '__main__', 'classvar': []} >>> From rbutler at mtsu.edu Sat Jun 17 18:26:48 2006 From: rbutler at mtsu.edu (Ralph Butler) Date: Sat, 17 Jun 2006 17:26:48 -0500 Subject: statically linked python Message-ID: Hi: I have searched the docs and google but have not totally figured out how to accomplish my task: On a linux box, I want to compile and link python so that it uses no shared libraries, but does support import of some "extra" modules. I have made a few attempts but with limited success. In particular, I have tried things like adding -static to the compiler options in the Makefile. At one point I managed to build a python that was close to what I wanted, e.g. when I ran "ldd python", it said: not a dynamic executable In that version, when I do some imports, e.g. sys, os, etc. they load fine. But, when I try to import some other modules, e.g. time, they are not found. I have tried similar procedures while also altering Modules/Setup.local (produced by configure) to contain: time timemodule.c # -lm # time operations and variables There has to be a simple, "elegant" way to accomplish this which I am simply overlooking. Any help would be appreciated. Thanks. --ralph From joh12005 at yahoo.fr Sat Jun 10 05:24:35 2006 From: joh12005 at yahoo.fr (joh12005 at yahoo.fr) Date: 10 Jun 2006 02:24:35 -0700 Subject: what is often before a pattern ? In-Reply-To: References: <1149801756.593936.95110@y43g2000cwc.googlegroups.com> Message-ID: <1149931475.290504.69480@c74g2000cwc.googlegroups.com> thanks, i 've checked, it may fit. i also find something about a longest common sequence which may be of interest, but i was unable to adapt it for list (words) rather than characters :( From klaus at seistrup.dk Sat Jun 3 04:36:43 2006 From: klaus at seistrup.dk (Klaus Alexander Seistrup) Date: Sat, 3 Jun 2006 08:36:43 +0000 (UTC) Subject: Missing unicode data? Message-ID: Hi group, I just came across the following exception: #v+ $ python Python 2.4.2 (#2, Sep 30 2005, 21:19:01) [GCC 4.0.2 20050808 (prerelease) (Ubuntu 4.0.1-4ubuntu8)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import unicodedata >>> u'\N{LATIN LETTER SMALL CAPITAL BARRED B}' UnicodeDecodeError: 'unicodeescape' codec can't decode bytes in position 0-38: unknown Unicode character name >>> unicodedata.name(u'\u1d03') Traceback (most recent call last): File "", line 1, in ? ValueError: no such name >>> ^D $ #v- When checking unicodedata.name() against each uchar in the file /usr/share/unidata/UnicodeData-4.0.1d1b.txt that came with the console-data package on my Ubuntu Linux installation a total of 1226 unicode characters seems to be missing from the unicodedata module (2477 missing characters when checking against the latest database from unicode.org?). Is this a deliberate omission? Cheers, Klaus. ?) http://www.unicode.org/Public/UNIDATA/UnicodeData.txt -- Klaus Alexander Seistrup SubZeroNet, Copenhagen, Denmark http://magnetic-ink.dk/ From diffuser78 at gmail.com Tue Jun 27 13:00:12 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 27 Jun 2006 10:00:12 -0700 Subject: file writing question In-Reply-To: <44a15b80$0$16556$636a55ce@news.free.fr> References: <1151423998.492022.269810@m73g2000cwd.googlegroups.com> <44a15b80$0$16556$636a55ce@news.free.fr> Message-ID: <1151427612.634890.262430@m73g2000cwd.googlegroups.com> Thanks Bruno....This helps me. Bruno Desthuilliers wrote: > diffuser78 at gmail.com wrote: > > Hi, I am a newbie so not very confident in file handling. > > > > I want to write to a file atrributes in this fashion > > #NameOfComputer:MAC_Address:IP_Address > > > > ------computer_details.txt > > begins----------------------------------------- > > IG1:8f00142a123c:192.168.2.101 > > IG2:8f00142a124d:192.168.2.102 > > IG3:8f00142a124e:192.168.2.103 > > IG4:8f00142a124f:192.168.2.104 > > IG5:8f00142a124a:192.168.2.105 > > IG6:8f00142a124b:192.168.2.106 > > ------computer_details.txt > > ends------------------------------------------- > > > > While writing this file I insert "\n" after every line so that details > > of every new computer goes into next line for readibility. > > > > > > After I have to read this file. While reading this file "\n" remains > > which I dont want. > > Then strip it: > > for line in open('computer_details.txt'): > name, mac, ip = line.strip().split(':') > # ... > > > Is there a neat way of writing to a file and not having "\n" ? > > Yes : don't add the newline after every line. But note that this may > make the file a bit more difficult to read and parse for both your > program and you !-) > > Also, may I suggest that you read the doc for the CSV module ? > > > -- > bruno desthuilliers > python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for > p in 'onurb at xiludom.gro'.split('@')])" From rbonvall at gmail.com Sun Jun 11 00:09:56 2006 From: rbonvall at gmail.com (Roberto Bonvallet) Date: Sun, 11 Jun 2006 00:09:56 -0400 Subject: Most elegant way to generate 3-char sequence In-Reply-To: References: <1149889784.391965.271570@h76g2000cwa.googlegroups.com> Message-ID: <1908cb6b0606102109yf53be79i8f5a6eb8c02a01cd@mail.gmail.com> 2006/6/10, SuperHik : > > Not necessarily vying for winner, but David's solution is highly > > specific as it doesn't do so well for something like > > > > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa > > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab > > Right. But that wasn't the question :p The question was about elegance, and elegance is when someone asks "do something 4 times for 5 strings of length 3" and you solve it for "do something n times for m strings of length p" :) -- Roberto Bonvallet From onurb at xiludom.gro Thu Jun 22 04:00:57 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Thu, 22 Jun 2006 10:00:57 +0200 Subject: python + postgres psql + os.popen In-Reply-To: <1150946077.931411.170930@u72g2000cwu.googlegroups.com> References: <1150946077.931411.170930@u72g2000cwu.googlegroups.com> Message-ID: <449a4e3b$0$7552$636a55ce@news.free.fr> damacy wrote: > hello, everyone. > > i am trying to write a program which executes SQL commands stored in > .sql files. > > i wrote a function called psql() whose contents look like the > following. > > ... > os.popen(command) > file = os.popen(command, 'w') > file.write(password) > file.close() > ... > > where command looks like > psql -h [host] -d [dbname] -U [username] -W -f "[filename]" > > this works well. But is a very strange way to access a RDBMS from Python code. Are you aware of the existence of db modules ? > can anyone help me? http://www.python.org/dev/peps/pep-0249/ http://initd.org/projects/psycopg1 -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From email at christoph-haas.de Wed Jun 14 03:26:24 2006 From: email at christoph-haas.de (Christoph Haas) Date: Wed, 14 Jun 2006 09:26:24 +0200 Subject: Logging to a file and closing it again properly (logging module) In-Reply-To: <1360b7230606132359q79497913v24479c2a8af526f6@mail.gmail.com> References: <20060612215823.GA18595@workaround.org> <1360b7230606132359q79497913v24479c2a8af526f6@mail.gmail.com> Message-ID: <20060614072624.GD13625@torf.workaround.org> On Wed, Jun 14, 2006 at 12:29:22PM +0530, Amit Khemka wrote: > On 6/13/06, Christoph Haas wrote: > >I have an application that is running in an endless loop processing an > >incoming queue. Every run is supposed to write a log file about the run > >and then close it again. While the 'logging' module is generally working > >well (even though the documentation makes me miss some proper examples > >how everything works together) I can't seem to close the log file again > >to open a new one. > > > >This is basically what I'm doing: > > > >log = logging.getLogger("myapplication") > >log.addHandler(logging.FileHandler("/tmp/testfile")) > >log.setLevel(logging.INFO) > >log.info("foo") > > > >Now I'm missing a way to tell this handler to go away. Through 'ipython' > >I found out there is a log.handlers array that contains all the > >handlers. Perhaps I could delete all of them but I'm sure there is a > >more proper way to close files again. > > > >Googling found me: > > > > .>>> logging._handlers.clear() > > .>>> logging.root.handlers = [] > > .>>> for l in logging.Logger.manager.loggerDict.values(): > > .>>> l.handlers = [] > > You can "close" the logger by just removing the handler from the logging > object > > # first creater a logger and file handler > fooLogger = logging.getLogger('FOO') > fooLogger.setLevel(logging.INFO) > fl = logging.FileHandler('foo.txt) > fl.setLevel(logging.INFO) > fooLogger.addHandler(fl) > > # remove the handler once you are done > fooLogger.removeHandler(fl) Thanks. That works great. I was looking for a way to close the log file using logging.basicConfig but it appears that it's too much magic. logging.getLogger() isn't really much more work but gives better control. Kindly Christoph From ketil+news at ii.uib.no Mon Jun 26 04:00:28 2006 From: ketil+news at ii.uib.no (Ketil Malde) Date: Mon, 26 Jun 2006 10:00:28 +0200 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <1150809118.677124.142230@u72g2000cwu.googlegroups.com> <1150815461.210286.53120@r2g2000cwb.googlegroups.com> <1150821239.077242.236710@y41g2000cwy.googlegroups.com> Message-ID: "Rob Thorpe" writes: >> I think statements like this are confusing, because there are >> different interpretations of what a "value" is. > But I mean the value as the semantics of the program itself sees it. > Which mostly means the datum in memory. I don't agree with that. Generally, a language specifies a virtual machine and doesn't need to concern itself with things like "memory" at all. Although langauges like C tries to, look at all the undefined behavior you get when you make assumptions about memory layout etc. Memory representation is just an artifact of a particular implementation of the language for a particular architecture. -k -- If I haven't seen further, it is by standing in the footprints of giants From tim.golden at viacom-outdoor.co.uk Mon Jun 19 05:54:48 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Mon, 19 Jun 2006 10:54:48 +0100 Subject: Check if a file is closed Message-ID: [camillo at rockit.it] | How to check if a file is closed? | | On Win32 you can call CreateFile with write and share write and if it | raises an error, the file is closed. | | How to do it in Python??? It's not clear whether you want a cross-platform Python-only solution. But if all you want is a way to use the Win32 CreateFile API in Python, then: http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/pywin32/win32file __CreateFile_meth.html 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 ________________________________________________________________________ From brochu121 at gmail.com Tue Jun 6 14:41:26 2006 From: brochu121 at gmail.com (david brochu jr) Date: Tue, 6 Jun 2006 14:41:26 -0400 Subject: RSS feeds Message-ID: <9583ed900606061141h72939138jdbdcfd7073da7c22@mail.gmail.com> Not sure where to post this one so here it goes...sorry to anyone if it shouldnt be here. I am looking to take RSS feeds a process them with a python program..any idea where I can get RSS feeds for sports stats, and how I would use the script to connect automatically to the feed? -------------- next part -------------- An HTML attachment was scrubbed... URL: From find at my.address.elsewhere Fri Jun 23 10:37:24 2006 From: find at my.address.elsewhere (Matthias Blume) Date: Fri, 23 Jun 2006 09:37:24 -0500 Subject: Saying "latently-typed language" is making a category mistake References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <86Qmg.10725$o4.1907@newsread2.news.pas.earthlink.net> <4g251pF1knc6tU1@individual.net> <4g28s6F1k9npnU1@individual.net> Message-ID: Pascal Costanza writes: > Matthias Blume wrote: >> Pascal Costanza writes: >> >>> Patricia Shanahan wrote: >>>> Vesa Karvonen wrote: >>>> ... >>>>> An example of a form of informal reasoning that (practically) every >>>>> programmer does daily is termination analysis. There are type systems >>>>> that guarantee termination, but I think that is fair to say that it >>>>> is not >>>>> yet understood how to make a practical general purpose language, whose >>>>> type system would guarantee termination (or at least I'm not aware >>>>> of such >>>>> a language). It should also be clear that termination analysis need not >>>>> be done informally. Given a program, it may be possible to >>>>> formally prove >>>>> that it terminates. >>>> To make the halting problem decidable one would have to do one of >>>> two >>>> things: Depend on memory size limits, or have a language that really is >>>> less expressive, at a very deep level, than any of the languages >>>> mentioned in the newsgroups header for this message. >>> Not quite. See http://en.wikipedia.org/wiki/ACL2 >> What do you mean "not quite"? Of course, Patricia is absolutely >> right. Termination-guaranteeing languages are fundamentally less >> expressive than Turing-complete languages. ACL2 was not mentioned in >> the newsgroup header. > > ACL2 is a subset of Common Lisp, and programs written in ACL2 are > executable in Common Lisp. comp.lang.lisp is not only about Common > Lisp, but even if it were, ACL2 would fit. So what? Patricia said "less expressive", you said "subset". Where is the contradiction? Perhaps you could also bring up the subset of Common Lisp where the only legal program has the form: nil Obviously, this is a subset of Common Lisp and, therefore, fits comp.lang.lisp. Right? Yes, if you restrict the language to make it less expressive, you can guarantee termination. Some restrictions that fit the bill already exist. IMHO, it is still wrong to say that "Lisp guaratees termination", just because there is a subset of Lisp that does. Matthias PS: I'm not sure if this language guarantees termination, though. :-) From invalidemail at aerojockey.com Sun Jun 25 15:18:58 2006 From: invalidemail at aerojockey.com (Carl Banks) Date: 25 Jun 2006 12:18:58 -0700 Subject: PEP thought experiment: Unix style exec for function/method calls References: <449e72ec$0$3530$ed2619ec@ptn-nntp-reader01.plus.net> Message-ID: <1151263138.807147.326970@r2g2000cwb.googlegroups.com> Michael wrote: > Suppose we could do the same for a python function - suppose we could > call the python function but either /without/ creating a new stack > frame or /replacing/ the current stack frame with the new one. I'm confused about what you mean. I'm guessing by "not creating a new stack frame" you wish to execute the bytecode from a different function in the current stack frame, correct? As for replacing the current stack frame, do you want to replace the whole stack, down to the __main__ module entry point, or just replace the top frame? Your comments and examples seem to be inconsistent about this. I'm going to assume you just want to replace or reuse the top frame in my replies. [snip] > Since os.exec* exists and "exec" already exists in python, I need to > differentiate what I mean by a unix style exec from python. So for > convenience I'll call it "cexe". > > Now, suppose I have: > ---------- > def set_name(): > name = raw_input("Enter your name! > ") > cexe greet() > > def greet(): > print "hello", name > > cexe set_name() > print "We don't reach here" > ---------- > > This would execute, ask for the user's name, say hello to them and then > exit - not reaching the final print "We don't reach here" statement. Only if you were to replace the whole stack. If you only replace or reuse the top frame, I would think greet would exit and execution would resume right after the point from which set_name was called. Or am I misunderstanding what you want? > Let's ignore for the moment that this example sucks (and is a good example > of the danger of this as a language feature), what I want to do here is > use this to explain the meaning of "cexe". > > There's two cases to consider: > cexe some_func_noargs() > > This transfers execution to the function that would normally be called > if I simply called without using "cexe" some_func_noargs() . However, > unlike a function call, we're /replacing/ the current thread of > execution with the thread of execution in some_func_noargs(), rather > than stacking the current location, in order to come back to later. > > ie, in the above this could also be viewed as "call without creating a > new return point" or "call without bothering to create a new stack > frame". > > It's this last point why in the above example "name" leaks between the > two function calls - due to it being used as a cexe call. I doubt this would be possible without a major change in how functions work in Python. The most obvious problem is that functions refer to local variables by an index, not by name. If you were to execute the bytecode of one function in the stack frame of another, Bad Things would happen. > Case 2: > given... > def some_func_withargs(colour,tone, *listopts, **dictopts) > > consider... > cexe some_func_withargs(foo,bar, *argv, **argd) > > This would be much the same as the previous case, except in the new > execution point, the name colour & tone map to the values foo & bar had > in the original context, whilst listopts and dictopts map the values > that argv & argd had in the original content) This is a lot more doable, but I'm not sure a new statement is needed. It seems like it wouldn't be terribly impossible to optimize the return statement to do this (in fact there's a certain situation where it's common to do just that, in other languages; more on that later). If function A were to return the result of calling function B, the A could possibly pop itself off the stack before calling B (but after evaluating B's arguments). B would then return directly to A's caller in place of A. Essentially, B has replaced A on the stack. Biggest problem is you'd have to know whether an object is a Python function at compile time--though that may not be so hard in the future. (Now, if you're thinking that you'll replace the whole stack and not just the top frame, Python already has the machinery to do this if you can tolerate wrapping up your main function to catch an exception and dispatching on it. For example: class _Cexe(Exception): def __init__(self,func,*args,**kwargs): self.func = func self.args = args self.kwargs = kwargs def cexe(func,*args,**kwargs): raise _Cexe(func,*args,**kwargs) def main_wrapper(*args,**kwargs): func = main while True: try: func(*args,**kwargs) return except _Cexe,e: func = e.func args = e.args kwargs = e.kwargs As an added bonus, you can do this higher up the stack if you want. A cexe statement wouldn't improve this too much; it wouldn't even make it more efficent. You can't just reset the stack pointer; you have to clean things up. The only upside to cexe I can think of is it could help reduce latency by delaying cleanup until garbage collection, but it wouldn't help overall efficiency too much.) [snip a lot] > It also struck me that any sufficiently interesting idea is likely to > have already been implemented, though perhaps not looking quite like the > above, so I thought I'd ask the questions: > > * Has anyone tried this sort of thing? Yes. There is a major use case for what you seem to be proposing, namely tail-recursive functions. A tail-recursive function is a recursive function that immediately returns the result of calling itself. A tail-recursive function never needs to keep its state around once it's called itself, and it's very common in functional languages, so it's an easy and common optimization. However, what you seem to be proposing is a generalization of that. It seems like it's possible, theoretically, to generalize this so that it works when you return the result of any function call, recursive or not. Theoretically. It wouldn't surprise me if functional languages like Haskell do this already. > * Has anyone tried simply not creating a new stack frame when doing > a function call in python? (or perhaps replacing the current one with > a new one) Doubt it. > * Has anyone else tried modelling the unix system exec function in > python? If so what did you find? > > * Since I can't find anything in the archives, I'm presuming my > searching abilities are bust today - can anyone suggest any better > search terms or threads to look at? Maybe look to see how tail-recursive optimization in languages such as Scheme work, and whether it can be generalized. > * Am I mad? :) Yep. :) Carl Banks From jzgoda at o2.usun.pl Thu Jun 15 16:38:21 2006 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Thu, 15 Jun 2006 22:38:21 +0200 Subject: a good programming text editor (not IDE) In-Reply-To: <1150402733.116243.9680@y41g2000cwy.googlegroups.com> References: <_xgkg.2317$No6.48542@news.tufts.edu> <1150402733.116243.9680@y41g2000cwy.googlegroups.com> Message-ID: BartlebyScrivener napisa?(a): > Emacs must be dying if this thread could get all the way to 20 with > nobody arguing with the vi folks. Will the Windows vim and gvim users > vouch for its stability on Windows? Sure. Do you need any legal assistance? -- Jarek Zgoda http://jpa.berlios.de/ From alanalan at newsgroup.nospam Thu Jun 1 08:11:32 2006 From: alanalan at newsgroup.nospam (A.M) Date: Thu, 1 Jun 2006 08:11:32 -0400 Subject: DB-API: how can I find the column names in a cursor? Message-ID: Hi I use a code similar to this to retrieve data from Oracle database: import cx_Oracle con = cx_Oracle.connect("me/secret at tns") cur = con.cursor() outcur = con.cursor() cur.execute(""" BEGIN MyPkg.MyProc(:cur); END;""", cur=outcur) for row in out_cur: print row The problem is I don't know how to find out what are the column name and type that comes out of query (each row in cursor). Is there any possibility that my Python code can find out the column name and type in each row in cursor? The other problem is accessing data in each row by column name. In Ruby I can say: Print row["ColName"] In Python; however, I must access to row contents by integer index, like PRINT ROW[0], which reduces my program's readability. Can I access to row's contents by column name? Any help would be appreciated, Alan From marek.rocki at wp.pl Wed Jun 14 19:19:27 2006 From: marek.rocki at wp.pl (marek.rocki at wp.pl) Date: 14 Jun 2006 16:19:27 -0700 Subject: __cmp__ method In-Reply-To: <1150324916.775821.142390@u72g2000cwu.googlegroups.com> References: <1150324916.775821.142390@u72g2000cwu.googlegroups.com> Message-ID: <1150327167.320873.12760@u72g2000cwu.googlegroups.com> Python documentation says: >__cmp__( self, other) > Called by comparison operations if rich comparison (see above) is not defined. So it seems you have to redefine rich comparisons __lt__, __gt__, __eq__ etc as well. If all you need is change sorting order, why not use appropriate parameters of sorted() function (cmp=... or key=...)? From daddyswart456 at hotmail.com Wed Jun 14 11:57:14 2006 From: daddyswart456 at hotmail.com (Kathy Garcia) Date: Wed, 14 Jun 2006 15:57:14 +0000 Subject: Python Help Message-ID: An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Tue Jun 13 01:20:53 2006 From: sjmachin at lexicon.net (John Machin) Date: Tue, 13 Jun 2006 15:20:53 +1000 Subject: Extending Python - Understanding Flags... In-Reply-To: <448E4918.3050105@lexicon.net> References: <448E4918.3050105@lexicon.net> Message-ID: <448E4B35.3020801@lexicon.net> On 13/06/2006 3:11 PM, John Machin wrote: > def bfunction(foo=0, bar="plugh", zot=None): > # keyword args, caller can do: > bfunction(zot=10**100) # using a keyword: args foo & bar get default values > bfunction(10, "xyzzy") # positional: foo = 10; bar = "xyzzy"; zot = 10**100 The last line above should end with zot = None instead of zot = 10**100 From 63q2o4i02 at sneakemail.com Mon Jun 26 00:39:45 2006 From: 63q2o4i02 at sneakemail.com (63q2o4i02 at sneakemail.com) Date: 25 Jun 2006 21:39:45 -0700 Subject: Interactive debugging Message-ID: <1151296785.275841.294080@y41g2000cwy.googlegroups.com> Hi, is there a way in python to place some sort of keyboard() type statement which stops the script and puts you back at the console? I'm looking for something like in matlab, where you place a keyboard() command (I think), then you're in debug mode in the console, and you type continue to re-enter the script where you left off. While you're in the debugger/console you're at the scope where the keyboard() call was and you can manipulate variables, etc. Is there something like this in python? I've been using winpdb, which is great, but sometimes I need more interactivity. Is this what pdb is about? thanks ms From claird at lairds.us Sun Jun 18 13:20:55 2006 From: claird at lairds.us (Cameron Laird) Date: Sun, 18 Jun 2006 17:20:55 +0000 Subject: download file from intranet linux server to windows clients References: <4492e5c1$0$15782$14726298@news.sunsite.dk> Message-ID: In article <4492e5c1$0$15782$14726298 at news.sunsite.dk>, Luis P. Mendes wrote: . . . >I'm building an intranet web server in Linux for around 40 windows >clients with Django. > >The problem is that I want to build an excel file based on criteria >entered by the client, that the client must be able do download to his >personal work space. I use pyExcelerator to create the Excel files. > >How can I do it? Do I need another excel generator? > >Client's information about its working directory should be read, but >how? I could only find the way to read the server environment >variables, where data is processed. . . . We do a lot of this--dynamic construction on the server-side of Excel documents, delivered as Web pages. My impression is that you're working too hard: don't bother worrying about where "the client's workspace" is; just let the browser manage all that. Browsers are adequate or better at downloading. From steve at holdenweb.com Thu Jun 29 06:46:52 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 29 Jun 2006 11:46:52 +0100 Subject: Immutability In-Reply-To: References: <4Qj*cEjkr@news.chiark.greenend.org.uk> Message-ID: Georg Brandl wrote: > Steve Holden wrote: [...] > >>Would it make sense, in the single argument case, to default the doc >>value to fget.__doc__ to support that use case, or should we just not >>create read-only properties by using property as a decorator? > > > This is actually already the case in 2.5. > Sorry, haven't had much time for python-checkins lately. But this would certainly argue that the decorator form for read-only properties is accepted at some level. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From james.wondrasek at gmail.com Thu Jun 1 20:13:47 2006 From: james.wondrasek at gmail.com (james.wondrasek at gmail.com) Date: 1 Jun 2006 17:13:47 -0700 Subject: Can Python format long integer 123456789 to 12,3456,789 ? References: <8oKfg.1621$Su3.139425@news20.bellglobal.com> Message-ID: <1149207227.173231.126990@h76g2000cwa.googlegroups.com> A.M wrote: > Hi, > > Is there any built in feature in Python that can format long integer > 123456789 to 12,3456,789 ? > > Thank you, > Alan I did this for putting commas into monetary amounts (thus the .2f): def commas(value): return "".join(commafy("%.2f" % value)) def commafy(s): pieces = s.split(".") l = len(pieces[0]) for i in range(0,l): if (l - i) % 3 or not i: yield pieces[0][i] else: yield "," yield pieces[0][i] if len(pieces) > 1: yield "." + pieces[1] jtm From gherron at islandtraining.com Wed Jun 7 02:21:50 2006 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 06 Jun 2006 23:21:50 -0700 Subject: A more elegant way to do this list comprehension? In-Reply-To: <12428afb0606062046nda97570j2b5eb7cab5518352@mail.gmail.com> References: <12428afb0606062046nda97570j2b5eb7cab5518352@mail.gmail.com> Message-ID: <4486707E.7010803@islandtraining.com> Levi Self wrote: > This probably seems very trivial, maybe even a bit silly, but I was > wondering if someone has a better list comprehension that does the > same thing as this one: > > >>> print [[[i]*i for i in range(1,9)][j][k] for j in range(8) for k > in range(j+1)] > [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 7, 7, > 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8] > > Thanks, > Levi Sure. Try: [i+1 for i in range(8) for j in range(i+1)] Gary Herron From bborcic at gmail.com Thu Jun 8 10:42:48 2006 From: bborcic at gmail.com (Boris Borcic) Date: Thu, 08 Jun 2006 16:42:48 +0200 Subject: How to generate k+1 length strings from a list of k length strings? In-Reply-To: References: Message-ID: <44883789$1_4@news.bluewin.ch> Girish Sahani wrote: > I have a list of strings all of length k. For every pair of k length > strings which have k-1 characters in common, i want to generate a k+1 > length string(the k-1 common characters + 2 not common characters). > e.g i want to join 'abcd' with bcde' to get 'abcde' but i dont want to > join 'abcd' with 'cdef' > Currently i'm joining every 2 strings, then removing duplicate characters > from every joined string and finally removing all those strings whose > length != k+1. Hum, since your code is not syntactically correct, anything will run faster :) I'd favor the following, that I find most readable sets = map(set,list_of_strings) res = set(''.join(sorted(s1|s2)) for s1 in sets for s2 in sets if len(s1^s2)==2) unless performance is really an issue Here's the code i've written: > > for i in range(0,len(prunedK) - 1,1): > if k in range(1,len(prunedK),1) & i+k <= len(prunedK) -1: > colocn = prunedK[i] + prunedK[i+k] > prunedNew1.append(colocn) > continue > for string in prunedNew1: > stringNew = withoutDup(string) > prunedNew.append(stringNew) > continue > > But this one is quite bad in the time aspect :( how do you know ? > Thanks in advance, > girish you should do your own homework From nogradi at gmail.com Sat Jun 24 09:08:30 2006 From: nogradi at gmail.com (Daniel Nogradi) Date: Sat, 24 Jun 2006 15:08:30 +0200 Subject: search engine In-Reply-To: <1151154081.787601.121110@i40g2000cwc.googlegroups.com> References: <1151151361.359777.269130@y41g2000cwy.googlegroups.com> <1151154081.787601.121110@i40g2000cwc.googlegroups.com> Message-ID: <5f56302b0606240608s49ab2a43p67d849d0616b8839@mail.gmail.com> > hai all, > i am student of computer science dept. i have planned to > design a search engine in python. i am seeking info about how to > proceed further. > i need to know what r the modules that can be used. There are these two guys Sacha or Sergey and Larry (if I remember correctly) who already wrote a cute search engine in python, perhaps you could ask them for some help. From rbonvall at gmail.com Wed Jun 7 12:22:56 2006 From: rbonvall at gmail.com (Roberto Bonvallet) Date: Wed, 7 Jun 2006 12:22:56 -0400 Subject: Concatenating dictionary values and keys, and further operations In-Reply-To: <1149571529.782630.144400@j55g2000cwa.googlegroups.com> References: <1149571529.782630.144400@j55g2000cwa.googlegroups.com> Message-ID: <1908cb6b0606070922m5edbdc6fm44c93f7e332b884a@mail.gmail.com> Girish said, through Gerard's forwarded message: > >Thanks a lot Gerard and Roberto.but i think i should explain the exact > >thing with an example. > >Roberto what i have right now is concatenating the keys and the > >corresponding values: > >e.g {'a':[1,2],'b':[3,4,5],'c':[6,7]} should give me > >{'ab':[1,2][3,4,5] 'ac':[1,2][6,7] 'bc':[3,4,5][6,7]} > >The order doesnt matter here.It could be 'ac' followed by 'bc' and 'ac'. > >Also order doesnt matter in a string:the pair 'ab':[1,2][3,4,5] is same as > >'ba':[3,4,5][1,2]. > >This representation means 'a' corresponds to the list [1,2] and 'b' > >corresponds to the list [3,4,5]. The problem if that the two lists aren't distinguishable when concatenated, so what you get is [1, 2, 3, 4, 5]. You have to pack both lists in a tuple: {'ab': ([1, 2], [3, 4, 5]), ...} >>> d = {'a':[1, 2], 'b':[3, 4, 5], 'c':[6, 7]} >>> d2 = dict(((i + j), (d[i], d[j])) for i in d for j in d if i < j) >>> d2 {'ac': ([1, 2], [6, 7]), 'ab': ([1, 2], [3, 4, 5]), 'bc': ([3, 4, 5], [6, 7])} > >Now, for each key-value pair,e.g for 'ab' i must check each feature in the > >list of 'a' i.e. [1,2] with each feature in list of 'b' i.e. [3,4,5].So I > >want to take cartesian product of ONLY the 2 lists [1,2] and [3,4,5]. You can do this without creating an additional dictionary: >>> d = {'a':[1, 2], 'b':[3, 4, 5], 'c':[6, 7]} >>> pairs = [i + j for i in d for j in d if i < j] >>> for i, j in pairs: ... cartesian_product = [(x, y) for x in d[i] for y in d[j]] ... print i + j, cartesian_product ... ac [(1, 6), (1, 7), (2, 6), (2, 7)] ab [(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5)] bc [(3, 6), (3, 7), (4, 6), (4, 7), (5, 6), (5, 7)] You can do whatever you want with this cartesian product inside the loop. > >Finally i want to check each pair if it is present in the file,whose > >format i had specified. I don't understand the semantics of the file format, so I leave this as an exercise to the reader :) Best regards. -- Roberto Bonvallet From userprogoogle-139 at yahoo.co.uk Thu Jun 22 05:50:04 2006 From: userprogoogle-139 at yahoo.co.uk (rodmc) Date: 22 Jun 2006 02:50:04 -0700 Subject: Help req: Problems with MySQLdb In-Reply-To: References: <1150968147.565850.156870@u72g2000cwu.googlegroups.com> Message-ID: <1150969803.984843.111950@y41g2000cwy.googlegroups.com> Hi, Thanks for your email. Well I am kind of new to exceptions in Python, but here is the code used below, as you can see it is somewhat basic. Is there a way to display more information about the exception? Best, rod try: #Exception handler for database queries db = MySQLdb.connect(host=DBSERVERIP, user="user", passwd="password", db="nuke") except: print "A database connection error has occurred" return False else: #The rest of the program Sybren Stuvel wrote: > rodmc enlightened us with: > > --- it refuses to connect on the above line and the exception is > > caught and a message displayed. > > So.... why do you think this exception and the error message contain > no useful information at all? > > Sybren > -- > The problem with the world is stupidity. Not saying there should be a > capital punishment for stupidity, but why don't we just take the > safety labels off of everything and let the problem solve itself? > Frank Zappa From pc at p-cos.net Fri Jun 23 07:41:47 2006 From: pc at p-cos.net (Pascal Costanza) Date: Fri, 23 Jun 2006 13:41:47 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: <1150986901.299913.139200@m73g2000cwd.googlegroups.com> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150902275.129780.50260@p79g2000cwp.googlegroups.com> <1150918629.818145.143220@y41g2000cwy.googlegroups.com> <4fv081F1jh4ifU1@individual.net> <1150986901.299913.139200@m73g2000cwd.googlegroups.com> Message-ID: <449BD37B.10904@p-cos.net> Marshall wrote: > I am sceptical of the idea that when programming in a dynamically > typed language one doesn't have to think about both models as well. > I don't have a good model of the mental process of working > in a dynamically typed language, but how could that be the case? > (I'm not asking rhetorically.) Do you then run your program over > and over, mechanically correcting the code each time you discover > a type error? In other words, if you're not thinking of the type model, > are you using the runtime behavior of the program as an assistant, > the way I use the static analysis of the program as an assistant? Yes. > I don't accept the idea about pairing the appropriateness of each > system according to whether one is doing exploratory programming. > I do exploratory programming all the time, and I use the static type > system as an aide in doing so. Rather I think this is just another > manifestation of the differences in the mental processes between > static typed programmers and dynamic type programmers, which > we are beginning to glimpse but which is still mostly unknown. Probably. > Oh, and I also want to say that of all the cross-posted mega threads > on static vs. dynamic typing, this is the best one ever. Most info; > least flames. Yay us! Yay! :) Pascal -- 3rd European Lisp Workshop July 3 - Nantes, France - co-located with ECOOP 2006 http://lisp-ecoop06.bknr.net/ From brochu121 at gmail.com Fri Jun 23 11:40:39 2006 From: brochu121 at gmail.com (brochu121 at gmail.com) Date: 23 Jun 2006 08:40:39 -0700 Subject: Python in HTML Message-ID: <1151077239.840572.175120@y41g2000cwy.googlegroups.com> Does anyone know of a way to embed python scripts into html, much like you would javascript or php? I do not want to use this to connect to a database, but rather for a functional script to be called when a user clicks on a link to open a page. From onurb at xiludom.gro Fri Jun 16 09:03:17 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 16 Jun 2006 15:03:17 +0200 Subject: a good programming text editor (not IDE) In-Reply-To: <1150392759.297671.168330@u72g2000cwu.googlegroups.com> References: <_xgkg.2317$No6.48542@news.tufts.edu> <1150392759.297671.168330@u72g2000cwu.googlegroups.com> Message-ID: <4492ac16$0$14877$626a54ce@news.free.fr> BartlebyScrivener wrote: > I see Eclipse mentioned here a lot. If you go for a Mammoth-weight GUI-only Java IDE and have a really powerful computer, why not ? -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From brian at sweetapp.com Thu Jun 1 11:10:14 2006 From: brian at sweetapp.com (Brian Quinlan) Date: Thu, 01 Jun 2006 17:10:14 +0200 Subject: New to Python: Do we have the concept of Hash in Python? In-Reply-To: References: Message-ID: <447F0356.3090207@sweetapp.com> A.M wrote: > Is there any built-in Hash implementation in Python? I am looking for a > container that I can access to it's items by name. Something like this: > > Print container["memeberName"] d = {"memberName" : "some value"} print d["memberName"] > I am asking this because I learned that DB-API in Python doesn't offer > access to cursor columns by name. The only option is access by index. I hope > that I've got it wrong! > > I learned Ruby perfectly supports that. Python does not use column names by default because they are not portable across database implementations. That being said, you can get them easily, if you want. Look at the "description" attribute of your cursor instance. Cheers, Brian From lhw1 at netspace_no_s_pa_m.net.au Mon Jun 26 21:09:45 2006 From: lhw1 at netspace_no_s_pa_m.net.au (Luke) Date: Tue, 27 Jun 2006 11:09:45 +1000 Subject: Beginner question: use function to read text file Message-ID: I'm pretty stuck at the moment and wondering if anyone can spot the problem. Trying to create a function that will read a text file into a list and return that list. I wrote the following function and saved it as 'fileloader.py' def fileload(fname): infile=open(fname) dates =[] times=[] open=[] high=[] low=[] close=[] vol=[] count=0 for line in infile: item=line.split() dates.append(item[0]) times.append(item[1]) open.append(item[2]) high.append(item[3]) low.append(item[4]) close.append(item[5]) vol.append(item[6]) #print dates[count],times[count],open[count],high[count],low[count],vol[count] count=count+1 return dates,times,open,high,low,close Then I executed the following script (merge contract v1.py): import fileloader filename='c:/Python24/test/testdata2.txt' fileloader.fileload(filename) I then get the following error messages: Traceback (most recent call last) File "C:\Python24\test\merge contract v1.py", in line3, in? fileloader.fileload(filename) File ("C:\Python24\text\fileloader.py", in line2, in fileload infile=open(fname) UnboundLocalError: local variable 'open' referenced before assignment Script terminated Thanks for any help, Luke From girish at cse.iitb.ac.in Fri Jun 9 19:51:09 2006 From: girish at cse.iitb.ac.in (Girish Sahani) Date: Sat, 10 Jun 2006 05:21:09 +0530 (IST) Subject: Error in Chain of Function calls (Code Attached) In-Reply-To: <448994e6$1_3@news.bluewin.ch> References: <448930f1$0$10302$636a55ce@news.free.fr> <448994e6$1_3@news.bluewin.ch> Message-ID: <60248.10.209.4.2.1149897069.squirrel@10.105.1.3> Thanks for the help boris....i'll try using sets instead of lists But i dont understand the point below...full traceback means what :-? > Girish Sahani wrote: > >>>> However i am getting an error at the line marked with ***. > >>> Which error ? How do you hope us to be of any help here if you don't >>> *at >>> least* provide the full traceback ? FWIW, the canonical way to do >>> things >>> is to: >>> - provide minimal *runnable* code exposing the problem >>> - explain what you hoped to get >>> - explain what you got instead (including full traceback) >>> >>> As a matter of fact, it's often the case that one solves the problem >>> when working on the first point !-) >>> >>> (snip) >> Ohh...I was thinking that posting the whole code would not be a good >> idea. > > And what changed your mind ? Please note the word "minimal" in bruno's > sentence > about submitting your code. And also the request for explanations. > >> The error i get above is: >> line 266, in colocationMiner >> prunedNew = genColocations(prunedK) > > OTOH, bruno asked for the full traceback, that's not it - that's not "the > error" > in any constructive sense, neither its type nor its real location. > -- > http://mail.python.org/mailman/listinfo/python-list > From antroy at gmail.com Tue Jun 13 13:08:41 2006 From: antroy at gmail.com (Ant) Date: 13 Jun 2006 10:08:41 -0700 Subject: Is there a better way of accessing functions in a module? In-Reply-To: <1150218398.443615.304880@p79g2000cwp.googlegroups.com> References: <1150218398.443615.304880@p79g2000cwp.googlegroups.com> Message-ID: <1150218521.603365.306410@u72g2000cwu.googlegroups.com> Ant wrote: ... > But this feels like a hack... Is there a cleaner way for accessing the > functions of the current module similar to the __dict__ attribute of > classes? i.e. a way to access the local symbol table? Sorry - posted too soon. Found the globals() built-in... From steve at holdenweb.com Mon Jun 12 03:00:13 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 12 Jun 2006 08:00:13 +0100 Subject: direct initialization of class attributes vs. declarations w/in __init__ In-Reply-To: <1150081483.255765.124450@j55g2000cwa.googlegroups.com> References: <1150041510.139609.171120@f6g2000cwb.googlegroups.com> <4f2thrF1fd4r4U1@uni-berlin.de> <1150043792.136250.99770@u72g2000cwu.googlegroups.com> <1150047314.025241.260750@c74g2000cwc.googlegroups.com> <1150062413.303012.177330@f6g2000cwb.googlegroups.com> <1150063606.929384.300040@j55g2000cwa.googlegroups.com> <1150081483.255765.124450@j55g2000cwa.googlegroups.com> Message-ID: digitalorganics at gmail.com wrote: > Fredrik Lundh wrote: > >>digitalorganics at gmail.com wrote: >> >> >>>Output from laptop comp.: >>> >>>1 >>>10 >>>2 >>>10 >>>3 >>>10 >> >>so how are you entering and running the code on your laptop ? >> >>what happens if you set the class attribute to 100 instead of 10 ? >> >> > > > You can see my other post which I just sent but, I was using PythonWin: > > 1. type code in editor > 2. hit run > 3. observe output in interactive window > Frankly I'd be less incredulous if you'd said you transferred the code between machines using some network- or file-based transfer mechanism. The facts are that if you have been entering "the same" code separately on two machines then by far the most likely source of any discrepancy is typographical error (a subject with which regular readers will know I am intimately familiar). The Python behaviour you now understand (access to class variables in the absence of an eponymous instance variable) is long-standing, and it is therefore unlikely that two correct Python installations will give different results for the same code. Ergo, the two pieces of code are different. Unless, that is, you can tell us different beyond all possibility of transcription errors. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From overly.crazy.steve at gmail.com Thu Jun 1 20:30:30 2006 From: overly.crazy.steve at gmail.com (overly.crazy.steve at gmail.com) Date: 1 Jun 2006 17:30:30 -0700 Subject: execfile then import back Message-ID: <1149208230.216141.5400@f6g2000cwb.googlegroups.com> I am seeing something strange with execfile. I've simplified the code to: ########## t.py ########## print "here" v = None def f(): global v v = 6 if __name__ == "__main__": f() print "0:", v execfile("x.py") print "0:", v execfile("y.py") print "0:", v ########## x.py and y.py (they are identical) ########## import testexec print "1:", v, testexec.v testexec.v = 7 Runing "python t.py" (with Python 2.4.2), the printout I got is: here 0: 6 here 1: 6 None 0: 6 1: 6 7 0: 6 So there is apparently 2 different instances of v at run time. Can someone please explain (1) why this is the case, and (2) assuming this is correct behavior, how I can avoid this? Thanks. From could.net at gmail.com Wed Jun 7 21:39:09 2006 From: could.net at gmail.com (Frank Potter) Date: Thu, 8 Jun 2006 09:39:09 +0800 Subject: Regular Expression question In-Reply-To: References: <1149714949.542234.148800@y43g2000cwc.googlegroups.com> Message-ID: <311b5ce10606071839v6376d6f3g404b44c2f969bd2b@mail.gmail.com> pyparsing is cool. but use only re is also OK # -*- coding: UTF-8 -*- import urllib2 html=urllib2.urlopen(ur"http://www.yahoo.com/").read() import re r=re.compile('[^"]+)"[^>]*>',re.IGNORECASE) for m in r.finditer(html): print m.group('image') I got these rusults: http://us.i1.yimg.com/us.yimg.com/i/ww/beta/edit_plink.gif http://us.i1.yimg.com/us.yimg.com/i/ww/bt1/125.gif http://us.i1.yimg.com/us.yimg.com/i/ww/bt1/13441.gif http://us.i1.yimg.com/us.yimg.com/i/ww/bt1/136.gif http://us.i1.yimg.com/us.yimg.com/i/ww/beta/y3.gif http://us.i1.yimg.com/us.yimg.com/i/ww/bt1/ml.gif http://us.i1.yimg.com/us.yimg.com/i/ww/bt1/my.gif http://us.i1.yimg.com/us.yimg.com/i/ww/bt1/msgn.gif http://us.i1.yimg.com/us.yimg.com/i/ww/v5_mail_t2.gif http://us.i1.yimg.com/us.yimg.com/i/ww/news/2006/06/07/0607notorious_big.jpg http://us.i1.yimg.com/us.yimg.com/i/ww/beta/wthr.gif http://us.i1.yimg.com/us.yimg.com/i/mntl/sh/04q2/camera.gif On 6/8/06, Paul McGuire wrote: > wrote in message > news:1149714949.542234.148800 at y43g2000cwc.googlegroups.com... > > Hi, > > I am new to python regular expression, I would like to use it to get an > > attribute of an html element from an html file? > > > > for example, I was able to read the html file using this: > > req = urllib2.Request(url=acaURL) > > f = urllib2.urlopen(req) > > > > data = f.read() > > > > my question is how can I just get the src attribute value of an img > > tag? > > something like this: > > (.*)(.*) > > > > I need to get the href of the image source. > > > > Thanks. > > > > As Fredrik pointed out, re's are not the only tool out there. Here's a > pyparsing solution. > > -- Paul > > > import pyparsing > import urllib > > # define HTML tag format using makeHTMLTags helper > # (we don't really care about the ending tag, > # even though makeHTMLTags returns definitions for both > # starting and ending tag patterns) > imgStartTag, dummy = pyparsing.makeHTMLTags("img") > > # get HTML source from some web site > htmlPage = urllib.urlopen("http://www.yahoo.com") > htmlSource = htmlPage.read() > htmlPage.close() > > # scan HTML source, printing SRC attribute from each tag > for tokens,start,end in imgStartTag.scanString(htmlSource): > print tokens.src > > > Prints: > > http://us.i1.yimg.com/us.yimg.com/i/ww/beta/edit_plink.gif > http://us.i1.yimg.com/us.yimg.com/i/ww/bt1/125.gif > http://us.i1.yimg.com/us.yimg.com/i/ww/bt1/13441.gif > http://us.i1.yimg.com/us.yimg.com/i/ww/bt1/136.gif > http://us.i1.yimg.com/us.yimg.com/i/ww/beta/y3.gif > http://us.i1.yimg.com/us.yimg.com/i/ww/bt1/ml.gif > http://us.i1.yimg.com/us.yimg.com/i/ww/bt1/my.gif > http://us.i1.yimg.com/us.yimg.com/i/ww/bt1/msgn.gif > http://us.i1.yimg.com/us.yimg.com/i/ww/v5_mail_t2.gif > http://us.i1.yimg.com/us.yimg.com/i/mntl/aut/06q2/hea_0411.gif > http://us.i1.yimg.com/us.yimg.com/i/mntl/aut/06q2/img_0607.jpg > http://us.i1.yimg.com/us.yimg.com/i/ww/news/2006/06/07/0607notorious_big.jpg > http://us.i1.yimg.com/us.yimg.com/i/ww/beta/news/video.gif > http://us.i1.yimg.com/us.yimg.com/i/buzz/2006/06/wholefoodssmall.jpg > http://us.i1.yimg.com/us.yimg.com/i/mntl/msg/06q2/img_im.jpg > http://us.i1.yimg.com/us.yimg.com/i/ww/trfc_bckt.gif > http://us.i1.yimg.com/us.yimg.com/i/mntl/sh/04q2/camera.gif > > > -- > http://mail.python.org/mailman/listinfo/python-list > From uval at rz.uni-karlsruhe.de Fri Jun 23 10:06:46 2006 From: uval at rz.uni-karlsruhe.de (Daniel Schüle) Date: Fri, 23 Jun 2006 16:06:46 +0200 Subject: what exceptions may file() and read() throw? Message-ID: Hello, currently I am using this instance method def getFilecontent(self, filename): try: return file(filename).read() except IOError, err_msg: print err_msg sys.exit(1) except: print "unknown exception in PackageParser" sys.exit(1) I tried to open a file for which I don't have the permissions to read (etc/shadow) and I tried to open a file which doesn't exist in both cases I got IOError exception, so my question is does it make sence to have except: print "unknown exception in PackageParser" sys.exit(1) or is it a dead code? are there some good reference sources to see what file() and read() may throw, IMHO it's OS dependent. Regards, Daniel From ljr2600 at gmail.com Sun Jun 11 22:00:17 2006 From: ljr2600 at gmail.com (ljr2600 at gmail.com) Date: 11 Jun 2006 19:00:17 -0700 Subject: Screen Scraping for Modern Applications? Message-ID: <1150077617.598735.85540@h76g2000cwa.googlegroups.com> Hello, I'm very new to python and still familiarizing myself with the language, sorry if the post seems moronic or simple. For a side project I'm working on I need to be able to scrape a modern computer desktop. Is there any basic material already available to do this? I'd rather not need to write my own to interact with hardware. Thanks! From meyer at mesw.de Sat Jun 17 11:13:48 2006 From: meyer at mesw.de (meyer at mesw.de) Date: 17 Jun 2006 08:13:48 -0700 Subject: Which compiler will Python 2.5 / Windows (Intel) be built with? In-Reply-To: <44933F17.7050500@v.loewis.de> References: <1150367139.495114.148550@g10g2000cwb.googlegroups.com> <44917535$1@nntp0.pdx.net> <1150391891.130185.4640@f6g2000cwb.googlegroups.com> <4492414C.10505@v.loewis.de> <1150444191.618761.22810@c74g2000cwc.googlegroups.com> <44933F17.7050500@v.loewis.de> Message-ID: <1150557228.922848.259890@u72g2000cwu.googlegroups.com> Martin, Martin v. L?wis wrote: > > * In a professional environment, it opens up another can of potential > > problems, where one would rather like to stay with one single > > compiler/build system. > That's a theoretic argument to me: Can you name four or five problems > out of that can? In bigger (i.e. real-world) projects, it can be a lot of hassle switching to another compiler, even from the same vendor. Of course, in theory C and C++ compilers should be compatible, but in practice there's lots of small things that are implemented differently. Among them are #pragmas, the support for precompiled headers, template instantiation, different semantics for "half-legal" constructs etc. Also, some syntactic constructs which compile on one compiler are rejected by another compiler. Further, often code implicitely depends on the behaviour of one single compiler, although the developer doesn't really know that. Of course you can cry fool on the developer that wrote the code and blame him for not following the C-whatever spec, or not using the "correct" way to do X, but fact is, there's always stuff that will not work when switching to another compiler. And there's a bunch of other stuff that will appear to work but "activate" bugs in the control structure that were there previously but luckily did not manifest with the other compiler. Btw, the same goes for different versions of libraries, say different versions of wxWidgets, MFC, Visual Basic (anyone tried to switch from VB6 to VB.NET?) and of course also for different versions of Java and its libraries. > > * The Makefiles/build system will need to be changed to work with the > > GCC toolchain > > If you are using distutils, you don't need a Makefile, and the > setup.py won't have to be tweaked. If you are not using distutils, > but, say, nmake already, then you will already have an earlier version > of the compiler - how else did you create the nmake files in the first > place? We have lots of stuff written in VC++6 which is not distutils-compatible, and we can't really switch that code over to GCC anytime soon, see above. All in all, we would end up compiling something with VC, linking it with GCC to another VC app (Python). No, thanks. > Still, if you really cannot use gcc, then go ahead and compile with > VS 2005. Just make sure you link with mscvr71.dll. If you absolutely > need that to work, you will find a way to make it work. The question is, is it cheaper and more hassle-free to spend the time to "find a way to make it work" and hope everything goes smoothly (remember, the fact, that it says "Linker results: 0 errors / 0 warnings" does not mean that the app will work as expected and as tested before) or to buy VC (which costs a mere few hundred dollars). Bottom Line: As I said before, I don't have a problem using VC2003 or anything. It's by far the cheapest and easiest way just to buy VC2003 and be done with it, than to fiddle around with GCC or anything. I just think that Python should use the best technology available at the time of release, which is VC2005 on Windows. But as I indicated before, of course I do understand the argument that the release cycle has already been planned and should not be changed, so we'll just live with it as it is now. Markus From rpdooling at gmail.com Thu Jun 15 12:04:31 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 15 Jun 2006 09:04:31 -0700 Subject: Python is fun (useless social thread) ;-) References: <1150381872.958342.180420@p79g2000cwp.googlegroups.com> <44917776$1@nntp0.pdx.net> Message-ID: <1150387471.341026.260090@c74g2000cwc.googlegroups.com> >> I'd like something a bit like a module, >> but I'd like to make several of them, >> and not have them interfere with each other." Thank you. I sense what you are saying, but at this point I'd be thinking, "Why not just make several modules?" :) I'll get to it. I've got my hands full just learning everything else. rd From robert.thorpe at antenova.com Wed Jun 21 12:27:23 2006 From: robert.thorpe at antenova.com (Rob Thorpe) Date: 21 Jun 2006 09:27:23 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: <1150731889.008745.12180@i40g2000cwc.googlegroups.com> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> Message-ID: <1150907242.960017.79600@r2g2000cwb.googlegroups.com> Rob Thorpe wrote: > Chris Smith wrote: > > Torben ?gidius Mogensen wrote: > > > That's not really the difference between static and dynamic typing. > > > Static typing means that there exist a typing at compile-time that > > > guarantess against run-time type violations. Dynamic typing means > > > that such violations are detected at run-time. This is orthogonal to > > > strong versus weak typing, which is about whether such violations are > > > detected at all. The archetypal weakly typed language is machine code > > > -- you can happily load a floating point value from memory, add it to > > > a string pointer and jump to the resulting value. ML and Scheme are > > > both strongly typed, but one is statically typed and the other > > > dynamically typed. > > > > Knowing that it'll cause a lot of strenuous objection, I'll nevertheless > > interject my plea not to abuse the word "type" with a phrase like > > "dynamically typed". If anyone considers "untyped" to be perjorative, > > as some people apparently do, then I'll note that another common term is > > "type-free," which is marketing-approved but doesn't carry the > > misleading connotations of "dynamically typed." We are quickly losing > > any rational meaning whatsoever to the word "type," and that's quite a > > shame. > > I don't think dynamic typing is that nebulous. I remember this being > discussed elsewhere some time ago, I'll post the same reply I did then > .. > A language is statically typed if a variable has a property - called > it's type - attached to it, and given it's type it can only represent > values defined by a certain class. > > A language is latently typed if a value has a property - called it's > type - attached to it, and given it's type it can only represent values > defined by a certain class. > > Some people use dynamic typing as a word for latent typing, others use > it to mean something slightly different. But for most purposes the > definition above works for dynamic typing also. > > Untyped and type-free mean something else: they mean no type checking > is done. Since people have found some holes in this definition I'll have another go:- Firstly, a definition, General expression (gexpr) are variables (mutable or immutable), expressions and the entities functions return. A statically typed language has a parameter associated with each gexpr called it's type. The code may test the type of a gexpr. The language will check if the gexprs of an operator/function have types that match what is required, to some criteria of sufficiency. It will emit an error/warning when they don't. It will do so universally. A latently typed language has a parameter associated with each value called it's type. The code may test the type of a value. The language may check if the gexprs of an operator/function have types that match what is required, to some criteria of sufficiency. It will not necessarily do so universally. An untyped language is one that does not possess either a static or latent type system. In an untyped language gexprs possess no type information, and neither do values. -- These definitions still have problems, they don't say anything about languages that sit between the various categories for example. I don't know where HM type system would come in them. From exarkun at divmod.com Fri Jun 30 15:33:00 2006 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Fri, 30 Jun 2006 15:33:00 -0400 Subject: Import bug: Module executed twice when imported! In-Reply-To: Message-ID: <20060630193300.29014.1981212929.divmod.quotient.16769@ohm> On Fri, 30 Jun 2006 19:13:00 +0100, Michael Abbott wrote: >Bump > >In article , > Michael Abbott wrote: > >> --- test.py --- >> import imptest >> execfile('subtest.py', dict(__name__ = 'subtest.py')) >> --- imptest.py --- >> print 'Imptest imported' >> --- subtest.py --- >> import imptest >> --- >> >> $ python test.py >> Imptest imported >> Imptest imported >> $ > >I claim this as an unreported (and highly obscure) Python bug. You set __name__ to 'subtest.py' when executing subtest.py which made the import system believe that when it found imptest.py it was being imported as a *sibling* of the running module, which was subtest.py, making the module being imported subtest.imptest. Since the first imptest was imported by the name imptest, subtest.imptest was determined to be a different module and re-executed. Set __name__ to 'subtest' as it would be if you had really imported subtest and the import system will correctly name the modules, causing imptest to be imported only once. Jean-Paul From fivenastydisco at hotmail.com Thu Jun 8 12:55:56 2006 From: fivenastydisco at hotmail.com (donkeyboy) Date: 8 Jun 2006 09:55:56 -0700 Subject: Newbie question about updating multiple objects ... In-Reply-To: <4eq5g6F1fl78oU1@uni-berlin.de> References: <1149753137.498806.314640@c74g2000cwc.googlegroups.com> <4eq5g6F1fl78oU1@uni-berlin.de> Message-ID: <1149785756.719736.118370@u72g2000cwu.googlegroups.com> Awesome Diez -- I'll give this a go tomorrow, and hopefully it will all work!! Diez B. Roggisch wrote: > fivenastydisco at hotmail.com wrote: > > I've copied in the code I'm using below, as it's not very long -- can > > anyone help me? > > I'll have some remarks: > > > > <--START--> > > > > from visual import * > > from random import randrange # to create random numbers > > > > numballs = 5 # number of balls > > balls = [] # a list to contain the balls > > > > # set up a box to collide with > > side_length = 100 > > minx = side_length * -10 > > maxx = side_length * 10 > > miny = side_length * -4 > > maxy = side_length * 4 > > > > # create a wireframe of space > > left = curve(pos=[(minx, miny),(minx, maxy)], color = color.white) > > top = curve(pos = [(minx, maxy),(maxx, maxy)], color = color.white) > > right = curve(pos = [(maxx, maxy),(maxx, miny)], color = color.white) > > bottom = curve(pos = [(maxx, miny),(minx,miny)], color = color.white) > > > > #create some balls > > for b in range(numballs): # for each ball > > x = randrange(minx, maxx) > > y = randrange(miny, maxy) > > > Don't use range - use xrange. range actually creates a list of numbers, > where xrange creates a iterator that will just return the subsequent > numbers. The difference: the first solution consumes memory linear to the > number of numbers! > > > balls.append(sphere(pos = (x,y), radius = 50, color = color.red)) # > > add balls > > > > dt = 0.05 # time interval > > velocity = vector(2,0.2,1) # velocity of the balls > > > > while (1==1): # forever ... > > rate(50) > > for b in range(numballs): # for each ball ... > > This is a C-ism (or JAVA-ism if you like). The for-loop in python allows you > to iterate over objects in iterables. And list is one of those. So > > for ball in balls: > ball.x = ... > > does the trick. And if you need an index, the commonly used idiom is > > for i, ball in enumerate(balls): > ... > > > if balls[b].x < minx: # check it hasn't overrun a boundary > > balls[b].x = maxx > > if balls[b].x > maxx: > > balls[b].minx > > if balls[b].y < miny: > > balls[b].y = maxy > > if balls[b].y > maxy: > > balls[b].y = miny > > You should do that checks above _after_ you changed the coordinates, not > before! > > > # NB betting this is where it's going wrong ... > > balls[b].pos = balls[b].pos + (velocity * dt) # update the > > position of the ball > > This could be the problem: you are using a python tuple and a vector object > and add them. Are you sure that works? The python tuples themselves > concatenate under the +-operator. So you'd create a large tuple of > coordinate differences here. > > I suppose that using a vector for the coordinates or doing the calculation > component-wise will solve the problem. > > HTH, > > Diez From aleax at mac.com Thu Jun 29 00:34:23 2006 From: aleax at mac.com (Alex Martelli) Date: Wed, 28 Jun 2006 21:34:23 -0700 Subject: Python in a nutshell - new edition ? References: <44A2C52A.6040807@skynet.be> <1hhnpen.1bkiv8l1d0r6puN%aleax@mac.com> <1151551938.499099.162520@75g2000cwc.googlegroups.com> Message-ID: <1hhnvof.1apknoe1v7zz8aN%aleax@mac.com> BartlebyScrivener wrote: > >> Yep, we're still aiming for OSCON '06 (Portland, end of July). > > Amazon says July 1st. Let me assure you that it _won't_ be on paper this coming Saturday (two days from now). Alex From digitalorganics at gmail.com Sun Jun 11 23:04:43 2006 From: digitalorganics at gmail.com (digitalorganics at gmail.com) Date: 11 Jun 2006 20:04:43 -0700 Subject: direct initialization of class attributes vs. declarations w/in __init__ In-Reply-To: References: <1150041510.139609.171120@f6g2000cwb.googlegroups.com> <4f2thrF1fd4r4U1@uni-berlin.de> <1150043792.136250.99770@u72g2000cwu.googlegroups.com> <1150047314.025241.260750@c74g2000cwc.googlegroups.com> <1150062413.303012.177330@f6g2000cwb.googlegroups.com> <1150063606.929384.300040@j55g2000cwa.googlegroups.com> Message-ID: <1150081483.255765.124450@j55g2000cwa.googlegroups.com> Fredrik Lundh wrote: > digitalorganics at gmail.com wrote: > > > Output from laptop comp.: > > > > 1 > > 10 > > 2 > > 10 > > 3 > > 10 > > so how are you entering and running the code on your laptop ? > > what happens if you set the class attribute to 100 instead of 10 ? > > You can see my other post which I just sent but, I was using PythonWin: 1. type code in editor 2. hit run 3. observe output in interactive window From eval.apply at gmail.com Tue Jun 27 17:59:43 2006 From: eval.apply at gmail.com (Joe Marshall) Date: 27 Jun 2006 14:59:43 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <1151384511.223582.305760@m73g2000cwd.googlegroups.com> <1151425350.679754.278820@i40g2000cwc.googlegroups.com> Message-ID: <1151445583.367455.288650@m73g2000cwd.googlegroups.com> QCD Apprentice wrote: > Joe Marshall wrote: > > Marshall wrote: > >> > >> The real question is, are there some programs that we > >> can't write *at all* in a statically typed language, because > >> they'll *never* be typable? > > > > Certainly! As soon as you can reflect on the type system you can > > construct programs that type-check iff they fail to type-check. > > Sorry, but can you elaborate on this last point a little? I think I > missed something. This is just the halting problem lifted up into the type domain. From rogue_pedro at yahoo.com Thu Jun 29 13:24:50 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 29 Jun 2006 10:24:50 -0700 Subject: Bug reporting impossible In-Reply-To: References: <1151598979.369897.140770@x69g2000cwx.googlegroups.com> Message-ID: <1151601890.184738.108590@x69g2000cwx.googlegroups.com> Nick Maclaren wrote: > In article <1151598979.369897.140770 at x69g2000cwx.googlegroups.com>, > "Simon Forman" writes: > |> Nick Maclaren wrote: > |> ... > |> > Create a file called '' in your current directory containing > |> > 'print "Oh, yeah?\n"' and then import a module that doesn't exist. > |> > Don't include the single quotes. > |> > |> Why would you have a file named '' in your current directory? > > Why would Python search for one? :-) Fair enough.. : ) > In both cases, the normal answer is "Someone made a mistake" but, if > you have a script that creates a files of the same names specified in > the current directory, what name should it use if you specify stdin? > It is one of the standard conventions, which is (after all) why Python > is searching for it. > > Anyway, I have now reported the bug - but this bug is more amusing than > serious. > > > Regards, > Nick Maclaren. I usually refrain from posting if I don't have anything to add to the discussion, but that struck me as perverse and I was curious. I certainly have no objection to having that bug fixed. : ) Peace, ~Simon From luismgz at gmail.com Thu Jun 15 14:34:13 2006 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 15 Jun 2006 11:34:13 -0700 Subject: Python is fun (useless social thread) ;-) In-Reply-To: <1150387471.341026.260090@c74g2000cwc.googlegroups.com> References: <1150381872.958342.180420@p79g2000cwp.googlegroups.com> <44917776$1@nntp0.pdx.net> <1150387471.341026.260090@c74g2000cwc.googlegroups.com> Message-ID: <1150396453.284391.143670@u72g2000cwu.googlegroups.com> BartlebyScrivener wrote: > >> I'd like something a bit like a module, > >> but I'd like to make several of them, > >> and not have them interfere with each other." > > Thank you. I sense what you are saying, but at this point I'd be > thinking, "Why not just make several modules?" :) I'll get to it. I've > got my hands full just learning everything else. > > rd To grasp the basics of OO, I strongly suggest you start with an example of a banking application. It is in Alan Gauld's tutorial here: http://www.freenetpages.co.uk/hp/alan.gauld/ Check the bank account class in "Object oriented programming". I think it is a very good real-life example of how to work with objects, and it was a real eye opener to me when I was in your situation. By the way, the whole tutorial is very good. I also recommend: Josh Cogliati's Python Tutorial for Non-Programmers A Byte of Python Hope it helps... Luis From jpellerin at gmail.com Fri Jun 30 22:16:16 2006 From: jpellerin at gmail.com (jpellerin+nose@gmail.com) Date: 30 Jun 2006 19:16:16 -0700 Subject: ANN: nose 0.9 released Message-ID: <1151720176.043929.121120@i40g2000cwc.googlegroups.com> I'm pleased to announce the release of nose 0.9. nose provides an alternate test discovery and running process for unittest, one that is intended to mimic the behavior of py.test as much as is reasonably possible without resorting to too much magic. nose can be installed via easy_install: easy_install nose nose 0.9 includes a host of new features, as well as numerous backwards-incompatible changes to interfaces and implementation. Thanks to the many folks who have contributed patches and ideas and made bug reports for the development version of 0.9, especially Mika Eloranta, Jay Parlar, Kevin Dangoor, Scot Doyle, Titus Brown and Philip J.Eby. Here's a quick rundown of what's new in 0.9 - Plugins The most important new feature is support for plugins using setuptools entrypoints. nose plugins can select and load tests (like the builtin doctest plugin), reject tests (like the builtin attrib plugin, contributed by Mika Eloranta, that allows users to select tests by attribute), watch and report on tests (like the builtin coverage and profiler plugins), completely replace test result output (like the html result plugin in the examples directory) or any combination of the above. Writing plugins is simple: subclass nose.plugins.Plugin and implement any of the methods in nose.plugins.IPluginInterface. - Better compatibility with unittest Test loading has been consolidated into a test loader class that is drop-in compatible with unittest.TestLoader. Likewise test result output, including output capture, assert introspection, and support for skipped and deprecated tests, in nose.result.TextTestResult. If you want those features and not the rest of nose, you can use just those classes. nose.main() has also been rewritten to have the same signature as unittest.main(). - Better command line interface Command line test selection is more intuitive and powerful, enabling easy and correct running of single tests while ensuring that fixtures (setup and teardown) are correctly executed at all levels. No more -f -m or -o options: now simply specify the tests to run: nosetests this/file.py that.module Tests may be specified down to the callable: nosetests this/file.py:TestClass that.module:this_test nosetests that.module:TestClass.test_method There are also new options for dropping into pdb on errors or failures, and stopping the test run on the first error or failure (thanks to Kevin Dangoor for the idea). - More! Helpful test decorators and functions in nose.tools. Support for generators in test classes. Better import path handling -- that you can shut off! Detailed verbose logging using the logging package. And more... Visit http://somethingaboutorange.com/mrl/projects/nose/ for more information. From nmm1 at cus.cam.ac.uk Thu Jun 15 11:27:15 2006 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 15 Jun 2006 15:27:15 GMT Subject: Numerics, NaNs, IEEE 754 and C99 References: <12904mjhl493t49@corp.supernews.com> <1290aik50hmk94a@corp.supernews.com> <4490329e$0$12356$636a55ce@news.free.fr> <12917f6jp7u90f8@corp.supernews.com> <44912058$0$29674$636a55ce@news.free.fr> <1292p7s46ef5off@corp.supernews.com> In article <1292tvei30ahhd4 at corp.supernews.com>, Grant Edwards writes: |> > |> > Firstly, a FAR more common assumption is that integers wrap in twos' |> > complement - Python does not do that. |> |> It used to, and I sure wish there was still a way to get that |> behavior back. Now I have to do all sorts of bitwise ands that |> I didn't use to. Given that it is perhaps THE most common cause of severe failure in large scientific codes, I don't agree that it should be the default. A 'twos complement' class would be quite reasonable. |> > Secondly, it is NOT incompatible with IEEE 754, which is a |> > pure hardware standard. All it does is to trap the exception |> > and take appropriate action (as permitted by that standard). |> |> There are two allowed (selectable?) behaviors for 1/0: trap and |> Inf. Er, no. The second is REQUIRED to set an exception flag, which IEEE 754 assumes that the code will test and take appropriate action (which can be anything, including aborting the program and replacing it by a NaN). See http://www.cs.berkeley.edu/~wkahan/JAVAhurt.pdf |> > Thirdly, virtually no hardware sticks strictly to IEEE 754, |> > and no language that I know of has EVER attempted to make it |> > the strict basis for its arithmetic model. |> |> All the HW and libraries I've used returned Inf for 1/0. Well, I have clearly used a much wider range than you have, then. But it isn't just that aspect I was referring to. You will also find that a high proportion of hardware traps into the kernel on overflow, and it is software that returns the infinity. |> > Fourthly, I am not proposing to change any hardware, |> |> IMO, having Python's FP results disagree with common HW FP |> results would be a pretty bad thing. No matter WHAT results are returned, they will do that! I was triggered into this project by attempting to write NaN-safe code and finding that the first few versions of Python I tried all did different things. When I saw that it just mapped what C does, all became clear. |> > and could even provide a Python option to deliver |> > mathematically incorrect results when you want them. |> |> As long as I can get IEEE 754 results, that's cool. I'd prefer |> if Python just let the HW do it's thing when possible. Including crash and burn? Seriously. I don't think that you realise just how many layers of fixup there are on a typical "IEEE 754" system, and how many variations there are even for a single platform. Regards, Nick Maclaren. From wrongbad at gmail.com Tue Jun 27 04:16:54 2006 From: wrongbad at gmail.com (I V) Date: Tue, 27 Jun 2006 01:16:54 -0700 Subject: Replace Whole Object Through Object Method References: <1151337453.804750.293180@b68g2000cwa.googlegroups.com> <44a041a6$0$17612$636a55ce@news.free.fr> <1151354259.082966.25820@p79g2000cwp.googlegroups.com> <1151376052.727979.71470@c74g2000cwc.googlegroups.com> Message-ID: On Mon, 26 Jun 2006 19:40:52 -0700, digitalorganics wrote: > A misuse of inheritance eh? Inheritance, like other language features, > is merely a tool. I happen to be using this tool to have my virtual > persons change roles at different points in their lifetime, as many > real people tend to do. Thus, at these points, B is indeed an A. What a > person is, whether in real life or in my program, is not static and > comes into definition uniquely for each moment (micro-moment, etc.) of > existence. Now, please, I have no intention of carrying the > conversation in such a silly direction, I wasn't inviting a discussion > on philosophy or some such. I seek to work the tools to my needs, not > the other way around. But thinking about the problem in the vocabulary provided by the programming language can be helpful in coming up with a solution. If inheritance tells you what an object _is_, and membership tells you what a role _has_, and a role is something that a person has, that suggests that an implementation where roles are members of a person might be simpler than trying to use inheritance. Like, for instance: class Role(object): def __init__(self, person): self.person = person class Worker(Role): def do_work(self): print self.name, "is working" class Employer(Role): def __init__(self, person): Role.__init__(self, person) self.employees = [] def add_employee(self, worker): self.employees.append(worker) def boss_people_around(self): for employee in employees: print self.name, "is telling", employee.name, "what to do" class Person(object): def __init__(self, name): self.roles = [] self.name = name def add_role(self, role_class): self.roles.append(role_class(self)) def forward_to_role(self, attr): for role in self.roles: try: return getattr(role, attr) except AttributeError: pass raise AttributeError(attr) def __getattr__(self, attr): self.forward_to_role(attr) bill = Person('Bill') bill.add_role(Worker) bob = Person('Bob') bob.add_role(Employer) bill.work() bob.boss_people_around() From scott.daniels at acm.org Tue Jun 20 15:18:19 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Tue, 20 Jun 2006 12:18:19 -0700 Subject: __getattribute__ doesn't work on 'type' type for '__class__' In-Reply-To: <8k8g92tgqmhu70au13od2fn1ihut04sr0o@4ax.com> References: <8k8g92tgqmhu70au13od2fn1ihut04sr0o@4ax.com> Message-ID: <4498450b$1@nntp0.pdx.net> Barry Kelly wrote: > I read in the documentation that these two expressions are > interchangeable: > x.__getattribute__('name') <==> x.name I think you'll find: getattr(x, 'name') <==> x.name is what is equivalent. You can define a '__getattribute__' method which will get used, but I doublbt thre is a promise for an exposed name '__getattribute__'. -- --Scott David Daniels scott.daniels at acm.org From steve at holdenweb.com Sat Jun 10 15:28:24 2006 From: steve at holdenweb.com (Steve Holden) Date: Sat, 10 Jun 2006 20:28:24 +0100 Subject: wxPython: Should you use a master sizer object? In-Reply-To: <448b072f$0$11723$c3e8da3@news.astraweb.com> References: <448b072f$0$11723$c3e8da3@news.astraweb.com> Message-ID: John Salerno wrote: > Steve Holden wrote: > >>John Salerno wrote: >> >>>Sorry for posting here again. I tried the wxPython list but I'm not sure >>>I'm sending to the right email address! It bounced back. Besides, your >>>opinions are too good to pass up. ;) >>> >>>My question was: >>> >>>I was wondering, is it recommended to always have a top-level sizer in >>>which you place all other sizers, or is it acceptable to have mulitple >>>sizers that are not grouped together? >> >>You should definitely create a master sizer, and then add sub-sizers to it. > > > Thanks. Also, I just found out that a Frame can't have more than one > sizer in it, meaning if you need multiple sizers you *have* to create a > master sizer first to nest the others. Now it's just a matter of > figuring out *how* to use them! I don't want to fall into the trap of > using them the way you can use the
element to lay out a form in > HTML... There doesn't seem to be any really usable material to help beginners. A recursive design approach seems best, breaking down each grouping, but I have sometimes found it difficult to adapt a design to changes. Although I'm a big fan of open source I must confess that to solve this problem I eventually bought a copy of wxDesigner, which while not perfect does help quite a lot, and allows cut/copy and paste of design elements. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From sjmachin at lexicon.net Fri Jun 16 20:32:32 2006 From: sjmachin at lexicon.net (John Machin) Date: Sat, 17 Jun 2006 10:32:32 +1000 Subject: Need Help comparing dates In-Reply-To: <1150502102.377475.38140@u72g2000cwu.googlegroups.com> References: <1150419503.224684.320550@c74g2000cwc.googlegroups.com> <1150502102.377475.38140@u72g2000cwu.googlegroups.com> Message-ID: <44934DA0.1050309@lexicon.net> On 17/06/2006 9:55 AM, colincolehour at gmail.com wrote: > So when I grab the date of the website, that date is actually a string? Yes. Anything you grab off a website (or read from a file) will be held in a string. Typically you would then need to convert it (or parts of it) to some other type(s) e.g. int, float, date, ... > > How would I got about converting that to a date? By following the instructions you have already been given. The response by Tim Chase gives you a stir-by-stir recipe. === You said "I am new to Python and am working on my first program". Here are some diagnostic questions the answers to which should enable us to prescribe some more help for you: In what other computer language(s) have you written programs? What book or tutorial are you using to learn Python? Have you worked through the book/tutorial's examples/exercises before starting "my first program"? Cheers, John From max at alcyone.com Mon Jun 5 18:27:08 2006 From: max at alcyone.com (Erik Max Francis) Date: Mon, 05 Jun 2006 15:27:08 -0700 Subject: C# equivalent to range() In-Reply-To: <1149545140.011616.130610@y43g2000cwc.googlegroups.com> References: <1149468919.951745.163700@g10g2000cwb.googlegroups.com> <1149481675.192638.275140@c74g2000cwc.googlegroups.com> <1149509893.031953.19310@i40g2000cwc.googlegroups.com> <1149545140.011616.130610@y43g2000cwc.googlegroups.com> Message-ID: Fuzzyman wrote: > FWIW I agree. If anyone didn't want to answer the question they didn't > need to. > > Why be rude to someone asking a polite question. It's not as if there > isn't much more *worse* noise on this group. Here were the "harsh" and "whining" responses to his question he's complaining about: | Bad guess. Ask questions about language X on comp.lang.X | Really, it isn't. Post in a C# discussion forum, describing the | behaviour you want from your program. | *Very* strong suggestion - read the following link: | | http://www.catb.org/~esr/faqs/smart-questions.html Sorry, if you think those are unacceptable tones for responses to off-topic questions, the real world is going to be something of an unpleasant shock. He asked a question. He was told how to get the answer. No one was rude until _he_ started being rude. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Society attacks early when the individual is helpless. -- B.F. Skinner From pats at acm.org Fri Jun 23 07:18:28 2006 From: pats at acm.org (Patricia Shanahan) Date: Fri, 23 Jun 2006 11:18:28 GMT Subject: Saying "latently-typed language" is making a category mistake In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> Message-ID: <86Qmg.10725$o4.1907@newsread2.news.pas.earthlink.net> Vesa Karvonen wrote: ... > An example of a form of informal reasoning that (practically) every > programmer does daily is termination analysis. There are type systems > that guarantee termination, but I think that is fair to say that it is not > yet understood how to make a practical general purpose language, whose > type system would guarantee termination (or at least I'm not aware of such > a language). It should also be clear that termination analysis need not > be done informally. Given a program, it may be possible to formally prove > that it terminates. To make the halting problem decidable one would have to do one of two things: Depend on memory size limits, or have a language that really is less expressive, at a very deep level, than any of the languages mentioned in the newsgroups header for this message. A language for which the halting problem is decidable must also be a language in which it is impossible to simulate an arbitrary Turing machine (TM). Otherwise, one could decide the notoriously undecidable TM halting problem by generating a language X program that simulates the TM and deciding whether the language X program halts. One way out might be to depend on the boundedness of physical memory. A language with a fixed maximum memory size cannot simulate an arbitrary TM. However, the number of states for a program is so great that a method that depends on its finiteness, but would not work for an infinite memory model, is unlikely to be practical. Patricia From sjmachin at lexicon.net Tue Jun 13 04:00:33 2006 From: sjmachin at lexicon.net (John Machin) Date: Tue, 13 Jun 2006 18:00:33 +1000 Subject: Getting "TypeError:list indices must be integers" In-Reply-To: <56871.10.209.4.1.1150184001.squirrel@10.105.1.3> References: <448E6466.10908@lexicon.net> <448E676F.9020602@lexicon.net> <56871.10.209.4.1.1150184001.squirrel@10.105.1.3> Message-ID: <448E70A1.6070906@lexicon.net> On 13/06/2006 5:33 PM, Girish Sahani wrote: > Python prints 'c','c' when i print repr(index1),repr(index2).This means > they are characters right?? > But i have defined indexList as follows (and also tested the output, both > are outputted as lists of numbers): > > for char in list1: > i = substring1.index(c) That would be "char", I presume, not "c". > indexList1.append(i) > > for char in list2: > j = substring2.index(char) > indexList2.append(j) > > (substring1 and substring2 are 2 different strings) > > Then i'm iterating over indexList1 and indexList2, so i fail to understand > why i am getting the typeError.... > > >> On 13/06/2006 5:08 PM, John Machin wrote: >>> On 13/06/2006 4:11 PM, Girish Sahani wrote: [SNIPPED] Girish, Could we please abide by the Geneva Convention: 1. Please don't top-post. 2. Please don't type what you thought was in your code; copy/paste actual most-recently-executed code. 3. Please reply to the newsgroup/mailing-list -- I've taken the liberty of dragging this back there as there appears to be no private content ... OK, so you've found that index1 and index2 each contain 'c'. Despite your belief that they should contain the results of some_string.index(some_char), the only reasonable hypothesis is that somebody is polluting the water further upstream. Who is that somebody? The usual and only suspect is *you*. Please go away and sprinkle print statements at likely spots further upstream until you have found the problem. Kindest possible regards, John From blye at telkomsa.net Sun Jun 25 05:43:20 2006 From: blye at telkomsa.net (bli) Date: 25 Jun 2006 02:43:20 -0700 Subject: win32com and name of com In-Reply-To: <1151033037_11067@sp6iad.superfeed.net> References: <1151001177.360087.202620@m73g2000cwd.googlegroups.com> <1151033037_11067@sp6iad.superfeed.net> Message-ID: <1151228600.761785.133940@r2g2000cwb.googlegroups.com> Roger Upole wrote: > "bli" wrote in message news:1151001177.360087.202620 at m73g2000cwd.googlegroups.com... > > > > (All authors are fairly sparse on the topic using Microsoft examples > > that are more self evident.) > > thanks muchly! > > > > Your best bet is the documentation for the application. > However, if the dll is registered correctly you can also > find the progid in the registry by searching for the dll name. > > Roger > > > > > ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==---- > http://www.newsfeeds.com The #1 Newsgroup Service in the World! >100,000 Newsgroups > ---= East/West-Coast Server Farms - Total Privacy via Encryption =--- Thank you! Phew, over that one, now passing parameters by reference or value! slight gripe : there is a more extended example of VB code than Python in Mark Hammonds seminal Py win32 book! viva comp.lang.python viva! From cdsmith at twu.net Mon Jun 19 16:56:26 2006 From: cdsmith at twu.net (Chris Smith) Date: Mon, 19 Jun 2006 14:56:26 -0600 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150749670.053433.242210@p79g2000cwp.googlegroups.com> Message-ID: Marshall wrote: > While I am quite sympathetic to this point, I have to say that > this horse left the barn quite some time ago. I don't think so. Perhaps it's futile to go scouring the world for uses of the phrase "dynamic type" and eliminating them. It's not useless to point out when the term is used in a particularly confusing way, though, as when it's implied that there is some class of "type errors" that is strictly a subset of the class of "errors". Terminology is often confused for historical reasons, but incorrect statements eventually get corrected. > PS. Hi Chris! Hi! Where are you posting from these days? -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation From petr.jakes at tpc.cz Thu Jun 29 15:33:01 2006 From: petr.jakes at tpc.cz (=?windows-1250?Q?Petr_Jake=9A?=) Date: Thu, 29 Jun 2006 21:33:01 +0200 Subject: small inaccuracy in the logging module documentation (Python Library Reference) In-Reply-To: <1151604839.290366.90950@m73g2000cwd.googlegroups.com> References: <_asng.501715$x64.12701762@phobos.telenet-ops.be> <1151391562.198586.249130@m73g2000cwd.googlegroups.com> <1151604839.290366.90950@m73g2000cwd.googlegroups.com> Message-ID: <1245429911.20060629213301@tpc.cz> Hi, I have found some inaccuracy in the Python Library Reference 6.29.5.4 TimedRotatingFileHandler (http://docs.python.org/lib/node349.html) 1) it is not really obvious from the documentation the "when" value has to be in the format "w0", "w1" ... "w6" if "Type of interval" is defined as a "week day" 2) next the documentation says: "If backupCount is non-zero, the system will save old log files by appending the extensions ".1", ".2" etc., to the filename" This is not really true, in this case. The extension is (depending on the "when" value): "timestamp" or "date+hour+minutes" or "date+hours" or "date". Regards Petr Jakes From max at alcyone.com Sun Jun 11 04:12:52 2006 From: max at alcyone.com (Erik Max Francis) Date: Sun, 11 Jun 2006 01:12:52 -0700 Subject: Xah Lee network abuse In-Reply-To: References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148495974.975395.12920@i40g2000cwc.googlegroups.com> <1149998343.493200.144990@h76g2000cwa.googlegroups.com> <5smdnb3j67LkURbZnZ2dnUVZ_qydnZ2d@speakeasy.net> Message-ID: Philippa Cowderoy wrote: > I'd still appreciate being referred to as "she" rather than "he" though. Oops, my bad. Never occurred to me after all these years, which is kind of embarrassing, actually :-). -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Isn't jumping of a bridge / Free fallin' -- Sandra St. Victor From meyer at mesw.de Thu Jun 15 17:57:56 2006 From: meyer at mesw.de (meyer at mesw.de) Date: 15 Jun 2006 14:57:56 -0700 Subject: Which compiler will Python 2.5 / Windows (Intel) be built with? In-Reply-To: References: <1150367139.495114.148550@g10g2000cwb.googlegroups.com> <44917535$1@nntp0.pdx.net> <1150391891.130185.4640@f6g2000cwb.googlegroups.com> <4491b9e1$1@nntp0.pdx.net> <1150406005.948538.188950@h76g2000cwa.googlegroups.com> Message-ID: <1150408676.147533.197480@y41g2000cwy.googlegroups.com> Fredrik, Fredrik Lundh wrote: > meyer at mesw.de wrote: > > > I'm not sure how that backs the point you made. Infact, you're saying > > that people accepted that Python 2.4 was compiled with VS2003 because > > VC6 could not longer be bought. How is that different from the current > > situation where the VS2003 toolkit cannot longer be downloaded and it > > is at least becoming increasingly difficult to buy versions of VS2003? > > You also seem to imply that there is a large group of people that want > > you to stay with VS2003 for compiling Python 2.5. > > what part of "Python 2.4 is built with VC2003 and everyone who's ever > built Windows stuff for Python 2.4 already has it" do you have trouble > understanding ? I'm actually a bit disappointed that this thread is slowly turning into a flame-war (and you would not be uninvolved when it does so). I originally only wanted to create a discussion on a simple topic. I understand that the Python community is exactly that -- a community where people voice their opinion and the result of a discussion will ultimately be a consensus that is followed. I do understand that a decision on the issue at stake has already been made, but as I explained in the GP I think that this is a decision that one might re-evaluate in light of new facts created by a third party (Microsoft). In any case, there's no reason to get hot about the topic. But responding to your original question, let me give an example so maybe you can see my point a bit clearer. I have a customer where I recently had to add a feature to a Python 2.4 extension. About a year ago, I wrote the extension, downloaded the 2003 toolkit from Microsoft, compiled the extension and installed it on the customer's site. Since then, I got a new laptop, and I never installed the 2003 toolkit again, because all my other software is in either pure Python or pure Visual C++ 6 w/ MFC. So I was at the customer's site and discovered that the 2003 toolkit is no longer available at Microsoft. Bummer! Since it is an important customer, I decided to phone around in the customer's city if any shop had a version of Visual Studio 2003 lying around so I would be able to compile the extension. They all would have readily sold me Visual Studio 2005, but had no 2003 in stock. Second bummer! What I'm trying to make here are two points: * Using outdated development tools for new releases is just begging for difficulties. Python 2.5 will be out there some time, and it will be increasingly difficult to get VS 2003. The support for VS 2003 (including support for security holes) will probably expire during the lifetime of Python 2.5. It's like releasing a Python 2.5 that does not work on Windows XP, only on Windows 2000. * There is currently a very good optimizing free (as in beer) compiler available for the Windows platform: The VS Toolkit 2005. But you won't be able to write extensions for Python 2.5 with this compiler. That's a pity for the Open Source community as whole, as many Open Source developers cannot afford to buy a commercial compiler (and many won't do it even if they could). Note that this is different from the situation we had a year ago. A year ago, we could download the 2003 toolkit and build extensions for Python 2.4. Now, when Python 2.5 comes out, we cannot download the 2003 toolkit anymore. Therefore, we cannot build extensions for 2.4, but not for 2.5 either. Of course those that still have an install of the 2003 toolkit lying around are happy -- but only until the next reinstall of their OS. Markus From sreeram at tachyontech.net Mon Jun 5 08:55:12 2006 From: sreeram at tachyontech.net (K.S.Sreeram) Date: Mon, 05 Jun 2006 18:25:12 +0530 Subject: finding file In-Reply-To: <44842761.6060201@tachyontech.net> References: <1149510738.569437.242050@f6g2000cwb.googlegroups.com> <44842761.6060201@tachyontech.net> Message-ID: <448429B0.8070304@tachyontech.net> K.S.Sreeram wrote: > filepaths = [os.path.join(os.getcwd(),f) for f in filenames] you can use os.path.abspath.... filepaths = [os.path.abspath(f) for f in filenames] -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 260 bytes Desc: OpenPGP digital signature URL: From Serge.Orlov at gmail.com Mon Jun 19 21:39:45 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 19 Jun 2006 18:39:45 -0700 Subject: statically linked python References: <1150588687.938894.86830@r2g2000cwb.googlegroups.com> <6JOdnf4KX7yxJgnZnZ2dnUVZ_rqdnZ2d@comcast.com> Message-ID: <1150767585.646047.128270@g10g2000cwb.googlegroups.com> Ralph Butler wrote: > Serge Orlov wrote: > > Ralph Butler wrote: > >> Hi: > >> > >> I have searched the docs and google but have not totally figured > >> out how to accomplish my task: On a linux box, I want to compile > >> and link python so that it uses no shared libraries, but does support > >> import of some "extra" modules. I have made a few attempts but > >> with limited success. In particular, I have tried things like > >> adding -static to the compiler options in the Makefile. > >> > >> At one point I managed to build a python that was close to what I > >> wanted, e.g. when I ran "ldd python", it said: > >> not a dynamic executable > >> In that version, when I do some imports, e.g. sys, os, etc. they > >> load fine. But, when I try to import some other modules, e.g. time, > >> they are not found. I have tried similar procedures while also > >> altering Modules/Setup.local (produced by configure) to contain: > >> time timemodule.c # -lm # time operations and variables > >> > >> There has to be a simple, "elegant" way to accomplish this which I am > >> simply overlooking. Any help would be appreciated. > > > > This has nothing to do with python. glibc doesn't support loading > > shared libraries into statically linked executables. At least it didn't > > support in 2002: > > http://www.cygwin.com/ml/libc-alpha/2002-06/msg00079.html > > Since it still doesn't work most likely it is still not supported, but > > you may ask glibc developers what is the problem. > > > > I do not want to load them. I want to statically link the code for a > module (e.g. time) directly into the statically linked executable. > Sorry if that was not clear. OK, so you're asking how to make a module builtin. I haven't done that myself, but let me give you a hint where to look: there is list of builtin modules sys.builtin_module_names if you search the whole python source distribution for some of the names in the list you'll get list of files where to look. I've just searched and found that only two files are involved: PC\config.c and setup.py From sjmachin at lexicon.net Tue Jun 6 20:22:00 2006 From: sjmachin at lexicon.net (John Machin) Date: Wed, 07 Jun 2006 10:22:00 +1000 Subject: tempfile Question In-Reply-To: References: Message-ID: <44861C28.8070706@lexicon.net> On 7/06/2006 7:50 AM, Gregory Pi?ero wrote: > Hey group, > > I have a command line tool that I want to be able to call from a > Python script. The problem is that this tool only writes to a file. > Another Fantastic Manual gives another idea: """ Pdftotext reads the PDF file, PDF-file, and writes a text file, text-file. If text-file is not specified, pdftotext converts file.pdf to file.txt. If text-file is '-', the text is sent to stdout. """ Why not try reading back the child process's stdout? I would have thought there would be no shortage of examples and help for this idea ... Cheers, John From jarrod.roberson at gmail.com Thu Jun 8 12:30:37 2006 From: jarrod.roberson at gmail.com (fuzzylollipop) Date: 8 Jun 2006 09:30:37 -0700 Subject: 10GB XML Blows out Memory, Suggestions? In-Reply-To: References: <1149594519.098115.8980@u72g2000cwu.googlegroups.com> <4eleh3F1eguosU1@uni-berlin.de> <1149648187.891942.258300@i40g2000cwc.googlegroups.com> <1149694031.712812.304940@u72g2000cwu.googlegroups.com> <1149696078.984114.51880@h76g2000cwa.googlegroups.com> <1149773399.508514.223910@f6g2000cwb.googlegroups.com> Message-ID: <1149784236.991546.23840@c74g2000cwc.googlegroups.com> Fredrik Lundh wrote: > fuzzylollipop wrote: > > > SAX style or a pull-parser has to be used when the data is "large" or > > when you don't really need to process every element and attribute. > > > > This problem looks like it is just a data export / import problem. In > > that case you will either have to use a sax style parser and parse the > > 10GB file. Or as I suggested in another reply, export the data in > > smaller chunks > > or use a parser that can do the chunking for you, on the way in... > > in Python, incremental parsers like cET's iterparse and the one in Amara > gives you *better* performance than SAX (including "raw" pyexpat) in > many cases, and offers a much simpler programming model. > > thats good to know, I haven't worked with cET yet. Haven't had time to get it installed :-( From sreeram at tachyontech.net Tue Jun 6 00:40:42 2006 From: sreeram at tachyontech.net (K.S.Sreeram) Date: Tue, 06 Jun 2006 10:10:42 +0530 Subject: Reading from a file and converting it into a list of lines: code not working In-Reply-To: <54688.10.209.4.1.1149567048.squirrel@10.105.1.3> References: <1149534126.129714.131860@f6g2000cwb.googlegroups.com> <1149535195.763340.220010@y43g2000cwc.googlegroups.com> <54688.10.209.4.1.1149567048.squirrel@10.105.1.3> Message-ID: <4485074A.9000109@tachyontech.net> Girish Sahani wrote: > 1) A dictionary with the numbers as keys and the letters as values. > e.g the above would give me a dictionary like > {1:'a', 2:'b', 3:'a', 5:'c', 6:'c' ........} def get_dict( f ) : out = {} for line in file(f) : n1,s1,n2,s2 = line.split(',') out.update( { int(n1):s1[1], int(n2):s2[1] } ) return out > 2) A list containing pairs of numbers from each line. > The above formmat would give me the list as > [[1,2],[3,5],[3,6][3,7][8,7]......] def get_pairs( f ) : out = [] for line in file(f) : n1,_,n2,_ = line.split(',') out.append( [int(n1),int(n2)] ) return out Regards Sreeram -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 260 bytes Desc: OpenPGP digital signature URL: From davidh at ilm.com Tue Jun 20 14:44:31 2006 From: davidh at ilm.com (David Hirschfield) Date: Tue, 20 Jun 2006 11:44:31 -0700 Subject: Getting external name of passed variable Message-ID: <4498420F.1050504@ilm.com> I'm not sure this is possible, but it sure would help me if I could do it. Can a function learn the name of the variable that the caller used to pass it a value? For example: def test(x): print x val = 100 test(val) Is it possible for function "test()" to find out that the variable it is passed, "x", was called "val" by the caller? Some kind of stack inspection? Any help greatly appreciated, -David -- Presenting: mediocre nebula. -------------- next part -------------- An HTML attachment was scrubbed... URL: From andrewfr_ice at yahoo.com Wed Jun 28 14:05:14 2006 From: andrewfr_ice at yahoo.com (Andrew Francis) Date: Wed, 28 Jun 2006 11:05:14 -0700 (PDT) Subject: A Solution using Tasks Re: [Stackless] Suggestion for a Solution ? Re: Blocking Problem with Stackless Python and Twisted In-Reply-To: <28dc07920606270844n33f158bbv77116d69907462cf@mail.gmail.com> Message-ID: <20060628180514.82631.qmail@web34208.mail.mud.yahoo.com> Hello Patrick: --- "Patrick M. Nielsen" wrote: > I had a similar problem, and Radix's threadless > Twisted snippet proved to be > a very viable solution > > Have a look at: > >http://twistedmatrix.com/trac/browser/sandbox/radix/threadless.py?rev=17407 Thanks for the advice. Bob Ippolito also suggested this. However I have been experimenting with the Twisted task class. I am still testing but I have done the following with success. 1. Set up a function - def pump(): stackless.schedule() 2. l = task.LoopingCall(pump) l.start(some_time_period) reactor.listenTCP(port, MyHttpFactory()) reactor.run() While Twisted waits for a connection, the call to pump() allows other tasklets that are waiting, a chance to run. Once I know all the ins-and-outs, I will write this up in the Wiki including an example. Thanks for everyone's help. Cheers, Andrew __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From deets at nospam.web.de Tue Jun 13 09:42:46 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 13 Jun 2006 15:42:46 +0200 Subject: Combining The Best Of Python, Ruby, & Java?????? References: <1150181049.815883.138580@c74g2000cwc.googlegroups.com> Message-ID: <4f7todF1har97U1@uni-berlin.de> > But semantically it is a proper functional language. The features may > not attract Python users who might prefer Boo/Jython/IronPython. But it > does offer something to disillusioned Groovy users. Are they disillusioned? Just wondering. Diez From fivenastydisco at hotmail.com Thu Jun 8 03:52:17 2006 From: fivenastydisco at hotmail.com (fivenastydisco at hotmail.com) Date: 8 Jun 2006 00:52:17 -0700 Subject: Newbie question about updating multiple objects ... Message-ID: <1149753137.498806.314640@c74g2000cwc.googlegroups.com> All, Apologies in advance: I'm new to Python and OO, and I'm sure this is a really simple question, but I just can't seem to crack it on my own, or through looking at examples. I'm playing around with VPython (http://www.vypthon.org) to try and teach myself about objects: I've got a box that I've put some balls in, and I'm trying to get said balls to move around and bounce off the walls of the box -- that's literally it. I can put multiple balls in the box, but I can't get them to update their position -- it works when I have one ball, but now that I have a list of balls, I can't get them to move. I've copied in the code I'm using below, as it's not very long -- can anyone help me? <--START--> from visual import * from random import randrange # to create random numbers numballs = 5 # number of balls balls = [] # a list to contain the balls # set up a box to collide with side_length = 100 minx = side_length * -10 maxx = side_length * 10 miny = side_length * -4 maxy = side_length * 4 # create a wireframe of space left = curve(pos=[(minx, miny),(minx, maxy)], color = color.white) top = curve(pos = [(minx, maxy),(maxx, maxy)], color = color.white) right = curve(pos = [(maxx, maxy),(maxx, miny)], color = color.white) bottom = curve(pos = [(maxx, miny),(minx,miny)], color = color.white) #create some balls for b in range(numballs): # for each ball x = randrange(minx, maxx) y = randrange(miny, maxy) balls.append(sphere(pos = (x,y), radius = 50, color = color.red)) # add balls dt = 0.05 # time interval velocity = vector(2,0.2,1) # velocity of the balls while (1==1): # forever ... rate(50) for b in range(numballs): # for each ball ... if balls[b].x < minx: # check it hasn't overrun a boundary balls[b].x = maxx if balls[b].x > maxx: balls[b].minx if balls[b].y < miny: balls[b].y = maxy if balls[b].y > maxy: balls[b].y = miny # NB betting this is where it's going wrong ... balls[b].pos = balls[b].pos + (velocity * dt) # update the position of the ball <--END--> Any ideas? I've run out of options. Any help would be very *gratefully* appreciatedd!! Thanks in advance JW From jo at durchholz.org Tue Jun 20 18:06:39 2006 From: jo at durchholz.org (Joachim Durchholz) Date: Wed, 21 Jun 2006 00:06:39 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: <7zy7vt1mz2.fsf@app-3.diku.dk> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> Message-ID: Torben ?gidius Mogensen schrieb: > That's not really the difference between static and dynamic typing. > Static typing means that there exist a typing at compile-time that > guarantess against run-time type violations. Dynamic typing means > that such violations are detected at run-time. Agreed. > This is orthogonal to > strong versus weak typing, which is about whether such violations are > detected at all. The archetypal weakly typed language is machine code > -- you can happily load a floating point value from memory, add it to > a string pointer and jump to the resulting value. I'd rather call machine code "untyped". ("Strong typing" and "weak typing" don't have a universally accepted definition anyway, and I'm not sure that this terminology is helpful anyway.) > Anyway, type inference for statically typed langauges don't make them > any more dynamically typed. It just moves the burden of assigning the > types from the programmer to the compiler. And (for HM type systems) > the compiler doesn't "guess" at a type -- it finds the unique most > general type from which all other legal types (within the type system) > can be found by instantiation. Hmm... I think this distinction doesn't cover all cases. Assume a language that a) defines that a program is "type-correct" iff HM inference establishes that there are no type errors b) compiles a type-incorrect program anyway, with an establishes rigorous semantics for such programs (e.g. by throwing exceptions as appropriate). The compiler might actually refuse to compile type-incorrect programs, depending on compiler flags and/or declarations in the code. Typed ("strongly typed") it is, but is it statically typed or dynamically typed? ("Softly typed" doesn't capture it well enough - if it's declarations in the code, then those part of the code are statically typed.) > You miss some of the other benefits of static typing, > though, such as a richer type system -- soft typing often lacks > features like polymorphism (it will find a set of monomorphic > instances rather than the most general type) and type classes. That's not a property of soft typing per se, it's a consequence of tacking on type inference on a dynamically-typed language that wasn't designed for allowing strong type guarantees. Regards, Jo From steve at holdenweb.com Wed Jun 7 08:30:24 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 07 Jun 2006 13:30:24 +0100 Subject: subprocesses, stdin/out, ttys, and beating insubordinate processes into the ground In-Reply-To: <4485EB13.1030106@rpath.com> References: <4485EB13.1030106@rpath.com> Message-ID: Jonathan Smith wrote: > First a bit about what I'm trying to do. I need a function which takes a > patchfile and patches a source directory. Thats it. However, I need to > be able to do so no matter what the patchlevel (-px) of the diff is. So, > my solution is to just try to patch until it works or you try a level > more than 3. However, if you have a reversed patch, or patch can't find > the right file, GNU patch tries to ask for input and I don't want that. > I know that patch will run non-interactively when backgrounded in a > shell (no controlling tty). This is what I've tried so far: > > def patchme(self, provides, f, destDir, patchlevels): > for patchlevel in patchlevels: > patchArgs = ['patch', '-d', destDir, '-p%s'%patchlevel, ] > if self.backup: > patchArgs.append(['-b', '-z', self.backup]) > if self.extraArgs: > patchArgs.append(self.extraArgs) > > log.info('attempting to patch the source with file %s and > patchlevel %s' % (f,patchlevel)) > p1 = subprocess.Popen([provides, f], > stdout=subprocess.PIPE, shell=False) > p2 = subprocess.Popen(patchArgs, stdin=p1.stdout, shell=False) > message = p2.communicate()[0] # patch seems to use stdout > for everything, even errors > > if message != None and self.patcherror.search(message): > os.kill(p2.pid, signal.SIGTERM) > elif p2.wait(): > log.info('patch did not apply with path level %s' % > patchlevel) > print message > else: > return > log.error('could not apply the patch to your build dir') > > > However, I still get an interactive prompt, no matter what I try! Using > shell=False did not help, nor did trying to kill the pid if python sees > a line from patch which isn't saying what its patching or giving info on > a specific hunk. Any suggestions? > > -smithj > > PS: if you're a maintainer for GNU patch, a --non-interactive would be > really nice ;-) (and no, -f and -t aren't good enough as they force > other things that I don't want) If the technique you want to use doesn't work, it's usually a good idea to try another technique. Your current approach is pretty dreadful, when it would be relatively easy to parse the start of the patchfile and determine the appropriate level (i.e. -p argument) by finding the file to be patched. Neither your approach nor my suggested alternative is that good when the patch is modifying a file whose name appears at several points in the directory hierarchy (as may be the case with README, for example), so it might be even better to parse the whole patchfile and ensure that the level you choose correctly identifies all target files. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From grante at visi.com Wed Jun 7 12:28:25 2006 From: grante at visi.com (Grant Edwards) Date: Wed, 07 Jun 2006 16:28:25 -0000 Subject: How do I automatically redirect stdout and stderr when using os.popen2? References: <1149696430.511354.276460@i40g2000cwc.googlegroups.com> Message-ID: <128dvl9f2hi91c5@corp.supernews.com> On 2006-06-07, mikem76 at gmail.com wrote: > How do I automatically redirect stdout and stderr when using os.popen2 > to start a long running process. popen2 does redirect stdout to a file object. That's the whole point of using it. If you don't want a file object that's connected to the child's stdout, then don't use popen2. > If the process prints a lot of stuff to stdout it will > eventually stop because it runs out of buffer space. Once I > start reading the stdout file returned by os.popen2 then the > process resumes. I know that I could just specify > /dev/null > when starting the process but I'd like to know if there is a > way to start a process using os.popen2 or some other way so > that all standard out and standard error goes to /dev/null or > some other file. Yes. Fork a child process then use the standard file descriptor operators to open /dev/null or some other file and then dup those file descriptors to stdout/stderr: http://docs.python.org/lib/os-fd-ops.html Then you can exec the program you want to run: http://docs.python.org/lib/os-process.html This is basically identical to the method use to do I/O redirection in C, so any decent book on C programming under Unix should have a good explanation. Hmmm, it looks like it's simpler touse the subprocess module. Just open /dev/null to get a file descriptor for it, and then pass that to subprocess.Popen(): http://docs.python.org/lib/module-subprocess.html -- Grant Edwards grante Yow! I selected E5... but at I didn't hear "Sam the Sham visi.com and the Pharoahs"! From fredrik at pythonware.com Mon Jun 5 06:16:12 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 05 Jun 2006 12:16:12 +0200 Subject: re beginner In-Reply-To: References: Message-ID: SuperHik wrote: > I'm trying to understand regex for the first time, and it would be very > helpful to get an example. I have an old(er) script with the following > task - takes a string I copy-pasted and wich always has the same format: > > >>> print stuff > Yellow hat 2 Blue shirt 1 > White socks 4 Green pants 1 > Blue bag 4 Nice perfume 3 > Wrist watch 7 Mobile phone 4 > Wireless cord! 2 Building tools 3 > One for the money 7 Two for the show 4 > > >>> stuff > 'Yellow hat\t2\tBlue shirt\t1\nWhite socks\t4\tGreen pants\t1\nBlue > bag\t4\tNice perfume\t3\nWrist watch\t7\tMobile phone\t4\nWireless > cord!\t2\tBuilding tools\t3\nOne for the money\t7\tTwo for the show\t4' the first thing you need to do is to figure out exactly what the syntax is. given your example, the format of the items you are looking for seems to be "some text" followed by a tab character followed by an integer. a initial attempt would be "\w+\t\d+" (one or more word characters, followed by a tab, followed by one or more digits). to try this out, you can do: >>> re.findall('\w+\t\d+', stuff) ['hat\t2', 'shirt\t1', 'socks\t4', ...] as you can see, using \w+ isn't good enough here; the "keys" in this case may contain whitespace as well, and findall simply skips stuff that doesn't match the pattern. if we assume that a key consists of words and spaces, we can replace the single \w with [\w ] (either word character or space), and get >>> re.findall('[\w ]+\t\d+', stuff) ['Yellow hat\t2', 'Blue shirt\t1', 'White socks\t4', ...] which looks a bit better. however, if you check the output carefully, you'll notice that the "Wireless cord!" entry is missing: the "!" isn't a letter or a digit. the easiest way to fix this is to look for "non-tab characters" instead, using "[^\t]" (this matches anything except a tab): >>> len(re.findall('[\w ]+\t\d+', stuff)) 11 >>> len(re.findall('[^\t]+\t\d+', stuff)) 12 now, to turn this into a dictionary, you could split the returned strings on a tab character (\t), but RE provides a better mechanism: capturing groups. by adding () to the pattern string, you can mark the sections you want returned: >>> re.findall('([^\t]+)\t(\d+)', stuff) [('Yellow hat', '2'), ('Blue shirt', '1'), ('White socks', ...] turning this into a dictionary is trivial: >>> dict(re.findall('([^\t]+)\t(\d+)', stuff)) {'Green pants': '1', 'Blue shirt': '1', 'White socks': ...} >>> len(dict(re.findall('([^\t]+)\t(\d+)', stuff))) 12 or, in function terms: def putindict(items): return dict(re.findall('([^\t]+)\t(\d+)', stuff)) hope this helps! From antroy at gmail.com Fri Jun 16 07:45:35 2006 From: antroy at gmail.com (Ant) Date: 16 Jun 2006 04:45:35 -0700 Subject: Extracting values from text file In-Reply-To: References: Message-ID: <1150458335.846295.248160@f6g2000cwb.googlegroups.com> > What I first though was if there was possible to make a filter such as: > > Apples (apples) > (ducks) Ducks > (butter) g butter Try something like: import re text = """> Some text that can span some lines. Apples 34 56 Ducks Some more text. """ filters = {"apples": re.compile(r"Apples\s+(\d+)"), "ducks": re.compile(r"(\d+)\s+Ducks"), "butter": re.compile(r"([0-9.]+)\s+g\s+butter")} out = [] for k,v in filters.iteritems(): matches = v.findall(text) for match in matches: out.append((k, match)) print out From max at alcyone.com Sun Jun 25 03:30:40 2006 From: max at alcyone.com (Erik Max Francis) Date: Sun, 25 Jun 2006 00:30:40 -0700 Subject: String negative indices? In-Reply-To: References: <1151054259.765401.252230@b68g2000cwa.googlegroups.com> <1151152577.661130.5690@g10g2000cwb.googlegroups.com> Message-ID: Steven D'Aprano wrote: >> Steven D'Aprano wrote: >> >>> In matrix maths, there are an infinite number of >>> different matrices where all the elements are zero -- they are all >>> distinct, different, zeroes. > >> What do you even mean by that? By "matrix maths," do you just mean >> matrices whose elements are reals, or something else? > > Given any matrix M, there is a matrix Z such that M+Z = M. That matrix Z > is equivalent to zero in the reals, where x+0 = x. Ah, of course. I knew this, I just misinterpreted your "distinct, different, zeroes" as referring to the elements but not the matrices. Just a misunderstanding. Every zero matrix is an additive identity, and there are an infinite number of them. That's certainly true. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis There's a reason why we / Keep chasing morning -- Sandra St. Victor From gyows at sbcglobal.net Tue Jun 6 15:56:07 2006 From: gyows at sbcglobal.net (Ransom) Date: 6 Jun 2006 12:56:07 -0700 Subject: Newbie: returning dynamicly built lists (using win32com) In-Reply-To: <_5khg.18219$0v4.12301@tornado.texas.rr.com> References: <1149613586.862299.125070@u72g2000cwu.googlegroups.com> <_5khg.18219$0v4.12301@tornado.texas.rr.com> Message-ID: <1149623767.697754.118160@c74g2000cwc.googlegroups.com> > 1. First of all, this is not the code you are running. I know this because > the unbalanced parens wont even compile. It really doesn't help when you > ask for help, but post the wrong code. "Ok! Ok! I must have, I must have put a decimal point in the wrong place or something. Shit. I always do that. I always mess up some mundane detail." -Michael Bolton Actually, this was a typo in my e-mail. And yes, I realize how annoying that can be when someone is seeking help. Thanks for your otherwise excellent response, though! G Paul McGuire wrote: > "Ransom" wrote in message > news:1149613586.862299.125070 at u72g2000cwu.googlegroups.com... > > Very newb here, but my question will hopefully be obvious to someone. > > > But when I try and put the output from the spreadsheet into > > a dynamic list after the TODO section thusly: > > > > outputlist = [] > > outputlist.extend(excel.ActiveSheet.Cells(32,6) > > return outputlist > > > > I get an error like: > > [ > 0x15450880>] > > > > 1. First of all, this is not the code you are running. I know this because > the unbalanced parens wont even compile. It really doesn't help when you > ask for help, but post the wrong code. > > 2. What you are getting is NOT an error. Read it very carefully. What you > have added to outputlist is a Range object. Look into the Excel COM > documentation (you can open up VB from Excel by pressing Alt-F11, then open > the Object Browser to see the object API) for how to access the methods and > properties of an Excel Range. I'm guessing one of the properties Value, > Value2, Text, or Formula will give you what you want. > > 3. The reason your print statement appears to work is because print > implicitly applies the str method to objects, while applying the repr method > to contents of a list. So "print excel.ActiveSheet.Cells(32,6)" will output > "42" or whatever - for grins, try "print > type(excel.ActiveSheet.Cells(32,6))" (taking care to insert enough parens > :) ) > > All that is gold does not glitter, not all who wander are lost, don't judge > a book by its cover, or a variable by its output, etc... > > -- Paul From Bulkan at gmail.com Sun Jun 25 20:34:46 2006 From: Bulkan at gmail.com (placid) Date: 25 Jun 2006 17:34:46 -0700 Subject: HTTP server In-Reply-To: <1151253325.924054.95100@c74g2000cwc.googlegroups.com> References: <1151134073.393065.187500@c74g2000cwc.googlegroups.com> <1151162732.819264.190560@i40g2000cwc.googlegroups.com> <1151241369.138325.173690@r2g2000cwb.googlegroups.com> <1151253325.924054.95100@c74g2000cwc.googlegroups.com> Message-ID: <1151282086.450972.128790@r2g2000cwb.googlegroups.com> Simon Forman wrote: > placid wrote: > > Simon Forman wrote: > > > > ... > > > For what you're asking about you'd probably want to use the > > > CGIHTTPRequestHandler from the CGIHTTPServer module instead. Check out > > > http://docs.python.org/lib/module-CGIHTTPServer.html > > > > This is what i was after, thanks for the tip. > > > > You're welcome, my pleasure. : ) > > ... > > > > Im having trouble running the following cgi script on windows > > > > > > > > #!c:/Python/python.exe -u > > > > text = """Content-type: text/html > > > > CGI 101 > >

A Second CGI script

> >
> >

Hello, CGI World!

> > """ > > print text > > > >
> > > > > > using this http server from > > http://effbot.org/librarybook/cgihttpserver.htm > > > > > > > > import CGIHTTPServer > > import BaseHTTPServer > > > > class Handler(CGIHTTPServer.CGIHTTPRequestHandler): > > cgi_directories = ["/cgi"] > > > > PORT = 8000 > > > > httpd = BaseHTTPServer.HTTPServer(("", PORT), Handler) > > print "serving at port", PORT > > httpd.serve_forever() > > > > > > > > i get the error number 403, when i try to access the cgi script which > > is located in a subdirectory called cgi where this file is (http > > server). I have a feeling that i need to change the Handler class or > > something, implement , but i couldnt find any examples other then this > > from eff-bot. > > > > It could also be this line of code, that a google search turned up, its > > the way of running cgi scripts on windows > > > > #!c:/Python/python.exe -u > > > > > > Cheers > > > Your cgi and server scripts look fine to me. > > Some diagnostic questions: > > What is the filename of your cgi script? > (It must end in ".py" or ".pyw" for CGIHTTPRequestHandler to recognize > it as a python script. See the is_python() method in the handler > class. Also, in this case the "#!c:/Python/python.exe -u" line isn't > needed, but it doesn't hurt. CGIHTTPRequestHandler should find the > python interpreter for you without it.) The file was named test.cgi. I changed it too test.py and it worked > > What was the exact URL that you're using to try to reach your script? > (It should look something like: > "http://localhost:8000/cgi/myscript.py") i was trying to access it at http://localhost:8000/test.cgi which i now know is wrong. > > What was the error message that accompanied the 403 error? > > Did you start the server script from the directory it's in? i started the server one directory above the cgi directory > What was the log output from your server script when you tried to > access the cgi script? The error message outputted by the server was localhost - - [26/Jun/2006 09:56:53] code 403, message CGI script is not a plain file ('/cgi/') Thanks for the help. I got it to work now. Cheers From sonaldgr8 at gmail.com Mon Jun 12 02:48:56 2006 From: sonaldgr8 at gmail.com (sonal) Date: 11 Jun 2006 23:48:56 -0700 Subject: How to link foreign keys & primary keys using python? References: <1149856668.055162.209650@u72g2000cwu.googlegroups.com> <1149862607.820399.224260@c74g2000cwc.googlegroups.com> Message-ID: <1150094936.861381.26150@i40g2000cwc.googlegroups.com> MTD wrote: > Your post is confusing. Here is my advice: investigate the use of > dictionaries. Dictionaries can allow you to define data in the form { > key:data }, e.g. > > { area_code : area_data } > > { (area_code,school_code) : school_data } > > { (school_code,student_code) : student_data } Thanx Mr. Marc... I am surely investigating the dictionaries... but the problem is that I have to use the existing code... and thats what is creating problems for me... :( From maric at aristote.info Mon Jun 26 11:46:36 2006 From: maric at aristote.info (Maric Michaud) Date: Mon, 26 Jun 2006 17:46:36 +0200 Subject: Get List of Classes In-Reply-To: <449FFC7E.2010600@tim.thechases.com> References: <1151332257.564563.139040@u72g2000cwu.googlegroups.com> <449FFC7E.2010600@tim.thechases.com> Message-ID: <200606261746.37706.maric@aristote.info> Le lundi 26 juin 2006 17:25, Tim Chase a ?crit?: > ?I couldn't find any nice > method for determining if a variable referenced a module other > than checking to see if that item had both a "__file__" and a > "__name__" attribute. Why not : In [8]: import types, sys In [9]: isinstance(sys, types.ModuleType) Out[9]: True ? Seems rather explicit IMO. -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From fanmail at micah-wedemeyer.net Fri Jun 2 17:55:38 2006 From: fanmail at micah-wedemeyer.net (Micah) Date: 2 Jun 2006 14:55:38 -0700 Subject: Reversible replacement of whitespace characters with visible characters References: <1149280203.974237.209080@y43g2000cwc.googlegroups.com> Message-ID: <1149285338.168243.22040@c74g2000cwc.googlegroups.com> James Stroud wrote: > Micah wrote: > > Hi, > > > > I'm looking for a tool to do the following 2 things: > > > > 1) Given a string (ie. file, std input, whatever), replace all > > whitespace characters with visible characters (like their Unicode value > > or something). The end result will be one long unbroken line > > > > 2) Given a string altered as in step 1, "decode" it back to the > > original string. > > > > Note: The original string (it will usually be source files) might > > already contain Unicode values, and these must remain and not be > > altered in step 2. > > > > Note 2: I'm working in a Windows XP environment, but I have access to > > cygwin if that makes a difference. > > > > Can anyone think of a tool that already does this? I could probably > > whip something up, but if there's already something that does it I'd > > rather just use it. > > > > Micah > > > > Try urllib. > > py> import urllib > py> astr = 'faf\tfasf dsf\ndsfds dsf dsaf \t\r' > py> urllib.quote(astr) > 'faf%09fasf%20dsf%0Adsfds%20dsf%20dsaf%20%09%0D' > py> print astr > faf fasf dsf > dsfds dsf dsaf > > James > > -- > James Stroud > UCLA-DOE Institute for Genomics and Proteomics > Box 951570 > Los Angeles, CA 90095 > > http://www.jamesstroud.com/ Perfect!! Just what I was looking for! From nmm1 at cus.cam.ac.uk Wed Jun 14 13:26:55 2006 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 14 Jun 2006 17:26:55 GMT Subject: Numerics, NaNs, IEEE 754 and C99 References: <12904mjhl493t49@corp.supernews.com> <4490315e$1@nntp0.pdx.net> Message-ID: In article <4490315e$1 at nntp0.pdx.net>, Scott David Daniels writes: |> Grant Edwards wrote: |> |> > While you're at it, the pickle modules need to be fixed so they |> > support NaN and Inf. ;) |> |> The NaN problem is portability -- NaN values are not standard, and |> pretending they are won't help. There are many possible NaNs, several |> of which have desirable behaviors, and different processors (and |> Floating Point settings) choose different bit representations for |> those NaNs. There are at least: Inf, -Inf, NaN, Ind (Indeterminant). The main meaning of NaN is Indeterminate (i.e. it could be anything). If you mean 'Missing', that is what was and is done in statistical packages, and it follows very different rules. There are several other meanings of NaN, but let's not go there, here. Though I have document I could post if people are interested. |> Being able to pickle some of these will produce values that "don't |> behave right" on a different machine. Up until now, I think you can |> send a pickle of a data structure and unpickle it on a different |> processor to get equivalent data. No, it could be done right. The unpickling would need to detect those values and raise an exception. You have to allow for it even on the same 'systems' because one Python might have been compiled with hard underflow and one with soft. Your really DON'T want to import denorms into programs that don't expect them. Regards, Nick Maclaren. From fredrik at pythonware.com Fri Jun 30 06:42:41 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 30 Jun 2006 12:42:41 +0200 Subject: FIXED: Re: optparse multiple arguments References: <1151657119.837675.213700@p79g2000cwp.googlegroups.com><1151657634.348133.291340@x69g2000cwx.googlegroups.com><1151658092.273456.32260@75g2000cwc.googlegroups.com><1151661717.240109.47650@h44g2000cwa.googlegroups.com> <1151663623.101732.264020@d56g2000cwd.googlegroups.com> Message-ID: Ritesh Raj Sarraf wrote: >> http://docs.python.org/lib/optparse-standard-option-actions.html > > That won't help because by design of my program, I can't limit the > number of arguments a user can pass to it. do you want options, arguments, or are you just somewhat confused ? From chris.uppal at metagnostic.REMOVE-THIS.org Wed Jun 21 05:54:00 2006 From: chris.uppal at metagnostic.REMOVE-THIS.org (Chris Uppal) Date: Wed, 21 Jun 2006 10:54:00 +0100 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> Message-ID: <44992e6c$3$664$bed64819@news.gradwell.net> Chris Smith wrote: > > It would be interesting to see what a language designed specifically to > > support user-defined, pluggable, and perhaps composable, type systems > > would look like. [...] > > You mean in terms of a practical programming language? If not, then > lambda calculus is used in precisely this way for the static sense of > types. Good point. I was actually thinking about what a practical language might look like, but -- hell -- why not start with theory for once ? ;-) > I think Marshall got this one right. The two are accomplishing > different things. In one case (the dynamic case) I am safeguarding > against negative consequences of the program behaving in certain non- > sensical ways. In the other (the static case) I am proving theorems > about the impossibility of this non-sensical behavior ever happening. And so conflating the two notions of type (-checking) as a kind of category error ? If so then I see what you mean, and it's a useful distinction, but am unconvinced that it's /so/ helpful a perspective that I would want to exclude other perspectives which /do/ see the two as more-or-less trivial variants on the same underlying idea. > I acknowledge those questions. I believe they are valid. I don't know > the answers. As an intuitive judgement call, I tend to think that > knowing the correctness of these things is of considerable benefit to > software development, because it means that I don't have as much to > think about at any one point in time. I can validly make more > assumptions about my code and KNOW that they are correct. I don't have > to trace as many things back to their original source in a different > module of code, or hunt down as much documentation. I also, as a > practical matter, get development tools that are more powerful. Agreed that these are all positive benefits of static declarative (more or less) type systems. But then (slightly tongue-in-cheek) shouldn't you be agitating for Java's type system to be stripped out (we hardly /need/ it since the JVM does latent typing anyway), leaving the field free for more powerful or more specialised static analysis ? > (Whether it's possible to create the same for a dynamically typed > language is a potentially interesting discussion; but as a practical > matter, no matter what's possible, I still have better development tools > for Java than for JavaScript when I do my job.) Acknowledged. Contrary-wise, I have better development tools in Smalltalk than I ever expect to have in Java -- in part (only in part) because of the late binding in Smalltalk and it's lack of insistence on declared types from an arbitrarily chosen type system. > On > the other hand, I do like proving theorems, which means I am interested > in type theory; if that type theory relates to programming, then that's > great! That's probably not the thing to say to ensure that my thoughts > are relevant to the software development "industry", but it's > nevertheless the truth. Saying it will probably win you more friends in comp.lang.functional than it looses in comp.lang.java.programmer ;-) -- chris From len-l at telus.net Wed Jun 28 14:40:15 2006 From: len-l at telus.net (Lenard Lindstrom) Date: Wed, 28 Jun 2006 11:40:15 -0700 Subject: [Pyrex] pyrex functions to replace a method (Re: replace a method in class: how?) In-Reply-To: <44A261CF.4000309@bryant.edu> References: <44A1C5C7.4090007@canterbury.ac.nz> Message-ID: <44A26A9F.14899.7AA9E9@len-l.telus.net> On 28 Jun 2006 at 7:02, Brian Blais wrote: > Greg Ewing wrote: > > Brian Blais wrote: > >> I have found a very similar problem trying to replace a method using a > >> function defined in pyrex. > > > > > > What *should* work is to define the method inside a > > class in Pyrex (plain class, not extension type) and > > extract it out of the class's __dict__. That's because > > Pyrex pre-wraps a function defined in a class in an > > unbound method object before putting it in the class. > > > > So I tried: > > #--------------------------------------------------------------------------------- > > #module_pyrex.pyx > > class update_funcs: > > def pyrex_update_within_class(self,val): > print "pyrex module within class",val > > > #--------------------------------------------------------------------------------- > > #(adding to test_replace_method.py) > > This.update4=module_pyrex.update_funcs.__dict__['pyrex_update_within_class'] > > t.update4('pyrex within class') # doesn't work > > #--------------------------------------------------------------------------------- > > and get: > > TypeError: unbound method pyrex_update_within_class() must be called with > update_funcs instance as first argument (got str instance instead) > > > did I do this wrong? Nothing. Python's method type is just too specialized to work as Greg suggested. You will have to provide your own method descriptor. This works: #-------------------------------------------------------------------- #module_pyrex.pyx cdef extern from "python.h": object PyMethod_New(object func, object self, object cls) # Yes, this has to be an extension type in Pyrex. cdef class InstanceMethod: cdef object fn def __init__(self, fn): self.fn = fn def __get__(self, instance, owner): return PyMethod_New(self.fn, instance, owner) def pyrex_update_within_class(self,val): print "pyrex module within class",val pyrex_update_within_class = InstanceMethod(pyrex_update_within_class) #-------------------------------------------------------------------- #(Make this replacement in main py module of original posting) This.update3=module_pyrex.pyrex_update_within_class #-------------------------------------------------------------------- InstanceMethod is minimal. Additions may be to make the fn attribute readable and a __call__ method that calls fn directly. Lenard Lindstrom From girish at cse.iitb.ac.in Tue Jun 13 02:11:48 2006 From: girish at cse.iitb.ac.in (Girish Sahani) Date: Tue, 13 Jun 2006 11:41:48 +0530 (IST) Subject: Getting "TypeError:list indices must be integers" Message-ID: <44592.10.209.4.1.1150179108.squirrel@10.105.1.3> Hi, Please check out the following loop,here indexList1 and indexList2 are a list of numbers. for index1 in indexList1: for index2 in indexList2: if ti1[index1] == ti2[index2] and not index1 != indexList1.pop(): index1+=1 index2+=1 continue elif index1 == indexList1.pop() and charList in pairList: k = string2.index(char2[0]) instance = ti2(k) tiNew = ti1.append(instance) tiNewList.append(tiNew) else: break On running my program, python gives me a TypeError saying: if ti1[index1] == ti2[index2] and not index1 != indexList1.pop(): TypeError: list indices must be integers Even though index1 and index2 are really integers.Please help! From dima at 127.0.0.1 Mon Jun 19 18:02:55 2006 From: dima at 127.0.0.1 (Dimitri Maziuk) Date: Mon, 19 Jun 2006 22:02:55 +0000 (UTC) Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> Message-ID: Yet Another Dan sez: ... Requiring an array index to be an integer is considered a typing > problem because it can be checked based on only the variable itself, > whereas checking whether it's in bounds requires knowledge about the array. You mean like subtype MyArrayIndexType is INTEGER 7 .. 11 type MyArrayType is array (MyArrayIndexType) of MyElementType Dima -- We're sysadmins. Sanity happens to other people. -- Chris King From andrew-news at andros.org.uk Tue Jun 27 18:43:03 2006 From: andrew-news at andros.org.uk (Andrew McLean) Date: Tue, 27 Jun 2006 23:43:03 +0100 Subject: Looking for Python code to obsfucate mailto links on web site In-Reply-To: References: Message-ID: Dan Sommers wrote: > On Sun, 25 Jun 2006 21:10:31 +0100, > Andrew McLean wrote: > >> I'm looking at putting some e-mail contact addresses on a web site, >> and wanted to make it difficult for spammers to harvest them. > > [ ... ] > >> Searching the web it looks like the best solution for me might be to >> embed JavaScript in the web page that dynamically generates the e-mail >> address in the browser client. > > [ ... ] > >> Now I could write suitable code myself, but would be surprised if it >> wasn't already available. Any pointers? > > Pointers? What do you think this is, C? ;-) Try this: > > def spam_averse_email_address( email_address, text ): > """return HTML-embedded javascript to create a spam-averse mailto link""" > > def char_codes( a_string ): > return ",".join(str(ord(a_char)) for a_char in a_string) > > return """""" % (char_codes(email_address), char_codes(text)) > > The newlines within the triple quoted string are important; use that > function something like this: > > print "" > print "Title > print " > print "

%s

" % spam_averse_email_address( 'email at mydomain.com', > 'click here to email me' ) > print "" > print "" > > You mentioned accessibility; make sure that your HTML does something > sensible if the user's browser doesn't do javascript. > > HTH, > Dan > That's great. Just what I was looking for. From pmartin at snakecard.com Fri Jun 16 11:00:16 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Fri, 16 Jun 2006 10:00:16 -0500 Subject: Pycrypto References: <1150446904.527285.255170@g10g2000cwb.googlegroups.com> <1150458752.342042.189650@h76g2000cwa.googlegroups.com> <1150462237.224431.213020@c74g2000cwc.googlegroups.com> <1150466793.537546.149690@p79g2000cwp.googlegroups.com> Message-ID: Hi, Look at the bin2ascii module. Philippe luca72 wrote: > > Excuse me again, > If the string is not a sting but hex number how i have to proced : > > look this page: > http://www.cs.eku.edu/faculty/styer/460/Encrypt/JS-AES.html > > Regards Luca From duncanm255 at hotmail.com Thu Jun 1 15:24:47 2006 From: duncanm255 at hotmail.com (D) Date: 1 Jun 2006 12:24:47 -0700 Subject: Starting New Process In-Reply-To: References: <1149172463.881528.131290@j55g2000cwa.googlegroups.com> <1149185284.820789.321130@y43g2000cwc.googlegroups.com> Message-ID: <1149189887.279693.146240@f6g2000cwb.googlegroups.com> Sorry, I should've specified - I'm familiar with sockets, but I was referring to spawning a 'vi' process independent of my Python app.. Carl wrote: > D wrote: > > > Thanks, Jean-Paul - is there any way to do it without using Twisted, > > since I am not very familiar with it? (i.e. just using the os library) > > Thanks. > > > > Jean-Paul Calderone wrote: > >> On 1 Jun 2006 07:34:23 -0700, D wrote: > >> >Hello, I need to write a server program that performs the following > >> >tasks: > >> > > >> >1) Listens on TCP port 5555 for a connection > >> >2) When client connects, launches application (for example, vi), then > >> >closes connection with client > >> >3) Goes back to listening on TCP port 5555 for an incoming connection > >> > >> Untested: > >> > >> from twisted.internet import protocol, reactor > >> > >> class ViRunner(protocol.Protocol): > >> def connectionMade(self): > >> reactor.spawnProcess( > >> None, > >> '/usr/bin/setsid', > >> ['setsid', '/usr/bin/vi']) > >> self.transport.loseConnection() > >> > >> f = protocol.ServerFactory() > >> f.protocol = ViRunner > >> reactor.listenTCP(5555, f) > >> reactor.run() > >> > >> Jean-Paul > > Use import socket ifyou don't want to use twisted (which is incredibly > good). Google for "+socket +python +server" and you will find what you are > looking for. > > See, for example, > http://floppsie.comp.glam.ac.uk/Glamorgan/gaius/wireless/5.html > > Carl From webraviteja at gmail.com Tue Jun 13 16:17:29 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 13 Jun 2006 13:17:29 -0700 Subject: Combining The Best Of Python, Ruby, & Java?????? In-Reply-To: <4f7todF1har97U1@uni-berlin.de> References: <1150181049.815883.138580@c74g2000cwc.googlegroups.com> <4f7todF1har97U1@uni-berlin.de> Message-ID: <1150229849.447116.147570@i40g2000cwc.googlegroups.com> Diez B. Roggisch wrote: > > But semantically it is a proper functional language. The features may > > not attract Python users who might prefer Boo/Jython/IronPython. But it > > does offer something to disillusioned Groovy users. > > Are they disillusioned? Just wondering. Nah! Just a poor passing attempt at humor. Groovy is a great language too. I should watch out. Maybe Groovy programmers have knives too :-). http://cardboard.nu/blog/2005_02_02/gosling_on_jvm_scripting.html From vedranf at riteh.hr Tue Jun 6 20:08:54 2006 From: vedranf at riteh.hr (=?ISO-8859-2?Q?Vedran_Fura=E8?=) Date: Wed, 07 Jun 2006 02:08:54 +0200 Subject: fsolve() from scipy crashes python on windows Message-ID: When I call optimize.fsolve(...) python interpreter crashes immediately, no error messages, nothing, just brings me back to c:\ On linux the same code works fine. I tried it on different computers. I seems that it doesn't crash on pentium4, only on athlon and pentium2. python 2.4.3 (activestate), scipy 0.4.8/0.4.9, windows xp Regards, Vedran Fura? From steven.bethard at gmail.com Sun Jun 18 23:56:03 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 18 Jun 2006 21:56:03 -0600 Subject: aligning SGML to text In-Reply-To: References: Message-ID: Steven Bethard wrote: > I have some plain text data and some SGML markup for that text that I > need to align. (The SGML doesn't maintain the original whitespace, so I > have to do some alignment; I can't just calculate the indices directly.) [snip] > Note that the SGML inserts spaces not only within the SGML elements, but > also around punctuation. [snip] > I need to determine the indices in the original text that each SGML > element corresponds to. Ok, below is a working version that doesn't use regular expressions. It's far from concise, but at least it doesn't fail like re does when I have more than 100 words. =) >>> import elementtree.ElementTree as etree >>> def align(text, sgml): ... # convert SGML tree to words, and assemble a list of the ... # start word index and end word index for each SGML element ... sgml = sgml.replace('&', '&') ... tree = etree.fromstring('%s' % sgml) ... words = [] ... if tree.text is not None: ... words.extend(tree.text.split()) ... word_spans = [] ... for elem in tree: ... elem_words = elem.text.split() ... start = len(words) ... end = start + len(elem_words) ... word_spans.append((start, end, elem.tag)) ... words.extend(elem_words) ... if elem.tail is not None: ... words.extend(elem.tail.split()) ... # determine the start character index and end character index ... # for each word from the SGML ... char_spans = [] ... start = 0 ... for word in words: ... while text[start:start + 1].isspace(): ... start += 1 ... end = start + len(word) ... assert text[start:end] == word, (text[start:end], word) ... char_spans.append((start, end)) ... start = end ... # convert the word indices for each SGML element to ... # character indices ... for word_start, word_end, label in word_spans: ... start, _ = char_spans[word_start] ... _, end = char_spans[word_end - 1] ... yield label, start, end ... >>> text = '''TNF binding induces release of AIP1 (DAB2IP) from TNFR1, resulting in cytoplasmic translocation and concomitant formation of an intracellular signaling complex comprised of TRADD, RIP1, TRAF2, and AIPl.''' >>> sgml = ''' TNF binding induces release of AIP1 ( DAB2IP ) from TNFR1 , resulting in cytoplasmic translocation and concomitant formation of an intracellular signaling complex comprised of TRADD , RIP1 , TRAF2 , and AIPl . ... ''' >>> list(align(text, sgml)) [('PROTEIN', 0, 3), ('PROTEIN', 31, 35), ('PROTEIN', 37, 43), ('PROTEIN', 50, 55), ('PROTEIN', 128, 159), ('PROTEIN', 173, 178), ('PROTEIN', 180, 184), ('PROTEIN', 186, 191)] STeVe From dndfan at hotpop.com Thu Jun 1 10:58:40 2006 From: dndfan at hotpop.com (The Prophet) Date: 1 Jun 2006 07:58:40 -0700 Subject: os.walk trouble Message-ID: <1149173920.903876.68370@c74g2000cwc.googlegroups.com> As my first Python script, I am trying to make a program that recurses a directory searching for files whose names match a pattern. I have a basic idea of what the regexp would look like (and I can get more information about that), but I am stuck with incorrect understanding of os.walk. I've tried: root, dirs, files = os.walk(dirname) but it fails for some reason. I have seen this done before in the tutorial (I think it's called sequence unpacking). What is the proper way to do this? Thanks in advance. From JohnRoth1 at jhrothjr.com Thu Jun 29 11:00:09 2006 From: JohnRoth1 at jhrothjr.com (John Roth) Date: 29 Jun 2006 08:00:09 -0700 Subject: Python docs bug In-Reply-To: References: Message-ID: <1151593209.084822.207460@j72g2000cwa.googlegroups.com> Lawrence D'Oliveiro wrote: > One long-standing irritation I have with the table of contents for the > Python Library Reference , is that > there is one very important section, "String Methods" > , which does not appear > there. That's because it is section 2.3.6.1, and the table of contents > only goes to 3 levels. I've found that to be quite irritating as well. That's the section I use the most, and I find it irritating that I have to drill down into the manual every time to find it. I wouldn't call it a bug though. I'd call it an example of pedantry over usability. John Roth From __peter__ at web.de Sun Jun 4 04:00:43 2006 From: __peter__ at web.de (Peter Otten) Date: Sun, 04 Jun 2006 10:00:43 +0200 Subject: Python less error-prone than Java References: <1149405998.784652.68510@y43g2000cwc.googlegroups.com> Message-ID: Kaz Kylheku wrote: > Would that be a case-insensitive lexicographic comparison, or > case-insensitive? How do you specify what kind of less-than and equal > you want to do? class Key(object): def __init__(self, value, key): self.keyval = key(value) self.key = key def __lt__(self, other): return self.keyval < self.key(other) def __gt__(self, other): return self.keyval > self.key(other) items = ["Alpha", "Beta", "Delta", "Gamma"] print binarySearch(items, Key("DELTA", str.lower)) # 2 You /can/ teach an old duck new tricks :-) Peter From rvtol+news at isolution.nl Wed Jun 21 14:02:21 2006 From: rvtol+news at isolution.nl (Dr.Ruud) Date: Wed, 21 Jun 2006 20:02:21 +0200 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <1150902019.850531.204740@g10g2000cwb.googlegroups.com> <1150910976.455179.55870@r2g2000cwb.googlegroups.com> Message-ID: Rob Thorpe schreef: > Dr.Ruud: >> Marshall: >>> "dynamic types." I don't have a firm definition for >>> that term, but my working model is runtime type tags. In which >>> case, I would say that among statically typed languages, >>> Java does have dynamic types, but C does not. C++ is >>> somewhere in the middle. >> >> C has union. > > That's not the same thing. That is your opinion. In the context of this discussion I don't see any problem to put C's union under "dynamic types". > The value of a union in C can be any of a > set of specified types. But the program cannot find out which, and > the language doesn't know either. > > With C++ and Java dynamic types the program can test to find the type. When such a test is needed for the program with the union, it has it. -- Affijn, Ruud "Gewoon is een tijger." From fredrik at pythonware.com Wed Jun 28 11:05:06 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 28 Jun 2006 17:05:06 +0200 Subject: How to measure execution time of a program References: <54032.10.209.4.1.1151481158.squirrel@10.105.1.3> <12a55ff5fg7be3b@corp.supernews.com> Message-ID: Grant Edwards wrote: >> You can get better resolution by using time.clock() instead of >> time.time(). > > Oh really? When I do it, time.clock() is worse: on Unix, time.clock() is a tick counter; if your process is running when the tick interrupt arrives, the internal counter value is incremented (whether the process actually used the full tick slot or not). the tick resolution is usually 1-10 milli- seconds. on Windows, time.clock() is a high-resolution CPU counter, with microsecond resolution. From felipe.lessa at gmail.com Sun Jun 11 17:11:51 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Sun, 11 Jun 2006 18:11:51 -0300 Subject: how to get the length of a number In-Reply-To: References: Message-ID: <1150060312.31060.13.camel@kenshin.CASA> Em Dom, 2006-06-11 ?s 22:33 +0200, Sybren Stuvel escreveu: > Felipe Almeida Lessa enlightened us with: > > To see how many decimal digits it has: > > > > import math > > math.ceil(math.log(i, 10)) > > That doesn't work properly. > > >>> import math > >>> math.ceil(math.log(10000, 10)) > 4.0 > >>> math.ceil(math.log(10001, 10)) > 5.0 > > But "10000" certainly has as much digits as "10001". Hmmm, you're right. math.floor(math.log(x, 10)) + 1 -- Felipe. From fcorreia at gmail.com Wed Jun 28 13:45:42 2006 From: fcorreia at gmail.com (Filipe) Date: 28 Jun 2006 10:45:42 -0700 Subject: handling unicode data In-Reply-To: References: <1151506510.391856.207460@y41g2000cwy.googlegroups.com> <1151514404.954008.282280@b68g2000cwa.googlegroups.com> Message-ID: <1151516742.596423.157450@b68g2000cwa.googlegroups.com> Fredrik Lundh wrote: > works for me, given your example: > >>> s = "Fran\xd8a" > >>> unicode(s, "iso-8859-1") > u'Fran\xd8a' > > what does > print repr(row[1]) > > print in this case ? It prints: 'Fran\xd8a' The error I'm getting is beeing thrown when I print the value to the console. If I just convert it to unicode all seems ok (except for not beeing able to show it in the console, that is... :). For example, when I try this: print unicode("Fran\xd8a", "iso-8859-1") I get the error: Traceback (most recent call last): File "a.py", line 1, in ? print unicode("Fran\xd8a", "iso-8859-1") File "c:\Program Files\Python24\lib\encodings\cp437.py", line 18, in encode return codecs.charmap_encode(input,errors,encoding_map) UnicodeEncodeError: 'charmap' codec can't encode character u'\xd8' in position 4 : character maps to From aahz at pythoncraft.com Sun Jun 11 11:51:49 2006 From: aahz at pythoncraft.com (Aahz) Date: 11 Jun 2006 08:51:49 -0700 Subject: [ANN] Cerealizer 0.4 -- a secure Pickle-like module References: Message-ID: In article , Jiba wrote: > >Cerealizer is now available under the Python license (and was >previously GPL'ed). Nothing except for Python itself should be released under the Python license. See http://wiki.python.org/moin/PythonSoftwareFoundationLicenseFaq -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I saw `cout' being shifted "Hello world" times to the left and stopped right there." --Steve Gonedes From rossberg at ps.uni-sb.de Tue Jun 20 08:01:20 2006 From: rossberg at ps.uni-sb.de (Andreas Rossberg) Date: Tue, 20 Jun 2006 14:01:20 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: <1150794745.148997.245840@b68g2000cwa.googlegroups.com> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> Message-ID: Rob Thorpe wrote: > > No, that isn't what I said. What I said was: > "A language is latently typed if a value has a property - called it's > type - attached to it, and given it's type it can only represent values > defined by a certain class." "it [= a value] [...] can [...] represent values"? > Easy, any statically typed language is not latently typed. Values have > no type associated with them, instead variables have types. A (static) type system assigns types to (all) *expressions*. This includes values as well as variables. Don't confuse type assignment with type annotation (which many mainstream languages enforce for, but also only allow for, variable declarations). - Andreas From fcorreia at gmail.com Fri Jun 30 12:14:28 2006 From: fcorreia at gmail.com (Filipe) Date: 30 Jun 2006 09:14:28 -0700 Subject: handling unicode data References: <1151506510.391856.207460@y41g2000cwy.googlegroups.com> <1151514404.954008.282280@b68g2000cwa.googlegroups.com> <1151516742.596423.157450@b68g2000cwa.googlegroups.com> Message-ID: <1151684068.319765.42270@y41g2000cwy.googlegroups.com> Marc 'BlackJack' Rintsch wrote: > The `unicode()` call doesn't fail here but the ``print`` because printing > unicode strings means they have to be encoded into a byte string again. > And whatever encoding the target of the print (your console) uses, it > does not contain the unicode character u'\xd8'. From the traceback it > seems your terminal uses `cp437` as encoding. > > As you can see here: http://www.wordiq.com/definition/CP437 there's no ? > in that character set. somethings are much, much, clearer to me now. thanks! For future reference, these links may also help: http://www.jorendorff.com/articles/unicode/python.html http://www.thescripts.com/forum/thread23314.html I've changed my windows console copdepage to latin1 and the following prints are now outputting "Fran?a", as expected: print unicode("Fran\x87a", "cp850").encode("iso-8859-1") print unicode("Fran\xe7a", "iso-8859-1").encode("iso-8859-1") However, I don't yet fully understand what's happening with Pymssql. The encoding I expected to be receiving from MSSqlServer was cp850 (the column in question uses the collation SQL_Latin1_General_CP850_CS_AS), but it doesn't seem to be what the query is returning. I tried converting to a unicode string from a few different encodings, but none of them seems to be the right one. For example, for cp850, using a latin1 console: -------------------------------------------------------- term = unicode(row[1], "cp850") print repr(term) print term ---- output ------------------------------------------- u'Fran\xcfa' Fran?a -------------------------------------------------------- And for iso-8859-1 (also got the same result for mbcs): -------------------------------------------------------- term = unicode(row[1], "iso-8859-1") print repr(term) print term ---- output ------------------------------------------- u'Fran\xd8a' Fran?a -------------------------------------------------------- What do you think? Might it be Pymssql doing something wrong? From sleepingsquirrel at yahoo.com Tue Jun 27 19:12:06 2006 From: sleepingsquirrel at yahoo.com (Greg Buchholz) Date: 27 Jun 2006 16:12:06 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: <1151425350.679754.278820@i40g2000cwc.googlegroups.com> References: <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <1151384511.223582.305760@m73g2000cwd.googlegroups.com> <1151425350.679754.278820@i40g2000cwc.googlegroups.com> Message-ID: <1151449926.348233.20910@p79g2000cwp.googlegroups.com> Joe Marshall wrote: > It isn't clear to me which programs we would have to give up, either. > I don't have much experience in sophisticated typed languages. It is > rather easy to find programs that baffle an unsophisticated typed > language (C, C++, Java, etc.). > > Looking back in comp.lang.lisp, I see these examples: > > (defun noisy-apply (f arglist) > (format t "I am now about to apply ~s to ~s" f arglist) > (apply f arglist)) Just for fun, here is how you might do "apply" in Haskell... {-# OPTIONS -fglasgow-exts #-} class Apply x y z | x y -> z where apply :: x -> y -> z instance Apply (a->b) a b where apply f x = f x instance Apply b as c => Apply (a->b) (a,as) c where apply f (x,xs) = apply (f x) xs f :: Int -> Double -> String -> Bool -> Int f x y z True = x + floor y * length z f x y z False= x * floor y + length z args = (1::Int,(3.1415::Double,("flub",True))) main = print $ apply f args ...which depends on the fact that functions are automatically curried in Haskell. You could do something similar for fully curried function objects in C++. Also of possible interest... Functions with the variable number of (variously typed) arguments http://okmij.org/ftp/Haskell/types.html#polyvar-fn ...But now I'm curious about how to create the "apply" function in a language like Scheme. I suppose you could do something like... (define (apply fun args) (eval (cons fun args))) ...but "eval" seems a little like overkill. Is there a better way? Greg Buchholz From david.nospam.hopwood at blueyonder.co.uk Wed Jun 28 07:03:05 2006 From: david.nospam.hopwood at blueyonder.co.uk (David Hopwood) Date: Wed, 28 Jun 2006 11:03:05 GMT Subject: languages with full unicode support In-Reply-To: References: <1151251736.590910.36050@u72g2000cwu.googlegroups.com> Message-ID: Tim Roberts wrote: > "Xah Lee" wrote: > >>Languages with Full Unicode Support >> >>As far as i know, Java and JavaScript are languages with full, complete >>unicode support. That is, they allow names to be defined using unicode. >>(the JavaScript engine used by FireFox support this) >> >>As far as i know, here's few other lang's status: >> >>C ? No. > > This is implementation-defined in C. A compiler is allowed to accept > variable names with alphabetic Unicode characters outside of ASCII. It is not implementation-defined in C99 whether Unicode characters are accepted; only how they are encoded directly in the source multibyte character set. Characters escaped using \uHHHH or \U00HHHHHH (H is a hex digit), and that are in the sets of characters defined by Unicode for identifiers, are required to be supported, and should be mangled in some consistent way by a platform's linker. There are Unicode text editors which encode/decode \u and \U on the fly, so you can treat this essentially like a Unicode transformation format (it would have been nicer to require support for UTF-8, but never mind). C99 6.4.2.1: # 3 Each universal character name in an identifier shall designate a character # whose encoding in ISO/IEC 10646 falls into one of the ranges specified in # annex D. 59) The initial character shall not be a universal character name # designating a digit. An implementation may allow multibyte characters that # are not part of the basic source character set to appear in identifiers; # which characters and their correspondence to universal character names is # implementation-defined. # # 59) On systems in which linkers cannot accept extended characters, an encoding # of the universal character name may be used in forming valid external # identifiers. For example, some otherwise unused character or sequence of # characters may be used to encode the \u in a universal character name. # Extended characters may produce a long external identifier. -- David Hopwood From fredrik at pythonware.com Tue Jun 27 04:05:54 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 27 Jun 2006 10:05:54 +0200 Subject: What technologies should I use for my application manager? References: <1151260635.570013.87210@b68g2000cwa.googlegroups.com><1151307031.166916.232330@m73g2000cwd.googlegroups.com> <1151394573.819701.242240@c74g2000cwc.googlegroups.com> Message-ID: "MrBlueSky" wrote: > Anyone else like to try and sell me on Zope or Django?! start here: http://www.djangoproject.com/documentation/tutorial1/ if you're on windows, and just want to tinker a little, http://effbot.org/zone/django.htm#installing might also be helpful. From stephan.diehl at gmx.net Thu Jun 22 10:52:53 2006 From: stephan.diehl at gmx.net (Stephan Diehl) Date: Thu, 22 Jun 2006 16:52:53 +0200 Subject: Registry of Methods via Decorators In-Reply-To: <1150983145.387222.5600@c74g2000cwc.googlegroups.com> References: <1150983145.387222.5600@c74g2000cwc.googlegroups.com> Message-ID: bayerj schrieb: > I want to make a registry of methods of a class during creation. My > attempt was this > > """ classdecorators.py > > Author: Justin Bayer > Creation Date: 2006-06-22 > Copyright (c) 2006 Chess Pattern Soft, > All rights reserved. """ > > class decorated(object): > > methods = [] > > @classmethod > def collect_methods(cls, method): > cls.methods.append(method.__name__) > return method > > class dec2(decorated): > > @collect_methods > def first_func(self): > pass > > @collect_methods > def second_func(self): > pass replace '@collect_methods' with '@decorated.collect_methods' and this will do what you want. But keep in mind, that the 'methods' list in decorated will be used for all derived classes. From fredrik at pythonware.com Tue Jun 6 14:37:32 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 06 Jun 2006 20:37:32 +0200 Subject: 10GB XML Blows out Memory, Suggestions? In-Reply-To: <4485C819.2030206@tachyontech.net> References: <1149594519.098115.8980@u72g2000cwu.googlegroups.com> <4eleh3F1eguosU1@uni-berlin.de> <4485C819.2030206@tachyontech.net> Message-ID: K.S.Sreeram wrote: > There's just NO WAY that the 10gb xml file can be loaded into memory as > a tree on any normal machine, irrespective of whether we use C or > Python. So the *only* way is to perform some kind of 'stream' processing > on the file. Perhaps using a SAX like API. So (c)ElementTree is ruled > out for this. both ElementTree and cElementTree support "sax-style" event generation (through XMLTreeBuilder/XMLParser) and incremental parsing (through iterparse). the cElementTree versions of these are even faster than pyexpat. the iterparse interface is described here: http://effbot.org/zone/element-iterparse.htm From robert.kern at gmail.com Mon Jun 19 11:59:58 2006 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 19 Jun 2006 10:59:58 -0500 Subject: comparing two arrays In-Reply-To: <1150727011.990165.228480@i40g2000cwc.googlegroups.com> References: <1150721380.948808.231760@h76g2000cwa.googlegroups.com> <1150727011.990165.228480@i40g2000cwc.googlegroups.com> Message-ID: Bas wrote: > You are comparing a normal python list to a constant, which are > obviously unequal. Try converting your lists to arrays first > (untested): > > import numeric/numpy as N > a =N.array([0,1,2,5,6,6]) > b = N.array([5,4,1,6,4,6]) > print a==6 and b==6 > print N.where(a==6 and b==6) Careful there. The "and" keyword cannot be overloaded and so neither Numeric nor numpy does. Either N.logical_and() should be used or (since the results of a==6 and b==6 are known to be boolean arrays) the & operator works fine as well. In [9]: import numpy as np In [10]: a = np.array([0,1,2,5,6,6]) In [11]: b = np.array([5,4,1,6,4,6]) In [12]: (a==6) & (b==6) Out[12]: array([False, False, False, False, False, True], dtype=bool) In [13]: np.where((a==6) & (b==6)) Out[13]: (array([5]),) The OP may also find that numpy questions are best handled on numpy-discussion rather than comp.lang.python . https://lists.sourceforge.net/lists/listinfo/numpy-discussion -- 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 From claird at lairds.us Sun Jun 11 23:25:42 2006 From: claird at lairds.us (Cameron Laird) Date: Mon, 12 Jun 2006 03:25:42 +0000 Subject: Screen Scraping for Modern Applications? References: <1150077617.598735.85540@h76g2000cwa.googlegroups.com> Message-ID: In article <1150077617.598735.85540 at h76g2000cwa.googlegroups.com>, wrote: . . . >For a side project I'm working on I need to be able to scrape a modern >computer desktop. Is there any basic material already available to do >this? I'd rather not need to write my own to interact with hardware. . . . Oh, no. Very hard. Very, very hard. At least as you've expressed it here, this is an exceptionally difficult task. What does "scrape" mean to you? Do you want to reproduce the display remotely, or extract text, or some other possibility? Does "modern computer" mean Windows to you? From scott.daniels at acm.org Thu Jun 15 11:17:20 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Thu, 15 Jun 2006 08:17:20 -0700 Subject: Which compiler will Python 2.5 / Windows (Intel) be built with? In-Reply-To: <1150367139.495114.148550@g10g2000cwb.googlegroups.com> References: <1150367139.495114.148550@g10g2000cwb.googlegroups.com> Message-ID: <44917535$1@nntp0.pdx.net> meyer at mesw.de wrote: > Hi everyone, > > which compiler will Python 2.5 on Windows (Intel) be built with? Same as for Python 2.4 (the decision was taken a while ago). Intel sells a compatible compiler, I believe. -- --Scott David Daniels scott.daniels at acm.org From foster at home.nl Wed Jun 7 11:11:07 2006 From: foster at home.nl (Maarten van Veen) Date: Wed, 07 Jun 2006 17:11:07 +0200 Subject: cgi and popen References: Message-ID: In article , Thomas Guettler wrote: > Am Wed, 07 Jun 2006 14:54:41 +0200 schrieb Maarten van Veen: > > > A long story made short, I've build a python/cgi website consisting of > > two pages. Page1 has a html form in which you can input a series of > > queries. Then via Popen it starts a pythons search script, which stores > > the results in a python shelve. > > As the Popen command is given it should redirect to page2, which will > > check if the shelve is ready (search finished) and if not displays a > > search page, refreshing itself after 10 seconds. > > The Popen command works nice when tried out in the console. The script > > isueing the Popen quits, and the other process keeps on running till > > finished. > > Hi, > > You can find out where the process hangs, by > sending SIGINT to the python script: > > kill -SIGINT PID > > This is like ctrl-c, you should get a traceback. > > If the page1 script is not alive anymore, during > the unwanted waiting, this does not work. > > Which form of popen do you use? Popen4 is the best, > because you cannot get a deadlock if there is output > on stdout and stderr. > > I guess you have the same strange thing, if you > ssh to the server, start the script1 and you want > to logoff before the subprocesses is finished. > > You can try to start the script like this: > > nohup nice mein-script >> $HOME/log/mein-script.log 2>&1 > HTH, > Thomas Thx for your reply Thomas. I use subprocess.Popen, because popen 1t/m 4 are deprecated. I found a dodgy way around my problem though. By inserting another page between the input and the results page,a user sees a "i'm searching" page which wants to redirect to the results page directly, but keeps waiting for the search process to finish. So I put what used to be my problem to good use. :D Maarten From emanuele.aina at gmail.com Thu Jun 15 18:56:02 2006 From: emanuele.aina at gmail.com (Emanuele Aina) Date: 15 Jun 2006 15:56:02 -0700 Subject: __lt__ slowing the "in" operator even if not called References: <1150318630.203249.191250@r2g2000cwb.googlegroups.com> <1150383992.319124.128520@h76g2000cwa.googlegroups.com> Message-ID: <1150412162.593718.61580@g10g2000cwb.googlegroups.com> andrewdalke at gmail.com dettagli?: > > Someone can explain me why? > > The list's __contains__ method is very simple [...] > So if you define "__lt__" in your object then the type gets a richcmp > function and your == test implicit in the 'in' search always incurs the > cost of figuring out that "__eq__" is not defined. Thank you for the detailed explanation! :) Do you think I should report this as a performance bug, maybe with the 'wishlist' priority, or I should accept the truth and hope for better luck next time? ;) From ksheka at gmail.com Mon Jun 19 06:38:50 2006 From: ksheka at gmail.com (K P S) Date: 19 Jun 2006 03:38:50 -0700 Subject: Simple script to make .png thumbnails from .zip archive... In-Reply-To: <1150664094.345764.280030@u72g2000cwu.googlegroups.com> References: <1150660266.413889.217280@c74g2000cwc.googlegroups.com> <1150664094.345764.280030@u72g2000cwu.googlegroups.com> Message-ID: <1150713530.440037.54650@y41g2000cwy.googlegroups.com> Thanks a lot. I'm really new to python, and haven't coded in over a decade, so please be patient. :-) I'm able to read a .jpg from a .zip archive, but can't seem to manipulate it. If I do this: zip=zipfile.ZipFile(inURL,mode="r") picture=zip.read("00.jpg") I get the image, but it is of "type" ZipFile. How can I change it to type Image? Or am I thinking about this in the wrong way? I would like to follow this with something like: picture.thumbnail((128, 128), Image.ANTIALIAS) But obviously I can't do this directly. What am I missing? hdante wrote: > Hi, > > I don't know zipfile by heart, but python official documentation is > always good ( docs.python.org ). You need a loop in the file list like > this: > > for file in zip: > process(file) > > Unfortunatelly, there are too many ways to create a thumbnail from an > image. I'll cite one, using the "python image" external module, that > I've found to be very easy: > > import Image > def process(file): > try: > image = Image.open(file) > image.thumbnail ((128,128), Image.ANTIALIAS) > image.save (file + '.thumb.png') > except: > print 'Skipping file', file > > Links: > http://docs.python.org/lib/lib.html - Python Library Reference > http://www.pythonware.com/library/pil/handbook/image.htm - The Image > Module > > K P S wrote: > > Hi. > > I'm looking for a small script that will take a .zip archive and pull > > the first .jpg from the archive and convert it to a .png. > > > > The reason for this is I want to have tuhmbnails for these archives in > > nautilus under gnome. I would like something similar to the following > > code, which will pull a thumbnail from an openoffice.org (oasis) > > document. What I want is a little more involved, I guess, since I > > don't know the name of the file (for the zip.read command), and I need > > to convert the file from .jpg to .png once I get it. Any help would be > > appreciated. Including a pointer to a web page of a manual with > > examples. :-) > > > > #!/usr/bin/python > > > > import zipfile > > import sys > > import gnomevfs > > > > inURL=gnomevfs.get_local_path_from_uri(sys.argv[1]) > > outURL=sys.argv[2] > > > > zip=zipfile.ZipFile(inURL,mode="r") > > picture=zip.read("Thumbnails/thumbnail.png") > > thumbnail=open(outURL,"w") > > thumbnail.write(picture) > > thumbnail.write("/n") > > zip.close() > > thumbnail.close() From trentm at activestate.com Mon Jun 19 16:27:14 2006 From: trentm at activestate.com (Trent Mick) Date: Mon, 19 Jun 2006 13:27:14 -0700 Subject: Active Python versions In-Reply-To: References: Message-ID: <449708A2.90406@activestate.com> Tom Del Rosso wrote: > Why is the Windows msi install file for ActivePython-2.4.3.12 only 15MB > whereas the older msi file for ActivePython-2.4.2.10 was 19MB? > > BTW, is that the prefered Python environment? Are you sure you are comparing the right packages? By my count: ActivePython-2.4.2.10-win32-x86.msi 19,053 KB ActivePython-2.4.3.12-win32-x86.msi 19,237 KB Note that the Windows *64-bit* builds are smaller (around 15MB) because they do not include PyWin32. Trent -- Trent Mick trentm at activestate.com From digitalorganics at gmail.com Mon Jun 26 11:57:33 2006 From: digitalorganics at gmail.com (digitalorganics at gmail.com) Date: 26 Jun 2006 08:57:33 -0700 Subject: Replace Whole Object Through Object Method Message-ID: <1151337453.804750.293180@b68g2000cwa.googlegroups.com> How can an object replace itself using its own method? See the following code: class Mixin: def mixin(object, *classes): NewClass = type('Mixin', (object.__class__,) + classes, {}) newobj = NewClass() newobj.__dict__.update(object.__dict__) return newobj def isClass(object): if 'classobj' in str(type(object)): return 1 elif "'type'" in str(type(object)): return 1 else: return 0 def listClasses(): classes = [] for eachobj in globals().keys(): if isClass(globals()[eachobj]): classes.append(globals()[eachobj]) print eachobj return classes def MixInto(Class, Mixin): if Mixin not in Class.__bases__: Class.__bases__ += (Mixin,) ------------------------------------------------------------------------ Okay, so the mixin function becomes part of whatever class I choose and hence its instances, but the problem is that the way I currently have it setup mixin() returns a new object, instead of replacing whatever class instance that calls it into that new object. I hope I'm making sense here. Basically what I need is for the method to be able to find out the name of the instance, then I can just go to the globals dictionary to do the replacement. Advance thanks to all who can help... From aum at spam.me.please Mon Jun 19 18:53:42 2006 From: aum at spam.me.please (aum) Date: Tue, 20 Jun 2006 10:53:42 +1200 Subject: wxPython GUI designer References: <1150661348.837969.46870@r2g2000cwb.googlegroups.com> Message-ID: On Sun, 18 Jun 2006 13:09:08 -0700, diffuser78 wrote: > I am newbie learning wxPython. I tried using GUI designer called > wxGlade. When it generated code I couldnt get the same level of > flexibility as writing the code by oneself. > > Any view on what you think about using GUI designer tools. > > Every help is appreciated. I use wxGlade all the time, and find it's great. My only complaint is that there are some controls it doesn't know about, such as wx.HtmlWindow, and I have to add these controls in wxGlade as 'custom' controls. But to me, that's pretty minor. To get the best out of wxGlade, you really need to subclass the classes that wxGlade generates. Don't look to wxGlade to write your app for you. It's there for gui structure (the 'view'), and it's up to you to flesh out the 'controller' side. So I'd recommend you persist with wxGlade - subclass all the classes that wxGlade generates, and add your own methods to handle events, set up the gui as you want, and (in some rare cases) do some extra initial bindings. I typically set wxGlade to generate a file called 'myapp_ui.py', and I write my own 'myapp.py', in which I 'import myapp_ui', then subclass the wxGlade-generated classes in 'myapp_ui'. Works a treat for me, and saves a lot of time compared to hand-coding the GUI. -- Cheers aum From belred at gmail.com Mon Jun 5 10:36:14 2006 From: belred at gmail.com (Bryan) Date: Mon, 05 Jun 2006 07:36:14 -0700 Subject: Open Source Charting Tool In-Reply-To: References: <1L0gg.1841$Su3.159041@news20.bellglobal.com> Message-ID: <4484415E.5060401@gmail.com> Harry George wrote: > See pygdchart > http://www.nullcube.com/software/pygdchart.html > this looks pretty nice. i don't see in the docs if and how it can be integrated with other gui toolkits such wxpython. :( bryan From jeremy+complangpython at jeremysanders.net Sun Jun 18 15:54:58 2006 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Sun, 18 Jun 2006 20:54:58 +0100 Subject: import hook References: <1hgrdu7.1djmypwdlt2uN%aleax@mac.com> Message-ID: Thomas Heller wrote: > There are also other ways. You could extend __path__ of foo, and the > pkgutil module might also be useful. The __path__ trick worked nicely, thanks. Here is the code in case anyone is interested # Allow veusz to be run even if not installed into PYTHONPATH try: import veusz except ImportError: # load in the veusz module, but change its path to # the veusz directory, and insert it into sys.modules import __init__ as veusz thisdir = os.path.dirname( os.path.abspath(__file__) ) veusz.__path__ = [thisdir] veusz.__name__ = 'veusz' sys.modules['veusz'] = veusz This is part of the main program. If it can't import it (i.e. it is not installed), it imports the __init__ module, renames it, and corrects its path, then sticks it into the list of imported modules. Jeremy -- Jeremy Sanders http://www.jeremysanders.net/ From sreeram at tachyontech.net Fri Jun 2 02:28:07 2006 From: sreeram at tachyontech.net (Sreeram Kandallu) Date: Fri, 02 Jun 2006 11:58:07 +0530 Subject: tp_richcompare Message-ID: <447FDA77.4060507@tachyontech.net> I'm writing an extension type, for which i'd like to implement only == and !=, but not the other comparison operators like <,<=,>,>=. What is the right way to do this? I currently have a tp_richcompare function, which handles Py_EQ, and Py_NE, but raises a TypeError for the other operations. Is this the 'right' way? Sreeram -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 260 bytes Desc: OpenPGP digital signature URL: From anton.vredegoor at gmail.com Thu Jun 22 09:58:04 2006 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Thu, 22 Jun 2006 15:58:04 +0200 Subject: How to generate all permutations of a string? In-Reply-To: References: Message-ID: Girish Sahani wrote: > I want to generate all permutations of a string. I've managed to > generate all cyclic permutations. Please help :) http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496724 anton From kylotan at gmail.com Fri Jun 30 05:32:40 2006 From: kylotan at gmail.com (Ben Sizer) Date: 30 Jun 2006 02:32:40 -0700 Subject: Py2exe make wxPython window looks bad In-Reply-To: <1151653241.416599.6450@i40g2000cwc.googlegroups.com> References: <1151653241.416599.6450@i40g2000cwc.googlegroups.com> Message-ID: <1151659960.245928.305910@d56g2000cwd.googlegroups.com> zdp wrote: > But when I convert the program to EXE file by Py2exe, and run it, the > look & feel is bad. It's just like the windows 9x. All controls has a > thick and emboss border. However, the scrollbars look good, same as the > window XP. Bear in mind that a lot of WinXP users stick with the old-style theme anyway, so you may want to consider them too when designing your forms. Sadly, WxWidget layouts tend to look bad on the old Windows theme, largely because there are too many unnecessary borders on the various elements, and I don't know if that's an inherent problem with the toolkit or just an oversight on the part of those who only develop under the newer themes. -- Ben Sizer From filipwasilewski at gmail.com Wed Jun 21 15:26:06 2006 From: filipwasilewski at gmail.com (Filip Wasilewski) Date: 21 Jun 2006 12:26:06 -0700 Subject: Update on Memory problem with NumPy arrays References: <1150907922.908497.120310@u72g2000cwu.googlegroups.com> Message-ID: <1150917966.428492.87350@y41g2000cwy.googlegroups.com> sonjaa wrote: > Hi > > last week I posted a problem with running out of memory when changing > values in NumPy arrays. Since then I have tried many different > approaches and > work-arounds but to no avail. [...] Based on the numpy-discussion this seems to be fixed in the SVN now(?). Anyway, you can use 'where' function to eliminate the loops: from numpy import * y = ones((501,501)) z = zeros((501,501)) it = 50 for kk in xrange(it): y[1,1] = 4 y[1,2] = 4 y[1,0] = 4 y[2,1] = 6 print "Iteration #:%s" %(kk) y = where((y == 4) | (y == 6), 2, y) best, fw From sdcook55 at sbcglobal.net Sun Jun 11 16:24:58 2006 From: sdcook55 at sbcglobal.net (Stan Cook) Date: Sun, 11 Jun 2006 20:24:58 GMT Subject: how to get the length of a number In-Reply-To: <1150057074.389755.157060@m38g2000cwc.googlegroups.com> References: <1150057074.389755.157060@m38g2000cwc.googlegroups.com> Message-ID: Saketh wrote: > Stan Cook wrote: >> Can anyone tell me how to get the length of a number. I >> know len(string) will get the length of a string, but it >> doesn't like len(int). I seem to remember something like %s >> string. I tried to set a variable = to %s int, but that >> doesn't work. Is there a function I've forgotten about to >> convert an integer to a string? >> >> Regards >> >> Stan > > Use str(int). Then use len(). For example, len(str(12345)) will give > you 5. > Ahhhh! How could I have forgotten that. Boy is my face red :) Thanks.... I'll try to make my next question a more intelligent one. Regards, Stan From claird at lairds.us Sat Jun 24 21:01:05 2006 From: claird at lairds.us (Cameron Laird) Date: Sun, 25 Jun 2006 01:01:05 +0000 Subject: Absolute noob to Linux programming needs language choice help References: <1150854682.904891.274480@c74g2000cwc.googlegroups.com> Message-ID: In article , Ben C wrote: . . . >My favourite's Python, but Tcl is definitely worth a look. It's been >around a bit longer than Python (so more time for every conceivable >problem to have been met by someone and fixed), and I'm not an expert >but I think it's particularly good for things like sockets-- they're >just sort of built in and are very easy to work with. Tcl's maturity advantage is tiny--*maybe* two years. Both began at the end of the '80s. There've been close to two decades since to obscure any initial leads. I entirely agree with you, though, that Tcl's [socket] command is a wonderful thing. From anton at appsolutions.com Sat Jun 24 15:25:11 2006 From: anton at appsolutions.com (Anton van Straaten) Date: Sat, 24 Jun 2006 19:25:11 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: <1151171007.230666.235430@r2g2000cwb.googlegroups.com> References: <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150904134.520639.71070@b68g2000cwa.googlegroups.com> <1151056505.908723.162580@u72g2000cwu.googlegroups.com> <1151171007.230666.235430@r2g2000cwb.googlegroups.com> Message-ID: Marshall wrote: > Anton van Straaten wrote: > >>But beyond that, there's an issue here about the definition of "the >>language". When programming in a latently-typed language, a lot of >>action goes on outside the language - reasoning about static properties >>of programs that are not captured by the semantics of the language. >> >>This means that there's a sense in which the language that the >>programmer programs in is not the same language that has a formal >>semantic definition. As I mentioned in another post, programmers are >>essentially mentally programming in a richer language - a language which >>has informal (static) types - but the code they write down elides this >>type information, or else puts it in comments. >> >>We have to accept, then, that the formal semantic definitions of >>dynamically-checked languages are incomplete in some important ways. >>Referring to those semantic definitions as "the language", as though >>that's all there is to the language in a broader sense, is misleading. >> >>In this context, the term "latently-typed language" refers to the >>language that a programmer experiences, not to the subset of that >>language which is all that we're typically able to formally define. > > > That is starting to get a bit too mystical for my tastes. It's informal, but hardly mystical. The formal semantic definitions of dynamically-checked languages I'm referring to are the typical "untyped" definitions, in which the language has a single static type. This means that when you as a programmer see a function that you "know" e.g. takes a number and returns a number, that knowledge is not something that's captured by the language's formal semantics or static type system. All that can be expressed in the language's static type system is that the function takes a value and returns a value. When you're programming in your favorite dynamically-typed language, I'll bet that you're not thinking of functions, or other expressions, in such a restricted way. Your experience of programming in the language thus relies heavily on features that are not a "property of the language", if "the language" is taken to mean its formal semantic definition. So in referring to a language as latently-typed, the word "language" can be taken to mean what a programmer thinks of as the language, rather than a formal definition that only captures a subset of what the programmer routinely deals with. If we don't acknowledge this distinction between the part of the language that we can capture formally and the part that we haven't (yet), then we'll be forever stuck without accepted terminology for the informal bits, because such terminology can always be objected to on the grounds that it isn't supported by formal semantics. Anton From jstobbs at gmail.com Wed Jun 7 09:07:50 2006 From: jstobbs at gmail.com (jstobbs at gmail.com) Date: 7 Jun 2006 06:07:50 -0700 Subject: python socket proxy In-Reply-To: <1149587437.299147.314670@h76g2000cwa.googlegroups.com> References: <1149577919.811693.178730@f6g2000cwb.googlegroups.com> <1149587437.299147.314670@h76g2000cwa.googlegroups.com> Message-ID: <1149685669.978416.235630@u72g2000cwu.googlegroups.com> Hi Thanks for the reply. I found a proxy that works for me. Now I would like to know if its possible to run a python script, so its not visible in the cmd window (windows, i know, its bad :-) ) Maybe run it as a windows service? Filip Wasilewski wrote: > jstobbs at gmail.com wrote: > > Hi all > > > > I am trying to create a lighweight tcp proxy server. > [...] > > There is a bunch of nice recipies in the Python Cookbook on port > forwarding. In the [1] and [2] case it should be fairly simple to add > an extra authentication step with pyOpenSSL. > > [1] http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/483730 > [2] http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/114642 > [3] http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/483732 > > best, > fw From george.sakkis at gmail.com Wed Jun 14 23:47:35 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 14 Jun 2006 20:47:35 -0700 Subject: __cmp__ method References: <1150324916.775821.142390@u72g2000cwu.googlegroups.com> <1150327439.729410.245140@p79g2000cwp.googlegroups.com> Message-ID: <1150343255.591897.226060@p79g2000cwp.googlegroups.com> Jon Clements wrote: > This probably isn't exactly what you want, but, unless you wanted to do > something especially with your own string class, I would just pass a > function to the sorted algorithm. > > eg: > > sorted( [a,b,c], cmp=lambda a,b: cmp(len(a),len(b)) ) > > gives you the below in the right order... Or even better in 2.4 or later: sorted([a,b,c], key=len) George From no at spam.net Fri Jun 9 15:15:36 2006 From: no at spam.net (No) Date: Fri, 9 Jun 2006 14:15:36 -0500 Subject: UltraEdit and Python References: Message-ID: In article , gdiaczok at verizon.net says... > How do I sent up Ultra Edit to work w/ Python? > > How do I get Ultra Edit to run a Python script currently in the edit window > and supply results? > > I can't figure out how to get Ultra Edit to invoke the Python debugger to > allow stepping through a Python script and view each line reults? Menu/Advanced/Tool Configuration: (Command tab) Menu Item Name: Python Command Line: "C:\Program Files\python24\python.exe" %F Working Directory: C:\ Menu/Advanced/Tool Configuration: (Options tab) Program Type: Dos Program Menu/Advanced/Tool Configuration: (Output tab) Command Output (DOC Commands): Output to List Box, Capture Output Replace selected text with: No Replace (This is with UltraStudio. Should be the same/similar in UltraEdit.) > > How do I set pause / break points in Ultra Edit for a Python script? > If you find out, let me know by posting here... -Rob From fredrik at pythonware.com Mon Jun 5 16:15:39 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 05 Jun 2006 22:15:39 +0200 Subject: xml.sax problem: getting parse() to read a string In-Reply-To: <1149536174.891894.13760@h76g2000cwa.googlegroups.com> References: <1149525288.546237.78700@u72g2000cwu.googlegroups.com> <1149536174.891894.13760@h76g2000cwa.googlegroups.com> Message-ID: sturnfie at gmail.com wrote: > I am getting the following error. > > File "acmtest.py", line 205, in parseMessage > parser.parseString(message) > AttributeError: ExpatParser instance has no attribute 'parseString' > > Am I simply missing that library here? Or am I calling it incorrectly? as mentioned in the documentation, and implied by my answer, parseString is a helper function in the xml.sax module, not a parser method. try doing xml.sax.parseString(string, handler) instead of that make_parser/setContentHandler/parse dance. From istvan.albert at gmail.com Mon Jun 26 08:57:09 2006 From: istvan.albert at gmail.com (Istvan Albert) Date: 26 Jun 2006 05:57:09 -0700 Subject: SWIG problems with gcc and Cygwin? In-Reply-To: References: Message-ID: <1151326629.311787.181620@c74g2000cwc.googlegroups.com> Michael Yanowitz wrote: > Also, not sure if related but I do have a win32 Python 2.4.3 and > Cygwin Python 2.4.1. Not sure if there are any conflicts. Any advice > in making these two co-exist? SWIG will work with the windows and cygwin python, just make sure you don't mix the various platforms. - Install two separate versions of swig one for windows (binary) and compile one in cygwin, - Pay attention to the path and make sure that you invoke the correct swig and python Istvan. From bayazee at gmail.com Wed Jun 28 18:19:15 2006 From: bayazee at gmail.com (Bayazee) Date: 28 Jun 2006 15:19:15 -0700 Subject: for and while loops In-Reply-To: <1151531527.496772.65130@i40g2000cwc.googlegroups.com> References: <1151531527.496772.65130@i40g2000cwc.googlegroups.com> Message-ID: <1151533155.078053.61100@x69g2000cwx.googlegroups.com> hi #Exercise 1 : s=0 while 1: s+=input("Enter a num : ") if s>=100: print "The sum is greater than 100 : ",s break #Exercise 1 : s=0 for i in range(5): s+=input("Enter num #%d > "%(i+1)) print "The Sum is : " , s From invalidemail at aerojockey.com Fri Jun 9 05:22:27 2006 From: invalidemail at aerojockey.com (Carl Banks) Date: 9 Jun 2006 02:22:27 -0700 Subject: Allowing zero-dimensional subscripts References: <1149801040.936452.26270@i40g2000cwc.googlegroups.com> <1149807149.516004.48590@f6g2000cwb.googlegroups.com> <1149832139.948242.64160@f6g2000cwb.googlegroups.com> Message-ID: <1149844947.822478.128580@g10g2000cwb.googlegroups.com> Steve Holden wrote: > Hey, I have an idea, why don't we look at the language reference manual > instead of imagining how we think it might work! I don't know. Sounds risky. > In section 3.2 we find: > > > """ > Tuples > The items of a tuple are arbitrary Python objects. Tuples of two or more > items are formed by comma-separated lists of expressions. A tuple of one > item (a `singleton') can be formed by affixing a comma to an expression > (an expression by itself does not create a tuple, since parentheses must > be usable for grouping of expressions). An empty tuple can be formed by > an empty pair of parentheses. > """ > > So it seems that your speculation is false. Section 2.6 specifically > defines "[" and "]" as delimiters. Section 5.3.2 defines a subscription > (a term I've not really grown to love, but what the heck) as > > subscription ::= primary "[" expression_list "]" > > and section 5.12, which defines expression_list, explicitly says > > """An expression list containing at least one comma yields a tuple.""". > > So it would appear that while your change might be very convenient to > allow you to refer to scalar values as zero-dimensional arrays, it > doesn't really fit into Python's conceptual framework. Sorry. Yes, that would appear to be so. You would have a point... if the documentation were correct. Only it's not. According to the reference manual, the rule for an expression_list is: expression_list ::= expression ( "," expression )* [","] But take the following legal Python subscripted array: a[1:2,...,3:4] Is "1:2" an expression? How about "..."? When I enter 1:2 at the Python prompt, I get a syntax error. The fact is, the documentation here is either wrong or simplified or both. (I don't think it's a big deal, actually: the real grammar has lots of complexity to handle tricky cases that would needlessly complicate the reference manual for a human reader.) So let's look at an excerpt the actual Python grammar (from 2.4.3). You'll be happy to know subscription isn't used. :) trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME subscriptlist: subscript (',' subscript)* [','] sliceop: ':' [test] subscript: '.' '.' '.' | test | [test] ':' [test] [sliceop] testlist: test (',' test)* [','] Clearly, the grammar rule used for list subscript is different from the one used for list of expressions (for some reason, what an ordinary person would call an expression is called a "test" in the grammar, whereas "expr" is a non-short-circuiting expression). So there's a regular way to create non-empty tuples, and a subscript way. And there's a regular way to create an empty tuple... but not a subscript way. So I'd say this change fits the conceptual framework of the tuple quite well; in fact, it makes subscript tuples more parallel to their regular counterparts. > One further point: if you really do conceptualize scalars as > zero-dimensional arrays, where is the value conceptually stored? Think of it this way: an array with n-dimensions of length 3 would have 3**n total entries. How many entries would a 0-dimensional array have? 3**0 == 1. Numeric has had zero-dimensional arrays for a long time, and has had no problem storing them. Think of the rule for accessing an element of an array: it's a base pointer + sum (indices*stride) for all indices. Now generalize it down to zero: there are no indices, so the scalar is stored at the base pointer. Carl Banks From brian at sweetapp.com Thu Jun 15 04:36:26 2006 From: brian at sweetapp.com (Brian Quinlan) Date: Thu, 15 Jun 2006 10:36:26 +0200 Subject: Possible inaccuracy in Python 2.4 when using profiler calibration Message-ID: <44911C0A.3010106@sweetapp.com> I have a misinformed theory that I'd like to share with the list. I believe that profiler calibration no longer makes sense in Python 2.4 because C functions are tracked and they have a different call overhead than Python functions (and calibration is done only using Python functions). Here is my reasoning (in code form): % c:\python24\python ... >>> import profile >>> p = profile.Profile() >>> for i in range(5): ... print p.calibrate(1000000) ... 4.00375499355e-006 3.95700929469e-006 3.94034406478e-006 4.00315854962e-006 3.99454335716e-006 Code ---- import profile profile.Profile.bias = 3.90e-006 # very conservative def bar(): l = [] for i in range(100000): l += [i] def foo(): l = [] for i in range(100000): l.append(i) # C function that can be tracked def baz(): bar() foo() profile.run('baz()', "out.prof") from pstats import Stats s = Stats('out.prof') s.sort_stats('time', 'calls') s.print_stats() from timeit import Timer t1 = Timer( 'bar()', 'from __main__ import bar',) print 'bar():', t1.timeit(1000) / 1000 t2 = Timer( 'foo()', 'from __main__ import foo',) print 'foo():', t2.timeit(1000) / 1000 Output ------ Thu Jun 15 10:22:29 2006 out.prof 100008 function calls in -0.090 CPU seconds Ordered by: internal time, call count ncalls tottime percall cumtime percall filename:lineno(function) 1 0.058 0.058 0.062 0.062 cal-test.py:4(bar) 2 0.006 0.003 0.006 0.003 :0(range) 1 0.004 0.004 -0.090 -0.090 cal-test.py:14(baz) 1 0.001 0.001 0.001 0.001 :0(setprofile) 1 0.000 0.000 -0.090 -0.090 profile:0(baz()) 1 0.000 0.000 -0.090 -0.090 :1(?) 0 0.000 0.000 profile:0(profiler) 1 -0.066 -0.066 -0.157 -0.157 cal-test.py:9(foo) 100000 -0.094 -0.000 -0.094 -0.000 :0(append) bar(): 0.0582713573932 foo(): 0.0370039776005 Analysis -------- As you can see, the profiler result for "bar" is pretty reasonable but it is not for "foo" or "append". I believe that is because the calling of the C function "append" takes less time than is accounted for in the bias measurement (which was generated by measuring the call time of a Python function). So the bias computation doesn't make sense in Python 2.4. What do y'all think? Is this a well known fact? Should I construct a test to see if C function call overhead is actually less than Python function call overhead? Cheers, Brian From struggleyb at gmail.com Tue Jun 27 02:59:34 2006 From: struggleyb at gmail.com (Bo Yang) Date: Tue, 27 Jun 2006 14:59:34 +0800 Subject: How do you use this list ? Message-ID: <44A0D756.8030107@gmail.com> Hi everyone , I have join this list for about 4 months , and everyday I receive hundreds of mails . There is no means to read all of them , so I just read something interesting for me . But if so , there are too much mails pile up in my inbox , I want to ask how do you use this list , reading every mail come in or just read what you think interesting ? Thank you ! Best Regard ! From arvind.mulay at gmail.com Mon Jun 26 00:19:18 2006 From: arvind.mulay at gmail.com (arvind) Date: 25 Jun 2006 21:19:18 -0700 Subject: Python database access Message-ID: <1151295558.067744.91470@b68g2000cwa.googlegroups.com> Hi all, I am going to work on Python 2.4.3 and MSSQL database server on Windows platform. But I don't know how to make the connectivity or rather which module to import. I searched for the modules in the Python library, but I couldn't find which module to go for. Please help me out! From alanalan at newsgroup.nospam Thu Jun 1 16:37:31 2006 From: alanalan at newsgroup.nospam (A.M) Date: Thu, 1 Jun 2006 16:37:31 -0400 Subject: New to Python: Do we have the concept of Hash in Python? References: Message-ID: <%aIfg.3027$EF1.232063@news20.bellglobal.com> "Fredrik Lundh" wrote in message news:mailman.6424.1149190330.27775.python-list at python.org... > A.M wrote: > >> This is my 1st day that I am seriously diving into Python and I have to >> finish this application by the end of today. Maybe it wasn't a good idea >> to choose the language that I don't know when I have to deliver my work >> in such short time. > > are your boss aware of this ? > > > > are your boss aware of this ? In fact my boss is quite impressed with my progress so far. I am a little confused about the fact that you got frustrated with my posts today. I am not asking for a big tutorial or deepest philosophy behind the concepts. The answer to this post could be just the word "Dictionary" which is 10 key stroke ! Does this hurt? From mw.visenso at googlemail.com Wed Jun 14 09:39:32 2006 From: mw.visenso at googlemail.com (Marco Wahl) Date: 14 Jun 2006 06:39:32 -0700 Subject: Where is documentation for += Message-ID: <1150292372.337690.25290@y41g2000cwy.googlegroups.com> Hello, by accident I found that += exists in python. E.g. >>> a = 0 >>> a += 42 >>> a 42 >>> a += 0.42 >>> a 42.420000000000002 >>> But I can't find any documentation for +=. Any hints? Best wishes From johnjsal at NOSPAMgmail.com Thu Jun 15 13:56:30 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 15 Jun 2006 17:56:30 GMT Subject: a good programming text editor (not IDE) In-Reply-To: <1150393919.514359.55580@h76g2000cwa.googlegroups.com> References: <_xgkg.2317$No6.48542@news.tufts.edu> <1150393919.514359.55580@h76g2000cwa.googlegroups.com> Message-ID: Ant wrote: > jEdit is for me still the best text editor available. Very extensible > with macros (which can be written in Jython with the appropriate plugin > installed). I like the idea of being extensible, but of course I can only write in Python. Are there any editors that support that? From uval at rz.uni-karlsruhe.de Fri Jun 23 11:21:54 2006 From: uval at rz.uni-karlsruhe.de (Daniel Schüle) Date: Fri, 23 Jun 2006 17:21:54 +0200 Subject: re question References: Message-ID: Hi [...] hm, that's wired I just tried it in python shell and it works but same code as script file fails for anyone who want to see for himself # package.vhd file bash % cat package.vhd library ieee; use ieee.std_logic_1164.all; package TEST123 is constant BASE End Package Test; # parser.py bash % cat parser.py #!/usr/bin/env python import sys, re reflags = re.DOTALL | re.MULTILINE | re.IGNORECASE pattern = re.compile(r'^\s*package\s+(?P\w+)\s+is\s+(?P.*?)\s+end(\s+package)?(\s+(?P=name))?\s*;', reflags) class PackageParser(object): def __init__(self, filename): self.package = file(filename).read() def parse(self): return pattern.search(self.package) if __name__ == "__main__": p = PackageParser("package.vhd") m = p.parse() if m is None: print "nothing" sys.exit(1) print m.group("content") print m.group("name") # testing bash % ./parser.py nothing ps: >>> sys.version '2.4.2 (#2, Mar 3 2006, 13:32:59) \n[GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)]' Regards, Daniel From felipe.lessa at gmail.com Sun Jun 11 16:54:41 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Sun, 11 Jun 2006 17:54:41 -0300 Subject: how to get the length of a number In-Reply-To: <1150057074.389755.157060@m38g2000cwc.googlegroups.com> References: <1150057074.389755.157060@m38g2000cwc.googlegroups.com> Message-ID: <1150059281.31060.10.camel@kenshin.CASA> Em Dom, 2006-06-11 ?s 13:17 -0700, Saketh escreveu: > Stan Cook wrote: > > Can anyone tell me how to get the length of a number. I > > know len(string) will get the length of a string, but it > > doesn't like len(int). I seem to remember something like %s > > string. I tried to set a variable = to %s int, but that > > doesn't work. Is there a function I've forgotten about to > > convert an integer to a string? > > > > Regards > > > > Stan > > Use str(int). Then use len(). For example, len(str(12345)) will give > you 5. $ python2.4 -mtimeit -s 'x=12345' 'len(str(x))' 1000000 loops, best of 3: 1.33 usec per loop $ python2.4 -mtimeit -s 'x=12345;from math import ceil,log' 'ceil(log(x, 10))' 1000000 loops, best of 3: 1.54 usec per loop $ python2.4 -mtimeit -s 'x=12345**123' 'len(str(x))' 1000 loops, best of 3: 209 usec per loop $ python2.4 -mtimeit -s 'x=12345**123;from math import ceil,log' 'ceil(log(x, 10))' 1000000 loops, best of 3: 1.55 usec per loop $ python2.4 -mtimeit -s 'x=12345**1234' 'len(str(x))' 100 loops, best of 3: 19.2 msec per loop $ python2.4 -mtimeit -s 'x=12345**1234;from math import ceil,log' 'ceil(log(x, 10))' 1000000 loops, best of 3: 1.53 usec per loop -- Felipe. From jmonnet at gmail.com Wed Jun 28 11:05:05 2006 From: jmonnet at gmail.com (Jeremy Monnet) Date: Wed, 28 Jun 2006 17:05:05 +0200 Subject: SimpleXMLRPCServer and client IP address Message-ID: <2b1bd02c0606280805m164c4fb8s1a43d76480904fb7@mail.gmail.com> Hello, I've started python a few weeks ago, and to now everything went fine with my cookbook and a learning book. Now, I've tried the SimpleXMLRPCServer, and it worked OK untill I tried to get the client IP address. I have searched a long time the Internet but couldn't find a _simple_ solution :-) #Code from liste_films import * import SimpleXMLRPCServer def isOpen(): # Here I want to get the clien IP address if CheckPerms(IP): return True else: return False if __name__ == '__main__': server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 8000)) server.register_function(isOpen) server.serve_forever() #end code Tips I've found were : - inherit from requestDispatcher and overload its methods. But that's not that Simple. - use the requestHandler and its method address_string(), but I didn't an easy to understand example - http://mail.python.org/pipermail/python-list/2006-May/340266.html but this thread seems not to have been finished :-( Furthermore, I think I should be able to access the socket object from where I am (at starting of isOpen() ), but I don't know how. "self" and "parent" are not defined, I can access the "server" object, but it says the other end s not connected ("transport endpoint"). I think this SimpleXMLRPCServer was not threaded (because it says in the API : "answer all requests one at a time"), so I don't understand why in the middle of my function the server.socket.getpeername() says it's not connected. I'm using python2.3 on linux (debian sid). Thanks for any help ! Jeremy -- Linux Registered User #317862 Linux From Scratch Registered User #16571 Please do not send me .doc, .xls, .ppt, as I will *NOT* read them. Please send me only open formats, as OpenDocument or pdf. From laurent.pointal at wanadoo.fr Sun Jun 4 14:33:07 2006 From: laurent.pointal at wanadoo.fr (Laurent Pointal) Date: Sun, 04 Jun 2006 20:33:07 +0200 Subject: ANN: PQRC - Python Quick Reference Card - v 0.55 References: <4481b8ff$0$19687$ba4acef3@news.orange.fr> <4482cd93$1_2@newspeer2.tds.net> Message-ID: <44832763$0$20143$ba4acef3@news.orange.fr> Kent Johnson wrote: > Laurent Pointal wrote: >> And I'll maintain a fixed URL at >> >> http://laurent.pointal.org/python/pqrc/ > > Broken at the moment. Its back. Its at my home ADSL, normally online, but my provider reset the connexion each 24h and its home maintained... the page contains only a link to the other URL which has the data and is beyond a larger bandwidth server. A+ Laurent. > > Kent From serge.orlov at gmail.com Tue Jun 27 16:05:55 2006 From: serge.orlov at gmail.com (Serge Orlov) Date: Tue, 27 Jun 2006 13:05:55 -0700 Subject: Problem with sets and Unicode strings In-Reply-To: <44a17d05$1@news.uni-ulm.de> References: <44a17d05$1@news.uni-ulm.de> Message-ID: On 6/27/06, Dennis Benzinger wrote: > Hi! > > The following program in an UTF-8 encoded file: > > > # -*- coding: UTF-8 -*- > > FIELDS = ("F?cher", ) > FROZEN_FIELDS = frozenset(FIELDS) > FIELDS_SET = set(FIELDS) > > print u"F?cher" in FROZEN_FIELDS > print u"F?cher" in FIELDS_SET > print u"F?cher" in FIELDS > > > gives this output > > > False > False > Traceback (most recent call last): > File "test.py", line 9, in ? > print u"F??cher" in FIELDS > UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 1: > ordinal not in range(128) > > > Why do the first two print statements succeed and the third one fails > with an exception? Actually all three statements fail to produce correct result. > Why does the use of set/frozenset remove the exception? Because sets use hash algorithm to find matches, whereas the last statement directly compares a unicode string with a byte string. Byte strings can only contain ascii characters, that's why python raises an exception. The problem is very easy to fix: use unicode strings for all non-ascii strings. From gherron at islandtraining.com Sun Jun 25 12:54:07 2006 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 25 Jun 2006 09:54:07 -0700 Subject: array manipulation without for loops In-Reply-To: <1151253182.496596.185420@r2g2000cwb.googlegroups.com> References: <1151251578.463273.24370@m73g2000cwd.googlegroups.com> <1151253182.496596.185420@r2g2000cwb.googlegroups.com> Message-ID: <449EBFAF.40801@islandtraining.com> Sheldon wrote: > Hi Gary, > > I am really trying to cut the time down as I have 600+ arrays with > dimensions (1215,1215) to compare and I do a lot more things with the > arrays. If I understand you correctly, there is no way around a for > loop? > Well no. I gave you two alternatives to for loops. But once we learn that your motivation is speed on large arrays, then, by all means, go with Alex's suggestion. Use numpy (or one if its earlier incarnations). See: http://numeric.scipy.org/ This is a HIGHLY efficient implementation of arrays for Python. It provides a number of very general operations that can be performed across arrays. Good luck Gary Herron > > /Sheldon > > Gary Herron wrote: > > >> Sheldon wrote: >> >>> Hi, >>> >>> I have two arrays that are of the same dimension but having 3 different >>> values: 255, 1 or 2. >>> I would like to set all the positions in both arrays having 255 to be >>> equal, i.e., where one array has 255, I set the same elements in the >>> other array to 255 and visa versa. Does anyone know how to do this >>> without using for loops? >>> >>> Sincerely, >>> Sheldon >>> >>> >>> >> Whatever for? Have you got something against for loops? >> >> However... >> >> You could roll you own loop: >> i=0 >> while i < whatever: >> # ... do something with i >> i += 1 >> >> But what's the point? This does the same as a for loop but slower. >> >> If you don't want any kind of a loop (again, What's the point?) you >> could write something recursive: >> >> def proc(i, ...): >> # ... do something with i >> if i < whatever: >> proc(i+1, ...) >> >> But this would be even slower. >> >> Gary Herron >> > > From gneuner2/ at comcast.net Tue Jun 20 13:08:34 2006 From: gneuner2/ at comcast.net (George Neuner) Date: Tue, 20 Jun 2006 13:08:34 -0400 Subject: What is Expressiveness in a Computer Language References: <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> Message-ID: On Mon, 19 Jun 2006 22:02:55 +0000 (UTC), Dimitri Maziuk wrote: >Yet Another Dan sez: > >... Requiring an array index to be an integer is considered a typing >> problem because it can be checked based on only the variable itself, >> whereas checking whether it's in bounds requires knowledge about the array. > >You mean like > subtype MyArrayIndexType is INTEGER 7 .. 11 > type MyArrayType is array (MyArrayIndexType) of MyElementType > If the index computation involves wider types it can still produce illegal index values. The runtime computation of an illegal index value is not prevented by narrowing subtypes and cannot be statically checked. George -- for email reply remove "/" from address From cfc at shell01.TheWorld.com Tue Jun 20 12:18:37 2006 From: cfc at shell01.TheWorld.com (Chris F Clark) Date: 20 Jun 2006 12:18:37 -0400 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150749670.053433.242210@p79g2000cwp.googlegroups.com> <1150754918.338770.89870@i40g2000cwc.googlegroups.com> Message-ID: Chris F Clark wrote: > A static > type system eliminates some set of tags on values by syntactic > analysis of annotations (types) written with or as part of the program > and detects some of the disallowed compuatations (staticly) at compile > time. Adreas relied: > Explicit annotations are not a necessary ingredient of a type system, > nor is "eliminating tags" very relevant to its function. While this is true, I disagree at some level with the second part. By eliminating tags, I mean allowing one to perform "type safe" computations without requiring the values to be tagged. One could argue that the tags were never there. However, many of the interesting polymorphic computations reaquire either that the values be tagged or that some other process assures that at each point one can determine apriori what the correct variant of computation is which applies. To me a static type system is one which does this apriori determination. A dynamic type system does not do a apriori and instead includes explicit information in the values being computed to select the corret variant computations. In that sense, a static type system is eliminating tags, because the information is pre-computed and not explicitly stored as a part of the computation. Now, you may not view the tag as being there, but in my mind if there exists a way of perfoming the computation that requires tags, the tag was there and that tag has been eliminated. To put it another way, I consider the tags to be axiomatic. Most computations involve some decision logic that is driven by distinct values that have previously been computed. The separation of the values which drive the compuation one-way versus another is a tag. That tag can potentially be eliminated by some apriori computation. In what I do, it is very valuable to move information from being explicitly represented in the computed result into the tag, so that I often have distinct "types" (i.e. tags) for an empty list, a list with one element, a list with two elements, and a longer list. In that sense, I agree with Chris Smith's assertion that "static typing" is about asserting general properties of the algorithm/data. These assertions are important to the way I am manipulating the data. They are part of my type model, but they may not be part of anyone else's, and to me toe pass a empty list to a function requiring a list with two elements is a "type error", because it is something I expect the type system to detect as incorrect. The fact that no one else may have that expectation does not seem relevant to me. Now, to carry this farther, since I expect the type system to validate that certain values are of certain types and only be used in certain contexts, I am happy when it does not require certain "tags" to be actualy present in the data. However, because other bits of code are polymorphic, I do expect certain values to require tags. In the end, this is still a win for me. I had certain data elements that in the abstract had to be represented explicitly. I have encoded that information into the type system and in some cases the type system is not using any bits in the computed representation to hold that information. Whenever that happens, I win and that solves one of the problems that I need solved. Thus, a type system is a way for me to express certain axioms about my algorithm. A dynamic type system encodes those facts as part of the computation. A static type system pre-calculates certain "theorems" from my axioms and uses those theorems to allow my algorithm to be computed without all the facts being stored as part of the computation. Hopefully, this makes my point of view clear. -Chris ***************************************************************************** Chris Clark Internet : compres at world.std.com Compiler Resources, Inc. Web Site : http://world.std.com/~compres 23 Bailey Rd voice : (508) 435-5016 Berlin, MA 01503 USA fax : (978) 838-0263 (24 hours) ------------------------------------------------------------------------------ From digitalorganics at gmail.com Mon Jun 12 10:42:42 2006 From: digitalorganics at gmail.com (digitalorganics at gmail.com) Date: 12 Jun 2006 07:42:42 -0700 Subject: Very nice python IDE (windows only) In-Reply-To: <448d5f3d$0$815$3a628fcd@textreader.nntp.hccnet.nl> References: <1149694235.741274.325200@u72g2000cwu.googlegroups.com> <1149701880.540109.10100@y43g2000cwc.googlegroups.com> <1149704292.676501.138530@h76g2000cwa.googlegroups.com> <448d5f3d$0$815$3a628fcd@textreader.nntp.hccnet.nl> Message-ID: <1150123358.105703.285570@y43g2000cwc.googlegroups.com> Great IDE! I love it. Two things that make me very happy: 1. Unlike PythonWin and Stan's Python Editor (SPE), PyScripter shows not just methods but also attributes in the class browser. [I'll mention that Eric3 also does this, but I don't use Eric3 much because the editor component doesn't allow scrolling through my code with a mouse wheel (something I'm extremely used to being able to do at this point).] 2. Extremely useful tooltips! You can receive context sensitive information on methods, variables, and classes just by hovering over them with your mouse! Awesome, truly awe inspiring. I also like the modern look! Very slick and configurable. The variable window below is nice too... Thanks for mentioning! Cheers, DigiO From sekhon.hari at googlemail.com Tue Jun 27 03:59:27 2006 From: sekhon.hari at googlemail.com (Hari Sekhon) Date: Tue, 27 Jun 2006 08:59:27 +0100 Subject: style question In-Reply-To: References: <44a01364@nntp0.pdx.net> Message-ID: On 26/06/06, Claudio Grondi wrote: > > Scott David Daniels wrote: > > Claudio Grondi wrote: > > <<>> > > > >> When necessary to skip first line _and_ indentation: > >> message = """ > >> This is line 1 > >> This is line 2 > >> This is line 3 > >> """.replace('\n ', '\n')[1:] # adjust here '\n ' to indentation > > > > > > Riffing on this idea: > > message = """ > > This is line 1 > > This is line 2 > > This is line 3 > > """.replace(""" > > """, '\n')[1:] > > This was intended as an excercise for the OP in case he likes that kind > of solution ... > > Claudio > > > > > --Scott David Daniels > > scott.daniels at acm.org > -- > http://mail.python.org/mailman/listinfo/python-list > I've decided to go with message = ( "This is line1. " "This is line2 " "This is line3\n") since I'm declaring many different messages inside various functions I feel it is important to keep the indentaion and code both aligned properly so the code looks nice and the output looks nice. It is easier than doing replace and splicing since I want to keep it as simple and clean as possible, in true pythonic tradition... Thanks for the input! -h -------------- next part -------------- An HTML attachment was scrubbed... URL: From grflanagan at yahoo.co.uk Fri Jun 30 04:12:45 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 30 Jun 2006 01:12:45 -0700 Subject: How to get indices of a two dimensional list In-Reply-To: <1151639976.664310.183620@x69g2000cwx.googlegroups.com> References: <1151639976.664310.183620@x69g2000cwx.googlegroups.com> Message-ID: <1151655165.022076.95460@x69g2000cwx.googlegroups.com> sramaswamy at gmail.com wrote: > I have a list > > x = [0] * 2 > x = x * [2] > x[1,1] = 7 > > This gives me the x value > [[0,0] [0,0] [0,0] [0,7]] > > I want to get the indices of the value 7. > i.e. something like > i = a.index(max(a)) gives me '1' > > This only gives me the index in one dimension. Is there any method by > which I can get (1,1) as the answer. > > Thanks in advance. If you post code that doesn't work, people won't treat you seriously. I have some code that might help if you'd like to try again. All the best Gerard From enleverlesX.XmcX at XmclaveauX.com Wed Jun 14 18:59:15 2006 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI) Date: Thu, 15 Jun 2006 00:59:15 +0200 Subject: Pb console Effbot Message-ID: <449094cb$0$1022$ba4acef3@news.orange.fr> Good evening! I installed the Console of EFFBOT (http://effbot.org/downloads/#console). It functions well. It's a very fun/friendly tool. Except a detail: when I send (by console.write()) more than 53200 characters, it does not occur anything. I circumvented the problem, with a loop which sends ranges of 50000 characters. But, I would like to know if somebody already encountered this problem. @-greetings Michel Claveau From junkytownMAKNI at gmail.com Fri Jun 9 20:32:15 2006 From: junkytownMAKNI at gmail.com (SuperHik) Date: Sat, 10 Jun 2006 02:32:15 +0200 Subject: Most elegant way to generate 3-char sequence In-Reply-To: References: <1149889784.391965.271570@h76g2000cwa.googlegroups.com> Message-ID: and the winner is... :D David Isaac wrote: > alpha = string.lowercase > x=(a+b+c for a in alpha for b in alpha for c in alpha) From rossberg at ps.uni-sb.de Tue Jun 20 09:53:29 2006 From: rossberg at ps.uni-sb.de (Andreas Rossberg) Date: Tue, 20 Jun 2006 15:53:29 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: <1150809118.677124.142230@u72g2000cwu.googlegroups.com> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <1150809118.677124.142230@u72g2000cwu.googlegroups.com> Message-ID: Rob Thorpe wrote: >> >>>No, that isn't what I said. What I said was: >>>"A language is latently typed if a value has a property - called it's >>>type - attached to it, and given it's type it can only represent values >>>defined by a certain class." >> >>"it [= a value] [...] can [...] represent values"? > > ??? I just quoted, in condensed form, what you said above: namely, that a value represents values - which I find a strange and circular definition. >>A (static) type system assigns types to (all) *expressions*. > > That's right most of the time yes, I probably should have said > expressions. Though I can think of static typed languages where the > resulting type of an expression depends on the type of the variable it > is being assigned to. Yes, but that's no contradiction. A type system does not necessarily assign *unique* types to individual expressions (consider overloading, subtyping, polymorphism, etc). > Well I haven't programmed in any statically typed language where values > have types themselves. They all have - the whole purpose of a type system is to ensure that any expression of type T always evaluates to a value of type T. So when you look at type systems formally then you certainly have to assign types to values, otherwise you couldn't prove any useful property about those systems (esp. soundness). - Andreas From kewashi at gmail.com Sun Jun 11 23:50:31 2006 From: kewashi at gmail.com (KenAggie) Date: 11 Jun 2006 20:50:31 -0700 Subject: Evaluating a Function After X Seconds: Python Equivalent to JavaScript's SetTimeout() Function In-Reply-To: <1150081288.699325.105850@j55g2000cwa.googlegroups.com> References: <1150081288.699325.105850@j55g2000cwa.googlegroups.com> Message-ID: <1150084231.639860.41130@m38g2000cwc.googlegroups.com> Yea -- the "sched" class is exactly what you need. Just import sched and then use it to schedule a function call in the future, either using relative time or an absolute time. The python help file tells you how in detail. - Ken ycoci0 at gmail.com wrote: > Hi all, > > Not exactly new to Python, just have not programmed a time dependent > function using it before. > > I imagine that many of you may also program some JavaScript and may be > familiar with JavaScript's SetTimeout( expression, after time interval > in milliseconds) function. Does Python have an equivalent to this? > > A SetTimeout-like Python function would be ideal for my application. > > > Best, > > Y-coci From ptmcg at austin.rr._bogus_.com Fri Jun 23 12:00:48 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 23 Jun 2006 16:00:48 GMT Subject: re question References: Message-ID: Shouldn't End Package Test; read: End Package Test123; -- Paul From iainking at gmail.com Thu Jun 1 11:15:38 2006 From: iainking at gmail.com (Iain King) Date: 1 Jun 2006 08:15:38 -0700 Subject: Trying to get FreeImagePy to work. In-Reply-To: <3PCfg.20835$cX1.315781@twister2.libero.it> References: <1148651668.578852.3160@i40g2000cwc.googlegroups.com> <7fEdg.13375$cX1.201311@twister2.libero.it> <1148655611.990937.322350@j73g2000cwa.googlegroups.com> <1149166096.176405.22780@i40g2000cwc.googlegroups.com> <3PCfg.20835$cX1.315781@twister2.libero.it> Message-ID: <1149174938.337973.85950@g10g2000cwb.googlegroups.com> Michele Petrazzo wrote: > Iain King wrote: > > Michele Petrazzo wrote: > >> Iain King wrote: > >>> Michele Petrazzo wrote: > >>> > >>> I downloaded and installed 0.9.9.3, and it now works. Thanks! > >>> > >> I advice you to don't use that ctypes version... Better is to use > >> the newest one and update freeimagepy! > >> > >>> Iain > >>> > >> Michele > > > > OK, Ive installed the latest versions I can find, which are > > FreeImagePy 1.2.4 and ctypes 0.9.9.6, and I'm back to the error I had > > earlier. Do you know what's wrong? > > > > Iain > > > > Can you download the last svn version from sf.net? Otherwise I'll send > you the last sources privately. > > Bye, > Michele Sorry, I hadn't heard of SVN before, so I didn't know what you were talking about earlier :). I got the TortoiseSVN client though, and checked out your newest build, copied it over the top of site-packages/freeimagepy, updated my ctypes back to 0.9.9.6 (I'd regressed again), ran my program, and it worked. Thanks! Next question (and what I'm using FreeImagePy for): I'm loading a pile of TIF's as thumbnails into a wx list control. I load the image with FIPY, convert it to PIL, use PIL's antialiasing thumbnail function, then load it from there into wx. However, when I'm do the fipy.convertToPil(), it inverts the image? I've inserted a fipy.invert() before the conversion as a temporary fix, but is there a reason for this? relevant code: def getHeaders(files): thumbs = [] for f in files: print "Adding %s" % f fi = FIPY.Image(f) fi.setCurrentPage(0) fi.invert() #temp fix thumb = fi.convertToPil() thumb.thumbnail(THUMBNAIL_SIZE, Image.ANTIALIAS) thumbs.append((os.path.basename(f), pilToBitmap(thumb))) thumbs.sort() return thumbs Iain p.s. thanks again From s99999999s2003 at yahoo.com Thu Jun 29 23:22:28 2006 From: s99999999s2003 at yahoo.com (s99999999s2003 at yahoo.com) Date: 29 Jun 2006 20:22:28 -0700 Subject: logging module question Message-ID: <1151637748.098340.21010@75g2000cwc.googlegroups.com> hi i have defined a function def logger(logfile,msg): import logging logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)-8s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S', filename='%s' % (logfile), filemode='a') logging.critical(msg) logging.error(msg) logging.warning(msg) logging.info(msg) logging.shutdown() In my main code: ----- some python code here--- logger("test.log","error") ..... ..... logger("test.log","another error") ... logger("test.log","yet another error") ... sys.exit(0) When i do the above, i get : self.stream.write(fs % msg) ValueError: I/O operation on closed file If i removed logging.shutdown(), it workds..what is wrong with my function ? thanks From bignose+hates-spam at benfinney.id.au Fri Jun 2 01:22:58 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 02 Jun 2006 15:22:58 +1000 Subject: Inheritance structure less important in dynamic languages? References: <447f95dc$0$1167$ba620e4c@news.skynet.be> Message-ID: <87verkxhal.fsf@benfinney.id.au> "Marvin" writes: > It's been claimed that inheritance structures are less important in > dynamic languages like Python. Who claimed that? I ask not because I doubt your assertion ("it was claimed"), but rather that if someone claimed something, it seems better to ask that person your next question: > Why is that and where can i read more about that? The person who claimed it is more likely to be able and willing to defend it. -- \ Eccles: "I just saw the Earth through the clouds!" Lew: "Did | `\ it look round?" Eccles: "Yes, but I don't think it saw me." | _o__) -- The Goon Show, _Wings Over Dagenham_ | Ben Finney From steve at holdenweb.com Mon Jun 5 14:34:05 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 05 Jun 2006 19:34:05 +0100 Subject: how not to run out of memory in cursor.execute In-Reply-To: <1149531057.098045.322960@c74g2000cwc.googlegroups.com> References: <1149447895.037396.81550@j55g2000cwa.googlegroups.com> <1149531057.098045.322960@c74g2000cwc.googlegroups.com> Message-ID: amberite wrote: > johnlichtenstein at gmail.com wrote: > >>I am using cx_Oracle and MySQLdb to pull a lot of data from some tables >>and I find that the cursor.execute method uses a lot of memory that >>never gets garbage collected. Using fetchmany instead of fetchall does >>not seem to make any difference, since it's the execute that uses >>memory. Breaking the query down to build lots of small tables doesn't >>help, since execute doesn't give its memory back, after reading enough >>small tables execute returns a memory error. What is the trick to get >>memory back from execute in cx_Oracle and MySQLdb? > > > cx_Oracle and MySQLdb must be handled differently, due to the fact that > MySQL does not actually have cursors (MySQLdb fakes them for you). > > To handle large resultsets efficiently in cx_Oracle simply use the > cursor iteration idiom: > > for row in cursor: > # do stuff with the row > > cx_Oracle takes care of the fetching for you, and your memory usage > should remain fairly constant when using this idiom. > > To handle large resultsets in MySQLdb, you have to resort to multiple > queries: > > l = 1000 > o = 0 > > cursor.execute('SELECT foo FROM Bar LIMIT %d OFFSET %d', (l, o)) > rows = cursor.fetchall() > while len(rows) > 0: > # process the fetched rows > o += l > cursor.execute('SELECT foo FROM Bar LIMIT %d OFFSET %d', (l, o)) > rows = cursor.fetchall() > > cursor.close() > > As you can see, the MySQLdb version is more involved, due to the lack > of real cursor support in the MySQL database. Any database with good > cursor support will likely have good cursor iteration support in the > corresponding DBAPI driver. > > Hope this helps, > > L. Daniel Burr > The MySQLdb solution you give is way more complicated than it needs to be, thereby skewing your opinion towards cx_Oracle unnecessarily. Look up the .fetchmany() method of cursors in the DB API. There is only any need to execute a single query no matter how large the result set: you simply need to keep calling .fetchmany(N) (where N is whatever you've decided by testing is your optimum chunk size) until it returns less than N rows, at which point you have exhausted the query. It's very little more effort to wrap this all up as a generator that effectively allows you to use the same solution as you quote for cx_Oracle. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From tim.golden at viacom-outdoor.co.uk Thu Jun 29 04:18:45 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 29 Jun 2006 09:18:45 +0100 Subject: handling unicode data Message-ID: [Filipe] | I've done some searching and settled for pymssql, but it's | not too late to change yet. Indeed, the good thing about the DBAPI-compatibility of such libraries is that you can often switch and switch about with no cost to you at all. (Believe me, I've done it). Sometimes there is a cost because... well, see the notes below. | I've found these options to connect to a MSSqlServer database: | | SQLServer for Python (discontinued?) | http://www.object-craft.com.au/projects/mssql/ | Pymssql | http://pymssql.sourceforge.net/ These two are broadly equivalent, wrapping the ntwdblib.dll library which -- as someone else has pointed out -- is going the way of all mortal libs. Advantage: + pretty much to-the-metal access to the database. + Both will work on Linux via FreeTDS Disadvantage: + the object-craft one, which I've been using for years, isn't supplied for 2.4+. I compiled it with the MingW compiler but the result didn't work (in some way which I now can't remember). I still use it for 2.3 work. + the pymssql one works in (indeed requires) 2.4 but doesn't allow for passthrough authentication, as far as I can determine. Worked around by having our DBA create named logons, but still a bit of a pain. As noted, doesn't seem to handle unicode especially well, which surprises me since the author is obviously from a non-Western character set nation. (I'm ashamed to say I've never tried to contact the pymssql developer to point out its shortcomings). | mxODBC (commercial license) | http://www.egenix.com/files/python/mxODBC.html This works fine, but requires a commercial license for non-personal use. Since I was happily using an opensource library, I've never looked into this too much. Also, doesn't support .nextset on cursors, which was a bit of a pain for me. Should work on Linux via iODBC or UnixODBC and FreeTDS | ADODB for Python (windows only) | http://phplens.com/lens/adodb/adodb-py-docs.htm This is a non-DBAPI extension, which is no problem if that's what you're after. It also requires mxODBC for MSSQL access (cf above). | ASPN Recipe | http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/144183 There seems to be quite enough discussion on the comments on this recipe! Personally, I felt that, unless I had no other options open to me, this would be an unwieldy solution. I can add: Adodbapi http://adodbapi.sourceforge.net/ which I also use for 2.4 work. Advantages: + Works wherever you have pywin32 (or ctypes, I suppose) and COM available. + DBAPI-compliant, wrapping standard(ish) Win32 functionality. Disadvantages: + The module developer has had to work with different behaviours among different drivers, and the results can be unwieldy, especially when looking at tracebacks. + I never quite worked out the transactional behaviour (altho' that probably says more about me than about the module). Basically, you generally have to commit with this module where you don't with the others. + There are one or two small bugs to do with, IIRC, empty row returns. There was some talk on the DBAPI-SIG (which I don't follow closely) about someone picking up the module as the original developer didn't seem to be around, but I'm not aware that anyone's done that. + Won't work on Linux ( In summary + Depends on what your requirements are, but... + Go for ADODBAPI for the widest spread of versions and licenses, but the least cross-platformability + Go for Object Craft MSSQL for <= 2.3 and best overall behaviour + Go for pymssql for >= 2.4 with some small limitations + Go for mxODBC for general purpose databasing, cross-platform, but without .nextset and possibly Commercial licensing + If all else fails, and you've got the SQL Server command line tools, use the ASPN Recipe 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 ________________________________________________________________________ From bignose+hates-spam at benfinney.id.au Tue Jun 13 17:54:28 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 14 Jun 2006 07:54:28 +1000 Subject: Test functions and test discovery (was: Re: Is there a better way of accessing functions in a module?) References: <1150218398.443615.304880@p79g2000cwp.googlegroups.com> Message-ID: <87hd2ooh63.fsf@benfinney.id.au> "Ant" writes: > def a_test(): > print "Test A" > > def b_test(): > print "Test B" Incidentally, the convention is to name test functions as 'test_foo' not 'foo_test'; this will make your module more easily compatible with existing testing tools. > if __name__ == "__main__": > tests = ["%s()" % x for x in dir() if x.endswith("test")] > > for test in tests: > eval(test) No need for eval. (You already found globals(), so I'll use that.) if __name__ == "__main__": test_funcs = [x for name, x in globals() if name.startswith("test") and hasattr(x, "__call__") ] for test in test_funcs: test() I'll concur with other posters on this thread and encourage you to consider using the standard 'unittest' module, and recommend 'nose' for test discovery and execution: -- \ "Unix is an operating system, OS/2 is half an operating system, | `\ Windows is a shell, and DOS is a boot partition virus." -- | _o__) Peter H. Coffin | Ben Finney From sjmachin at lexicon.net Tue Jun 6 19:56:13 2006 From: sjmachin at lexicon.net (John Machin) Date: Wed, 07 Jun 2006 09:56:13 +1000 Subject: tempfile Question In-Reply-To: References: Message-ID: <4486161D.6060102@lexicon.net> On 7/06/2006 7:50 AM, Gregory Pi?ero wrote: > Hey group, > > I have a command line tool that I want to be able to call from a > Python script. The problem is that this tool only writes to a file. > > So my solution is to give the tool a temporary file to write to and > then have Python read that file. I figure that's the safest way to > deal with this sort of thing. (But I'm open to better methods). > > Here's my code so far, could anyone tell me the proper way to use > tempfile. This code won't let the tool write to the file because > Python has it locked. But I'm worried that if I close the file then > windows might take it away? I have no idea. Me neither, not having faced this situation before. To acquire an idea, I'd Read The Fantastic Manual: (my comments enclosed in []) """ TemporaryFile( [mode='w+b'[, bufsize=-1[, suffix[, prefix[, dir]]]]]) Return a file (or file-like) object that can be used as a temporary storage area. The file is created using mkstemp. It will be destroyed as soon as it is closed (including an implicit close when the object is garbage collected).[That seems to answer one question] Under Unix, the directory entry for the file is removed immediately after the file is created. Other platforms do not support this; your code should not rely on a temporary file created using this function having or not having a visible name in the file system. The mode parameter defaults to 'w+b' so that the file created can be read and written without being closed. Binary mode is used so that it behaves consistently on all platforms without regard for the data that is stored. bufsize defaults to -1, meaning that the operating system default is used. The dir, prefix and suffix parameters are passed to mkstemp(). NamedTemporaryFile( [mode='w+b'[, bufsize=-1[, suffix[, prefix[, dir]]]]]) This function operates exactly as TemporaryFile() does, except that the file is guaranteed to have a visible name in the file system (on Unix, the directory entry is not unlinked). That name can be retrieved from the name member of the file object. Whether the name can be used to open the file a second time, while the named temporary file is still open, varies across platforms (it can be so used on Unix; it cannot on Windows NT or later [That seems to answer the other question]). New in version 2.3. """ So I'd be thinking about using the (deprecated) mktemp() instead, perhaps trying to cut down the chance of conflicts by (a) using a prefix e.g. "pdf2txttmp" and/or (b) using a dir of "." -- then asking the cognoscenti what are the drawbacks of this approach. HTH, John From onurb at xiludom.gro Mon Jun 26 04:51:50 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Mon, 26 Jun 2006 10:51:50 +0200 Subject: Mix-In Class Methods At Run-Time In-Reply-To: <1151270770.030282.237050@u72g2000cwu.googlegroups.com> References: <1151191406.755252.210300@i40g2000cwc.googlegroups.com> <1151193767.589325.158820@m73g2000cwd.googlegroups.com> <1151269186.710343.41210@c74g2000cwc.googlegroups.com> <1151270770.030282.237050@u72g2000cwu.googlegroups.com> Message-ID: <449fa027$0$24929$626a54ce@news.free.fr> digitalorganics at gmail.com wrote: (snip) > Two additional questions though: 1) is there a way for a function to > get a reference to its caller automatically (as in, without the caller > having to pass it in)? It's possible with sys._getframe() and a decorator - but consider it a hack. > and 2) what's the reason to use newstyle classes > versus the old? All this is explained on python.org (there's a menu entry for this in the documentation menu). AFAICT, newstyle classes can do whatever oldstyle classes did, *and much more* (descriptors and usable metaclasses) - and they are somewhat faster too. So - compatibility with older Python versions (< 2.2 IIRC) set aside -, there's just no reason to use oldstyle classes. > In order to create the dynamic class "NewClass" in the > code above I called type() but that requires at least one new style > class as a base. Thus, I had to have at least one of my animals inherit > from "object" and this seemed a nuisance since OMG, eight more keystrokes - talk about a nuisance... > I don't at this point > know what the benefit of "newstyle" classes is. See it the other way round : the *only* benefit of oldstyle classes is compatibility with pre-2.2 Python versions. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From alainpoint at yahoo.fr Mon Jun 19 05:51:45 2006 From: alainpoint at yahoo.fr (alainpoint at yahoo.fr) Date: 19 Jun 2006 02:51:45 -0700 Subject: Just out of curiosity: Which languages are they using at Google and what for? Message-ID: <1150710705.482745.230070@r2g2000cwb.googlegroups.com> I know Google are using Python for testing purposes. But for the rest ? is it PHP or Java or .NET? Which technology is rendering the google main page? And of course th obvious question, why not Python? Alain From anton at appsolutions.com Thu Jun 22 19:50:26 2006 From: anton at appsolutions.com (Anton van Straaten) Date: Thu, 22 Jun 2006 23:50:26 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: <1150892256.591282.43880@u72g2000cwu.googlegroups.com> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150892256.591282.43880@u72g2000cwu.googlegroups.com> Message-ID: <61Gmg.27175$VE1.20@newssvr14.news.prodigy.com> Rob Thorpe wrote: >>So, will y'all just switch from using "dynamically typed" to "latently >>typed", and stop talking about any real programs in real programming >>languages as being "untyped" or "type-free", unless you really are >>talking about situations in which human reasoning doesn't come into >>play? I think you'll find it'll help to reason more clearly about this >>whole issue. > > > I agree with most of what you say except regarding "untyped". > > In machine language or most assembly the type of a variable is > something held only in the mind of the programmer writing it, and > nowhere else. In latently typed languages though the programmer can > ask what they type of a particular value is. There is a vast > difference to writing code in the latter kind of language to writing > code in assembly. The distinction you describe is pretty much exactly what I was getting at. I may have put it poorly. > I would suggest that at least assembly should be referred to as > "untyped". Yes, I agree. While we're talking about "untyped", I want to expand on something I wrote in a recent reply to Vesa Karvonen: I accept that "untyped" has a technical definition which means that a language doesn't statically assign types to terms. But this doesn't capture the distinction between "truly" untyped languages, and languages which tag their values to support the programmer's ability to think in terms of latent types. The point of avoiding the "untyped" label is not because it's not technically accurate (in a limited sense) -- it's because in the absence of other information, it misses out on important aspects of the nature of latently typed languages. My reply to Vesa goes into more detail about this. Anton From rupole at hotmail.com Tue Jun 13 22:56:43 2006 From: rupole at hotmail.com (Roger Upole) Date: Tue, 13 Jun 2006 22:56:43 -0400 Subject: DispatchEx('.Application') References: <1150220324.353472.253180@h76g2000cwa.googlegroups.com> Message-ID: <1150253480_60381@sp6iad.superfeed.net> There's a project to create a COM api for Firefox that's identical to IE: http://www.iol.ie/~locka/mozilla/mozilla.htm Roger wrote in message news:1150220324.353472.253180 at h76g2000cwa.googlegroups.com... > When using win32com and DispatchEx to work with a webbrowser, eg: > > from win32com.client import DispatchEx > > ie = DispatchEx('InternetExplorer.Application') > > can anyone suggest the right answer to this? > > mf = DispatchEx('MozillaFirefox.Application') > > It is an invalid class string, but I don't know how to find the right > class string for Mozilla (or any other window for that matter)? Can > somebody suggest to me an easy way to 'get' this information. > > After that I intend to do this: > > mf.Navigate('www.groups.google.com.au/etc'') > > Will all of these functions work with Firefox or is it only Internet > Explorer(I can use either but I prefer Firefox?) > ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups ----= East and West-Coast Server Farms - Total Privacy via Encryption =---- From steve at holdenweb.com Mon Jun 5 10:04:58 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 05 Jun 2006 15:04:58 +0100 Subject: is it possible to find which process dumped core In-Reply-To: <1149514829.032643.193890@h76g2000cwa.googlegroups.com> References: <1149514829.032643.193890@h76g2000cwa.googlegroups.com> Message-ID: su wrote: > to find which process dumped core at the promt we give > > $ file core.28424 > > core.28424: ELF 32-bit LSB core file of 'soffice.bin' (signal 11), > Intel 80386, version 1 (SYSV), from 'soffice.bin' > > from this command we know 'soffice.bin' process dumped core. Now can i > do the same using python i.e. finding which process dumped core? if so > how can i do it? > Unfortunately, without some debugging, all you are likely to find is that /usr/bin/python (or some other interpreter executable) dumped core. You'd have to poke around inside the core image to find out which file was being executed when the interpreter failed. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From gandalf at designaproduct.biz Thu Jun 8 05:31:51 2006 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Thu, 08 Jun 2006 11:31:51 +0200 Subject: simplexmlrpcserver and allow_none Message-ID: <4487EE87.9060106@designaproduct.biz> Hello, I ran in the same problem again. Many others have the same problem. Just Google for this: "SimpleXMLRPCServer allow_none site:python.org". Looks like the 'allow_none' patch was commited to trunk on 2005 Dec ( http://mail.python.org/pipermail/python-checkins/2005-December/048289.html ) I just upgraded to Python 2.4.3 (it was released on March 29, 2006) and SimpleXMLRPCServer.py still has the old code. I can work around this by coping the whole file into a new file and patch it, but I hate to do that. I wonder why it has not been commited to the standard library yet. Does anyone know if it will be in the next bugfix release? Thanks, Laszlo From kenneth.m.mcdonald at sbcglobal.net Wed Jun 28 16:52:27 2006 From: kenneth.m.mcdonald at sbcglobal.net (Kenneth McDonald) Date: Wed, 28 Jun 2006 15:52:27 -0500 Subject: [OT] Prolog and Regular Expressions, Was: Re: perspective on ruby In-Reply-To: References: <1145555339.316764.123210@i39g2000cwa.googlegroups.com> <1he41sz.r7aasv1oo5lfN%aleaxit@yahoo.com> Message-ID: <44A2EC0B.10000@sbcglobal.net> Lawrence D'Oliveiro wrote: > In article , > Edward Elliott wrote: > > >> XML? Conceptually (and more elegantly) covered >> as LISP s-expressions. >> > > "...Lisp is still #1 for key algorithmic techniques such as recursion > and condescension." > -- Verity Stob > > > >> XSLT? Just a bastardized spawn of Prolog. >> > > As is any kind of pattern matching, including everyone's favourite > regular expressions. Prolog did it all. > I'm assuming you're kidding--there is a lot of difference between an RE that produces a highly optimized finite state machine to quickly match a string, and a language that uses brute-force depth-first recursion, plus some nonobvious tricks, to do the same thing. Like many orders of magnitude in execution time :-) That said, it'd be nice if there were some easy way to access a Prolog engine from Python. When Prolog is appropriate, it's _really_ appropriate. Cheers, Ken From grahn+nntp at snipabacken.dyndns.org Thu Jun 29 15:33:00 2006 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 29 Jun 2006 19:33:00 GMT Subject: struct.unpack on 64-bit platforms References: <1150993826.726685.301740@p79g2000cwp.googlegroups.com> Message-ID: On 22 Jun 2006 09:30:26 -0700, Nadav Samet wrote: ... > But apparently, on 64-bit platforms it tries to read 64-bit unsigned > integer (since > that's what the C Type unsigned long means on 64-bit platforms). On /some/ 64-bit platforms. Others let unsigned long be 32-bit and introduce the 64-bit 'long long' types (and 64-bit pointers). The term "64-bit", like "32-bit" before it, is too vague to use in technical discussions, IMHO. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From grflanagan at yahoo.co.uk Mon Jun 19 03:55:10 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 19 Jun 2006 00:55:10 -0700 Subject: aligning SGML to text In-Reply-To: References: <1150663092.362101.130490@f6g2000cwb.googlegroups.com> Message-ID: <1150703710.151861.282340@y41g2000cwy.googlegroups.com> Steven Bethard wrote: > Gerard Flanagan wrote: > > Steven Bethard wrote: > >> I have some plain text data and some SGML markup for that text that I > >> need to align. (The SGML doesn't maintain the original whitespace, so I > >> have to do some alignment; I can't just calculate the indices directly.) > >> For example, some of my text looks like: [...] > > > > Steve > > > > This is probably an abuse of itertools... > > [snip hammering] > > Thanks for taking a look. Yeah, the alignment's a big part of the > problem. It'd be really nice if the thing that gives me SGML didn't add > whitespace haphazardly. ;-) > > STeVe I see, the problem was different than I thought. When all you have is a hammer... :-) Gerard From sybrenUSE at YOURthirdtower.com.imagination Tue Jun 6 04:37:22 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Tue, 6 Jun 2006 10:37:22 +0200 Subject: C# equivalent to range() References: <1149468919.951745.163700@g10g2000cwb.googlegroups.com> <1149481675.192638.275140@c74g2000cwc.googlegroups.com> <1149509893.031953.19310@i40g2000cwc.googlegroups.com> Message-ID: Erik Max Francis enlightened us with: >> The other zilion persons who were not interested (other than the four I >> mentioned above) silently and peacefully ignored the question on went >> on with their happy lifes. > > That's because many of them have killfiled you. I can say that I didn't killfile him. I just peacefully ignored the question and went on with my happy life - I simply don't know anything about C#. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From rune.strand at gmail.com Sun Jun 18 12:36:46 2006 From: rune.strand at gmail.com (Rune Strand) Date: 18 Jun 2006 09:36:46 -0700 Subject: Tetris In-Reply-To: <1150647716.792057.283860@u72g2000cwu.googlegroups.com> References: <1150647716.792057.283860@u72g2000cwu.googlegroups.com> Message-ID: <1150648606.287709.279520@i40g2000cwc.googlegroups.com> Devon G. Parks wrote: > I've been searching google and this group for a while now for a good > tutorial on making a Tetris-style game in Python. I hear Tetris is a > good starting point, and although I am fairly new to programming I > think I would learn best if I had some code to experiment with because > without a tutorial I have no idea where to start. If you know of a > tutorial that is specific to this game please let me know where to find > it. There's a 600-liners here: http://www.pygame.org/projects/21/133/ Not a tutorial, but maybe just as good? From onurb at xiludom.gro Thu Jun 1 04:55:23 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 01 Jun 2006 10:55:23 +0200 Subject: How do you practice programming? In-Reply-To: <1149151097.741307.79440@f6g2000cwb.googlegroups.com> References: <1149151097.741307.79440@f6g2000cwb.googlegroups.com> Message-ID: <447eabee$0$19567$636a55ce@news.free.fr> Ray wrote: > OK, maybe I shoot a more general question to the group since there are > so many great programmers here: how do you practice your craft? I'm certainly not one of them, but... (snip) > How do you do your practice? > 1/ programming 2/ programming 3/ lurking here, reading posts and sometimes trying to answer, reading source code of the oss apps/frameworks I'm working with, searching practical solutions in the cookbook etc 4/ programming -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From neuruss at gmail.com Thu Jun 1 22:09:13 2006 From: neuruss at gmail.com (Neuruss) Date: 1 Jun 2006 19:09:13 -0700 Subject: C# equivalent to range() Message-ID: <1149214153.359809.288610@i39g2000cwa.googlegroups.com> I'm sorry for asking about another language here, but since I only know Python and I'm trying to write something in C#, I guess this is the best place... I'd like to know how to write this in C#: x=[] sz = 10000000 x.extend(range(sz)) My question is about "range" and "extend". Is there any equivalent in C#? Thanks in advance, Neuruss From ptmcg at austin.rr._bogus_.com Thu Jun 15 13:16:55 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Thu, 15 Jun 2006 17:16:55 GMT Subject: code folding, a unique problem to python? References: Message-ID: "John Salerno" wrote in message news:jxfkg.2314$No6.48555 at news.tufts.edu... > > But my question is more general: is it possible to implement code > folding with Python given that it has no real block delimiters? SciTE can fold Python. From a at tempinbox.com Wed Jun 28 01:23:58 2006 From: a at tempinbox.com (a) Date: 27 Jun 2006 22:23:58 -0700 Subject: how do i make an array global Message-ID: <1151472238.400461.42350@p79g2000cwp.googlegroups.com> def fn(): for i in range(l) global count count[i]= .... how do i declare count to be global if it is an array subsequently i should access or define count as an array error: global name 'count' is not defined thanks -a From johnjsal at NOSPAMgmail.com Mon Jun 5 16:30:21 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 05 Jun 2006 20:30:21 GMT Subject: GUI Program Error In-Reply-To: References: <1149536396.375285.319390@y43g2000cwc.googlegroups.com> <920hg.2238$No6.47697@news.tufts.edu> Message-ID: Bernard Lebel wrote: > Unless you were being sarcastic? ;-) Just temporarily dense. :) From akameswaran at gmail.com Fri Jun 9 17:00:30 2006 From: akameswaran at gmail.com (akameswaran at gmail.com) Date: 9 Jun 2006 14:00:30 -0700 Subject: More pythonic shell sort? Message-ID: <1149886830.566152.304500@h76g2000cwa.googlegroups.com> Disclaimer - I recognize this is not a practical exercise. There are many implementations around that would do the job better, more efficiently (Meaning in C) or whatever. I caught some thread about sorting and started thinking about shell sort.... and as part of my trying to pythonise my mind and break my java mindset So I decided to tackle this old school problem with the python mindset. I played around with some list comprehensions, trying to use slicing inteligently etc. Anyway this is what I came up with. If anyone has suggestions on a more pythonic way to go (all attempts at using list comprehensions turned into unruly rubbish quite quickly) I'd appreciate the input. An aside - can anyone tell me where the use += and -= is documented? it works but I can't find it in my docs. (don't ask about shellSorters 1 thru 3) class shellSorter4(object): def __init__(self,gapSeq): self.gapSeq = gapSeq # gap sequences are notoriously hard to tune self.gapSeq.sort(reverse=True) def sort(self,myList): for gap in self.gapSeq: for i in range(1,gap+1): self.gapInsertionSort(myList,i,gap) def gapInsertionSort(self,theList,start,gap): for i in range(start,len(theList),gap): j = i curElem = theList[j] while (j > 0) and (theList[j-gap] > curElem): j -=gap # undocumented feature?? if j!=i: theList.insert(j,theList.pop(i)) theList.insert(j+gap,theList.pop(j+1)) From torbenm at app-1.diku.dk Mon Jun 19 07:53:01 2006 From: torbenm at app-1.diku.dk (=?iso-8859-1?q?Torben_=C6gidius_Mogensen?=) Date: 19 Jun 2006 13:53:01 +0200 Subject: What is Expressiveness in a Computer Language References: <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <2006061410510511272-raffaelcavallaro@pasdespamsilvousplaitmaccom> <2006061501423327544-raffaelcavallaro@pasdespamsilvousplaitmaccom> <2006061611492350073-raffaelcavallaro@pasdespamsilvousplaitmaccom> <2006061618250975249-raffaelcavallaro@pasdespamsilvousplaitmaccom> <7zhd2himme.fsf@app-3.diku.dk> Message-ID: <7z8xnt8iqq.fsf@app-1.diku.dk> George Neuner writes: > On 19 Jun 2006 10:19:05 +0200, torbenm at app-3.diku.dk (Torben ?gidius > Mogensen) wrote: > >I expect a lot of the exploration you do with incomplete programs > >amount to the feedback you get from type inference. > > The ability to write functions and test them immediately without > writing a lot of supporting code is _far_ more useful to me than type > inference. I can't see what this has to do with static/dynamic typing. You can test individula functions in isolation is statically typed languages too. > I'm not going to weigh in on the static v dynamic argument ... I think > both approaches have their place. I am, however, going to ask what > information you think type inference can provide that substitutes for > algorithm or data structure exploration. None. But it can provide a framework for both and catch some types of mistakes early. Torben From jmdeschamps at gmail.com Thu Jun 15 14:53:16 2006 From: jmdeschamps at gmail.com (jmdeschamps at gmail.com) Date: 15 Jun 2006 11:53:16 -0700 Subject: billionlaughs, on me :-(( - on winXP help! Message-ID: <1150397596.520219.125780@c74g2000cwc.googlegroups.com> Looking up different blogs etc on xml parsers I wind up on the site of Computer stuff, www.razorvine.net. And in the browser torture section, the billionlaughs.xml link (that you shouldn't use if you don't know what your doing, as was my case (mea culpa)) Thinking I was about to crash the browser, I look up the web for assorted advice and find nothing except a post about the *killer xml file*... So hereb goes nothing... click, hang, reboot, hangs, (mouse pointer moves, that's it folks) the disk spins occasionally, the vents go up mad, I guess the CPU is working - have know idea on what. I'm able to boot in safe mode but don't know what to do next? Any ideas ? Further details? Thanks in advance (I know this is not directly related to python, but regulars here are my only source of knowledge to this point, on this "Billion Laughs" DoS attack) Jean-Marc From sjmachin at lexicon.net Thu Jun 1 20:10:47 2006 From: sjmachin at lexicon.net (John Machin) Date: 1 Jun 2006 17:10:47 -0700 Subject: Can Python format long integer 123456789 to 12,3456,789 ? In-Reply-To: <8oKfg.1621$Su3.139425@news20.bellglobal.com> References: <8oKfg.1621$Su3.139425@news20.bellglobal.com> Message-ID: <1149207047.692374.114300@h76g2000cwa.googlegroups.com> A.M wrote: > Hi, > > Is there any built in feature in Python that can format long integer > 123456789 to 12,3456,789 ? > Sorry about my previous post. It would produce 123,456,789. "12,3456,789" is weird -- whose idea PHB or yours?? From vinay_sajip at yahoo.co.uk Wed Jun 14 04:47:49 2006 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 14 Jun 2006 01:47:49 -0700 Subject: Logging to a file and closing it again properly (logging module) References: <20060612215823.GA18595@workaround.org> <1360b7230606132359q79497913v24479c2a8af526f6@mail.gmail.com> Message-ID: <1150274869.415775.209050@f6g2000cwb.googlegroups.com> Christoph Haas wrote: > Thanks. That works great. I was looking for a way to close the log file > using logging.basicConfig but it appears that it's too much magic. > logging.getLogger() isn't really much more work but gives better > control. You may also need to close the handler - removeHandler just removes the handler from the Logger's internal list. If there are specific areas in the documentation which you feel are lacking clarity, please post more specific information. Documentation patches are especially welcome ;-) Regards, Vinay Sajip From a at tempinbox.com Mon Jun 26 17:20:58 2006 From: a at tempinbox.com (a) Date: 26 Jun 2006 14:20:58 -0700 Subject: psyco+webpy In-Reply-To: References: <1151348303.344822.18720@u72g2000cwu.googlegroups.com> Message-ID: <1151356858.647976.161520@b68g2000cwa.googlegroups.com> > psyco.cannotcompile(??.GET) this gives an error message invalid syntax Amaury Forgeot d'Arc wrote: > a a ?crit : > > hi i tried psyco+webpy > > > > here is the error that i got > > please let me know if any of you has success run psyco+webpy > > thanks > > > > import web, psyco > > urls = ( > > '/', 'view', > > '/add','add' > > ) > > psyco.full() > > psyco.log() > > psyco.profile() > > > > Launching server: http://0.0.0.0:8080/ > > Traceback (most recent call last): > > File "C:\Python24\lib\site-packages\web.py", line 2054, in > > run_wsgi_app > > result = self.server.app(env, self.wsgi_start_response) > > File "C:\Python24\lib\site-packages\web.py", line 1894, in wsgifunc > > result = func() > > File "C:\Python24\lib\site-packages\web.py", line 1872, in > > func = lambda: handle(getattr(mod, name), mod) > > File "C:\Python24\lib\site-packages\web.py", line 1051, in handle > > return tocall(*([urllib.unquote(x) for x in args] + fna)) > > File "C:\mark\web1\codepsyco.py", line 27, in GET > > web.render('view.html') > > File "C:\Python24\lib\site-packages\web.py", line 1707, in render > > terms.update(sys._getframe(1).f_locals) > > File "C:\Python24\Lib\site-packages\psyco\support.py", line 129, in > > __getattr__ > > Functions optimized by Psyco have limitations concerning access of their > local variables, as stated there: > http://psyco.sourceforge.net/psycoguide/bugs.html > As a workaround, you should prevent psyco from optimizing the functions > calling render(). > > psyco.cannotcompile(web.djangoerror) > psyco.cannotcompile(??.GET) > > P.S. I just had a look at the web.py code and it seems that there are > several uses of _getframe(x).f_locals. I find this trick not very > pythonic (a function's docstring even says:"""Guido van Rossum doesn't > want you to use this function.""") and anyway psyco will not appreciate it. > > -- > Amaury From akameswaran at gmail.com Sat Jun 10 23:26:41 2006 From: akameswaran at gmail.com (akameswaran at gmail.com) Date: 10 Jun 2006 20:26:41 -0700 Subject: More pythonic shell sort? In-Reply-To: <448A4892.1090402@lexicon.net> References: <1149886830.566152.304500@h76g2000cwa.googlegroups.com> <448A4892.1090402@lexicon.net> Message-ID: <1149996401.898150.12480@j55g2000cwa.googlegroups.com> Thanks for the critique. John Machin wrote: > On 10/06/2006 7:00 AM, akameswaran at gmail.com wrote: > > Disclaimer - I recognize this is not a practical exercise. There are > > many implementations around that would do the job better, more > > efficiently (Meaning in C) or whatever. > > > > I caught some thread about sorting and started thinking about shell > > sort.... and as part of my trying to pythonise my mind and break my > > java mindset > > > > So I decided to tackle this old school problem with the python mindset. > > > > > > I played around with some list comprehensions, trying to use slicing > > inteligently etc. > > Slicing? I don't see any, and besides you don't want to be copying > chunks of your list anyway -- see below. That was two of the other sort implementations I tried - far uglier than this. there were sorts 1-3. And while I liked the idea of using the list manipulations built into python - they absolutely were horrible for this. I was almost tempted to post that as well - but it really was an abomination. > > > Anyway this is what I came up with. If anyone has > > suggestions on a more pythonic way to go (all attempts at using list > > comprehensions turned into unruly rubbish quite quickly) I'd > > appreciate the input. An aside - can anyone tell me where the use += > > and -= is documented? it works but I can't find it in my docs. > > (don't ask about shellSorters 1 thru 3) > > > > class shellSorter4(object): > > > > def __init__(self,gapSeq): > > self.gapSeq = gapSeq # gap sequences are > > notoriously hard to tune > > self.gapSeq.sort(reverse=True) > > Not exactly stand-alone, if it needs another sort for its initialisation :-) > > > > > def sort(self,myList): > > for gap in self.gapSeq: > > for i in range(1,gap+1): > > Use xrange instead of range, to save memory. for large sorts, yeah xrange is good. with the runs I was doing, it was irrelevant > > > self.gapInsertionSort(myList,i,gap) > > > > def gapInsertionSort(self,theList,start,gap): > > Having a method call here will slow it down somewhat. true enough, performance wasn't a consideration on this one > > > > for i in range(start,len(theList),gap): > > j = i > > curElem = theList[j] > > while (j > 0) and (theList[j-gap] > curElem): > > I think that you mean "while j >= gap" ... otherwise theList[j-gap] will > be using Python's wrap-around negative subscripting to access something > at the other end of the list! And you'll never know, because the last > pass with gap == 1 will (laboriously) clean up any mess. You should > instrument your code with counts of comparisons and rearrangements, and > compare those with examples from the textbooks and the literature *AND* > your pencil-and-paper experiments with a gap-list of (say) [5, 1] on a > small number of elements. good catch on that one. Didn't think about it. and with the low probability of it happening it WOULD have been missed - doh. The versions I was running were instrumented - but took that out for clarities sake. However j>= gap would not work - say on the first run where gap should be N/2 (just the worst case) but obviously the first elements would never get sorted. . An additional test for j-gap >0 would suffice. > > > j -=gap # undocumented > > feature?? > > if j!=i: > > theList.insert(j,theList.pop(i)) > > theList.insert(j+gap,theList.pop(j+1)) > > Quadruple yuck. Each pop() and insert() could involve moving many list > elements unnecessarily. It's not "pythonic" to use advanced language > features when they are inefficient for the job at hand. All you need is > len(alist), alist[i] = value, and value = alist[i]. A simple translation > of a shellsort written in C would do the job admirably. > I didn't really think of pop and insert as advanced features. But it was part of my goals to use features that exist in python - remembering that they are python lists, not funky arrays. As far as C goes, that was shellSorter1. Since performance wasn't my goal - I rather liked the expresiveness of the pop and insert. makes it almost read like a book. > Perhaps to Pythonise your mind you should try an object-oriented example > -- one that truly needs a class or two; your shellsort doesn't really > need a class (that's your Java background shining through!). > True enough - java is hard to break sometimes. I was tempted to add some try catches just for fun too. I've written quite a bit that is more complex - then I get caught in just making it work. Hence the point of writing simple well understood problems. > HTH, > John From davidh at ilm.com Tue Jun 20 14:46:27 2006 From: davidh at ilm.com (David Hirschfield) Date: Tue, 20 Jun 2006 11:46:27 -0700 Subject: Running code on assignment/binding Message-ID: <44984283.4020807@ilm.com> Another deep python question...is it possible to have code run whenever a particular object is assigned to a variable (bound to a variable)? So, for example, I want the string "assignment made" to print out whenever my class "Test" is assigned to a variable: class Test: ... x = Test would print: "assignment made" Note that there's no "()" after x = Test, I'm not actually instantiating Test, just binding the class to the variable "x" Make sense? Possible? -David -- Presenting: mediocre nebula. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alikakakhel at yahoo.com Mon Jun 5 12:53:20 2006 From: alikakakhel at yahoo.com (greenflame) Date: 5 Jun 2006 09:53:20 -0700 Subject: reordering elements of a list In-Reply-To: <1149382009.640607.217470@y43g2000cwc.googlegroups.com> References: <1149382009.640607.217470@y43g2000cwc.googlegroups.com> Message-ID: <1149526400.739601.178280@u72g2000cwu.googlegroups.com> Thanks all for your help! From jmdeschamps at gmail.com Mon Jun 19 22:49:26 2006 From: jmdeschamps at gmail.com (jmdeschamps at gmail.com) Date: 19 Jun 2006 19:49:26 -0700 Subject: Active Python versions In-Reply-To: References: <2hElg.41514$mF2.19600@bgtnsc04-news.ops.worldnet.att.net> <1150769349.111390.280450@y41g2000cwy.googlegroups.com> Message-ID: <1150771765.929963.72200@p79g2000cwp.googlegroups.com> Tom Del Rosso wrote: > jmdeschamps at gmail.com typed > in news://1150769349.111390.280450 at y41g2000cwy.googlegroups.com, > > > Maybe the OP is refering to PythonWin editor (as compared to IDLE) > > which is in ActiveState's release but not in the Python.org release... > > makes for a very different subject, and hopefully for very different > > answer direction. > > Yes. I just wanted to know which programming environment is prefered by > regular users, maybe even one that I haven't heard of yet. > ... try reading this very recent (still active) thread: http://groups.google.com/group/comp.lang.python/browse_frm/thread/9577320064fa33eb/7ad49f0d44ecbc47?hl=en#7ad49f0d44ecbc47 My two-grain of salt: PythonWin is simple and nice BUT breaks if you do Tkinter Gui (and try to run a program while the previous run isn't finished) Python Scripter - light, nice, some nice features but missing code folding, if you like that... Pydev + Eclipse (Eclipse is Java based plugin type environment) lots of stuff (to much for some) and heavy [t's Java after all ;-) ] But nowadays with RAM, and processor speed - it's nice to do almost every task in the same basic environment (plugins for almost anything) BTW Kudos to all the people behind these apps (mark hammond of pywin fame, kiriakos vlahos for python scripter , and fabio zadrozny for pydev) jean-marc From rainbow.cougar at gmail.com Thu Jun 15 09:50:24 2006 From: rainbow.cougar at gmail.com (rainbow.cougar at gmail.com) Date: 15 Jun 2006 06:50:24 -0700 Subject: Numerics, NaNs, IEEE 754 and C99 References: Message-ID: <1150379424.085598.4130@u72g2000cwu.googlegroups.com> Nick Maclaren wrote: > ... > Now, I should like to improve this, but there are two problems. The > first is political, and is whether it would be acceptable in Python to > restore the semantics that were standard up until about 1980 in the > numerical programming area. I.e. one where anything that is numerically > undefined or at a singularity which can deliver more than one value is > an error state (e.g. raises an an exception or returns a NaN). This > is heresy in the C99 and Java camps, and is none too acceptable in the > IEEE 754R one. > >... As one of the few people on this group who will admit to programming before 1980, let alone doing numerical programming then (I presume writing code to process gigabytes of seismic data via Fast Fourier equations meet your criteria), the only semantics that existed then were for the program to *CRASH* hard when a singularity or undefined state occurred. When using the various flavors of FORTRAN and vector processors the undefined states could take a few microseconds to manifest, but crash and burn they would, with some difficulty to analyze the burning wreckage. C is not a mathematically based language as FORTRAN is, so it is funny to criticize it for being what it never was, however IEEE754 and NaN's and the other standardizations put into place make back analyzing what is wrong with your program and/or data far easier then what we had before. Curtis From steve at holdenweb.com Mon Jun 12 09:23:04 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 12 Jun 2006 14:23:04 +0100 Subject: Searching and manipulating lists of tuples In-Reply-To: <1150117632.693617.45310@c74g2000cwc.googlegroups.com> References: <1150117632.693617.45310@c74g2000cwc.googlegroups.com> Message-ID: MTD wrote: > Hello, > > I'm wondering if there's a quick way of resolving this problem. > > In a program, I have a list of tuples of form (str,int), where int is a > count of how often str occurs > > e.g. L = [ ("X",1),("Y",2)] would mean "X" occurs once and "Y" occurs > twice > > If I am given a string, I want to search L to see if it occurs already. > If it does, I find the corresponding tuple and increment the integer > part. If not, I append the new element with int = 1. > > e.g. > > algorithm(L, "X") would produce output L = [("X",2),("Y",2)] > algorithm(L,"Z") would produce L = [("X",1),("Y",2),("Z",1)] > > I tried to create an algorithm of the following form: > >>>>def algorith(list,str): > > ... flag = True > ... for l in list: > ... if l[0] == str: > ... l[1] += 1 > ... flag = False > ... if flag: > ... list.append((str,1)) > ... > > > But: > > >>>>algorith(L,"X") > > > gives: > > Traceback (most recent call last): > File "", line 1, in ? > File "", line 5, in algorith > TypeError: object does not support item assignment > > > So clearly that doesn't work... any ideas? > [Nit: try not to use built-in names like "list" and "str" for your own purposes, as it stops you from using the bult-ins]. There are many ways you could do this more efficiently. The most efficient solution doesn't use a list at all, but a dictionary (the following code is untested): def algorith(d, s): if s in d: d[s] += 1 else: d[s] = 1 regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From JJLaRocque at gmail.com Wed Jun 21 12:04:11 2006 From: JJLaRocque at gmail.com (JJLaRocque at gmail.com) Date: 21 Jun 2006 09:04:11 -0700 Subject: returning index of minimum in a list of lists In-Reply-To: <1150905017.886816.81750@m73g2000cwd.googlegroups.com> References: <1150901648.832039.165590@b68g2000cwa.googlegroups.com> <1150905017.886816.81750@m73g2000cwd.googlegroups.com> Message-ID: <1150905851.500826.165160@m73g2000cwd.googlegroups.com> Thanks so much for your help. I was wondering if there was anything even simpler, but this will be great. forman.simon at gmail.com wrote: > JJLaRocque at gmail.com wrote: > > Hi all, > > Is there a simple python function to return the list index of the > > minimum entry in a list of lists? > > ie, for [[3,3,3,3], [3,3,3,1], [3,3,3,3]] to return 2,4. > > Or, same question but just for a list of numbers, not a list of lists. > > Thanks, > > Josh > > One way to do this is to generate (value, index-in-main-list, > index-in-secondary-list) tuples and then just take the minimum. > > def f(L): > '''Return indices of the first minimum value in a list of lists.''' > return min( > (n, i, j) > for i, L2 in enumerate(L) > for j, n in enumerate(L2) > )[1:] > > L = [[3, 3, 3, 3], [3, 3, 3, 1], [3, 3, 3, 3]] > > print f(L) # prints (1, 3) > > Note: In python (and most other languages) indices begin at 0, so your > return values of (2, 4) wouldn't be correct. > > For a list of numbers it's simpler. > > L = [3, 3, 3, 1, 3, 3] > print min((n, i) for i, n in enumerate(L))[1] # prints 3 > > Hope this helps > > ~Simon From felipe.lessa at gmail.com Fri Jun 9 17:47:40 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Fri, 09 Jun 2006 18:47:40 -0300 Subject: Writing PNG with pure Python In-Reply-To: References: <1149853401.521169.112530@i39g2000cwa.googlegroups.com> Message-ID: <1149889660.2754.3.camel@kenshin.CASA> Em Sex, 2006-06-09 ?s 12:30 -0400, Alan Isaac escreveu: > It's your code, so you get to license it. > But if you wish to solicit patches, > a more Pythonic license is IMHO more likely > to prove fruitful. "Pythonic license"? That's new to me. I can figure out what a "Python-like license" is, but I'm clueless about a "Pythonic license". -- Felipe. From jes at nl.demon.net Fri Jun 30 10:38:28 2006 From: jes at nl.demon.net (Jim Segrave) Date: Fri, 30 Jun 2006 14:38:28 -0000 Subject: string replace References: <1aapg.21924$_J1.275201@twister2.libero.it> Message-ID: <12aadr4q9i03o78@corp.supernews.com> In article <1aapg.21924$_J1.275201 at twister2.libero.it>, Michele Petrazzo wrote: >Hi, >a lot of times I need to replace more than one char into a string, so I >have to do something like > >value = "test" >chars = "e" >for c in chars: > value = value.replace(c, "") > >A solution could be that "replace" accept a tuple/list of chars, like >that was add into the new 2.5 for startswith. > >I don't know, but can be this feature included into a future python release? Let's say you want to make every vowel uppercase: import string trans_table = string.maketrans('aeiou', 'AEIOU') "I don't know, but can be this feature included into".translate(trans_table) prints: "I dOn't knOw, bUt cAn bE thIs fEAtUrE InclUdEd IntO" That more than addresses your requirements, as it can do multiple character substitutions multiple times in one call. -- Jim Segrave (jes at jes-2.demon.nl) From fredrik at pythonware.com Fri Jun 9 04:01:07 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 09 Jun 2006 10:01:07 +0200 Subject: Select hangs after some reads In-Reply-To: References: <1149737234.816833.177710@j55g2000cwa.googlegroups.com> <1149764138.868847.326250@i39g2000cwa.googlegroups.com> <128g8uvi6aj4240@corp.supernews.com> <1149779056.498540.46620@f6g2000cwb.googlegroups.com> Message-ID: Steve Holden wrote: > Nope, I wouldn't look any harder. You and I both know you won't find > them. "The client" in this case was the client's transport layer, not > the client application - I should have said "sender", since I referred > to the system at the other end as the "receiver". you know that it's a terminology issue when three experienced developers reply "well, it already does that", "you cannot do that", and "I don't understand what you mean" to the same question. (if you're playing "Who Wants To Be A Millionaire", this is the right time to take the money and quit...) From colincolehour at gmail.com Wed Jun 28 17:28:27 2006 From: colincolehour at gmail.com (colincolehour at gmail.com) Date: 28 Jun 2006 14:28:27 -0700 Subject: XML validationg against XSD file in Python Message-ID: <1151530107.316152.311040@b68g2000cwa.googlegroups.com> I have tried searching for tips or tutorials on validating an XML file against and XSD file in python but I haven't had any luck. Can someone point me in the right direction to how this would be achieved. I've read that Python has built in libraries for DTD validation but nothing about XSD. Thanks, Colin From Kiran.Karra at gmail.com Wed Jun 14 17:00:35 2006 From: Kiran.Karra at gmail.com (Kiran) Date: 14 Jun 2006 14:00:35 -0700 Subject: wxPython, tree Control text cutoff In-Reply-To: <4490740c$0$7765$7a628cd7@news.club-internet.fr> References: <1150312112.865135.199390@g10g2000cwb.googlegroups.com> <4490740c$0$7765$7a628cd7@news.club-internet.fr> Message-ID: <1150318835.222950.150320@p79g2000cwp.googlegroups.com> Ah, dang. Nice find! thanks a lot for your help. Also, your note is completely called for. I realize that my code was very complicated, and I just pasted what I had instead of simplifying it down. Next time, I will do so. thanks again! Kiran jean-michel bain-cornu wrote: > Kiran a ?crit : > > Hello all, > > I am using a tree to display stuff, and it is constantly updated, but > > what I have noticed is in the lowest level, there is clearly noticable > > cutoff of the text I place there. The cutoff is existent even if I do > > not update the text inside the tree constantly. It seems that the text > > is halfway below where it should line up. I tried placing an image to > > see if that would correct it, but it does not. The image is perfectly > > lined up, but the text is still misaligned. > > > > Any known issues of this and how to fix it? By the way, it happens in > > both Linux and Windows. > Hi Kiran, > It works fine if you change : > x = self.tree.AppendItem(self.connections[i][j][0], "") > to > x = self.tree.AppendItem(self.connections[i][j][0], " ") > I let you imagine the explanation... > Regards, > jm > > Just a hint : it'd be helpfull to solve such a bug if you make your > program more simple. To find out the solution, I reduced your program to > what's following, and the light came : > > import wx > import wx.gizmos as gizmos > > class AlarmsWindow(wx.MDIChildFrame): > def __init__(self, parent, title, size, pos): > wx.MDIChildFrame.__init__(self, parent, -1, title, size = size, > pos =pos) > self.tree = gizmos.TreeListCtrl(self, -1, style = > wx.TR_DEFAULT_STYLE| wx.TR_FULL_ROW_HIGHLIGHT) > # create some columns > self.tree.AddColumn("Connection") > self.tree.AddColumn("Alarm") > self.tree.AddColumn("Value") > self.tree.SetMainColumn(0) > > self.root = self.tree.AddRoot("Connections") > self.tree.Expand(self.root) > self.tree.GetMainWindow().Bind(wx.EVT_RIGHT_UP, self.OnRightUp) > self.Show() > > child = self.tree.AppendItem(self.root, 'name') > self.tree.SetItemText(child, 'name') > child2= self.tree.AppendItem(child,'name2') > ## x = self.tree.AppendItem(child2, "") > x = self.tree.AppendItem(child2, "XXX") > self.tree.SetItemText(x, 'alarm', 1) > self.tree.SetItemText(x, 'value', 2) > > def OnRightUp(self, evt): > pass > > class MDIFrame(wx.MDIParentFrame): > def __init__(self): > wx.MDIParentFrame.__init__(self, None, -1, "MDI Parent", size > =(600, 400)) > child = AlarmsWindow(self, "Alarm", (400, 300), (0, 0)) > > > if __name__=='__main__': > app = wx.PySimpleApp() > frame = MDIFrame() > frame.Show() > app.MainLoop() From bdesth.quelquechose at free.quelquepart.fr Thu Jun 22 19:31:11 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 23 Jun 2006 01:31:11 +0200 Subject: Status of optional static typing in Python? In-Reply-To: References: Message-ID: <449af81d$0$31818$626a54ce@news.free.fr> Christian Convey a ?crit : > Hi guys, > > I'm looking at developing a somewhat complex system, and I think some > static typing will help me keep limit my confusion. Then I think you're suffering from an alas too common delusion. Static typing (at least declarative static typing) will only makes your system more complex. But if you want some help in managing complexity, you may want to look at interfaces systems (Zope3 interfaces or Peak's Protocol) and multidispatch (Peak's Protocol dispatch package). From serge.orlov at gmail.com Tue Jun 27 17:59:23 2006 From: serge.orlov at gmail.com (Serge Orlov) Date: Tue, 27 Jun 2006 14:59:23 -0700 Subject: Problem with sets and Unicode strings In-Reply-To: <44a19d55$2@news.uni-ulm.de> References: <44a17d05$1@news.uni-ulm.de> <44a19d55$2@news.uni-ulm.de> Message-ID: On 6/27/06, Dennis Benzinger wrote: > Serge Orlov wrote: > > On 6/27/06, Dennis Benzinger wrote: > >> Hi! > >> > >> The following program in an UTF-8 encoded file: > >> > >> > >> # -*- coding: UTF-8 -*- > >> > >> FIELDS = ("F?cher", ) > >> FROZEN_FIELDS = frozenset(FIELDS) > >> FIELDS_SET = set(FIELDS) > >> > >> print u"F?cher" in FROZEN_FIELDS > >> print u"F?cher" in FIELDS_SET > >> print u"F?cher" in FIELDS > >> > >> > >> gives this output > >> > >> > >> False > >> False > >> Traceback (most recent call last): > >> File "test.py", line 9, in ? > >> print u"F??cher" in FIELDS > >> UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 1: > >> ordinal not in range(128) > >> > >> > >> Why do the first two print statements succeed and the third one fails > >> with an exception? > > > > Actually all three statements fail to produce correct result. > > So this is a bug in Python? No. > > frozenset remove the exception? > > > > Because sets use hash algorithm to find matches, whereas the last > > statement directly compares a unicode string with a byte string. Byte > > strings can only contain ascii characters, that's why python raises an > > exception. The problem is very easy to fix: use unicode strings for > > all non-ascii strings. > > No, byte strings contain characters which are at least 8-bit wide > . Yes, but later it's written that non-ascii characters do not have universal meaning assigned to them. In other words if you put byte 0xE4 into a bytes string all python knows about it is that it's *some* character. If you put character U+00E4 into a unicode string python knows it's a "latin small letter a with diaeresis". Trying to compare *some* character with a specific character is obviously undefined. > But I don't understand what > Python is trying to decode and why the exception says something about > the ASCII codec, because my file is encoded with UTF-8. Because byte strings can come from different sources (network, files, etc) not only from the sources of your program python cannot assume all of them are utf-8. It assumes they are ascii, because most of wide-spread text encodings are ascii bases. Actually it's a guess, since there are utf-16, utf-32 and other non-ascii encodings. If you want to experience the life without guesses put sys.setdefaultencoding("undefined") into site.py From onurb at xiludom.gro Tue Jun 20 12:45:42 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Tue, 20 Jun 2006 18:45:42 +0200 Subject: [OT] code is data In-Reply-To: References: <44965f53$0$12743$636a55ce@news.free.fr> <4496b29f$0$27412$626a54ce@news.free.fr> <4496e9c9$0$14868$626a54ce@news.free.fr> <4fokj4F1ihat3U1@uni-berlin.de> <4497c20e$0$29656$636a55ce@news.free.fr> <4fpuh5F1i9bl1U1@uni-berlin.de> <4497d72d$0$30964$636a55ce@news.free.fr> <4fq5fkF1k346bU1@uni-berlin.de> Message-ID: <44982637$0$29812$626a54ce@news.free.fr> Anton Vredegoor wrote: > Diez B. Roggisch wrote: > > <...> > >>> The whole point of a code transformation mechanism like the one Anton is >>> talking about is to be dynamic. Else one just needs a preprocessor... >> >> >> No, it is not the whole point. The point is >> "" >> The idea is that we now have a fast parser (ElementTree) with a >> reasonable 'API' and a data type (XML or JSON) that can be used as an >> intermediate form to store parsing trees. Especially statically typed >> little languages seem to be very swallow-able. Maybe I will be able to >> reimplement GFABasic (my first love computer language, although not my >> first relationship) someday, just for fun. >> """ >> >> No on-the-fly code generation here. He essentially wants >> lisp-style-macros >> with better parsing. Still a programming language. Not a data-monger. > > > The 'problem' is that a lot of incredibly smart people are reading and > replying here who are seeing a lot more into my post than I was prepared > for :-) no comment... (snip various transformations examples) > > So if we can transform documents, images and XML, why not sourcecode? > (snip preliminary precautions) > it would be easy to convert all datatypes > into the datatypes of another language, thereby making it possible to > exchange code between languages. You mean like 'converting' javascript to python or python to ruby (or converting any home-grown DSL to Python, etc) ? > Algorithms just being things that > convert sets of data-objects into other sets of data-objects. > > Now if one would equate standardized code exchange between languages and > within a language with macros then I guess there is nothing left for me > to do but wait till a certain google bot comes knocking at my ip-address > port 80 and transfers me to the google equivalent of Guantanamo. Lol !-) Well, given this quote from another of your posts: """ The idea is to have a way to transform a Python (.py) module into XML and then do source code manipulations in XML-space using ElementTree. """ I effectively understood something like a python to python transformation, which of course led me to something very very like macros. > But the whole point of distinguishing macros from official language > structures *is* standardization, as some other clever poster already > pointed out, so it would be extremely unfair to equate trans-language > standardized code exchange with the guerrilla type macro activities that > are plaguing the Lisp community. > > Then there are some people who keep insisting they don't understand what > I'm talking about until I simplify things enough to get them on-board, count me in then :( > but then simply dismiss my ideas with 'you can already do that easily > with this standard python construct'. This strategy was also eloquently > refuted by some other poster, so I don't need to repeat it :-) > > I've gotten a lot of things to think about, so thanks all for your > thoughts, but since this is getting way above my head I'll just wimp out > and leave the rest of the thread to the experts! No way you will escape from your responsabilities so easily !-) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From johnjsal at NOSPAMgmail.com Thu Jun 8 13:00:01 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 08 Jun 2006 17:00:01 GMT Subject: wxpython: where is the demo? Message-ID: I just realized that after installing wxPython, it did not add the usual menu item to my Start menu (Windows), where I can access the docs and demo. I searched through the wxPython folder in the site-packages directory, but I can't seem to find it. Anyone know how I can get this back? Thanks. From wrongbad at gmail.com Mon Jun 26 15:42:18 2006 From: wrongbad at gmail.com (I V) Date: Mon, 26 Jun 2006 12:42:18 -0700 Subject: Beginner Programmer Question References: <1151342733.742416.180370@r2g2000cwb.googlegroups.com> <1151343383.139891.219270@u72g2000cwu.googlegroups.com> <1151343641.509435.245210@u72g2000cwu.googlegroups.com> <1151343759.716134.169950@c74g2000cwc.googlegroups.com> <1151343949.958134.257960@b68g2000cwa.googlegroups.com> <1151344078.584742.95990@y41g2000cwy.googlegroups.com> Message-ID: On Mon, 26 Jun 2006 10:47:58 -0700, kydavis77 at gmail.com wrote: > whats the difference between raw input and input? 'input' is used to ask the user to input a python expression, which is then run, and 'input' returns the result of executing that expression. For example: (define a function which prints something out) >>> def func(): ... print "You're calling a function" ... return "Function result" ... (now, call input) >>> res = input('Type python here: ') (python outputs the prompt ) Type python here: (and, if you type the python code to call a function after the prompt) Type python here: func() (then python calls the function, which prints out) You're calling a function (meanwhile, the result of calling the function gets assigned to 'res') >>> print res Function result 'raw_input' just returns whatever text the user typed in. That's what you want to use here. 'raw_input' returns a string, which you'll need to convert to a number with the 'int' function, like so: text = raw_input('Type in a number: ') number = int(text) From esj at harvee.org Wed Jun 21 09:19:27 2006 From: esj at harvee.org (Eric S. Johansson) Date: Wed, 21 Jun 2006 09:19:27 -0400 Subject: need all python dialog equivalent In-Reply-To: <1150872252.418400.13070@i40g2000cwc.googlegroups.com> References: <1150872252.418400.13070@i40g2000cwc.googlegroups.com> Message-ID: <4499475F.5080706@harvee.org> hdante at gmail.com wrote: > dialog binary is 110 KB. Won't it fit ? missing library. I have ncurses and newt and dialog seems to require something called ncursesw. I've been trying to find the Python newt module as well and that seems to be as invisible as the creature it's named after. From runlevelten at gmail.com Tue Jun 20 11:19:15 2006 From: runlevelten at gmail.com (Ten) Date: Tue, 20 Jun 2006 16:19:15 +0100 Subject: a good programming text editor (not IDE) In-Reply-To: <1150533881.540254.270400@i40g2000cwc.googlegroups.com> References: <_xgkg.2317$No6.48542@news.tufts.edu> <1150406662.900552.46650@u72g2000cwu.googlegroups.com> <1150533881.540254.270400@i40g2000cwc.googlegroups.com> Message-ID: <200606201619.16118.runlevelten@gmail.com> On Saturday 17 June 2006 09:44, 63q2o4i02 at sneakemail.com wrote: > Istvan Albert wrote: > > Scott David Daniels wrote: > > > To paraphrase someone else (their identity lost in my mental fog) about > > > learning VI: > > > "The two weeks you'll spend hating vi (or vim) as you learn it > > > will be repaid in another month, ad the rest is pure profit." > > > > Time and again I hear this (no shortage of Vim fans, same with Emacs), > > and I know I should know better but always believe them yet again. > > Invariably I download Vim play with it for an hour, get increasingly > > frustrated and give up. Most likely I'm greatly spoiled by using > > EditPlus (Windows only), it just makes it so easy to do the basic > > programming tasks that I need, everywhere else I turn I see far more > > functionality but at the price of not being able to do basic tasks as > > efficiently as I need them. > > > > Say I want to be able to execute the python program I'm currently > > editing. Nothing simpler in EditPlus, Tools->Configure Tools->Add Tool > > then specify which program you want to run, what parameters it takes > > and whether to capture the output or not ... total time it took me > > first time I wanted to do this ... about 3 minutes ... from now on > > pressing Ctrl-1 while editing the source will execute the python on the > > current source *and* it displays the output in a lower pane as it runs > > *and* it allows me to simultanously edit the file *while* the program > > is running. Outstanding. > > > > Yet after searching and reading stuff for more than an hour I was > > unable to accomplish the same thing in Vim though I'm already familiar > > enough with basic editing and setup (through my previous trials and > > tribulations) ... I have a few solutions that end up doing something > > similar but are quite a few keypresses longer both to invoke or to get > > back to the source that I'm writing, or I lose editing control while > > the program is running ... etc... > > > > So if the OP is on windows just head over and get EditPlus (UltraEdit > > and TextPad seem to be similar), and just accept the fact that you are > > already using an editor that as good as an editor can get ... I know > > I'd pay that registration once again for an editor that works the same > > way on Linux... > > > > i. > > I'm a huge EditPlus fan and there are not enough good things I can say > about it. The main thing about GUIs which unix people don't seem to > get is discoverability is key. Every time I've tried using x-emacs or > x-anything (or even Scite as it seems to be popular), there is very > little that is intuitive or obvious about the interface, and even > though you have a GUI right there in front of you, things are still > controlled in dot whatever files, with some special syntax and magic > words for everything! Even doing a search and replace in x-emacs is > f*cked up. I was trying to use it for something a few years ago (I > dunno, maybe 2002 or 2003 on debian or 2000 on redhat), and it just > didn't work the way I expected it to work, ie it didn't follow what has > become the standard GUI (read: windows) way of doing things. There > should be a dialog for search and replace. If it doesn't do it that > way, then don't pretend to be a gui, because you're not, you're > pandering to the "we want a gui crowd" while still stickin' it to 'em > by forcing them to remember commands for shit like changing word > wrapping (oh my god there's a *mode* for word wrapping? m-x-wtf > change-the-mode-to-something-I-forget-what) and reminding everyone what > a privilege it is to learn f***king lisp to enable some obscure little > tweak which could just as easily have shown up in a checkbox. Scite > was jacked because the main window didn't have anything discoverable on > it, and one of the main menus just had a list of syntaxes you could use > to highlight your code... and the other menu opened up your dot > whatever file to change the settings. That's just retarded. > > I think there is a fine line between being too dumbed down to do > anything (point click ooh aahh), and so "flexible", "customizable", and > "free" that it feels you have to roll-your-own text editor each time > you want to start a new project. This is the best article on guis and > stuff I've read in a while. > http://www.joelonsoftware.com/uibook/fog0000000249.html > > Anyway, the only thing editplus doesn't do that I wish it did is code > folding. All the stuff you guys are talking about: line numbers, > syntax highlighting, custom tools (running the interpreter), regexp > search and replace, keeping your environment the same between sessions, > soft word wrap, tab-vs-spaces, auto-indent, braces-matching, bla bla... > it does it all in an appropriately gui manner without making you feel > like a moron for not psychically knowing the command ahead of time, or > for not having someone to copy a dot whatever file from, or not Reading > TFM (which of course never tells you what you want to know anyway -- > it's either a patronizingly simple-minded 3rd grade tutorial, or it > tells you what a command does if you already know its f***king name!). > And of course all these editplus things are accessible via the keyboard > without necessarily hitting alt to go to the menu. And no, it doesn't > read email or newsgroups, run custom scripts to beautify your code, or > have 20MB of stuff to download and 20 years of history to catch up on. > I've rarely needed anything more than straightforward editing, so I > guess I'm not worthy to have an opinion of how shitty *nix is for > pretending to have guis. If you (meaning y'all) like to feel superior > by memorizing commands how to change the word wrapping mode, > braces-indenting mode, background color, foreground color, > braces-matching, apropos-me-this, then by all means make things > difficult for the rest of us lowly non-professional programmers (I'm a > hardware designer by trade, but like to fuck around python for fun). > For me, when I just have something quick and dirty, I use editplus and > that makes me sooo happpyyyyy. If there were something like this for > Linux I might even consider switching long term. Speaking as a user of emacs, imo EditPlus is a very sound little product - I did some work with it a while back and it stands out in my memory as a fairly pleasant experience. In the same sort of vein on other platforms, BlueFish is a nice basic GUI-based editor, and whilst touted as a web editor, it has enough features (piping output or files through other apps, a configurable dialog for each code snippet, etc.) that it's perfectly usable as a programming editor of the sort you're referring to. Still, before you decide to tell all the unix/vim/emacs/whatever users that they're a bunch of elitist swine, it might be nice to remember that some aren't, and might not deserve to be branded as such for no reason other than that you, personally, can't stand to use program X! Incidentally, x-emacs, kde and gnome are not the same as windows, neither is os x, therefore they may be unfamiliar in some ways. To me that's not really a legitimate technical or HCI-based criticism of software people have written, it's a statement of the obvious. Is your grill deficient because it doesn't work in the same way as your toaster? Something to ponder. Good luck to you. Cheers, Ten. -- There are 10 types of people in this world, those who understand binary, and those who don't. From Peter.Silva at ec.gc.ca Mon Jun 19 12:29:25 2006 From: Peter.Silva at ec.gc.ca (Peter Silva) Date: 19 Jun 2006 09:29:25 -0700 Subject: transfer rate limiting in socket.py In-Reply-To: References: <1150491228.229045.163110@h76g2000cwa.googlegroups.com> Message-ID: <1150734565.753038.240580@c74g2000cwc.googlegroups.com> I looked at twisted briefly. It looks like it is server oriented. Does it work in for clients initiating connections? Jean-Paul Calderone wrote: > On 16 Jun 2006 13:53:48 -0700, Peter Silva wrote: > >Hi folks, > > > >I have a need in a network data distribution application to send out > >data to folks who want it using the protocol of their choice. I?d > >like it to support a variety of protocols and I don?t want to > >implement any of them :-) > >http, ftp (via ftplib) , https (dunno how yet), ssl, ssh, sftp (via > >paramiko) > > > >The thing is... I want rate-limiting so that in the case of a failure > >of a single client > >I don?t penalize the other clients, or if my server (which is acting > >as a client pushing to remote servers.) goes down, it doesn?t saturate > >the link when it comes back. > > > >So I want to have all the protocols limit the number of bytes they send > >per second. > >It looks like the easiest way to do this is to dive into socket.py... > >and look! it says: > > > ># Wrapper module for _socket, providing some additional facilities > ># implemented in Python. > > > >note the ?additional facilities implemented in python? ... > > > >so we just add logic to: > >-- add a ?maxrate? argument to the constructor and/or an attribute to > >modify the setting... > >-- tally bytes, and time, and know when we are going ?too fast? > >-- when too fast.. in the ?flush? routine, in the synchronous case, > >sleep for the correct time to come back under budget. in the async, > >return without writing. > > -- do something similar for reading. > > > > Anybody think this would be fun? > > Use Twisted instead. It supports every protocol you mentioned, and > rate limiting too. > > Jean-Paul From bdesth.quelquechose at free.quelquepart.fr Mon Jun 26 19:46:48 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 27 Jun 2006 01:46:48 +0200 Subject: Replace Whole Object Through Object Method In-Reply-To: <1151342941.256085.243000@p79g2000cwp.googlegroups.com> References: <1151337453.804750.293180@b68g2000cwa.googlegroups.com> <44a0132d$0$21282$626a54ce@news.free.fr> <1151342941.256085.243000@p79g2000cwp.googlegroups.com> Message-ID: <44a041a6$0$17612$636a55ce@news.free.fr> digitalorganics at gmail.com a ?crit : > Bruno Desthuilliers wrote: (snip) >> >>Instead of exposing problems with your solution, you may want to expose >>the real use case ? > > > I'm working with a team that's doing social modeling, and for example, > I need to model workers that at some point in the program may or may > not also become employers. If I understand correctly, only some of the existing workers will become employers ? > Now, I want the workers to take on all > behaviors and attributes of an employer in addition to their > pre-existing "worker" behaviors and attributes. wrt/ behaviors, it's easy as pie. Attributes (I mean instance attributes) are another problem, but I don't have enough informations to deal with this problem here. > Also, as I'm sure you > guessed, the workers' attributes need to retain their values at that > point in the program, so a brand new worker-employer object wouldn't in > itself do the trick. Here's a simple stupid possible solution: class Worker(object): def __init__(self, ...) # init code here # behaviours here def becomeEmployer(self): self.___class__ = Employer class Employer(Worker): # behaviours here w = Worker(...) w.becomeEmployer() Note that there's no initializer in the Employer class - it wouldn't get called anyway (not automatically at least). From rossberg at ps.uni-sb.de Sun Jun 25 04:40:44 2006 From: rossberg at ps.uni-sb.de (rossberg at ps.uni-sb.de) Date: 25 Jun 2006 01:40:44 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: <1151171007.230666.235430@r2g2000cwb.googlegroups.com> References: <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150904134.520639.71070@b68g2000cwa.googlegroups.com> <1151056505.908723.162580@u72g2000cwu.googlegroups.com> <1151171007.230666.235430@r2g2000cwb.googlegroups.com> Message-ID: <1151224844.569347.167420@r2g2000cwb.googlegroups.com> Marshall wrote: > > > > This means that there's a sense in which the language that the > > programmer programs in is not the same language that has a formal > > semantic definition. As I mentioned in another post, programmers are > > essentially mentally programming in a richer language - a language which > > has informal (static) types - but the code they write down elides this > > type information, or else puts it in comments. > > > > [...] > > > > In this context, the term "latently-typed language" refers to the > > language that a programmer experiences, not to the subset of that > > language which is all that we're typically able to formally define. That language is not a subset, if at all, it's the other way round, but I'd say they are rather incomparable. That is, they are different languages. > That is starting to get a bit too mystical for my tastes. I have to agree. \sarcasm One step further, and somebody starts calling C a "latently memory-safe language", because a real programmer "knows" that his code is in a safe subset... And where he is wrong, dynamic memory page protection checks will guide him. - Andreas From johnjsal at NOSPAMgmail.com Wed Jun 7 09:52:26 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 07 Jun 2006 13:52:26 GMT Subject: tkinter: making widgets instance or not? In-Reply-To: References: Message-ID: John McMonagle wrote: > def __init__(self, master): > self.parent = master > self.entry1 = self.draw_entry('First Name:') > self.entry2 = self.draw_entry('Last Name:') Genius! :) Looks like you solved both of my problems! Thanks! From marshall.spight at gmail.com Sat Jun 24 13:43:27 2006 From: marshall.spight at gmail.com (Marshall) Date: 24 Jun 2006 10:43:27 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150904134.520639.71070@b68g2000cwa.googlegroups.com> <1151056505.908723.162580@u72g2000cwu.googlegroups.com> Message-ID: <1151171007.230666.235430@r2g2000cwb.googlegroups.com> Anton van Straaten wrote: > > But beyond that, there's an issue here about the definition of "the > language". When programming in a latently-typed language, a lot of > action goes on outside the language - reasoning about static properties > of programs that are not captured by the semantics of the language. > > This means that there's a sense in which the language that the > programmer programs in is not the same language that has a formal > semantic definition. As I mentioned in another post, programmers are > essentially mentally programming in a richer language - a language which > has informal (static) types - but the code they write down elides this > type information, or else puts it in comments. > > We have to accept, then, that the formal semantic definitions of > dynamically-checked languages are incomplete in some important ways. > Referring to those semantic definitions as "the language", as though > that's all there is to the language in a broader sense, is misleading. > > In this context, the term "latently-typed language" refers to the > language that a programmer experiences, not to the subset of that > language which is all that we're typically able to formally define. That is starting to get a bit too mystical for my tastes. Marshall From grante at visi.com Tue Jun 27 11:05:05 2006 From: grante at visi.com (Grant Edwards) Date: Tue, 27 Jun 2006 15:05:05 -0000 Subject: How do you use this list? References: <12a2foromcuj30b@corp.supernews.com> Message-ID: <12a2i91ir8cg8a8@corp.supernews.com> On 2006-06-27, Klaus Alexander Seistrup wrote: > Grant Edwards wrote: > >> Find an NNTP server and read it as a newsgroup. > > Or Google Groups: http://groups.google.com/group/comp.lang.python I did heard a rumor that they finally fixed the "follow-up" function that had been broken since day 1. Still, it does a bad reputation similar to AOL used to... -- Grant Edwards grante Yow! My EARS are GONE!! at visi.com From and-google at doxdesk.com Wed Jun 21 10:47:11 2006 From: and-google at doxdesk.com (and-google at doxdesk.com) Date: 21 Jun 2006 07:47:11 -0700 Subject: new python icons for windows References: <1150811271.282850.321510@p79g2000cwp.googlegroups.com> Message-ID: <1150901231.837272.129040@g10g2000cwb.googlegroups.com> Istvan Albert wrote: > But these new icons are too large, too blocky and too pastel. Hooray! Glad to see *someone* doesn't like 'em, I'll expect a few more when b1 hits. :-) Although I can't really see 'large', 'blocky' or 'pastel'... they're the same size and shape as other Windows document icons, and I personally find the Python logo colours quite striking. If it's the new-fangled shadey gradienty kind of nonsense you don't like, you could also try the low-colour versions. eg. ICOs compiled with only 16-colour and 16/32 sizes: http://doxdesk.com/file/software/py/pyicons-tiny.zip > For example it resembles the icon for text files. This is intentional: to make it obvious that .py files are the readable, editable scripts, contrasting with .pyc's binary gunk - something that wasn't 100% clear before. With the obviousness of the Python-plus and the strong difference between the white and black base document icons, squinting shouldn't really be necessary IMO. > can someone point me to a page/link that contains the old icons? Sure, http://svn.python.org/view/python/branches/release24-maint/PC/py.ico http://svn.python.org/view/python/branches/release24-maint/PC/pyc.ico http://svn.python.org/view/python/branches/release24-maint/PC/pycon.ico -- And Clover mailto:and at doxdesk.com http://www.doxdesk.com/ From wahab at chemie.uni-halle.de Sun Jun 18 18:06:23 2006 From: wahab at chemie.uni-halle.de (Mirco Wahab) Date: Mon, 19 Jun 2006 00:06:23 +0200 Subject: Extracting values from text file In-Reply-To: References: <20060617232543.9a0338fb.randhol+valid_for_reply_from_news@pvv.org> <20060618133459.2a56f781.randhol+valid_for_reply_from_news@pvv.org> Message-ID: Thus spoke Dennis Lee Bieber (on 2006-06-18 22:37): > The only cure for that is complete and painful bone marrow > transplant As a start, after six months of no PERL go back and try > reading some of your code. Uhhh, this is like giving the mounted knight a longbow and push him onto the battlefield of Agincourt ;-) Regards Mirco From ziga.seilnacht at gmail.com Tue Jun 20 16:47:56 2006 From: ziga.seilnacht at gmail.com (Ziga Seilnacht) Date: 20 Jun 2006 13:47:56 -0700 Subject: __getattribute__ doesn't work on 'type' type for '__class__' References: <8k8g92tgqmhu70au13od2fn1ihut04sr0o@4ax.com> Message-ID: <1150836476.323431.206520@u72g2000cwu.googlegroups.com> Barry Kelly wrote: [snipped] > Yet when I try this with the 'type' type, it doesn't work: > > ---8<--- > >>> x.__class__.__class__ > > >>> x.__class__.__getattribute__('__class__') > Traceback (most recent call last): > File "", line 1, in ? > TypeError: descriptor '__getattribute__' requires a 'int' object but > received a 'str' > --->8--- > > Why is this? The problem is that your class (I would guess that x is an int) and its type have a method with the same name. As is normal for attribute lookup, the instance's attribute is first looked up in its __dict__. Since x.__class__ is a type, this results in __getattribute__ being an unbound method of that type. What you are doing is similar to: >>> L = ["spam", "eggs"] >>> "".__class__.join(L) Traceback (most recent call last): ... TypeError: descriptor 'join' requires a 'str' object but received a 'list' Which as you can see, fails with the same error message. > -- Barry > > -- > http://barrkel.blogspot.com/ Hope this helps, Ziga From vesa.karvonen at cs.helsinki.fi Wed Jun 21 12:04:44 2006 From: vesa.karvonen at cs.helsinki.fi (Vesa Karvonen) Date: 21 Jun 2006 16:04:44 GMT Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> Message-ID: In comp.lang.functional Anton van Straaten wrote: [...] This static vs dynamic type thing reminds me of one article written by Bjarne Stroustrup where he notes that "Object-Oriented" has become a synonym for "good". More precisely, it seems to me that both camps (static & dynamic) think that "typed" is a synonym for having "well-defined semantics" or being "safe" and therefore feel the need to be able to speak of their language as "typed" whether or not it makes sense. > Let me add another complex subtlety, then: the above description misses > an important point, which is that *automated* type checking is not the > whole story. I.e. that compile time/runtime distinction is a kind of > red herring. I agree. I think that instead of "statically typed" we should say "typed" and instead of "(dynamically|latently) typed" we should say "untyped". > In a statically-checked language, people tend to confuse automated > static checking with the existence of types, because they're thinking in > a strictly formal sense: they're restricting their world view to what > they see "within" the language. That is not unreasonable. You see, you can't have types unless you have a type system. Types without a type system are like answers without questions - it just doesn't make any sense. > Then they look at programs in a dynamically-checked language, and see > checks happening at runtime, and they assume that this means that the > program is "untyped". Not in my experience. Either a *language* specifies a type system or not. There is little room for confusion. Well, at least unless you equate "typing" with being "well-defined" or "safe" and go to great lengths to convince yourself that your program has "latent types" even without specifying a type system. > It's certainly close enough to say that the *language* is untyped. Indeed. Either a language has a type system and is typed or has no type system and is untyped. I see very little room for confusion here. In my experience, the people who confuse these things are people from the dynamic/latent camp who wish to see types everywhere because they confuse typing with safety or having well-defined semantics. > But a program as seen by the programmer has types: the programmer > performs (static) type inference when reasoning about the program, and > debugs those inferences when debugging the program, finally ending up > with a program which has a perfectly good type scheme. It's may be > messy compared to say an HM type scheme, and it's usually not proved to > be perfect, but that again is an orthogonal issue. There is a huge hole in your argument above. Types really do not make sense without a type system. To claim that a program has a type scheme, you must first specify the type system. Otherwise it just doesn't make any sense. > Mathematicians operated for thousands of years without automated > checking of proofs, so you can't argue that because a > dynamically-checked program hasn't had its type scheme proved correct, > that it somehow doesn't have types. That would be a bit like arguing > that we didn't have Math until automated theorem provers came along. No - not at all. First of all, mathematics has matured quite a bit since the early days. I'm sure you've heard of the axiomatic method. However, what you are missing is that to prove that your program has types, you first need to specify a type system. Similarly, to prove something in math you start by specifying [fill in the rest]. > 1. "Untyped" is really quite a misleading term, unless you're talking > about something like the untyped lambda calculus. That, I will agree, > can reasonably be called untyped. Untyped is not misleading. "Typed" is not a synonym for "safe" or "having well-defined semantics". > So, will y'all just switch from using "dynamically typed" to "latently > typed" I won't (use "latently typed"). At least not without further qualification. -Vesa Karvonen From juergen.huber at kirchnersoft.com Fri Jun 30 07:17:04 2006 From: juergen.huber at kirchnersoft.com (Juergen Huber) Date: Fri, 30 Jun 2006 13:17:04 +0200 Subject: delete first line in a file References: <44a4f854$0$12942$91cee783@newsreader02.highway.telekom.at><44a50151$0$12935$91cee783@newsreader02.highway.telekom.at> Message-ID: <44a50825$0$3888$91cee783@newsreader01.highway.telekom.at> Fredrik Lundh wrote: > Juergen Huber wrote: > >> ok...i thought as much, that i have to copy this file! >> >> how will i do that?! >> how will i fix this file => delete the first line?! >> >> with which commands could i do that?! > > start here: > > http://docs.python.org/tut/node9.html#SECTION009200000000000000000 > > that documentation i have already read, but it wouldn`t help me for my problem! i know, how i can read the first line an print them on the screen! but...how can i say python, delete the first line?! thats my problem! in the entry of my posting i wrote, that i am a newbie and so please understand me, that i ask so questions?! :-) thanks for your help! From maric at aristote.info Wed Jun 14 09:56:16 2006 From: maric at aristote.info (Maric Michaud) Date: Wed, 14 Jun 2006 15:56:16 +0200 Subject: Correctly reading stdout/stderr from subprocess In-Reply-To: <200606141314.14587.maric@aristote.info> References: <20060613222002.GB5153@workaround.org> <200606141314.14587.maric@aristote.info> Message-ID: <200606141556.16856.maric@aristote.info> Le Mercredi 14 Juin 2006 13:14, Maric Michaud a ?crit?: > or use a > threaded version here it is. I did it just to validate my point and because i don't use threads very often in python, some exercises can't hurt :) def run(command): import subprocess run = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # Wait for the process to return import thread, threading out, err = [], [] out_ended, err_ended = threading.Event(), threading.Event() def getOutput(output, lines, ended_event) : for i in output.readlines() : lines.append(i.rstrip('\n')) ended_event.set() out_thread = thread.start_new_thread(getOutput, (run.stdout, out, out_ended)) err_thread = thread.start_new_thread(getOutput, (run.stderr, err, err_ended)) out_ended.wait() err_ended.wait() returncode = run.wait() return returncode, out, err > (much more complicated). isn't it. -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From john at castleamber.com Thu Jun 8 17:12:49 2006 From: john at castleamber.com (John Bokma) Date: 8 Jun 2006 21:12:49 GMT Subject: Importing again and again References: <1149796920.757115.290840@h76g2000cwa.googlegroups.com> Message-ID: "abcd" wrote: > If I have code which imports a module over and over again...say each > time a function is called, does that cause Python to actually re-import > it...or will it skip it once the module has been imported?? > > for example: > > def foo(): > import bar > bar.printStuff() > > foo() > foo() > foo() > foo() > > ...will that re-import bar 4 times...or just import it once? is this a > big performance hit? I am new to Python so this might be a weird question, but it there a reason why you import bar inside foo? -- John MexIT: http://johnbokma.com/mexit/ personal page: http://johnbokma.com/ Experienced programmer available: http://castleamber.com/ Happy Customers: http://castleamber.com/testimonials.html From skip at pobox.com Wed Jun 28 15:46:10 2006 From: skip at pobox.com (skip at pobox.com) Date: Wed, 28 Jun 2006 14:46:10 -0500 Subject: Psyco tagging the same function multiple times In-Reply-To: <1151521307.573299.190830@y41g2000cwy.googlegroups.com> References: <1151521307.573299.190830@y41g2000cwy.googlegroups.com> Message-ID: <17570.56450.158124.456181@montanaro.dyndns.org> >> What (if anything) does it mean that it tagged Watcher.processUpdate >> more than once? olsongt> I think that's what Armin means by a *specializing* compiler. olsongt> I believe it will compile multiple versions based on the olsongt> arguments going into a block of code. I don't think that's the case here. The types of the arguments to this particular method are always the same (self and a complex SWIG-wrapped beast). It's not like I'm passing in floats one time and ints the next. Skip From onurb at xiludom.gro Fri Jun 16 08:59:48 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 16 Jun 2006 14:59:48 +0200 Subject: a good programming text editor (not IDE) In-Reply-To: <_xgkg.2317$No6.48542@news.tufts.edu> References: <_xgkg.2317$No6.48542@news.tufts.edu> Message-ID: <4492ab45$0$13040$626a54ce@news.free.fr> John Salerno wrote: (snip) > Based on another thread, I tried out Scite, but no matter what I do it > doesn't seem to remember the window size and position, or any options I > choose (like showing line numbers). This is in the configuration files. Don't remember which and where, but I clearly remember having done this. > > And naturally there are Emacs and Vim, but I just don't know if I need > to invest *that* much time into learning one of them If you have a lot of file editing to do in a lot of various formats, then investing time on learning how to effectively use a powerful and extensible test editor is the WiseThingTodo(tm). > (probably Vim, > since I hear it's lighter and faster). It's a bit faster at startup, yes. Else, I'm not sure it makes a real difference wrt/ performances and power. It's more a matter of personal preference than anything else IMHO. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From jo at durchholz.org Wed Jun 21 07:10:55 2006 From: jo at durchholz.org (Joachim Durchholz) Date: Wed, 21 Jun 2006 13:10:55 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> Message-ID: Matthias Blume schrieb: > Joachim Durchholz writes: > >> Matthias Blume schrieb: >>> Perhaps better: A language is statically typed if its definition >>> includes (or ever better: is based on) a static type system, i.e., a >>> static semantics with typing judgments derivable by typing rules. >>> Usually typing judgmets associate program phrases ("expressions") with >>> types given a typing environment. >> This is defining a single term ("statically typed") using three >> undefined terms ("typing judgements", "typing rules", "typing >> environment"). > > This was not meant to be a rigorous definition. Rigorous or not, introducing additional undefined terms doesn't help with explaining a term. > Also, I'm not going to repeat the textbook definitions for those > three standard terms here. These terms certainly aren't standard for Perl, Python, Java, or Lisp, and they aren't even standard for topics covered on comp.lang.functional (which includes dynamically-typed languages after all). Regards, Jo From faik at pardus.org.tr Thu Jun 15 08:49:59 2006 From: faik at pardus.org.tr (Faik Uygur) Date: Thu, 15 Jun 2006 15:49:59 +0300 Subject: umask option for tarfile extract In-Reply-To: References: <200606151442.13111.faik@pardus.org.tr> Message-ID: <200606151549.59881.faik@pardus.org.tr> Per?embe 15 Haziran 2006 15:20 tarihinde, Fredrik Lundh ?unlar? yazm??t?: > Faik Uygur wrote: > > While extracting a tar file, is there a way to give an umask option for > > creating the non-existing upper directories of the file within the tar > > archive. > > os.umask Nope, this will not help. tarfile.py changes the mode after creating the missing directory. So whatever it is, it changes that to 0777. - Faik From roman.yakovenko at gmail.com Tue Jun 6 08:02:07 2006 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Tue, 6 Jun 2006 15:02:07 +0300 Subject: Distutils: setup script for binary files Message-ID: <7465b6170606060502g74cba971ua41241e8e3a1acdd@mail.gmail.com> Hi. I want to create setup script, that will install compiled extension module plus few binaries the extension module depends on. For example: I have package X: X: __init__.py _x_.dll ( or so ) some other dll's ( so's ) _x_.dll depends on. I took a look on Python documentation, http://docs.python.org/dist/describing-extensions.html, but it only describes how to create setup script for extension module from source files. I think, I can treat _x_.dll as it was regular Python script. My problem is, that on Linux I should put "some other so's" in some directory, program loader can find. How can I do this? Any help is appreciated. Thanks -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ From duncanm255 at hotmail.com Mon Jun 5 11:32:10 2006 From: duncanm255 at hotmail.com (D) Date: 5 Jun 2006 08:32:10 -0700 Subject: Starting New Process In-Reply-To: <1149189887.279693.146240@f6g2000cwb.googlegroups.com> References: <1149172463.881528.131290@j55g2000cwa.googlegroups.com> <1149185284.820789.321130@y43g2000cwc.googlegroups.com> <1149189887.279693.146240@f6g2000cwb.googlegroups.com> Message-ID: <1149521530.000954.101520@c74g2000cwc.googlegroups.com> Sorry to bring it back up, but is there a way to spawn the process without Twisted? From fredrik at pythonware.com Mon Jun 26 02:52:01 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 26 Jun 2006 08:52:01 +0200 Subject: Interactive debugging In-Reply-To: <1151296785.275841.294080@y41g2000cwy.googlegroups.com> References: <1151296785.275841.294080@y41g2000cwy.googlegroups.com> Message-ID: 63q2o4i02 at sneakemail.com wrote: > Hi, is there a way in python to place some sort of keyboard() type > statement which stops the script and puts you back at the console? see the third example on this page: http://effbot.org/librarybook/code.htm From sjmachin at lexicon.net Mon Jun 5 08:51:45 2006 From: sjmachin at lexicon.net (John Machin) Date: Mon, 05 Jun 2006 22:51:45 +1000 Subject: re beginner In-Reply-To: <4483f42e$0$5594$626a54ce@news.free.fr> References: <44834d62$0$6192$626a54ce@news.free.fr> <4483665A.206@lexicon.net> <4483f42e$0$5594$626a54ce@news.free.fr> Message-ID: <448428E1.9060803@lexicon.net> On 5/06/2006 10:30 PM, Bruno Desthuilliers wrote: > John Machin a ?crit : >> On 5/06/2006 10:38 AM, Bruno Desthuilliers wrote: >> >>> SuperHik a ?crit : >>> >>>> hi all, >>>> > (snip) > >>>> I have an old(er) script with the following task - takes a string I >>>> copy-pasted and wich always has the same format: >>>> > (snip) > >>> >>> def to_dict(items): >>> items = items.replace('\t', '\n').split('\n') >> >> >> In case there are leading/trailing spaces on the keys: > > There aren't. Test passes. > > (snip) > >> Fantastic -- at least for the OP's carefully copied-and-pasted input. > > That was the spec, and my code passes the test. > >> Meanwhile back in the real world, > > The "real world" is mostly defined by customer's test set (is that the > correct translation for "jeu d'essai" ?). Code passes the test. period. "Jeu d'essai" could be construed as "toss a coin" -- yup, that fits some user test sets I've seen. In the real world, you are lucky to get a test set that covers all the user-expected "good" cases. They have to be driven with whips to think about the "bad" cases. Never come across a problem caused by "FOO " != "FOO"? You *have* lead a charmed life, so far. > >> there might be problems with multiple tabs used for 'prettiness' >> instead of 1 tab, non-integer values, etc etc. > > Which means that the spec and the customer's test set is wrong. Not my > responsability. That's what you think. The users, the pointy-haired boss, and the evil HR director may have other ideas :-) > Any way, I refuse to change anything in the parsing > algorithm before having another test set. > >> In that case a loop approach that validated as it went and was able to >> report the position and contents of any invalid input might be better. > > One doesn't know what *will* be better without actual facts. You can be > right (and, from my experience, you probably are !-), *but* you can be > wrong as well. Until you have a correct spec and test data set on which > the code fails, writing any other code is a waste of time. Better to > work on other parts of the system, and come back on this if and when the > need arise. Unfortunately one is likely to be told in a Sunday 03:00 phone call that the "test data set on which the code fails" is somewhere in the production database :-( Cheers, John From sreeram at tachyontech.net Thu Jun 8 23:09:47 2006 From: sreeram at tachyontech.net (K.S.Sreeram) Date: Fri, 09 Jun 2006 08:39:47 +0530 Subject: capture video from camera In-Reply-To: <1149803564.942255.244570@i40g2000cwc.googlegroups.com> References: <1149598946.182874.121650@c74g2000cwc.googlegroups.com> <1149603488.012417.269760@j55g2000cwa.googlegroups.com> <1149618799.409008.33060@h76g2000cwa.googlegroups.com> <1149686461.261815.81670@i39g2000cwa.googlegroups.com> <1149803564.942255.244570@i40g2000cwc.googlegroups.com> Message-ID: <4488E67B.2020209@tachyontech.net> dan wrote: > I hope you won't be deterred from posting further questions to the > group by Fredrik's somewhat terse and unfriendly reply. > > comp.lang.python is a forum generally noted for its pleasing admixture > of erudition and encouragement. Fredrik is uncommonly distinguished in > the scope and depth of his knowledge. He does himself, and the group in > general, an injustice by the intolerance of his response. People need to learn to be precise and to-the-point in their posts. If not, its a waste of time for a lot of people.. more so for frequent contributors like fredrik. I hope criticism like yours does not deter him! -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 260 bytes Desc: OpenPGP digital signature URL: From claird at lairds.us Thu Jun 22 16:53:37 2006 From: claird at lairds.us (Cameron Laird) Date: Thu, 22 Jun 2006 20:53:37 +0000 Subject: Network Programming in Python References: <1151002934.586359.174540@m73g2000cwd.googlegroups.com> <1151006542.682915.83500@c74g2000cwc.googlegroups.com> Message-ID: In article <1151006542.682915.83500 at c74g2000cwc.googlegroups.com>, wrote: >I have Python 2.4.2 on windows and Linux both. I got an import error. >how can we obtain the twisted libraries ? . . . Look for "Downloading" under . From arvind.mulay at gmail.com Thu Jun 29 05:29:11 2006 From: arvind.mulay at gmail.com (arvind) Date: 29 Jun 2006 02:29:11 -0700 Subject: Widget access Message-ID: <1151573351.708542.63070@m73g2000cwd.googlegroups.com> how to make the widgets defined inside the function available outside it without using OOPs concept? From martin at v.loewis.de Wed Jun 28 12:38:34 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 28 Jun 2006 18:38:34 +0200 Subject: String Question In-Reply-To: <1151508909.273667.270910@x69g2000cwx.googlegroups.com> References: <1151508909.273667.270910@x69g2000cwx.googlegroups.com> Message-ID: <44A2B08A.7050104@v.loewis.de> diffuser78 at gmail.com wrote: > mac_string = '001485e55503' (This is the mac address of a computer.) > Since the MAC adddress are hexadecimal, how should I go about it here. > > Please help, every help is appreciated. Thanks I could not quite understand what you are trying to achieve, but it appears that you want to convert a character strings of hexadecimal characters into a byte string with the same bytes. I recommend this: py> import binascii py> binascii.a2b_hex("001485e55503") '\x00\x14\x85\xe5U\x03' Of course, if the string is fixed, you could just as well use the result string (i.e. '\x00\x14\x85\xe5U\x03') directly. Regards, Martin From bdesth.quelquechose at free.quelquepart.fr Sun Jun 4 20:38:22 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 05 Jun 2006 02:38:22 +0200 Subject: re beginner In-Reply-To: References: Message-ID: <44834d62$0$6192$626a54ce@news.free.fr> SuperHik a ?crit : > hi all, > > I'm trying to understand regex for the first time, and it would be very > helpful to get an example. I have an old(er) script with the following > task - takes a string I copy-pasted and wich always has the same format: > > >>> print stuff > Yellow hat 2 Blue shirt 1 > White socks 4 Green pants 1 > Blue bag 4 Nice perfume 3 > Wrist watch 7 Mobile phone 4 > Wireless cord! 2 Building tools 3 > One for the money 7 Two for the show 4 > > >>> stuff > 'Yellow hat\t2\tBlue shirt\t1\nWhite socks\t4\tGreen pants\t1\nBlue > bag\t4\tNice perfume\t3\nWrist watch\t7\tMobile phone\t4\nWireless > cord!\t2\tBuilding tools\t3\nOne for the money\t7\tTwo for the show\t4' > > I want to put items from stuff into a dict like this: > >>> print mydict > {'Wireless cord!': 2, 'Green pants': 1, 'Blue shirt': 1, 'White socks': > 4, 'Mobile phone': 4, 'Two for the show': 4, 'One for the money': 7, > 'Blue bag': 4, 'Wrist watch': 7, 'Nice perfume': 3, 'Yellow hat': 2, > 'Building tools': 3} > > Here's how I did it: > >>> def putindict(items): > ... items = items.replace('\n', '\t') > ... items = items.split('\t') > ... d = {} > ... for x in xrange( len(items) ): > ... if not items[x].isdigit(): d[items[x]] = int(items[x+1]) > ... return d > >>> > >>> mydict = putindict(stuff) > > > I was wondering is there a better way to do it using re module? > perheps even avoiding this for loop? There are better ways. One of them avoids the for loop, and even the re module: def to_dict(items): items = items.replace('\t', '\n').split('\n') return dict(zip(items[::2], map(int, items[1::2]))) HTH From deets at nospam.web.de Sat Jun 24 20:22:17 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 25 Jun 2006 02:22:17 +0200 Subject: 2Qs In-Reply-To: References: Message-ID: <4g639jF1lnks9U1@uni-berlin.de> if x>10 and y>10 and z>10 and sum((x,y,z)): print "OK" Diez From Dennis.Benzinger at gmx.net Wed Jun 28 12:40:26 2006 From: Dennis.Benzinger at gmx.net (Dennis Benzinger) Date: Wed, 28 Jun 2006 18:40:26 +0200 Subject: Problem with sets and Unicode strings In-Reply-To: References: <44a17d05$1@news.uni-ulm.de> <44a19d55$2@news.uni-ulm.de> Message-ID: <44a2b101$1@news.uni-ulm.de> Serge Orlov wrote: > On 6/27/06, Dennis Benzinger wrote: >> Serge Orlov wrote: >> > On 6/27/06, Dennis Benzinger wrote: >> >> Hi! >> >> >> >> The following program in an UTF-8 encoded file: >> >> >> >> >> >> # -*- coding: UTF-8 -*- >> >> >> >> FIELDS = ("F?cher", ) >> >> FROZEN_FIELDS = frozenset(FIELDS) >> >> FIELDS_SET = set(FIELDS) >> >> >> >> print u"F?cher" in FROZEN_FIELDS >> >> print u"F?cher" in FIELDS_SET >> >> print u"F?cher" in FIELDS >> >> >> >> >> >> gives this output >> >> >> >> >> >> False >> >> False >> >> Traceback (most recent call last): >> >> File "test.py", line 9, in ? >> >> print u"F??cher" in FIELDS >> >> UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in >> position 1: >> >> ordinal not in range(128) >> >> >> >> >> >> Why do the first two print statements succeed and the third one fails >> >> with an exception? >> > >> > Actually all three statements fail to produce correct result. >> >> So this is a bug in Python? > > No. > >> > frozenset remove the exception? >> > >> > Because sets use hash algorithm to find matches, whereas the last >> > statement directly compares a unicode string with a byte string. Byte >> > strings can only contain ascii characters, that's why python raises an >> > exception. The problem is very easy to fix: use unicode strings for >> > all non-ascii strings. >> >> No, byte strings contain characters which are at least 8-bit wide >> . > > Yes, but later it's written that non-ascii characters do not have > universal meaning assigned to them. In other words if you put byte > 0xE4 into a bytes string all python knows about it is that it's *some* > character. If you put character U+00E4 into a unicode string python > knows it's a "latin small letter a with diaeresis". Trying to compare > *some* character with a specific character is obviously undefined. > [...] But says: Strings are compared lexicographically using the numeric equivalents (the result of the built-in function ord()) of their characters. Unicode and 8-bit strings are fully interoperable in this behavior. Doesn't this mean that Unicode and 8-bit strings can be compared and this comparison is well defined? (even if it's is not meaningful) Thanks for your anwsers, Dennis From a.schmolck at gmail.com Sat Jun 10 12:49:47 2006 From: a.schmolck at gmail.com (Alexander Schmolck) Date: 10 Jun 2006 17:49:47 +0100 Subject: Very newbie programming References: <448ae8ce_1@news.tm.net.my> Message-ID: TheSaint writes: > # Filling the c with the list of devices which are recorded to be mounted > > d = filter((lambda a: a[:2] =='/d'),mnt.readlines()) # non /dev-mounts are > off > d = map((lambda a: a.split()[:1]),d) # only the first info column is used Just focusing one one detail: 1. you don't need the parens around the lambda 2. you can just write the above as d = [a.split()[:1] for a in mnt if a.startswith('/d')] 'as From jjlee at reportlab.com Thu Jun 29 17:34:58 2006 From: jjlee at reportlab.com (John J. Lee) Date: Thu, 29 Jun 2006 21:34:58 GMT Subject: Passing a Cookie with httplib References: <12a5p6h9ug19818@corp.supernews.com> Message-ID: <87bqsbk5ml.fsf@reportlab.com> Grant Edwards writes: > On 2006-06-28, scott at bogusaddress.com wrote: > > > From a shell script, I have used /usr/bin/curl to access a web site > > and pass a cookie > > I use ClientCookie for that. > > http://wwwsearch.sourceforge.net/ClientCookie/ Note that ClientCookie has moved, to become part of mechanize (well, is moving -- mechanize is still in beta): > http://wwwsearch.sourceforge.net/ClientCookie/ mechanize exports a superset of the ClientCookie interface, so "import mechanize as ClientCookie" should be all you need to do to switch (modulo some trivial details, documented at the URL below). Also note that module cookielib in the Python 2.4 stdlib contains most of the functionality of ClientCookie (specifically, all the cookie handling code, of course). John From larry.bates at websafe.com Mon Jun 19 09:57:49 2006 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 19 Jun 2006 08:57:49 -0500 Subject: copyfile avoiding overwrites and race conditions In-Reply-To: <1150494450.684069.104490@h76g2000cwa.googlegroups.com> References: <1150494450.684069.104490@h76g2000cwa.googlegroups.com> Message-ID: <4496AD5D.1040309@websafe.com> manuelg at gmail.com wrote: > Here is a code fragment, where I am trying to copy a file, avoiding > overwrites and race conditions. The filename gets a '02','03','04' etc > appended to the end if a file with that name already exists. > > I know the writing of the single space is overkill, but I am surprised > I cannot find an example of this floating around the web and newsgroups > > my understanding of 'os.open' and 'os.fdopen' is minimal > > ## start fragment > > i = 0 > while True: > > if i >= 100: raise RanOutFileNamesError(fullpath) > i += 1 > > if i > 1: > name0 = '%s_%02i%s' % (suggested_name, i, file_extension) > else: > assert i == 1 > name0 = '%s%s' % (suggested_name, file_extension) > fullpath = os.path.join(path0, name0) > > # create dummy file, force overwrite > > try: > fd = os.open( > fullpath, > os.O_CREAT | os.O_EXCL | os.O_WRONLY) > except OSError: > continue > > # is this really necessary? > file = os.fdopen(fd, "w") > file.write(' ') > file.close() > > shutil.copyfile(original_filepath, fullpath) > > return fullpath > > ## end fragment > I guess my approach would be different. To eliminate any race conditions, I would keep a small text file that always contained the next filename that is to be written. Something like: nextfiletowrite=/path/filename006.dat I would try to get a lock on this file, read it, extract next filename, increment the counter portion of the filename, write it back out and unlock it. Now I have the name of the file to write that is unique to my instance and I can write it without worrying about other processes. Hope this helps. -Larry Bates From grflanagan at yahoo.co.uk Fri Jun 2 01:48:15 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 1 Jun 2006 22:48:15 -0700 Subject: grouping a flat list of number by range In-Reply-To: <1149226773.350717.271520@g10g2000cwb.googlegroups.com> References: <1149196642.001466.53990@c74g2000cwc.googlegroups.com> <1149226773.350717.271520@g10g2000cwb.googlegroups.com> Message-ID: <1149227295.288802.278990@i39g2000cwa.googlegroups.com> Gerard Flanagan wrote: > joh12005 at yahoo.fr wrote: > > hello, > > > > i'm looking for a way to have a list of number grouped by consecutive > > interval, after a search, for example : > > > > [3, 6, 7, 8, 12, 13, 15] > > > > => > > > > [[3, 4], [6,9], [12, 14], [15, 16]] > > > > (6, not following 3, so 3 => [3:4] ; 7, 8 following 6 so 6, 7, 8 => > > [6:9], and so on) > > > > i was able to to it without generators/yield but i think it could be > > better with them, may be do you an idea? > > > > best regards, > > > > a list comprehension/itertools version (this won't work with an empty > list): > > from itertools import groupby > > a = [3, 6, 7, 8, 12, 13, 15] > > result = [[3, 4], [6,9], [12, 14], [15, 16]] > > b = [ list(g)[0] for k,g in groupby(range(a[0],a[-1]+2), lambda x: > x in a)] > > c = [ b[i:i+2] for i in range(0,len(a),2) ] > > assert c == result > > > Gerard change len(a) to len(b) in case a has duplicates like [3,3,3,6,7,8,12,13,15] Gerard From ilias at lazaridis.com Sun Jun 4 08:11:06 2006 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Sun, 04 Jun 2006 15:11:06 +0300 Subject: HOST - dreamhost.com / Liberality (Hosting, Basic Requirement) Message-ID: <4482CDDA.9060905@lazaridis.com> crossposted to 5 groups, which are affected by this case. followup not applicable. - I am currently selecting a Hosting Provider / Project Host... http://case.lazaridis.com/multi/wiki/Host For this larger scale project... http://case.lazaridis.com/multi - An incident within usenet has reminded me to include a very Basic Requirement, which is "Terms of Service / Liberality". - The incident: http://xahlee.org/Periodic_dosage_dir/t2/harassment.html It _seems_ that Mr. Xah Les's account was terminated by dreamhost.com because of a) the inability of several people to detect the interconnections within writings which lead to perfectly valid cross-posts within the usenet. b) the non-liberal and essentially non-professional way of how dreamhost.com deals with abuse complaints. - The accusations of "dreamhost.com" are simply wrong. The behaviour of dreamhost.com looks like a case of "selective ruling", whilst using a right defined within the "Terms of Service" to terminate accounts essentially at free will. Can someone trust his business or even his private activities to a hosting company, which cancels accounts in such a way? I do not: http://case.lazaridis.com/multi/wiki/DreamhostAudit But possibly I am wrong, and all this is just a missunderstanding. - To dreamhost.com: You should install an autoresponder to your abuse email, which reminds people that it is * nearly inpossible to rate the content posted to usenet * neally inpossible to detect validity of cross-posts especially within complex analytical/philosophical writings * other important facts People can then decide if they still wish to send the abuse complain (e.g. can follow a link within the autoresponder). You should additionally make a clear statement, that you do _not_ have the right to cancel acounts _without_ any reason, and that you do _not_ intervene into a persons right to speek within the usenet, without a clear and undoubtable proof of abuse (e.g. court decision, or at least verfication of independend entities or mediators). Additionally, it would be gentle if your company would make a _public_ statement subjecting this case, thus any interested party can verify the validity of the statements. - To Mr. Xah Lee: You should change to a more liberal services provider, one which plays in the "Major League" and which respects free speech. Such a provider would just reject such ridiculous abuse complaints. If, for any reason, you are not able to switch to another hosting provider, please let me know. I will see what I can do for you to keep your free speech up. Additionally, I would like to suggest you to not invest too much time into all this. Better use this time to find people and to react in an organized manner. - To the complaining people: To which 'species' do you belong? http://lazaridis.com/core/eval/species.html Setting up an thread filter: http://lazaridis.com/core/eval/filter.html I have seldom seen a more ridiculous argumentation-line than then "spam/abuse" one. - To anyone: Any form of censorship and "suppression of freedom of expression" should be kept out of from open-source projects and from usenet. It is the within the responsibility of every entity (including commercial companies) to act against it. http://dev.lazaridis.com/base/wiki/LiberalProjectDefinition - - - . -- http://lazaridis.com From rpdooling at gmail.com Thu Jun 15 11:11:41 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 15 Jun 2006 08:11:41 -0700 Subject: Python in Windows ng References: <449131ab$0$10456$afc38c87@news.optusnet.com.au> Message-ID: <1150384301.362722.309330@c74g2000cwc.googlegroups.com> >> newsgroup for running/programming Python on Windows One of Python's many virtues is its portability. Separate newsgroups aren't needed. If you would like a nice summary of the potential glitches and gotchas using Python on Windows, try the Alan Gauld tutorial. It's a frames page, so I can't deep link for you, but go to "Handling Files" then scroll down the page to "Some Operating System Gotchas" http://www.freenetpages.co.uk/hp/alan.gauld/ rd From pc at p-cos.net Tue Jun 27 16:59:47 2006 From: pc at p-cos.net (Pascal Costanza) Date: Tue, 27 Jun 2006 22:59:47 +0200 Subject: What is a type error? In-Reply-To: <1151374704.304776.60630@u72g2000cwu.googlegroups.com> References: <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <7i3mg.204167$8W1.155367@fe1.news.blueyonder.co.uk> <44992e6c$2$664$bed64819@news.gradwell.net> <%Igmg.464974$xt.353729@fe3.news.blueyonder.co.uk> <4fv0v3F1kipa6U1@individual.net> <4gakhiF1m698cU1@individual.net> <1151374704.304776.60630@u72g2000cwu.googlegroups.com> Message-ID: <4gdki2F1ldalhU2@individual.net> Marshall wrote: > Pascal Costanza wrote: >> Consider division by zero: appropriate arguments for division are >> numbers, including the zero. > > A bold assertion! > > The general question is, what do we do about partial functions? > > >> The dynamic type check will typically not >> check whether the second argument is zero, but will count on the fact >> that the processor will raise an exception one level deeper. > > This is an implementation artifact, and hence not relevant to our > understanding of the issue. No, it's not. I am pretty sure that you can model this formally. Pascal -- 3rd European Lisp Workshop July 3 - Nantes, France - co-located with ECOOP 2006 http://lisp-ecoop06.bknr.net/ From sjmachin at lexicon.net Mon Jun 5 08:13:00 2006 From: sjmachin at lexicon.net (John Machin) Date: Mon, 05 Jun 2006 22:13:00 +1000 Subject: re beginner In-Reply-To: References: <44834d62$0$6192$626a54ce@news.free.fr> <4483665A.206@lexicon.net> Message-ID: <44841FCC.7040302@lexicon.net> On 5/06/2006 7:47 PM, Fredrik Lundh wrote: > John Machin wrote: > >> Fantastic -- at least for the OP's carefully copied-and-pasted input. >> Meanwhile back in the real world, there might be problems with >> multiple tabs used for 'prettiness' instead of 1 tab, non-integer >> values, etc etc. > > yeah, that's probably why the OP stated "which always has the same format". > Such statements by users are in the the same category as "The cheque is in the mail" and "Of course I'll still love you in the morning". From nmm1 at cus.cam.ac.uk Thu Jun 29 13:45:17 2006 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 29 Jun 2006 17:45:17 GMT Subject: Bug reporting impossible References: Message-ID: In article , Fredrik Lundh writes: |> Nick Maclaren wrote: |> |> > It's definitely worth fixing, but not as a high priority. Invoking a |> > file spuriously is potentially serious, with very low probability. |> |> the traceback printer is reading the file (using a very robust reader), |> it's not "invoking" it. Boggle! Upon checking, that is indeed the case. All right - that drops the importance of the bug another notch. It's still an issue on systems with 'active' files, but that makes the chances of serious trouble even less likely than before. Regards, Nick Maclaren. From samaloth at gmail.com Mon Jun 19 22:37:09 2006 From: samaloth at gmail.com (Saint Malo) Date: 19 Jun 2006 19:37:09 -0700 Subject: Newbie Question In-Reply-To: <1150767801.754519.165440@y41g2000cwy.googlegroups.com> References: <1150750938.973049.114780@y41g2000cwy.googlegroups.com> <129e55eahc35f00@corp.supernews.com> <1150753085.332654.283270@f6g2000cwb.googlegroups.com> <1150767309.831092.188530@h76g2000cwa.googlegroups.com> <1150767801.754519.165440@y41g2000cwy.googlegroups.com> Message-ID: <1150771029.756430.19960@p79g2000cwp.googlegroups.com> BTW my program isn't about red blue yellow etc. I'm just using it as an example. I guess i didn't asked the question correctly or am not expressing myself correctly. Let me try one more. Ok. Contents of text file follow: red blue purble yellow blue green Now lets imagine i wrote some code to look for the word red. Once the program has found red i want it to print something like the following line. If you add red and blue you obtain the color purple... How do i turn each color in the line into a separate string? Now is that possible? placid wrote: > BartlebyScrivener wrote: > > Saint Malo wrote: > > > If the program searches for blue, i just want it to print blue > > > > Huh? Tell it to print whatever you want. > > > > for line in file: > > if 'blue' in line: > > print 'blue' > > > > for line in file: > > if 'brown' in line: > > print 'brown' > > > > for line in file: > > if 'red' in line: > > print 'weasels rip my flesh' > > wow Dude, this is not efficient at all! You only need to read the file > once not as many times as there are words in your looking for in the > lines of the file From hauck at gseos.com Mon Jun 26 19:46:19 2006 From: hauck at gseos.com (Tommytrojan) Date: Mon, 26 Jun 2006 16:46:19 -0700 Subject: How do I limit access to objects in Python? Message-ID: Hi, I have an application that embeds the Python interpreter. My users have access to the interpreter through a console like window and they can run Python scripts. For my application I use some Python modules (say module Restricted) that I don't want to give my users access to. However, the modules that I make public to my users and that I want my users to be able to use themselves use the Restricted module. Any suggestions on how to solve this? I was thinking of instantiating a separate interpreter but I don't think this will solve my problem. Thanks, Thomas From george.sakkis at gmail.com Fri Jun 23 09:27:56 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 23 Jun 2006 06:27:56 -0700 Subject: Flight search automation Message-ID: <1151069276.861472.292270@r2g2000cwb.googlegroups.com> I'm trying to use mechanize to fill in a "find a flight" form and then get back the results, but I'm not sure how to make it wait until the results page appears; the response after submitting the form is the "please wait while we are searching for your flights" page. Any ideas ? George From ptmcg at austin.rr._bogus_.com Sun Jun 4 20:07:56 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Mon, 05 Jun 2006 00:07:56 GMT Subject: re beginner References: <44834d62$0$6192$626a54ce@news.free.fr> <4483665A.206@lexicon.net> Message-ID: "John Machin" wrote in message news:4483665A.206 at lexicon.net... > Fantastic -- at least for the OP's carefully copied-and-pasted input. > Meanwhile back in the real world, there might be problems with multiple > tabs used for 'prettiness' instead of 1 tab, non-integer values, etc etc. > In that case a loop approach that validated as it went and was able to > report the position and contents of any invalid input might be better. Yeah, for that you'd need more like a real parser... hey, wait a minute! What about pyparsing?! Here's a pyparsing version. The definition of the parsing patterns takes little more than the re definition does - the bulk of the rest of the code is parsing/scanning the input and reporting the results. The pyparsing home page is at http://pyparsing.wikispaces.com. -- Paul stuff = 'Yellow hat\t2\tBlue shirt\t1\nWhite socks\t4\tGreen pants\t1\nBlue bag\t4\tNice perfume\t3\nWrist watch\t7\tMobile phone\t4\nWireless cord!\t2\tBuilding tools\t3\nOne for the money\t7\tTwo for the show\t4' print "Original input string:" print stuff print from pyparsing import * # define low-level elements for parsing itemWord = Word(alphas, alphanums+".!?") itemDesc = OneOrMore(itemWord) integer = Word(nums) # add parse action to itemDesc to merge separate words into single string itemDesc.setParseAction( lambda s,l,t: " ".join(t) ) # define macro element for an entry entry = itemDesc.setResultsName("item") + integer.setResultsName("qty") # scan through input string for entry's, print out their named fields print "Results when scanning for entries:" for t,s,e in entry.scanString(stuff): print t.item,t.qty print # parse entire string, building ParseResults with dict-like access results = dictOf( itemDesc, integer ).parseString(stuff) print "Results when parsing entries as a dict:" print "Keys:", results.keys() for item in results.items(): print item for k in results.keys(): print k,"=", results[k] prints: Original input string: Yellow hat 2 Blue shirt 1 White socks 4 Green pants 1 Blue bag 4 Nice perfume 3 Wrist watch 7 Mobile phone 4 Wireless cord! 2 Building tools 3 One for the money 7 Two for the show 4 Results when scanning for entries: Yellow hat 2 Blue shirt 1 White socks 4 Green pants 1 Blue bag 4 Nice perfume 3 Wrist watch 7 Mobile phone 4 Wireless cord! 2 Building tools 3 One for the money 7 Two for the show 4 Results when parsing entries as a dict: Keys: ['Wireless cord!', 'Green pants', 'Blue shirt', 'White socks', 'Mobile phone', 'Two for the show', 'One for the money', 'Blue bag', 'Wrist watch', 'Nice perfume', 'Yellow hat', 'Building tools'] ('Wireless cord!', '2') ('Green pants', '1') ('Blue shirt', '1') ('White socks', '4') ('Mobile phone', '4') ('Two for the show', '4') ('One for the money', '7') ('Blue bag', '4') ('Wrist watch', '7') ('Nice perfume', '3') ('Yellow hat', '2') ('Building tools', '3') Wireless cord! = 2 Green pants = 1 Blue shirt = 1 White socks = 4 Mobile phone = 4 Two for the show = 4 One for the money = 7 Blue bag = 4 Wrist watch = 7 Nice perfume = 3 Yellow hat = 2 Building tools = 3 From greg.ewing at canterbury.ac.nz Wed Jun 28 19:52:25 2006 From: greg.ewing at canterbury.ac.nz (Greg Ewing) Date: Thu, 29 Jun 2006 11:52:25 +1200 Subject: [Pyrex] pyrex functions to replace a method (Re: replace a method in class: how?) In-Reply-To: <44A261CF.4000309@bryant.edu> References: <44A06A6B.6010200@bryant.edu> <44A11564.9030009@bryant.edu> <44A1C5C7.4090007@canterbury.ac.nz> <44A261CF.4000309@bryant.edu> Message-ID: <44A31639.6010709@canterbury.ac.nz> Brian Blais wrote: > TypeError: unbound method pyrex_update_within_class() must be called > with update_funcs instance as first argument (got str instance instead) Hm. Okay, so that doesn't work either. But I just tried the following, and it seems to work: import new class C(str): pass C.ord = new.instancemethod(ord, None, C) c = C("a") print c.ord() -- Greg From JJLaRocque at gmail.com Wed Jun 21 10:54:08 2006 From: JJLaRocque at gmail.com (JJLaRocque at gmail.com) Date: 21 Jun 2006 07:54:08 -0700 Subject: returning index of minimum in a list of lists Message-ID: <1150901648.832039.165590@b68g2000cwa.googlegroups.com> Hi all, Is there a simple python function to return the list index of the minimum entry in a list of lists? ie, for [[3,3,3,3], [3,3,3,1], [3,3,3,3]] to return 2,4. Or, same question but just for a list of numbers, not a list of lists. Thanks, Josh From bdesth.quelquechose at free.quelquepart.fr Thu Jun 22 19:45:10 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 23 Jun 2006 01:45:10 +0200 Subject: Specifing arguments type for a function In-Reply-To: <1150804645.542646.38570@g10g2000cwb.googlegroups.com> References: <200606201328.02784.maric@aristote.info> <1150804645.542646.38570@g10g2000cwb.googlegroups.com> Message-ID: <449afb64$0$16558$636a55ce@news.free.fr> George Sakkis a ?crit : > Maric Michaud wrote: > > >>Le Mardi 20 Juin 2006 13:28, Maric Michaud a ?crit : >> >>>if not getattr(arg, '__iter__') and not getattr(arg, '__getitem__') : >>> raise ValueError('Function accepts only iterables') # or error handling >>>code >> >>oops, hasattr of course : >> >>if not hasattr(arg, '__iter__') and not hasattr(arg, '__getitem__') : >> raise ValueError('Function accepts only iterables') # or error handling > > > This is ok - in theory. In practice I've found that e.g. strings are > more often than not handled as scalars although they are typically > iterables. >>> hasattr('', '__iter__') False > Also tuples may or may not be considered as iterables, > depending on what they are used for. >>> hasattr((), '__setitem__') False >>> hasattr('', '__setitem__') False > The definition of scalar is > application-dependent, that's why there is not an isscalar() builtin. From frank at chagford.com Wed Jun 14 02:50:50 2006 From: frank at chagford.com (Frank Millman) Date: 13 Jun 2006 23:50:50 -0700 Subject: "groupby" is brilliant! In-Reply-To: References: <1150180151.643245.148210@y43g2000cwc.googlegroups.com> Message-ID: <1150267850.745328.281240@i40g2000cwc.googlegroups.com> Benji York wrote: > Frank Millman wrote: > > reader = csv.reader(open('trans.csv', 'rb')) > > rows = [] > > for row in reader: > > rows.append(row) > > Why do you create a list of rows instead of just iterating over the > reader directly? > -- > Benji York A - didn't think of it - good idea B - can't always do it - B1 - if the file is not sorted, I have to sort the rows first B2 - if I need to update the file, I can modify the rows in place, and then call csv.writer(open('trans.csv','wb')).writerows(rows) BTW, I know that B2 is simplistic - to be safe I should rename, then write, then unlink. I will do that for production code. BTW2, an alternative to B2 is reader = csv.reader(open('trans.csv', 'rb')) newtrans = open('newtrans.csv','wb') writer = csv.writer(newtrans) for row in reader: [process and modify row] writer.writerow(row) newtrans.close() [unlink and rename] Could be useful if the file is large. Food for thought. Thanks Frank From johnjsal at NOSPAMgmail.com Fri Jun 30 13:39:08 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 30 Jun 2006 17:39:08 GMT Subject: Chapter 9 Tutorial for Classes Not Working In-Reply-To: <1151681635.648736.35170@i40g2000cwc.googlegroups.com> References: <1151681635.648736.35170@i40g2000cwc.googlegroups.com> Message-ID: <0ldpg.2384$No6.49378@news.tufts.edu> tac-tics wrote: >> x = MyClass >> xf = x.f >> while True: >> print xf() > > Python has some VERY nasty gotchas concerning parenthesis (or lack > there of). Is this really a gotcha? I don't think you should blame Python for this mistake. Even a novice programmer like myself can intuitively understand that parentheses are needed. And while this *is* something unique to Python (or maybe unique to dynamic languages in general?), the actual usage of parentheses is consistent with other programming languages, so Python or not, it should just make sense to write x = MyClass() instead of x = MyClass From marshall.spight at gmail.com Mon Jun 19 16:41:10 2006 From: marshall.spight at gmail.com (Marshall) Date: 19 Jun 2006 13:41:10 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> Message-ID: <1150749670.053433.242210@p79g2000cwp.googlegroups.com> Chris Smith wrote: > > Basically, I start objecting when someone starts comparing "statically > typed" and "dynamically typed" as if they were both varieties of some > general concept called "typed". They aren't. Furthermore, these two > phrases were invented under the misconception that that are. If you > mean something else by types, such as the idea that a value has a tag > indicating its range of possible values, then I tend to think it would > be less confusing to just say "type" and then clarify the meaning it > comes into doubt, rather than adopting language that implies that those > types are somehow related to types from type theory. While I am quite sympathetic to this point, I have to say that this horse left the barn quite some time ago. Marshall PS. Hi Chris! From brian at sweetapp.com Sat Jun 3 02:11:44 2006 From: brian at sweetapp.com (Brian Quinlan) Date: Sat, 03 Jun 2006 08:11:44 +0200 Subject: Sampling a population In-Reply-To: References: <44805F53.6090409@sweetapp.com> Message-ID: <44812820.8080205@sweetapp.com> Robert Kern wrote: > [numpy implementation snipped] > Ed Schofield has an implementation of an algorithm by Marsaglia[1] which turns > sampling into a fast table lookup. If your probabilities have limited precision > (2**-30 or so rather than the full double precision 2**-52 or so), then this > might be an attractive option. > > [1] http://www.jstatsoft.org/v11/i03/v11i03.pdf > Thanks a lot for the numpy implementation and for the literature reference! I'll try to figure out how little precision I need in my sampling. Cheers, Brian From iainking at gmail.com Wed Jun 7 06:22:03 2006 From: iainking at gmail.com (Iain King) Date: 7 Jun 2006 03:22:03 -0700 Subject: Bug in list comprehensions? Message-ID: <1149675723.118917.276940@j55g2000cwa.googlegroups.com> I was playing with list comprehensions, to try and work out how doubled up versions work (like this one from another thread: [i for i in range(9) for j in range(i)]). I think I've figured that out, but I found something strange along the way: >>> alpha = ["one", "two", "three"] >>> beta = ["A", "B", "C"] >>> [x for x in alpha for y in beta] ['one', 'one', 'one', 'two', 'two', 'two', 'three', 'three', 'three'] >>> [x for x in y for y in beta] ['C', 'C', 'C'] >>> beta = [alpha, alpha, alpha] >>> beta [['one', 'two', 'three'], ['one', 'two', 'three'], ['one', 'two', 'three']] >>> [x for x in y for y in beta] ['C', 'C', 'C'] >>> [y for y in beta] [['one', 'two', 'three'], ['one', 'two', 'three'], ['one', 'two', 'three']] >>> [x for x in y for y in beta] ['one', 'one', 'one', 'two', 'two', 'two', 'three', 'three', 'three'] Shoudn't both lines '[x for x in y for y in beta]' produce the same list? I'm guessing I'm the one confused here... but I'm confused! What's going on? Iain From steven.bethard at gmail.com Wed Jun 7 00:19:42 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 6 Jun 2006 22:19:42 -0600 Subject: python-dev Summary for 2006-04-01 through 2006-04-15 Message-ID: python-dev Summary for 2006-04-01 through 2006-04-15 ++++++++++++++++++++++++++++++++++++++++++++++++++++ .. contents:: [The HTML version of this Summary is available at http://www.python.org/dev/summary/2006-04-01_2006-04-15] ============= Announcements ============= --------------------- Python 2.5a1 Released --------------------- Python 2.5 alpha 1 was released on April 5th. Please download it and try it out, particularly if you are an extension writer or you embed Python -- you may want to change things to support 64-bit sequences, and if you have been using mismatched PyMem_* and PyObject_* allocation calls, you will need to fix these as well. Contributing threads: - `TRUNK FREEZE. 2.5a1, 00:00 UTC, Wednesday 5th of April. `__ - `outstanding items for 2.5 `__ - `chilling svn for 2.5a1 `__ - `Reminder: TRUNK FREEZE. 2.5a1, 00:00 UTC, Wednesday 5th of April. `__ - `RELEASED Python 2.5 (alpha 1) `__ - `TRUNK is UNFROZEN `__ - `segfault (double free?) when '''-string crosses line `__ - `pdb segfaults in 2.5 trunk? `__ - `IMPORTANT 2.5 API changes for C Extension Modules and Embedders `__ ---------------------- Contributor agreements ---------------------- If you're listed in the `Python acknowledgments`_, and you haven't signed a `contributor agreement`_, please submit one as soon as possible. Note that this includes even the folks that have been around forever -- the PSF would like to be as careful as possible on this one. .. _Python acknowledgments: http://svn.python.org/projects/python/trunk/Misc/ACKS .. _contributor agreement: http://www.python.org/psf/contrib-form-python.html Contributing threads: - `PSF Contributor Agreement for pysqlite `__ --------------------------- Firefox Python bug searches --------------------------- Anthony Baxter has created a `Firefox searchbar`_ for finding Python bugs by their SourceForge IDs. There are also two Firefox sidebar options: `Mark Hammond's`_ and `Daniel Lundin's`_. .. _Firefox searchbar: http://www.python.org/~anthony/searchbar/ .. _Mark Hammond's: http://starship.python.net/~skippy/mozilla/ .. _Daniel Lundin's: http://projects.edgewall.com/python-sidebar/ Contributing thread: - `Firefox searchbar engine for Python bugs `__ ------------------------------------------------- Building Python with the free MS Toolkit compiler ------------------------------------------------- Paul Moore documented how to build Python on Windows with the free MS Toolkit C++ compiler `on the wiki`_. The most up-to-date version of these instructions is in `PCbuild/readme.txt`_. .. _on the wiki: http://wiki.python.org/moin/Building_Python_with_the_free_MS_C_Toolkit .. _PCbuild/readme.txt: http://svn.python.org/projects/python/trunk/PCbuild/readme.txt Contributing thread: - `Building Python with the free MS Toolkit compiler `__ ---------------------------------------------- Please login to the wiki when you make changes ---------------------------------------------- Skip Montanaro has requested that anyone posting to the wiki sign in first, as this makes things easier for those monitoring changes to the wiki. When you're logged in, your changes appear with your name, and so can be immediately recognized as not being wiki-spam. Contributing thread: - `Suggestion: Please login to wiki when you make changes `__ --------------------------- Checking an older blamelist --------------------------- While the buildbot blamelist may scroll off the `main page`_ in a matter of hours, you can still see the blamelist for a particular revision by checking a particular build number, e.g. to see build 800 of the trunk on the G4 OSX, you could check http://www.python.org/dev/buildbot/trunk/g4%20osx.4%20trunk/builds/800. .. _main page: http://www.python.org/dev/buildbot/all/ Contributing threads: - `Preserving the blamelist `__ - `TODO Wiki (was: Preserving the blamelist) `__ ========= Summaries ========= ------------------------- Garbage collection issues ------------------------- One of the problems with garbage-collecting generators (now that they have a __del__ method) was that GC normally assumes that because the *type* has a __del__ method, the *instance* needs finalization. Many generator instances may not need finalization even though their type has a __del__ slot, so generators have been special-cased in the garbage-collection code so that GC can sometimes tell that a generator does not need its finalizer called. As a side note, Tim Peters pointed out that if you're worried about cyclic-gc and __del__ methods, one of the ways to avoid problems is to remove the __del__ method from the object you think might be included in a cycle, and add an attribute to that object that holds a "closing" object with a __del__ method that simply closes all your resources. Since your main object won't have a __del__, it will be easily collected, which should make the closing object collectable too. Contributing threads: - `reference leaks, __del__, and annotations `__ - `reference leaks, __del__, and annotations `__ - `Debugging opportunity :-) `__ ------------------ ElementTree naming ------------------ The elementtree package was included in Python 2.5 as xml.etree. There were some complaints about the naming schemes (which aren't quite `PEP 8`_-compliant) but changing these while elementtree is still distributed as a standalone package seemed like a bad idea. People generally felt that style-motivated renamings should all wait until Python 3000. .. _PEP 8: http://www.python.org/dev/peps/pep-0008/ Contributing thread: - `elementtree in stdlib `__ ----------------------------- Externally maintained modules ----------------------------- Brett Cannon was putting together a PEP for externally maintained code in the stdlib (e.g. ctypes and pysqlite). The PEP will list all modules and packages within the stdlib that are maintained externally, as well as the contact info for their maintainers and the locations where bugs and patches should be reported. At the time of this summary, he had not yet been assigned a PEP number. Contributing threads: - `PEP to list externally maintained modules and where to report bugs? `__ - `need info for externally maintained modules PEP `__ -------------------------------------- String prefix for internationalization -------------------------------------- Martin Blais proposed an ``i`` prefix for internationalized strings to get rid of the ``_()`` required by pygettext. This would allow pygettext to more easily identify internationalized strings, and reduce the number of parentheses necessary in internationalized code. However, it would only have saved two key-strokes, it would have required the introduction of ``iu`` and ``ir`` prefixes, and it would have forced some rewriting of the tools that currently do string extraction using ``_()``, so the idea was rejected. Contributing thread: - `The "i" string-prefix: I18n'ed strings `__ --------------------------- PEP 359: The make statement --------------------------- Steven Bethard introduced a PEP for the make statement which would have made the statement:: make : syntactic sugar for:: class : __metaclass__ = The goal was to allow the creation of non-class objects from a namespace without requiring a misleading ``class`` statement and ``__metaclass__`` hook. With appropriately defined objects, the make statement would have supported syntax like:: make block_property x: '''The x of the frobulation''' def fget(self): ... def fset(self): ... make Schema registration: make String name: max_length = 100 not_empty = True make PostalCode postal_code: not_empty = True make Int age: min = 18 In current Python these would have to be created using class statements which misleadingly created objects that were not classes. Responses were mixed, and the discussion continued on into the next fortnight. .. _PEP 359: http://www.python.org/dev/peps/pep-0359/ Contributing thread: - `PEP 359: The "make" Statement `__ --------------------------------------------- Formatting exceptions with their module names --------------------------------------------- Georg Brandl checked in a patch to make traceback.format_exception_only() prepend the exception's module name in the same way the interpreter does. This caused a number of doctests to fail because the exception module names were not included. After some discussion, it seemed like people agreed that even though some doctests would be broken, it was more important to have the interpreter and traceback.format_exception_only() produce the same output. Contributing thread: - `[Python-checkins] r45321 - in python/trunk: Lib/test/test_traceback.py Lib/traceback.py Misc/NEWS `__ ------------------- Benchmarking python ------------------- Benji York and a few others ran Python 2.5a1 through pystone and found it mostly comparable to 2.4.2. However, Raymond Hettinger pointed out that pystone isn't really an appropriate benchmark for comparing across versions -- it's intended more for comparing across architectures and compilers. Contributing threads: - `2.5a1 Performance `__ - `Buildbot slave locks (Was: 2.5a1 Performance) `__ ------------------------------------------------------ PySocketSockObject, socketmodule.c, _ssl.c and Windows ------------------------------------------------------ Tim Peters noticed that on Windows, socketmodule.c and _ssl.c disagreed about the offset of the ``sock_timeout`` member of a ``PySocketSockObject``. Turns out that since _socket was built by a .vcproj but _ssl was built by _ssl.mak (which had forgotten to define WIN32), doubles were aligned to an 8-byte boundary when socketmodule.c was compiled but a 4-byte boundary when _ssl was compiled. Contributing thread: - `Who understands _ssl.c on Windows? `__ ------------------------------ Getting a dictionary of counts ------------------------------ Alex Martelli proposed adding a ``tally()`` function to the collections module which would count the number of each value in an iterable and produce a dictionary. So for example:: tally('abacaab') == {'a': 4, 'c': 1, 'b': 2} People generally thought the function would be useful, but there was some discussion as to whether or not it would be better to provide a collections.bag object instead. The discussion fizzled out without any patches being produced. Contributing thread: - `tally (and other accumulators) `__ ------------------------ Building Python with C++ ------------------------ Anthony Baxter has donated some of his recent time to getting Python to compile with g++. He got Python core to compile correctly, but there were lots of errors in the Modules code that wasn't C++ safe. If you'd like to help Anthony out and fix some bugs, try it yourself using ``CC=g++ ./configure --with-cxx=g++`` Contributing thread: - `building with C++ `__ ---------------------- Adding PEP 302 support ---------------------- Phillip J. Eby has been working on adding `PEP 302`_ import loader support to the necessary modules around Python. In the process, he noticed that both runpy and test.test_importhooks reimplement the base `PEP 302`_ algorithm, and suggested adding functions to pkgutil that would allow such modules to all share the same code for this kind of thing. The code appears to have been checked in, but docs do not appear to be available yet. .. _PEP 302: http://www.python.org/dev/peps/pep-0359/ Contributing threads: - `PEP 302 support for traceback, inspect, site, warnings, doctest, and linecache `__ - `Proposal: expose PEP 302 facilities via 'imp' and 'pkgutil' `__ - `PEP 302 support for pydoc, runpy, etc. `__ ----------------------------------------- Having Python use dlopen() on Darwin/OS X ----------------------------------------- Zachary Pincus asked about using the normal code path for Unix-like systems through dlopen() for Darwin/OS X instead of the officially discouraged NeXT-derived APIs that Python was using at the time. Bob Ippolito approved the patch, and OS X users should hopefully see the change in Python 2.5. Contributing thread: - `Use dlopen() on Darwin/OS X to load extensions? `__ ------------------------------- Saving the hash value of tuples ------------------------------- Noam Raphael suggested `caching the hash value of tuples`_ in a similar way to what is done for strings now. But without any measurements showing that this improved performance, and with the relative rareness of hashing tuples, Guido thought that this was a bad idea. .. _caching the hash value of tuples: http://bugs.python.org/1462796 Contributing thread: - `Saving the hash value of tuples `__ ------------------ sqlite3.dll issues ------------------ If a Windows user tries ``import sqlite3`` and Python finds SQLite's sqlite3.dll before it finds pysqlite's sqlite.py module, Python will end up incorrectly raising an ImportError. Martin v. L?wis suggested that maybe Python should stop treating .dll files as extension modules so conflicts like this could be avoided. It was unclear at the end of the thread if this (or any other) route was being persued. Contributing thread: - `Renaming sqlite3 `__ ---------------- New Python icons ---------------- Andrew Clover made some `new Python icons`_ available based on the logo on the new website. People on python-dev really liked them, and it looked like they'd probably make it into Python 2.5. .. _new Python icons: http://doxdesk.com/img/software/py/icons2.png Contributing threads: - `New-style icons, .desktop file `__ - `New-style icons, .desktop file `__ ---------------------------------------- Py_Initialize/Py_Finalize leaking memory ---------------------------------------- Martin v. L?wis corrected some documentation errors that claimed that Py_Finalize would release all memory (it can't be guaranteed to do so). In the process, Martin and Tim Peters discussed a `recent bug`_ where running Py_Initialize/Py_Finalize in a loop left more and more objects behind each time. The hope was to get the number of added objects after a Py_Initialize/Py_Finalize pair back down to zero if possible, and Martin found at least one leak, but it was unclear at the end of the thread how close they had gotten. .. _recent bug: http://bugs.python.org/1445210 Contributing thread: - `Py_Finalize does not release all memory, not even closely `__ ---------------------- Removing PyObject_REPR ---------------------- Thomas Wouters noticed that the ``PyObject_REPR()`` macro, which was originally introduced as an internal debugging API, leaks a PyString object. It looked like the macro would either be removed entirely, or redefined to call Py_DECREF appropriately and return a newly allocated (and thus freeable) string. Contributing thread: - `PyObject_REPR() `__ ------------------------------------------ uriparse module to replace urlparse module ------------------------------------------ Paul Jimenez offered up his `uriparse module`_ which improves on urlparse. Currently, urlparse doesn't comply with STD66 (a.k.a. RFC3986), as it hard-codes some URI schemes instead of applying the same syntax to all of them. Martin v. L?wis asked for more documentation, and John J Lee suggested deprecating a few functions from urllib and putting RFC-compliant versions in uriparse. The discussion then moved to the tracker, but at the time of this summary, the remaining issues had not yet been resolved. .. _uriparse module: http://bugs.python.org/1462525 Contributing thread: - `New uriparse.py `__ -------------------------------------- Line numbers with the new AST compiler -------------------------------------- Jeremy Hylton noticed that with the new AST-based compiler, the line numbers for things like the implicit ``return None`` at the end of a function were occasionally different from previous versions of Python. The changes looked harmless, so Guido said it was fine to leave the code as it was. Jeremy promised to look into some of the other special cases for alpha 2. Contributing thread: - `line numbers, pass statements, implicit returns `__ ================ Deferred Threads ================ - `PY_FORMAT_SIZE_T warnings on OS X `__ ================== Previous Summaries ================== - `Class decorators `__ - `I'm not getting email from SF when assigned a bug/patch `__ - `improving quality `__ =============== Skipped Threads =============== - `gmane.comp.python.devel.3000 has disappeared `__ - `refleaks in 2.4 `__ - `Name for python package repository `__ - `[Python-checkins] r43545 - in python/trunk: Doc/lib/libcalendar.tex Lib/calendar.py `__ - `Bug Day on Friday, 31st of March `__ - `String formating in python 3000 `__ - `SF #1462485 - StopIteration raised in body of 'with' statement suppressed `__ - `SF #1462700 - Errors in PCbuild `__ - `Whole bunch of test failures on OSX `__ - `SF:1463370 add .format() method to str and unicode `__ - `Need Py3k group in trackers `__ - `posixmodule.c patch- revision 43586 `__ - `Twisted and Python 2.5a0r43587 `__ - `r43613 - python/trunk/Doc/lib/libcsv.tex `__ - `current 2.5 status `__ - `Should issubclass() be more like isinstance()? `__ - `The "Need for Speed" Sprint, Reykjavik, Iceland, May 21-28, 2006 `__ - `suggest: nowait option in subprocess.communicate `__ - `strftime/strptime locale funnies... `__ - `PY_SSIZE_T_MIN? `__ - `How to determine if char is signed or unsigned? `__ - `Possible issue with 2.5a1 Win32 binary `__ - `Don Beaudry `__ - `Default Locale, was; Re: strftime/strptime locale funnies... `__ - `dis module and new-style classes `__ - `module aliasing `__ - `str.partition? `__ - `subprocess maintenance - SVN write access `__ - `[IronPython] base64 module `__ - `base64 module `__ - `packaging/bootstrap issue `__ - `Patch or feature? Tix.Grid working for 2.5 `__ - `Weekly Python Patch/Bug Summary `__ - `Subversion downtime today `__ - `Win64 AMD64 (aka x64) binaries available64 `__ - `int()'s ValueError behaviour `__ - `threadless brownian.py `__ - `Subversion repository back up `__ - `DRAFT: python-dev summary for 2006-02-01 to 2006-02-15 `__ - `Failing "inspect" test: test_getargspec_sublistofone `__ - `updating PyExpat (Was: need info for externally maintained modules PEP) `__ - `DRAFT: python-dev summary for 2006-02-16 to 2006-02-28 `__ - `DRAFT: python-dev summary for 2006-03-01 to 2006-03-15 `__ - `Checking assigned bugs/patches `__ - `String initialization (was: The "i" string-prefix: I18n'ed strings) `__ - `Request for review `__ - `cleanup list `__ - `unicode vs buffer (array) design issue can crash interpreter `__ - `int vs ssize_t in unicode `__ - `Any reason that any()/all() do not take a predicate argument? `__ - `Any reason that any()/all() do not take a predicateargument? `__ - `Exceptions doctest Re: Request for review `__ - `Is test_sundry really expected to succeed on Windows? `__ - `Checkin 45232: Patch #1429775 `__ - `[Python-checkins] r45334 - python/trunk/Lib/test/leakers/test_gen1.py python/trunk/Lib/test/leakers/test_generator_cycle.py python/trunk/Lib/test/leakers/test_tee.py `__ - `ia64 debian buildbot `__ - `[Python-3000] Removing 'self' from method definitions `__ - `Procedure for sandbox branches in SVN? `__ - `Calling Thomas Heller and Richard Jones `__ ======== Epilogue ======== This is a summary of traffic on the `python-dev mailing list`_ from April 01, 2006 through April 15, 2006. It is intended to inform the wider Python community of on-going developments on the list on a semi-monthly basis. An archive_ of previous summaries is available online. An `RSS feed`_ of the titles of the summaries is available. You can also watch comp.lang.python or comp.lang.python.announce for new summaries (or through their email gateways of python-list or python-announce, respectively, as found at http://mail.python.org). This python-dev summary is the 2nd written by the python-dev summary master, Steve Bethard (You want 'em faster, you write em! ;-) ). To contact me, please send email: - Steve Bethard (steven.bethard at gmail.com) Do *not* post to comp.lang.python if you wish to reach me. The `Python Software Foundation`_ is the non-profit organization that holds the intellectual property for Python. It also tries to advance the development and use of Python. If you find the python-dev Summary helpful please consider making a donation. You can make a donation at http://python.org/psf/donations.html . Every cent counts so even a small donation with a credit card, check, or by PayPal helps. -------------------- Commenting on Topics -------------------- To comment on anything mentioned here, just post to `comp.lang.python`_ (or email python-list at python.org which is a gateway to the newsgroup) with a subject line mentioning what you are discussing. All python-dev members are interested in seeing ideas discussed by the community, so don't hesitate to take a stance on something. And if all of this really interests you then get involved and join `python-dev`_! ------------------------- How to Read the Summaries ------------------------- That this summary is written using reStructuredText_. Any unfamiliar punctuation is probably markup for reST_ (otherwise it is probably regular expression syntax or a typo :); you can safely ignore it. We do suggest learning reST, though; it's simple and is accepted for `PEP markup`_ and can be turned into many different formats like HTML and LaTeX. Unfortunately, even though reST is standardized, the wonders of programs that like to reformat text do not allow us to guarantee you will be able to run the text version of this summary through Docutils_ as-is unless it is from the `original text file`_. .. _python-dev: http://www.python.org/dev/ .. _SourceForge: http://sourceforge.net/tracker/?group_id=5470 .. _python-dev mailing list: http://mail.python.org/mailman/listinfo/python-dev .. _c.l.py: .. _comp.lang.python: http://groups.google.com/groups?q=comp.lang.python .. _PEP Markup: http://www.python.org/peps/pep-0012.html .. _Docutils: http://docutils.sf.net/ .. _reST: .. _reStructuredText: http://docutils.sf.net/rst.html .. _PSF: .. _Python Software Foundation: http://python.org/psf/ .. _original text file: http://www.python.org/dev/summary/2006-04-01_2006-04-15.rst .. _archive: http://www.python.org/dev/summary/ .. _RSS feed: http://www.python.org/dev/summary/channews.rdf From dan_2718 at yahoo.co.uk Fri Jun 9 11:58:13 2006 From: dan_2718 at yahoo.co.uk (dan) Date: 9 Jun 2006 08:58:13 -0700 Subject: capture video from camera References: <1149598946.182874.121650@c74g2000cwc.googlegroups.com> <1149603488.012417.269760@j55g2000cwa.googlegroups.com> <1149618799.409008.33060@h76g2000cwa.googlegroups.com> <1149686461.261815.81670@i39g2000cwa.googlegroups.com> <1149803564.942255.244570@i40g2000cwc.googlegroups.com> Message-ID: <1149868693.224926.267470@f6g2000cwb.googlegroups.com> K.S.Sreeram wrote: > dan wrote: > > I hope you won't be deterred from posting further questions to the > > group by Fredrik's somewhat terse and unfriendly reply. > > > > comp.lang.python is a forum generally noted for its pleasing admixture > > of erudition and encouragement. Fredrik is uncommonly distinguished in > > the scope and depth of his knowledge. He does himself, and the group in > > general, an injustice by the intolerance of his response. > > People need to learn to be precise and to-the-point in their posts. If > not, its a waste of time for a lot of people.. more so for frequent > contributors like fredrik. I hope criticism like yours does not deter him! > Hi K.S, People learn through encouragement and appropriate example, not through criticism... Best wishes, Dan From pmartin at snakecard.com Sun Jun 25 08:54:02 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Sun, 25 Jun 2006 07:54:02 -0500 Subject: USB and Python References: Message-ID: Many thanks, Philippe Philippe Martin wrote: > Hi, > > I need to talk to a USB device (PC or other) from Python - I am not > talking about mounting a file system but sharing information as you would > though a TCP-IP socket layer or an RS232 interface. > > Is there such "low-level" module available for Windows / Linux ? > > Thanks, > > Philippe From claird at lairds.us Sun Jun 18 17:21:05 2006 From: claird at lairds.us (Cameron Laird) Date: Sun, 18 Jun 2006 21:21:05 +0000 Subject: Passing data to system command References: Message-ID: <1nsgm3-ogr.ln1@lairds.us> In article , Chris Hieronymus wrote: . . . >input. How do I get the data into the system call? I used to do >things in csh and awk, >i.e., something like > >awk '{; print $1, $2}' filename | psxy options> >! output.ps . . . There are several aspects to what you're after. First, I think, is to experiment with import os os.system("awk '{print $%column}'" % desired_column) Does that move you forward? From dreedmac at columbus.rr.com Sun Jun 25 12:33:17 2006 From: dreedmac at columbus.rr.com (David Reed) Date: Sun, 25 Jun 2006 12:33:17 -0400 Subject: Python taught in schools? In-Reply-To: <1151248803.267792.98120@m73g2000cwd.googlegroups.com> References: <1151220913.406987.162420@u72g2000cwu.googlegroups.com> <1151248803.267792.98120@m73g2000cwd.googlegroups.com> Message-ID: > > MilkmanDan wrote: >> I'll be a college freshman this fall, attending Florida Institute of >> Tech studying electrical engineering. >> >> I was considering taking some classes in programming and computer >> science, and I happened to notice that everything taught is using C >> ++. >> After further research, it seems to me that C++ seems to be the >> dominating language in universities. Actually, I think Java is the most commonly used language in the CS1, although C++ may be more popular at engineering institutions. >> >> By comparison, our local community college teaches a few classes >> in VB, >> Java, Javascript, C++, and for some reason, PASCAL. >> >> I'm certianly not against any of this, but out of curiousity does >> anyone know of a school that teaches Python? See the following for a list compiled from responses on the python- edu list. http://studypack.com/comp/mod/glossary/view.php?id=2835 Dave From scott.daniels at acm.org Thu Jun 15 18:00:45 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Thu, 15 Jun 2006 15:00:45 -0700 Subject: Which compiler will Python 2.5 / Windows (Intel) be built with? In-Reply-To: <1150406005.948538.188950@h76g2000cwa.googlegroups.com> References: <1150367139.495114.148550@g10g2000cwb.googlegroups.com> <44917535$1@nntp0.pdx.net> <1150391891.130185.4640@f6g2000cwb.googlegroups.com> <4491b9e1$1@nntp0.pdx.net> <1150406005.948538.188950@h76g2000cwa.googlegroups.com> Message-ID: <4491d3c0$1@nntp0.pdx.net> meyer at mesw.de wrote: > I understand that you are far in the release cycle and that this change > would maybe even delay the whole release process. Those are good > points. OTOH I think that sometimes it's better to change decisions in > light of new facts. There is no maybe to it. You could ask Tony Baxter, but a huge amount of testing and debugging has gone on, and there is a single person trying to keep the source VS2005 compatible. > Of course I don't know exactly when this decision was fixed, but I > guess since then Microsoft has created two new facts that cannot be ignored: > > * It wasn't clear that Microsoft would stop distributing the free 2003 > toolkit in favor of the 2005 toolkit. I cannot remember that they did > something like this in the past, so this is something that came as a > surprise. > > * At least to me it wasn't clear that Microsoft would release a new > version of Visual Studio so early, and that it would link to a new, > incompatible C runtime. Nor was it clear to the PyDev community. Microsoft offered free development systems to those among the PyDev group who were core developers, and we took that offer. At the time we had no idea it was on such a short-windowed product. VC6 lasted a _long_ time. > One can like or not like Microsoft politics, but I think in case of > those new and surprising facts a re-evaluation of the decision for > compiling Python with VS2003 might very well be justified. If we were pre-alpha, or possibly just after alpha1, I might agree with you. >> Note there was strong resistance to leaving VC6 for Python 2.4. That >> resistance was overcome only by the fact that it was no longer possible >> to purchase suitable versions of VC6. > I'm not sure how that backs the point you made. I pointed that out to explain that we are reluctant to force developers to continuously upgrade their VC toolkits and build procedures. Just because you want to hop from 2.3 to 2.5, doesn't mean that there aren't those already on 2.4 (and they have already suffered through new build info pain). > In fact, you're saying that people accepted that Python 2.4 was > compiled with VS2003 because VC6 could not longer be bought. How is > that different from the current situation where the VS2003 toolkit > cannot longer be downloaded and it is at least becoming increasingly > difficult to buy versions of VS2003? As nikie pointed out, you can buy a 1-year MSDN Pro Subscription that includes the VS2003 system. All that stopped is the free toolkit. > You also seem to imply that there is a large group of people that want > you to stay with VS2003 for compiling Python 2.5. Of course I have no > actual figures, but at least in this thread it seems to me that every > single person who wrote in this thread until now was pro-2005 and > against-2003. Taking percentages of people who complain is not reflect necessarily reflective of percentages of the general population. If I recall correctly, there was some angst about using VC6, because it was only available for a hefty-for-hobbyists price. That was quelled with the explanation that essentially all Windows developers used the Visual Studio toolkit. As to MinGW, nobody has signed up to commit long-term to doing the PyDev work that is required to get (and keep) it working. Such a developer would be welcome. There _are_ notes out there on the web to help you get such things going; I have done my own little bit to share what I know about how to do that. --Scott David Daniels scott.daniels at acm.org From fredrik at pythonware.com Tue Jun 27 02:04:29 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 27 Jun 2006 08:04:29 +0200 Subject: Replace Whole Object Through Object Method In-Reply-To: <1151342941.256085.243000@p79g2000cwp.googlegroups.com> References: <1151337453.804750.293180@b68g2000cwa.googlegroups.com> <44a0132d$0$21282$626a54ce@news.free.fr> <1151342941.256085.243000@p79g2000cwp.googlegroups.com> Message-ID: digitalorganics at gmail.com wrote: > I'm working with a team that's doing social modeling, and for example, > I need to model workers that at some point in the program may or may > not also become employers. Now, I want the workers to take on all > behaviors and attributes of an employer in addition to their > pre-existing "worker" behaviors and attributes. Also, as I'm sure you > guessed, the workers' attributes need to retain their values at that > point in the program, so a brand new worker-employer object wouldn't in > itself do the trick. so why not just do that, instead of trying to come up with overly convoluted ways to abuse a class mechanism that you don't fully understand ? I suspect that your team would prefer if you got your inspiration from GoF instead of Goldberg. From jstroud at ucla.edu Fri Jun 16 15:59:02 2006 From: jstroud at ucla.edu (James Stroud) Date: Fri, 16 Jun 2006 12:59:02 -0700 Subject: a good programming text editor (not IDE) In-Reply-To: References: <_xgkg.2317$No6.48542@news.tufts.edu> <1150402733.116243.9680@y41g2000cwy.googlegroups.com> <4492ae6c$0$19179$626a54ce@news.free.fr> Message-ID: Tim Chase wrote: >> No need to argue. I started with vim, and finally switched to >> emacs less than one year later. > > > Both are very-much-so good editors. I made the opposite switch > from emacs to vim in less than a year. Both are good^Wgreat > editors, so one's decision to use one over the other is more a > matter of working style. I don't grok LISP, and just never felt > at home in emacs, despite all the power I could see that was > there. I grok vim (and its similar power/extensibility), so I > migrated to it. I have to laugh at the whole holy-war thing, as > it's somewhat like arguing about a favorite color. "But blue is > so better than green! The sky is blue!" "Nuh, uh! Green is far > better than blue! Grass is green!" (okay, here in Texas, that > doesn't always hold as true...maybe personality #2 should be > arguing for brown instead). > > My best friend is an emacs user, and I'm a vimmer...it doesn't > come between us. :) > > -tkc Yes, heartwarming, but if you are thinking marriage... -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From alanalan at newsgroup.nospam Thu Jun 1 16:07:01 2006 From: alanalan at newsgroup.nospam (A.M) Date: Thu, 1 Jun 2006 16:07:01 -0400 Subject: How to format datetime values References: <1149190242.446952.52180@j55g2000cwa.googlegroups.com> Message-ID: "BartlebyScrivener" wrote in message news:1149190242.446952.52180 at j55g2000cwa.googlegroups.com... > Are you trying to get banned, or what? > > It's the equivalent of me asking you: > > Hey, does Ruby have anything like dictionaries and will you teach me > about strings? Oh, and what's an object? > > Go read the bleeping tutorial. > > rd > Well, I did investigate all tutorial and google and I wasn't able to find any built-in way for datetime formatting in Python. In fact I cannot find any way to format a long integer into 99,999,9999 format. I know how to format strings with C printf like formatter, but I am sure what I am trying to do can't be done with C printf formatting. I also found that mx.DateTime perfectly does date formatting and much more, but I don't want to add another step to the deployment process. >> It's the equivalent of me asking you: >> and will you teach me about strings? Oh, and what's an object? The answer to this post could be just a function name. I don't think I asked about broad concepts such as the object or strings. What I am asking here is just a clue. From usenet.rpdillon at xoxy.net Thu Jun 1 22:45:20 2006 From: usenet.rpdillon at xoxy.net (R. P. Dillon) Date: Thu, 01 Jun 2006 19:45:20 -0700 Subject: is a wiki engine based on a cvs/svn a good idea? In-Reply-To: References: Message-ID: <1149215920_13437@sp6iad.superfeed.net> TWiki, written in perl, makes extensive use of versioning/diff functionality you mention through the use of RCS, which, IIRC, is the basis for CVS. This method eliminates the need for the repository as such, and merely requires the presence of the RCS files (and RCS). Unless you _want_ to host your data on a separate machine than the one hosting the wiki, you might consider RCS as an alternative to CVS. OTOH, it is clearly a good idea to base your software on such a tool, given that TWiki does it and has proven to be quite successful. =) Rick piotr malin'ski wrote: > I'm planning to wite a fully featured wiki in Python in one of > frameworks. I've seen some notes about wiki/documentation management > scripts that use SVN as a data storage/versioning. > I've been using SVN a bit but I don't know if it's a good idea to use > it in a wiki engine. Pro: versioning / diffs, Cons: you need your own > svn/cvs repository, can pyLucene or Xapwrap index this? From justin.mailinglists at gmail.com Mon Jun 5 23:12:08 2006 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: 5 Jun 2006 20:12:08 -0700 Subject: Again, Downloading and Displaying an Image from the Internet in Tkinter References: <1149555597.559051.162590@i39g2000cwa.googlegroups.com> <1149556130.667899.199470@j55g2000cwa.googlegroups.com> Message-ID: <1149563528.127044.32210@y43g2000cwc.googlegroups.com> cannot help you with Tkinter but... save=open("image.jpg","wb") save.write(web_download.read()) save.close() perhaps this would let you open the file in Paint From jon+usenet at unequivocal.co.uk Wed Jun 21 09:41:12 2006 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: 21 Jun 2006 13:41:12 GMT Subject: OS specific command in Python References: <1150781429.090359.148560@c74g2000cwc.googlegroups.com> <1150783324.258644.65770@u72g2000cwu.googlegroups.com> Message-ID: In article <1150783324.258644.65770 at u72g2000cwu.googlegroups.com>, stephanearnold at yahoo.fr wrote: >> So basically, instead of typing in on the command line argument I want >> to have it in a python program and let it do the action. > > Try exec() and execfile() from the standard library (IIRC) Ths os.spawn...() functions are likely to be better suited to what he wants to do. >> ssh Admin at 192.168.2.10 .....etc > > When you connect (via ssh or telnet) to a remote machine, you need to > type (manually) your username and your password. Programming that is > never easy. Indeed, so it is much easier to use public-key authentication with an unencrypted private key, that way you don't have to type any passwords. See the "AUTHORIZED_KEYS FILE FORMAT" section of the 'sshd' man page, and the 'ssh-keygen' command. From sreeram at tachyontech.net Thu Jun 29 20:48:35 2006 From: sreeram at tachyontech.net (K.S.Sreeram) Date: Fri, 30 Jun 2006 06:18:35 +0530 Subject: Reddit broke - should have remained on Lisp? In-Reply-To: <1151627462.297352.205150@i40g2000cwc.googlegroups.com> References: <1151626961.232761.255550@d56g2000cwd.googlegroups.com> <1151627462.297352.205150@i40g2000cwc.googlegroups.com> Message-ID: <44A474E3.8050806@tachyontech.net> Luis M. Gonz?lez wrote: > Alok wrote: >> While posting a comment on http://www.reddit.com I got an error page >> with the following curious statement on it. >> >> "reddit broke (sorry)" >> "looks like we shouldn't have stopped using lisp..." > > I don't know if this is true or not, but blaming a language for a poor > development is a little bit ridiculous... Have people lost all sense of humor?? Its just reddit's attempt at humor! I've rarely seen any server errors on reddit, but even when I do see one.. its funny! Here's another one: http://www.flickr.com/photos/pvera/sets/72057594050280833/ Check out their testimonials, its hilarious! http://reddit.com/static/spreddit/testimonials.html Regards Sreeram -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 260 bytes Desc: OpenPGP digital signature URL: From grante at visi.com Sun Jun 18 11:30:10 2006 From: grante at visi.com (Grant Edwards) Date: Sun, 18 Jun 2006 15:30:10 -0000 Subject: maximum integer length? References: Message-ID: <129asc2kok1o4b0@corp.supernews.com> On 2006-06-18, Sybren Stuvel wrote: > nate enlightened us with: >> Obviously I didn't have enough memory for that, but I was able to c**3. >> (I think anyways, it is still trying to display the result) >> >> So I am just wondering how long an integer can be with 400 megabytes of >> memory. > > I guess the best way would be a binary search for the proper value of > the integer. You already have an upper (c**d) and a lower (c**3) bound > for your search. > >> each integer takes up a byte right? > > That depends on the size of the integer, doesn't it? > >> If I have 400 megabytes that would mean I could have a long integer >> with up to 419,430,400,000 integers? > > Que? An integer is just a whole number without fraction. What are you > talking about? He's talking about decimal digits. Each decimal digit takes up 3.322 bits. A byte can hold about 2.4 digits. 400MB should be able to hold an integer with about 1,010,000,000 decimal digits. -- Grant Edwards grante at visi.com From martin at v.loewis.de Mon Jun 5 10:32:05 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 05 Jun 2006 16:32:05 +0200 Subject: strategy pattern and non-public virtual functions In-Reply-To: <1149516464.874257.194030@j55g2000cwa.googlegroups.com> References: <1149516464.874257.194030@j55g2000cwa.googlegroups.com> Message-ID: <44844066$0$14208$9b622d9e@news.freenet.de> pythoncurious at gmail.com wrote: > Just translating this code to python won't work, due to the name > mangling of private functions: > class B(object): > def f(self): > self.__f() > > class D(B): > def __f(self): > pass > > d = D() > d.f() > > So my questions are: > 1. Is there a "pythonic" way to do what I'm trying to do? Just use a single underscore, i.e. "_f" instead of "__f". > 2. Should I be doing this at all? Any thoughts? I can't spot the strategy pattern here; neither in the C++ code nor in the Python code. For this to be the strategy pattern, you should have two objects: the context, and the strategy object. So for example, you could have class Context: def f(self): return self.strategy.f() class D: def f(self): pass Then, assigning to context.strategy lets you change the strategy dynamically. It's not clear to what you are trying achieve with your pattern, so it is hard to tell whether you should do this at all. Most likely, the answer is "no". If you are really looking for the strategy pattern: be aware that people often use the strategy pattern as a work-around for functions not being first-class objects. In Python, they are, so you can often allow for arbitrary callables in the strategy pattern. Regards, Martin From florencio.cano at gmail.com Fri Jun 2 09:21:20 2006 From: florencio.cano at gmail.com (Florencio Cano) Date: Fri, 2 Jun 2006 15:21:20 +0200 Subject: Which exceptions are recommended to me handled? Message-ID: Hello, Is it recommended as a good programming practice to catch all exceptions and raise our own exceptions or let Python itself raise these kinds of exceptions? For example imagine a function that needs an integer and '34' is passed, this is ok because inside the function it uses int(variable) but if a 'hello' is passed it will raise a ValueError exception. Is it better to handle this exception or let Python raise directly ValueError and stop execution or what is recommended? Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From Kiran.Karra at gmail.com Tue Jun 6 10:20:34 2006 From: Kiran.Karra at gmail.com (Kiran) Date: 6 Jun 2006 07:20:34 -0700 Subject: Namespace problems Message-ID: <1149603634.391551.229700@c74g2000cwc.googlegroups.com> Hello All, I am kind of a beginner to python, but here is the deal. I am writing a wxpython Application, in which I have a GUI. This GUI imports some other modules that I have written, using the format import mymodule as _MyModule Now, this GUI in addition to having all it's bells and whistles has a console (from pyshell), so that the user can run their own scripts inside this GUI. What I am trying to do is to get these scripts that the user runs to be able to see all the other objects created and modules imported by the GUI. To make this clear, what I want to be able to do for example is in my script, do , dir(mymodule), already having imported mymodule in the GUI. Any ideas on how to make this happen? I don't want to import mymodule in this script, i want this script to see the mymodule that I imported in the main GUI. thanks a lot for your help, Kiran From jorge.vargas at gmail.com Fri Jun 23 22:41:47 2006 From: jorge.vargas at gmail.com (Jorge Vargas) Date: Fri, 23 Jun 2006 22:41:47 -0400 Subject: module docstring, documentation, anything? please note is the module type/object NOT some module In-Reply-To: <32822fe60606231917r495b166i47ee7f19a6c873fb@mail.gmail.com> References: <32822fe60606231917r495b166i47ee7f19a6c873fb@mail.gmail.com> Message-ID: <32822fe60606231941l156051e7m806c23b2b02d0be8@mail.gmail.com> On 6/23/06, Jorge Vargas wrote: > > Hi everyone I have wasted 2 hours trying to figure out how to get a > reference to the module object. that is the one returned by > > __import__ or when you call a module for name like > >>> import sys > >>> sys > > > the reason I want this is that I want to introspec my module > > so I need some way to indentify what elements are inside the module, to > execute something like: > > ""for all the classes defined in this module do " > I found an ugly hack to the docs help(type(sys)) -------------- next part -------------- An HTML attachment was scrubbed... URL: From jstroud at ucla.edu Sat Jun 10 19:32:16 2006 From: jstroud at ucla.edu (James Stroud) Date: Sat, 10 Jun 2006 16:32:16 -0700 Subject: Most elegant way to generate 3-char sequence In-Reply-To: References: <1149889784.391965.271570@h76g2000cwa.googlegroups.com> <4489F30A.9000006@ucla.edu> Message-ID: Steve Holden wrote: > James Stroud wrote: > >> Rob Cowie wrote: >> >>> Hi all, >>> >>> I wish to generate a sequence of the form 'aaa', 'aab', aac'.... 'aba', >>> 'abb', 'abc' etc. all the way to 'zzz'. >>> >>> How would you construct a generator to acheive this? >>> >>> A simple, working but somewhat inelegant solution is... >>> >>> alpha = ['a','b','c','d'] #shortened for brevity >>> alpha2 = ['a','b','c','d'] >>> alpha3 = ['a','b','c','d'] >>> >>> def generator(): >>> for char in alpha: >>> for char2 in alpha2: >>> for char3 in alpha3: >>> yield char + char2 + char3 >>> >>> x = generate() >>> x.next() # etc, etc, etc, >>> >> >> >> A touch more efficient: >> >> import string >> alpha = string.lowercase >> >> def generator(choices, length): >> length -= 1 >> for a in choices: >> if length: >> for g in generator(choices, length): >> yield a + g >> else: >> yield a >> >> for a in generator(alpha, 3): >> print a >> > Frankly, this doesn't seem more elegant than the original, particularly > once it uses a single string. > > regards > Steve Are you sure you understand what each do? -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From victimorcrime at yahoo.com Fri Jun 2 22:32:13 2006 From: victimorcrime at yahoo.com (RJ) Date: Fri, 02 Jun 2006 22:32:13 -0400 Subject: beginner code problem References: <2006060218415316807-victimorcrime@yahoocom> Message-ID: <1js1821c2hlj77132f758pv371ttb0o3a4@4ax.com> Thanks for all the help and examples. As I mentioned, I'm trying to teach myself and starting with the basics (if, elif, else, while, for, raw_input, int are about all I know so far and don't know that well yet) Some of the example posted are still beyond my understanding but it's good to see other ways of acheiving the result and other things to look up and read about. I've read a bit about Python but only really started trying yesterday. Right now I'm still strugling but with practice I hope for it to come easier and I'll keep learning more syntax. I didn't even think about random.randrange being out of the loop but it makes sence now. Chalk it up to a newbie mistake and a learning experience. I really do appreciate the help and I'm sure this is only the first of many questions I'll have. It's good to know that there are others who can help me understand my mistakes. Rob From raNOsky at deveSPAMler.com Thu Jun 1 13:44:40 2006 From: raNOsky at deveSPAMler.com (Giovanni Bajo) Date: Thu, 1 Jun 2006 19:44:40 +0200 Subject: struct: type registration? References: <447e4b98$1@news.eftel.com> <447EDF7C.3080104@lexicon.net> Message-ID: John Machin wrote: >> Looks like you totally misread my message. > > Not at all. > > Your function: > > def mystring_pack(s): > if len(s) > 20: > raise ValueError, "a mystring can be at max 20 chars" > s = (s + "\0"*20)[:20] > s = struct.pack("20s", s) > return s > > can be even better replaced by (after reading the manual "For packing, > the string is truncated or padded with null bytes as appropriate to > make it fit.") by: > > def mystring_pack(s): > if len(s) > 20: > raise ValueError, "a mystring can be at max 20 chars" > return s > # return s = (s + "\0"*20)[:20] # not needed, according to the > manual # s = struct.pack("20s", s) > # As I said, this particular instance of using struct.pack is a > big fat no-op. John, the point of the example was to show that one could write custom packer/unpacker which calls struct.pack/unpack and, after that, post-processes the results to obtain some custom data type. Now, I apologize if my example wasn't exactly the shortest, most compact, most pythonic piece of code. It was not meant to be. It was meant to be very easy to read and very clear in what it is being done. You are nitpicking that part of my code is a no-op. Fine. Sorry if this confused you. I was just trying to show a simple pattern: custom packer: adjust data, call struct.pack(), return custom unpacker: call struct.unpack(), adjust data, return I should have chosen a most complex example probably, but I did not want to confuse readers. It seems I have confused them by choosing too simple an example. -- Giovanni Bajo From yairchu at gmail.com Fri Jun 2 06:35:49 2006 From: yairchu at gmail.com (yairchu at gmail.com) Date: 2 Jun 2006 03:35:49 -0700 Subject: struct: type registration? In-Reply-To: References: Message-ID: <1149244549.497806.211280@y43g2000cwc.googlegroups.com> using struct for the stuff you're up to and you'll finish with weird unmaintainable code. save yourself a lot of pain and use construct instead. http://pyconstruct.wikispaces.com/ From sonja.coussell at gmail.com Wed Jun 21 16:21:40 2006 From: sonja.coussell at gmail.com (sonjaa) Date: 21 Jun 2006 13:21:40 -0700 Subject: Update on Memory problem with NumPy arrays In-Reply-To: <1150917966.428492.87350@y41g2000cwy.googlegroups.com> References: <1150907922.908497.120310@u72g2000cwu.googlegroups.com> <1150917966.428492.87350@y41g2000cwy.googlegroups.com> Message-ID: <1150921300.876636.173330@c74g2000cwc.googlegroups.com> I've been in contact with Travis O, and he said it was fixed in the SVN. thanks for the suggestions, I'll try them out now. best Sonja Filip Wasilewski wrote: > sonjaa wrote: > > Hi > > > > last week I posted a problem with running out of memory when changing > > values in NumPy arrays. Since then I have tried many different > > approaches and > > work-arounds but to no avail. > [...] > > Based on the numpy-discussion this seems to be fixed in the SVN now(?). > > Anyway, you can use 'where' function to eliminate the loops: > > from numpy import * > > y = ones((501,501)) > z = zeros((501,501)) > it = 50 > > for kk in xrange(it): > y[1,1] = 4 > y[1,2] = 4 > y[1,0] = 4 > y[2,1] = 6 > > print "Iteration #:%s" %(kk) > y = where((y == 4) | (y == 6), 2, y) > > > best, > fw From greg at cosc.canterbury.ac.nz Sat Jun 10 04:51:02 2006 From: greg at cosc.canterbury.ac.nz (greg) Date: Sat, 10 Jun 2006 20:51:02 +1200 Subject: Allowing zero-dimensional subscripts In-Reply-To: <1149844947.822478.128580@g10g2000cwb.googlegroups.com> References: <1149801040.936452.26270@i40g2000cwc.googlegroups.com> <1149807149.516004.48590@f6g2000cwb.googlegroups.com> <1149832139.948242.64160@f6g2000cwb.googlegroups.com> <1149844947.822478.128580@g10g2000cwb.googlegroups.com> Message-ID: <4evff5F1gmkhbU1@individual.net> Carl Banks wrote: > Think of it this way: an array with n-dimensions of length 3 would have > 3**n total entries. How many entries would a 0-dimensional array have? > 3**0 == 1. Er, hang on a minute. Along which dimension of this 0-dimensional array does it have a length of 3? :-) -- Greg From fredrik at pythonware.com Wed Jun 7 16:33:25 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 07 Jun 2006 22:33:25 +0200 Subject: Convert Date to Short formate In-Reply-To: <1149709855.899702.89100@c74g2000cwc.googlegroups.com> References: <1149709855.899702.89100@c74g2000cwc.googlegroups.com> Message-ID: aqmaiya wrote: > there is string value 'Dec 06, 2000' I want to convert that string > date to SHORT FORMAT like '2000-12-06-. Please help me how do I do > that? you mean ISO format, right? the easiest way is probably to use the time.strptime module to parse the original string into a time tuple, and then use time.strftime to format the tuple as an ISO date: >>> s = "Dec 06, 2000" >>> t = time.strptime(s, "%b %d, %Y") >>> t (2000, 12, 6, 0, 0, 0, 2, 341, -1) >>> time.strftime("%Y-%m-%d", t) '2000-12-06' also see: http://docs.python.org/lib/module-time.html From bdesth.quelquechose at free.quelquepart.fr Mon Jun 5 22:09:16 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 06 Jun 2006 04:09:16 +0200 Subject: follow-up to FieldStorage In-Reply-To: References: Message-ID: <4484b428$0$29635$636a55ce@news.free.fr> John Salerno a ?crit : > If I want to get all the values that are entered into an HTML form and > write them to a file, is there some way to handle them all at the same > time, or must FieldStorage be indexed by each specific field name? AFAIK, FieldStorage is a somewhat dict-like object, but I'm not sure it supports the whole dict interface. At least, it does support keys(), so you should get by with: for k in fs.keys(): print >> myfile, k, ":", fs[k] But reading the doc may help... From phoolimin at gmail.com Sun Jun 11 12:27:35 2006 From: phoolimin at gmail.com (phoolimin at gmail.com) Date: 11 Jun 2006 09:27:35 -0700 Subject: ANN: Dao 1.0.0-alpha is released Message-ID: <1150043255.902842.277460@g10g2000cwb.googlegroups.com> Hello, It is a pleasure to announce in this mailing list the newly released Dao. This is the first release after the Dao interpreter being re-designed and re-implemented as a virtual register machine since the beginning of this year. There have been many great improvements on both the language and the efficiency of the virtual machine. 10-20 times speedup has been observed. I am sure you will be surprised when you try it and compare it with other scripting languages. Some important language features have been added, such as switch-case control, for-in-do control, setting function parameter types and default values, passing parameters by name, and function overloading by parameter types; OOP in Dao is also greatly improved; reflection methods are newly supported. In one word, the release represents a milestone in the development of Dao. Two modules are also released along with the virtual machine: DaoMySQL and DaoPyhon. DaoPython is particularly interesting, because it allows Python modules to be loaded by Dao, then Python variables, functions and classes can be used conviniently in Dao scripts. However, since the virtual machine is almost written from scratch only since the beginning of this year, it could not be very robust (it should be more robust than any previous releases), that is why it is release as an alpha release. A formal release will be made once the virtual machine is well tested (please join us, if you want this process to be faster). For more detail about this release: please visit http://www.xdao.org, and http://xdao.org/dokuwiki/. Your suggestions and comments are extremely welcome! Limin FU From vasudevram at gmail.com Fri Jun 9 13:34:50 2006 From: vasudevram at gmail.com (vasudevram) Date: 9 Jun 2006 10:34:50 -0700 Subject: Request new feature suggestions for my PDF conversion toolkit - xtopdf In-Reply-To: References: <1149789349.974338.242080@i39g2000cwa.googlegroups.com> Message-ID: <1149874490.845360.300740@y43g2000cwc.googlegroups.com> > Thanks! You're welcome. > So here is an idea for a great enhancement: > rst -> PDF What is rst? I Googled for it, first few hits found didn't make sense (like Remote Sensing Tutorial :-). The one that did seem to make sense (in relation to xtopdf), was this : http://docutils.sourceforge.net/rst.html i.e. reStructured Text. Is that the one you mean? - Vasudev David Isaac wrote: > "vasudevram" wrote in message > news:1149789349.974338.242080 at i39g2000cwa.googlegroups.com... > > http://sourceforge.net/projects/xtopdf > > Serendipity: > I was just looking for this functionality. > Thanks! > > So here is an idea for a great enhancement: > rst -> PDF > The good news: the project is all Python, > so you will only have to write a writer! > (But to make this great: support stylesheets!) > > Alan Isaac From runlevelten at gmail.com Thu Jun 29 04:58:42 2006 From: runlevelten at gmail.com (Ten) Date: Thu, 29 Jun 2006 09:58:42 +0100 Subject: New to Python: Do we have the concept of Hash in Python? In-Reply-To: References: Message-ID: <200606290958.42417.runlevelten@gmail.com> On Friday 02 June 2006 13:07, Piet van Oostrum wrote: > >>>>> "A.M" (AM) wrote: > > > >AM> This is my 1st day that I am seriously diving into Python and I have > >AM> to finish this application by the end of today. > > Are you serious? > -- > Piet van Oostrum > URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] > Private email: piet at vanoostrum.org It's not that unfeasible - I can think of a few instances off the top of my head where management have read something in a magazine or heard something in conversation, then come in full of vim and vigour the next day - telling people to create item X using buzzword technology Y by the end of the day, the week or whatever, despite the devs having never seen it, despite the timescale being insufficient, and despite there being *real* work to do. Even if it's just because they want to see it, or to impress other management types with their use of the latest "trend", I believe the best response is to just get on with it. Self-preservation and all that. Even so, the idea of using python across the company is actually a very sensible one, so I expect it's programmer's enthusiasm fuelling things in this case. -- There are 10 types of people in this world, those who understand binary, and those who don't. From eric_brunel at despammed.com Tue Jun 13 09:38:20 2006 From: eric_brunel at despammed.com (Eric Brunel) Date: Tue, 13 Jun 2006 15:38:20 +0200 Subject: Making a Label that looks the same as a button. References: <1150204443.568118.185030@c74g2000cwc.googlegroups.com> Message-ID: On 13 Jun 2006 06:14:03 -0700, Dustan wrote: > I have a Button object that gets replaced by a Label when clicked. > > Button(buttonsframe,text=' ',command=c,font=buttonsFont) > Note that the text is a single space. buttonsFont uses 'Courier New' as > a family. > > When clicked, the Button is destroyed and replaced with a Label object: > Label(buttonsframe,text=x,font=buttonsFont,relief=RAISED) > > The intent is for the Label object to look identical to the button > object, except for the non-space character x. The Label object is a > little smaller than the Button object. When I set borderwidth, the > label object does increase in size, but that's not going to make it > look the same, since it makes the border thicker. > > How do I get the Label object to look just like the Button object? There is least two other options that are different for Labels and Buttons: >>> b = Button(root) >>> b.cget('padx') '3m' >>> b.cget('pady') '1m' >>> l = Label(root) >>> l.cget('padx') '1' >>> l.cget('pady') '1' The padx and pady are the distance between the text and the widget borders. They are larger on a Button. BTW, you can get all configuration options for any widget with: for k in widget.configure().keys(): print k, ':', widget.cget(k) So you can easily compare common options between a standard Label and a standard Button. HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From fredrik at pythonware.com Sun Jun 11 16:49:01 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 11 Jun 2006 22:49:01 +0200 Subject: how to get the length of a number In-Reply-To: <1150060312.31060.13.camel@kenshin.CASA> References: <1150060312.31060.13.camel@kenshin.CASA> Message-ID: Felipe Almeida Lessa wrote: > Hmmm, you're right. > > math.floor(math.log(x, 10)) + 1 x = 0 From penneys at bigfoot.com Mon Jun 5 11:07:51 2006 From: penneys at bigfoot.com (MrBlueSky) Date: 5 Jun 2006 08:07:51 -0700 Subject: Pmw ScrolledCanvas: How to scroll to specific item? In-Reply-To: <1149496482.138396.159020@i40g2000cwc.googlegroups.com> References: <1149496482.138396.159020@i40g2000cwc.googlegroups.com> Message-ID: <1149520071.288497.248730@u72g2000cwu.googlegroups.com> MrBlueSky wrote: > Hi, I've got a ScrolledCanvas object (sc) and have identified an item > on the canvas to which I wish to scroll. I've been reading around and > experimenting but with not much success. > > So far I've managed to get the item's bbox using sc.bbox(item) > And got the proportion of the canvas that's visible using sc.xview() > and sc.yview() > And established the whole canvas bbox using sc.bbox(ALL) > > I've even gone on to use some rudimentary maths to work out whether I > need to scroll, then used: > sc.xview_moveto(itemX) > > But this is all rather messy and I've not yet got it working. > There must be an easier way?! > > Thanks! > > John Done it! I realised that searching for the way to do this using Tk would give me the clue. For the benefit of any other poor soul who wants to do this, here's my code: def scrollToItem(self, item): """Work out whether the specified item is on display. If it's not, scroll to it.""" # Bounding box for the item xItemMin, yItemMin, xItemMax, yItemMax = self.bbox(item) # Find out what proportion (0.0 to 1.0) of the canvas is # currently on view xViewMinP, xViewMaxP = self.xview() yViewMinP, yViewMaxP = self.yview() # Find out the full extent of the canvas scrollRegionStr = self.component("canvas").cget("scrollregion") scrollRegionElementsStr=scrollRegionStr.split(' ',4) xCanvasMin = float(scrollRegionElementsStr[0]) yCanvasMin = float(scrollRegionElementsStr[1]) xCanvasMax = float(scrollRegionElementsStr[2]) yCanvasMax = float(scrollRegionElementsStr[3]) xRange = float(xCanvasMax - xCanvasMin) yRange = float(yCanvasMax - yCanvasMin) # Work out the canvas coordinates of the bit of the canvas that's # currently on view xViewMin = float(xViewMinP)*xRange xViewMax = float(xViewMaxP)*xRange yViewMin = float(yViewMinP)*yRange yViewMax = float(yViewMaxP)*yRange if xItemMin < xViewMin: newXViewP = float(xItemMin - xCanvasMin)/xRange self.xview_moveto(newXViewP) elif xItemMax > xViewMax: newXViewP = float(xItemMax - xCanvasMin - (xViewMax-xViewMin))/xRange self.xview_moveto(newXViewP) if yItemMin < yViewMin: newYViewP = float(yItemMin - yCanvasMin)/yRange self.yview_moveto(newYViewP) elif yItemMax > yViewMax: newYViewP = float(yItemMax - yCanvasMin - (yViewMax-yViewMin))/yRange self.xview_moveto(newYViewP) (I'd still very much appreciate any critique of this!) John From jo at durchholz.org Wed Jun 21 11:34:19 2006 From: jo at durchholz.org (Joachim Durchholz) Date: Wed, 21 Jun 2006 17:34:19 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <0%Wlg.3521$MF6.947@tornado.socal.rr.com> <44992e6c$0$664$bed64819@news.gradwell.net> Message-ID: Andreas Rossberg schrieb: > Chris Uppal wrote: > >> It's worth noting, too, that (in some sense) the type of an object can >> change over time[*]. > > No. Since a type expresses invariants, this is precisely what may *not* > happen. No. A type is a set of allowable values, allowable operations, and constraints on the operations (which are often called "invariants" but they are invariant only as long as the type is invariant). I very much agree that the association of a type with a value or a name should be constant over their lifetime - but that doesn't follow from the definition of "type", it follows from general maintainability considerations (quite strong ones actually). Regards, Jo From no at spam.please Thu Jun 1 22:55:57 2006 From: no at spam.please (D H) Date: Thu, 01 Jun 2006 21:55:57 -0500 Subject: C# equivalent to range() In-Reply-To: <1149214153.359809.288610@i39g2000cwa.googlegroups.com> References: <1149214153.359809.288610@i39g2000cwa.googlegroups.com> Message-ID: Neuruss wrote: > I'm sorry for asking about another language here, but since I only know > Python and I'm trying to write something in C#, I guess this is the > best place... > > I'd like to know how to write this in C#: > > x=[] > sz = 10000000 > x.extend(range(sz)) > > My question is about "range" and "extend". Is there any equivalent in > C#? > > Thanks in advance, > Neuruss > List mylist = new List(); for (int i=0; i<10000000; i++) { mylist.Add(i); } You can use AddRange, C# 2.0 anonymous delegates, IEnumerable, yield, foreach, and so forth instead, but for your example this is simplest. Another option is to use boo. http://boo.codehaus.org/ It uses python's syntax but is as fast as C#. The only change you'd have to make in that code is to capitalize the Extend method call. From ptmcg at austin.rr._bogus_.com Mon Jun 12 01:44:53 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Mon, 12 Jun 2006 05:44:53 GMT Subject: Screen Scraping for Modern Applications? References: <1150077617.598735.85540@h76g2000cwa.googlegroups.com> <1150088989.408815.290690@c74g2000cwc.googlegroups.com> Message-ID: wrote in message news:1150088989.408815.290690 at c74g2000cwc.googlegroups.com... > > > Scrape means simply scraping pixel colors from locations on the screen. > I'll worry about assembling it into meaningful information. > I've used pywinauto to interact with a Flash animation panel, running within an Internet Explorer browser. By "interact" I mean moving and clicking the mouse, and capturing images, which can then be processed to access individual pixels. -- Paul From marc.t.davies at gmail.com Wed Jun 21 07:58:13 2006 From: marc.t.davies at gmail.com (MTD) Date: 21 Jun 2006 04:58:13 -0700 Subject: Iteration over recursion? In-Reply-To: References: <1150808045.539887.291180@i40g2000cwc.googlegroups.com> <1150873424.345733.165730@m73g2000cwd.googlegroups.com> Message-ID: <1150891093.829475.202600@i40g2000cwc.googlegroups.com> I've been testing my recursive function against your iterative function, and yours is generally a quite steady 50% faster on factorizing 2**n +/- 1 for 0 < n < 60. I think that, for a challenge, I'll try to make a recursive function that matche or beats the iterative function -- it's worth the experiment! Cheers, MTD From sreeram at tachyontech.net Tue Jun 27 02:17:37 2006 From: sreeram at tachyontech.net (K.S.Sreeram) Date: Tue, 27 Jun 2006 11:47:37 +0530 Subject: Select in Python In-Reply-To: <1151388082.261840.306260@75g2000cwc.googlegroups.com> References: <1151388082.261840.306260@75g2000cwc.googlegroups.com> Message-ID: <44A0CD81.5090307@tachyontech.net> Dio wrote: > while 1: > (rr, wr, er) = select([stdin], [], []) > for fd in rr: > print fd > > program block in the first select(), after I type something and "enter > ", it never block in select() again,why? select blocks until there is some data to read from stdin, but it does not *clear* the data. so once you enter data, select will not block until you read the data. once you're done reading the available data, you can again use select to block until more data is available. Regards Sreeram -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 260 bytes Desc: OpenPGP digital signature URL: From dnew at san.rr.com Sun Jun 25 16:00:25 2006 From: dnew at san.rr.com (Darren New) Date: Sun, 25 Jun 2006 20:00:25 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: <1151255749.436492.70680@m73g2000cwd.googlegroups.com> References: <7zpshbsvjy.fsf@app-1.diku.dk><4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150904134.520639.71070@b68g2000cwa.googlegroups.com> <1151030140.202720.245140@y41g2000cwy.googlegroups.com> <1151255749.436492.70680@m73g2000cwd.googlegroups.com> Message-ID: Marshall wrote: > Also: has subtyping polymorphism or not, has parametric polymorphism or > not. And covariant or contravariant. -- Darren New / San Diego, CA, USA (PST) Native Americans used every part of the buffalo, including the wings. From maric at aristote.info Wed Jun 14 07:19:41 2006 From: maric at aristote.info (Maric Michaud) Date: Wed, 14 Jun 2006 13:19:41 +0200 Subject: determining file type In-Reply-To: <1150281704.342529.206640@u72g2000cwu.googlegroups.com> References: <1150276935.270798.5550@i40g2000cwc.googlegroups.com> <1150281704.342529.206640@u72g2000cwu.googlegroups.com> Message-ID: <200606141319.42127.maric@aristote.info> Le Mercredi 14 Juin 2006 12:41, Ritesh Raj Sarraf a ?crit?: > Also, > f = file ('some_file.jpg') > > throws an error. > "str object is not callable" stange, did you define a function named file ? You can use open instead. -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From ptmcg at austin.rr._bogus_.com Tue Jun 6 09:56:14 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Tue, 06 Jun 2006 13:56:14 GMT Subject: 10GB XML Blows out Memory, Suggestions? References: <1149594519.098115.8980@u72g2000cwu.googlegroups.com> Message-ID: <2Qfhg.18186$0v4.787@tornado.texas.rr.com> wrote in message news:1149594519.098115.8980 at u72g2000cwu.googlegroups.com... > I wrote a program that takes an XML file into memory using Minidom. I > found out that the XML document is 10gb. > > I clearly need SAX or something else? > You clearly need something instead of XML. This sounds like a case where a prototype, which worked for the developer's simple test data set, blows up in the face of real user/production data. XML adds lots of overhead for nested structures, when in fact, the actual meat of the data can be relatively small. Note also that this XML overhead is directly related to the verbosity of the XML designer's choice of tag names, and whether the designer was predisposed to using XML elements over attributes. Imagine a record structure for a 3D coordinate point (described here in no particular coding language): struct ThreeDimPoint: xValue : integer, yValue : integer, zValue : integer Directly translated to XML gives: 4 5 6 This expands 3 integers to a whopping 101 characters. Throw in namespaces for good measure, and you inflate the data even more. Many Java folks treat XML attributes as anathema, but look how this cuts down the data inflation: This is only 50 characters, or *only* 4 times the size of the contained data (assuming 4-byte integers). Try zipping your 10Gb file, and see what kind of compression you get - I'll bet it's close to 30:1. If so, convert the data to a real data storage medium. Even a SQLite database table should do better, and you can ship it around just like a file (just can't open it up like a text file). -- Paul From sigzero at gmail.com Sun Jun 11 20:00:00 2006 From: sigzero at gmail.com (Robert Hicks) Date: 11 Jun 2006 17:00:00 -0700 Subject: Xah Lee network abuse In-Reply-To: References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148495974.975395.12920@i40g2000cwc.googlegroups.com> <1149998343.493200.144990@h76g2000cwa.googlegroups.com> Message-ID: <1150070400.803537.163570@f6g2000cwb.googlegroups.com> Erik Max Francis wrote: > Mallor wrote: > > > I know I'm coming late to the barbeque. In passing, I ask: do you have > > an objective, impartial perspective on the subject of committing > > crimes? Because libel is a crime. > > No, it is a tort. > Can I have whipped cream and strawberries on that tort? :Robert From tdelaney at avaya.com Mon Jun 5 17:31:40 2006 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Tue, 6 Jun 2006 07:31:40 +1000 Subject: C# equivalent to range() Message-ID: <2773CAC687FD5F4689F526998C7E4E5FF1E753@au3010avexu1.global.avaya.com> *Very* strong suggestion - read the following link: http://www.catb.org/~esr/faqs/smart-questions.html Tim Delaney From steve at holdenweb.com Fri Jun 9 11:48:51 2006 From: steve at holdenweb.com (Steve Holden) Date: Fri, 09 Jun 2006 16:48:51 +0100 Subject: Win XP: Problem with shell scripting in Python In-Reply-To: References: Message-ID: A.M wrote: >>I dare hardly suggest this, but might it not be better to use Python's >>database functionality to perform the task? The language can access both >>databases, and you might find it quicker. Then again, if your database >>experience is limited, you may not ... >> >>regards >> Steve >>-- >>Steve Holden +44 150 684 7255 +1 800 494 3119 >>Holden Web LLC/Ltd http://www.holdenweb.com >>Love me, love my blog http://holdenweb.blogspot.com >>Recent Ramblings http://del.icio.us/steve.holden >> > > > Hi Steven, > > > > Based on my experience, the fastest possible way to import raw data into > Oracle is SQL*Loader. Similarly, the fastest way to extract raw data from > SQL server is BCP. > > > > My script transfers 40,000,000 records (actually big records) from sql > server to oracle in 20 Min. I tried ODBC to do the same work. I turned off > all record locking and transactions through query hints. The actual program > was a C# program. After 12 hours, I just stopped the program. > I'm not that surprised - it was just an inquiry. Usually the database bulk dump and load utilities take advantage of every trick in their respective books to provide speed. A native driver might have done better than ODBC, but you are probably correct on going that route for speed. > > > I created DOS batch files to control BCP and SQL*Loader steps. It is faster > than any fancy GUI tools. Now I am using Python. > > I am thinking to add comprehensive logging to the ETL (extract transform > load) process. All details command line outputs will be stored in database. > System administrators can query database and watch how the ETL job is > working. > > At this point I have quite challenge with capturing BCP's stdout/stderr > output to string variables in Python program. > > I'll post the final outcome here. > OK, good luck. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From james.ryland.miller at gmail.com Fri Jun 30 16:33:57 2006 From: james.ryland.miller at gmail.com (python programming newb) Date: 30 Jun 2006 13:33:57 -0700 Subject: Newb Tkinter Question: Object has no attribute 'tk' Message-ID: <1151699637.322220.228050@b68g2000cwa.googlegroups.com> Hi all, first post. I'm new to python and tkinter. I'm trying to write a program that opens the root window with a button that then opens a toplevel window that then has it's own widgets. I can get the new toplevel window to open but none of the widgets appear. The console gives me: AttributeError: 'NewWindow' object has no attribute 'tk' Here's my code: #### from Tkinter import * class Application(Frame): """The full screen window with menu""" def __init__(self, master): Frame.__init__(self, master) self.grid() self.create_menu() self.create_widget() def create_menu(self): """Create file and help menu""" #Create Filemenu filemenu = Menu(menubar, tearoff=0) filemenu.add_command(label = "Exit", command = root.quit) menubar.add_cascade(label="File", menu=filemenu) #Create Helpmenu helpmenu = Menu(menubar, tearoff=0) helpmenu.add_command(label="About", command=hello) menubar.add_cascade(label="Help", menu=helpmenu) def create_widget(self): """Make a button in the center that when pushed opens another window""" self.bttn1 = Button(self, text = "Push to open new window", command=NewWindow) self.bttn1.grid() class NewWindow(object): def __init__(self): self.z = Toplevel() self.z.geometry("640x480") self.z.title("This is the New Window") self.frame = Frame(self.z) self.create_widgetnew() self.frame.grid() def create_widgetnew(self): self.lbl = Label(self, text = "Here is a label") self.lbl.grid(row = 0, column = 1, sticky = N) self.bttn = Button(self, text = "Close", command=self.z.quit) self.bttn.grid(row = 2, column = 1, sticky = S) #Main def hello(): print "hello in the terminal" root = Tk() root.title("ROOT WINDOW") root.geometry("300x200") menubar = Menu(root) root.config(menu=menubar) mainapp=Application(root) root.mainloop() From mail at microcorp.co.za Tue Jun 13 04:24:44 2006 From: mail at microcorp.co.za (H J van Rooyen) Date: Tue, 13 Jun 2006 10:24:44 +0200 Subject: Intermittent Failure on Serial Port (Other thread code) References: <1150130330.843537.305310@f14g2000cwb.googlegroups.com> Message-ID: <00b801c68ec2$f7c01c80$03000080@hendrik> I would like to publicly thank Serge Orloff for the effort he has put in so far and his patience... He is a Scholar and a Gentleman. Serge Orloff wrote: | H J van Rooyen wrote: | | > Note that the point of failure is not the same place in the python file, but it | > is according to the traceback, again at a flush call... | | Yes, traceback is bogus. Maybe the error is raised during garbage | collection, although the strace you've got doesn't show that. The main | reason of the failure seems to be a workaround in python's function | new_buffersize, it doesn't clear errno after lseek and then this errno | pops up somewhere else. There are two places I can clearly see that | don't clear errno: file_dealloc and get_line. Obviously this stuff | needs to be fixed, so you'd better file a bug report. Ouch! - I am new in this neck of the woods - what are the requirements for something like this and where should I send it to so its useful? - so far its so very vague in my mind that I am not sure that I can actually tell someone else properly what's wrong - except for a "it does not work" bleat which is not very illuminating... | I'm not sure how | to work around this bug in the meantime, since it is still not clear | where this error is coming from. Try to pin point it. I will put in a lot of try - except stuff looking for this errno 29 and see what comes up and where. Not sure if this will catch it but it may give a clue.. |For example, if | your code relies on garbage collection to call file.close, try to close | all files in your program explicitly. It seems like a good idea anyway, | since your program is long running, errors during close are not that | significant. Instead of standard close I'd call something like this: | | def soft_close(f): | try: | f.close() | except IOError, e: | print >>stderr, "Hmm, close of file failed. Error was: %s" % | e.errno As you remark - the code is long running - its supposed to work for ever and come back up again if the power has failed - so for now the serial port is never explicitly closed - I open and close the other files as I use them to try to make sure the data is written to disk instead of just cached to memory. I will put this sort of thing in everywhere now to try and isolate whatever it is that is biting me, not only on the close statements. | | > The "close failed" is explicable - it seems to happen during closedown, with the | > port already broken.., | | It is not clear who calls lseek right before close. lseek is called by | new_buffersize that is called by file.read. But who calls file.read | during closedown? When I said closedown - I meant whatever the system does after the exception was raised - I have not yet gotten as far as writing a clean close... - so far I am concentrating on the polling protocol, to safely get the data from the readers to the disk - port to file.... hence the name :-) Now there is another thread running - it accesses files, (disk and a fifo to trigger the disk write) but not the serial port - I have not laid any stress on it because I thought it was irrelevant, but now I am not so sure - the code follows below - So question - is this error number a process global thing or is it local to a thread or an object? - it could be this thread that calls read while the other one is in the process of dying after the exception - it should not access the port, though, although it repetitively reads a fifo... - come to think of it - it could be this thread that first raises the ESPIPE for all I know (that is if its global and not thread specific)... def maintain_onsite(fifoname, filename): """Here we keep track of who is in, and who out of the site""" j = thread.get_ident() print 'New Thread identity printed by new thread is:', j pfifo = open(fifoname,'r',1) # Reading, line buffered unblock(pfifo) # call some magic global on_site #use top level dictionary to avoid a lot of copying s = "" d = {} while True: try: s = pfifo.readline() except IOError: time.sleep(1) continue if s == '': continue if s != 'goon\n': # see if we got a go on signal continue d = on_site # make a copy of the on site dictionary pfile = open(filename,'w',1) # The file of people on site for x in d: pfile.write(x + ' ' + d[x] + '\n') # rewrite it - a bit brute force... pfile.close() s = '' # clean out the receive string again Here is unblock code: # Some magic to make a file non blocking - from the internet def unblock(f): """Given file 'f', sets its unblock flag to true.""" fcntl.fcntl(f.fileno(), fcntl.F_SETFL, os.O_NONBLOCK) - Hendrik From gerkarcher at gmail.com Wed Jun 28 20:31:25 2006 From: gerkarcher at gmail.com (gerkarcher at gmail.com) Date: 28 Jun 2006 17:31:25 -0700 Subject: web Develop question In-Reply-To: <1151515979.877494.316720@m73g2000cwd.googlegroups.com> References: <1151514841.490454.284770@i40g2000cwc.googlegroups.com> <1151515979.877494.316720@m73g2000cwd.googlegroups.com> Message-ID: <1151541085.359563.156990@i40g2000cwc.googlegroups.com> Dear Luis , Thanks for your kindly answer , so you say that installing mod_python and a template like chetaah or dyango I can do like as I do with php and Apache ? < ? print........ ?> Thanks , regards Richard Luis M. Gonz?lez ha escrito: > gerkarcher at gmail.com wrote: > > hi guys , > > > > I' m new to python ...and I would like to ask you , wich is the best > > template for developing dinamic generated pages using python ? > > > > I would like to use something easy to install and develop like php > ? > tags and with a lots of features . > > > > thanks in advance and sorry for this silly question . > > > > regards, > > > > richard > > I suppose you're asking about frameworks. > There are many to choose from. There are two that are getting a lot of > attention lately: Django and Turbogears, but it seems there are as many > options as developers out there... > If you're running your own server, you can choose anyone. > The real problem is finding a shared hosting service with the option of > your choice (at an affordable price). > > I am very comfortable with bare-bones mod_python. Mod_python is a > module that embeds the python interpreter into Apache (a la php). It is > not a framework (what's more, many frameworks rely on mod_python), but > it gives you many facilities for web development. > > I find specially handy its publisher handle, which lets you match urls > to pages. > It can be complemented with a template system, like Cheetah (very good) > or its own PSP (python server pages implementation) as a template > system. > It also gives you the best performance (as far as I know, please > correct me if I'm wrong). > > Luis From max at alcyone.com Thu Jun 22 21:19:31 2006 From: max at alcyone.com (Erik Max Francis) Date: Thu, 22 Jun 2006 18:19:31 -0700 Subject: String negative indices? In-Reply-To: References: Message-ID: drtimhill at comcast.net wrote: > Is there some magic I'm missing here? Wouldn't it actually be better for Python to treat 0 as a > special case here, so that x[-2:0] and x[-2:] generated the same result? No, since x[-2:0:-1] already has meaning and it isn't what you want. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis The mind is not a vessel to be filled but a fire to be kindled. -- Plutarch From deets at nospam.web.de Fri Jun 23 09:07:13 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 23 Jun 2006 15:07:13 +0200 Subject: Unicode problem with exec In-Reply-To: References: Message-ID: <4g27bsF1jkkchU2@uni-berlin.de> Thomas Heller schrieb: > I'm using code.Interactive console but it doesn't work correctly > with non-ascii characters. I think it boils down to this problem: > > Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)] on > win32 > Type "help", "copyright", "credits" or "license" for more information. >>>> print u"?" > ? >>>> exec 'print u"?"' > Traceback (most recent call last): > File "", line 1, in ? > File "", line 1, in ? > File "c:\python24\lib\encodings\cp850.py", line 18, in encode > return codecs.charmap_encode(input,errors,encoding_map) > UnicodeEncodeError: 'charmap' codec can't encode character u'\x84' in > position 0: character maps to >>>> ^Z > > Why does the exec call fail, and is there a workaround? Most probably because you failed to encode the snippet as whole - so the embedded unicode literal isn't encoded properly. As your exec-encoding seems to be cp850, maybe exec u"print u'?'".encode("cp850") works. Diez From grante at visi.com Wed Jun 14 19:38:14 2006 From: grante at visi.com (Grant Edwards) Date: Wed, 14 Jun 2006 23:38:14 -0000 Subject: Numerics, NaNs, IEEE 754 and C99 References: <12904mjhl493t49@corp.supernews.com> <1290aik50hmk94a@corp.supernews.com> <4490329e$0$12356$636a55ce@news.free.fr> Message-ID: <12917f6jp7u90f8@corp.supernews.com> On 2006-06-14, Nick Maclaren wrote: > > In article , > Gary Herron writes: >|> >|> The IEEE standard specifies (plus or minus) infinity as the result of >|> division by zero. This makes sense since such is the limit of division >|> by a quantity that goes to zero. The IEEE standard then goes on to >|> define reasonable results for arithmetic between infinities and real >|> values. The production of, and arithmetic on, infinities is a choice >|> that any application may want allow or not. > > The mistake you have made (and it IS a mistake) is in assuming > that the denominator approaches zero from the direction > indicated by its sign. I assume the "you" in that sentence refers to the IEEE FP standards group. I just try to follow the standard, but I have found that the behavior required by the IEEE standard is generally what works best for my applications. > There are many reasons why it is likely to not be, but let's give only > two: > > It may be a true zero - i.e. a count that is genuinely zero, or > the result of subtracting a number from itself. I do real-world engineering stuff with measured physical quatities. There generally is no such thing as "true zero". > I fully agree that infinity arithmetic is fairly well-defined for > most operations, but it most definitely is not in this case. It should > be reserved for when the operations have overflowed. All I can say is that 1/0 => Inf sure seems to work well for me. -- Grant Edwards grante Yow! World War Three can at be averted by adherence visi.com to a strictly enforced dress code! From marshall.spight at gmail.com Fri Jun 23 17:44:11 2006 From: marshall.spight at gmail.com (Marshall) Date: 23 Jun 2006 14:44:11 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: <1151080381.150026.236440@r2g2000cwb.googlegroups.com> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <449b07bb$0$11073$9b4e6d93@newsread4.arcor-online.net> <1151028214.668765.182330@p79g2000cwp.googlegroups.com> <1151080381.150026.236440@r2g2000cwb.googlegroups.com> Message-ID: <1151099051.667267.202730@g10g2000cwb.googlegroups.com> Joe Marshall wrote: > Marshall wrote: > > Timo Stamm wrote: > > > > > > This is actually one of the most interesting threads I have read in a > > > long time. If you ignore the evangelism, there is a lot if high-quality > > > information and first-hand experience you couldn't find in a dozen books. > > > > Hear hear! This is an *excellent* thread. The evangelism is at > > rock-bottom > > and the open exploration of other people's way of thinking is at what > > looks to me like an all-time high. > > What are you, some sort of neo-static pseudo-relational > object-disoriented fascist? I prefer to think in terms of "object orientatedness." But you're close. I'd say rather that I'm a quasi-theoretical, neo-relational, crypto-logical fascist. But definitely fascist. Once after a lengthy debate with a schemer, he dubbed me (good naturedly) "Il Duce." Heh. Marshall From pjb at informatimago.com Tue Jun 27 01:57:26 2006 From: pjb at informatimago.com (Pascal Bourguignon) Date: Tue, 27 Jun 2006 07:57:26 +0200 Subject: What is Expressiveness in a Computer Language References: <7zy7vt1mz2.fsf@app-3.diku.dk> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <1151384511.223582.305760@m73g2000cwd.googlegroups.com> Message-ID: <87odwf3zuh.fsf@thalassa.informatimago.com> "Marshall" writes: > Yes, an important question (IMHO the *more* important question > than the terminology) is what *programs* do we give up if we > wish to use static typing? I have never been able to pin this > one down at all. Well, given Turing Machine equivalence... I'd mention retrospective software. But you can always implement the wanted retrospective features as a layer above the statically typed language. So the question is how much work the programmer needs to do to implement a given program with static typing or with dynamic typing. > The real question is, are there some programs that we > can't write *at all* in a statically typed language, because > they'll *never* be typable? I think there might be, but I've > never been able to find a solid example of one. More than *never* typable, you want to identify some kind of software that is not *economically* statically typable. Was it costlier to develop the software developed in non statically typed programming languages than in a statically typed programming language? -- __Pascal Bourguignon__ http://www.informatimago.com/ "I have challenged the entire quality assurance team to a Bat-Leth contest. They will not concern us again." From larry.bates at websafe.com Fri Jun 2 16:42:58 2006 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 02 Jun 2006 15:42:58 -0500 Subject: Open Source Charting Tool In-Reply-To: <1L0gg.1841$Su3.159041@news20.bellglobal.com> References: <1L0gg.1841$Su3.159041@news20.bellglobal.com> Message-ID: ReportLab Graphics can do 2D and pie charts, but I don't think it does 3D charts yet. www.reporlab.org Larry Bates A.M wrote: > Hi, > > > > I developed a HTML reporting tool that renders Oracle data to HTML and > Oracle. > > > > At this point I have to add charts (3d bars and pie charts) to this > application. I don't think that I have to do it from scratch. > > > > Is there any open source charting tool that help me create charts in JPG or > gif format? > > > > Thanks, > > Alan > > From kkylheku at gmail.com Fri Jun 9 14:32:18 2006 From: kkylheku at gmail.com (Kaz Kylheku) Date: 9 Jun 2006 11:32:18 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> Message-ID: <1149877938.754797.119750@g10g2000cwb.googlegroups.com> Xah Lee wrote: > Has anyone read this paper? And, would anyone be interested in giving a > summary? Not you, of course. Too busy preparing the next diatribe against UNIX, Perl, etc. ;) From aarondesk at yahoo.com Mon Jun 19 19:05:38 2006 From: aarondesk at yahoo.com (aarondesk) Date: 19 Jun 2006 16:05:38 -0700 Subject: Function definition Message-ID: <1150758338.302466.102040@r2g2000cwb.googlegroups.com> I have a little .py file that has the format: def fxn(a): do stuff other stuff ... r = fxn(a) .... Now I've tried putting the function declaration after the call but the program wouldn't work. Is there anyway to put function declarations at the end of the program, rather than putting them at the beginning, which is rather clunky? Thanks. Aaron From diffuser78 at gmail.com Wed Jun 21 10:43:17 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 21 Jun 2006 07:43:17 -0700 Subject: Remote Boot Manager Scripting (Python) Message-ID: <1150900997.367853.106320@g10g2000cwb.googlegroups.com> I just started to write a small project in Python. I was wondering if there can be something like remote boot manager. I have to remotely start a computer. It has dual boot (WinXP and Linux). My remote computer is Linux which will send command to remotely boot the other computer. Can we write python script or some utility which would let us select the Operating System to boot ? For example If we send parameter "WIN" it boots into Windows and if we send "NIX" it boots into Linux. Every help is appreciated. Thanks From pc at p-cos.net Thu Jun 22 03:59:29 2006 From: pc at p-cos.net (Pascal Costanza) Date: Thu, 22 Jun 2006 09:59:29 +0200 Subject: What is a type error? In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <7i3mg.204167$8W1.155367@fe1.news.blueyonder.co.uk> <44992e6c$2$664$bed64819@news.gradwell.net> <%Igmg.464974$xt.353729@fe3.news.blueyonder.co.uk> Message-ID: <4fv0v3F1kipa6U1@individual.net> Chris Smith wrote: > While this effort to salvage the term "type error" in dynamic languages > is interesting, I fear it will fail. Either we'll all have to admit > that "type" in the dynamic sense is a psychological concept with no > precise technical definition (as was at least hinted by Anton's post > earlier, whether intentionally or not) or someone is going to have to > propose a technical meaning that makes sense, independently of what is > meant by "type" in a static system. What about this: You get a type error when the program attempts to invoke an operation on values that are not appropriate for this operation. Examples: adding numbers to strings; determining the string-length of a number; applying a function on the wrong number of parameters; applying a non-function; accessing an array with out-of-bound indexes; etc. >> In the terminology I'm suggesting, the object has no type in this language >> (assuming we're talking about a Smalltalk-like language without any type system >> extensions). > > I suspect you'll see the Smalltalk version of the objections raised in > response to my post earlier. In other words, whatever terminology you > think is consistent, you'll probably have a tough time convincing > Smalltalkers to stop saying "type" if they did before. If you exclude > "message not understood" as a type error, then I think you're excluding > type errors from Smalltalk entirely, which contradicts the psychological > understanding again. Sending a message to an object that does not understand that message is a type error. The "message not understood" machinery can be seen either as a way to escape from this type error in case it occurs and allow the program to still do something useful, or to actually remove (some) potential type errors. Which view you take probably depends on what your concrete implementation of "message not understood" does. For example, if it simply forwards the message to another object that is known to be able to respond to it, then you remove a potential type error; however, if it pops up a dialog box to ask the user how to continue from here, it is still a type error, but just gives you a way to deal with it at runtime. Pascal -- 3rd European Lisp Workshop July 3 - Nantes, France - co-located with ECOOP 2006 http://lisp-ecoop06.bknr.net/ From maric at aristote.info Mon Jun 26 21:01:19 2006 From: maric at aristote.info (Maric Michaud) Date: Tue, 27 Jun 2006 03:01:19 +0200 Subject: Replace Whole Object Through Object Method In-Reply-To: <1151354259.082966.25820@p79g2000cwp.googlegroups.com> References: <1151337453.804750.293180@b68g2000cwa.googlegroups.com> <44a041a6$0$17612$636a55ce@news.free.fr> <1151354259.082966.25820@p79g2000cwp.googlegroups.com> Message-ID: <200606270301.20218.maric@aristote.info> Le lundi 26 juin 2006 22:37, digitalorganics at gmail.com a ?crit?: > Won't work because there will be employers that aren't workers. > And yes, only some workers will become employers, but also only some > employers will also be workers (at some point in program). Let me be > more clear: > > workers > --> subset of workers --become--> employers > employers > --> subset of employers --become--> workers > > It is very important that both should maintain attribute values, > regardless of whether they take on new "roles". Furthermore, this is a > very simple case and ultimately in my program an object should be able > to dynamically take on a multitude of roles (classes of behavior) > without mucking at all with their pre-existing states. This seem to be a OO design problem and you clearly make a misuse of inheritance, if a person can eventually have many roles, but doesn't have this role for all his lifetime, then the person *is* not his roles. That the meaning of inheritance, class B(A) means a B is a A. The association between a person and his roles is obviously a 1-n association, which can be rendered by different patterns (delegation, composition, strategy, etc.). You should google on "design patterns" and make your choice. -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From siona at chiark.greenend.org.uk Thu Jun 1 11:16:51 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 01 Jun 2006 16:16:51 +0100 (BST) Subject: DB-API: how can I find the column names in a cursor? References: Message-ID: A.M wrote: >The other problem is accessing data in each row by column name. In Ruby I >can say: > >Print row["ColName"] > >In Python; however, I must access to row contents by integer index, like >PRINT ROW[0], which reduces my program's readability. > >Can I access to row's contents by column name? columns = dict((name, col) for col, name in enumerate(cursor.description)) print row[columns["ColName"]] And please don't top-post. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From aleax at mac.com Thu Jun 1 22:16:15 2006 From: aleax at mac.com (Alex Martelli) Date: Thu, 1 Jun 2006 19:16:15 -0700 Subject: An oddity in list comparison and element assignment References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> <1149183898.338397.199070@y43g2000cwc.googlegroups.com> Message-ID: <1hg9oed.gknalqf3jq8N%aleax@mac.com> wrote: ... > I agree with Alex that checking for this type of inequality is not a > trivial programming exercise. It requires (at least) a parallel I'm not asking for ANY programming: I'm asking for a *straightforward operational definition*. If the concept which you hanker after is NOT subject to a straightforward operational definition, then I would rule out that said concept could POSSIBLY be "natural". > Alternatively, it might make sense to disallow == for containers by > raising a TypeError although that would eliminate a largely useful > feature. This may be the best example I've ever seen of Emerson's well-known quote about foolish consistency -- except that I don't think this behavior would be "consistent" (either wisely or foolishly) with anything except a vague handwaving set of constraints whose "naturalness" (assuming it's unfeasible to provide a good and straightforward operational definition) is out of the question. Alex From http Sun Jun 25 10:28:04 2006 From: http (Paul Rubin) Date: Sun, 25 Jun 2006 14:28:04 GMT Subject: pypy-0.9.0: stackless, new extension compiler References: Message-ID: <7xwtb5cnt7.fsf@ruckus.brouhaha.com> I've been away from Usenet for a while but this is the most interesting stuff I've seen here in ages. Way cool. From luismgz at gmail.com Wed Jun 21 13:26:08 2006 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 21 Jun 2006 10:26:08 -0700 Subject: Iterating a list in reverse ? In-Reply-To: <1150909005.604896.122290@m73g2000cwd.googlegroups.com> References: <1150909005.604896.122290@m73g2000cwd.googlegroups.com> Message-ID: <1150910768.407356.121330@y41g2000cwy.googlegroups.com> Andy Dingley wrote: > Python newbie: I've got this simple task working (in about ten > different ways), but I'm looking for the "favoured" and "most Python > like" way. > > Forwards I can do this > for t in listOfThings: > print t > > Now how do I do it in reverse? In particular, how might I do it if I > only wanted to iterate part-way through (with a conditional test and a > break), or if I had a large list ? > > reverse( listOfThings ) > for t in listOfThings: > print t listOfThings = [1,2,3,4,5,6] for i in listOfThings: print i # print from 1 to 6 for i in listOfThings[::-1]: print i # prints from 6 to 1 From td_01 at att.net.invalid Mon Jun 19 17:01:50 2006 From: td_01 at att.net.invalid (Tom Del Rosso) Date: Mon, 19 Jun 2006 21:01:50 GMT Subject: Active Python versions References: Message-ID: <2hElg.41514$mF2.19600@bgtnsc04-news.ops.worldnet.att.net> Trent Mick typed in news://mailman.7218.1150748874.27775.python-list at python.org, > Tom Del Rosso wrote: >> Why is the Windows msi install file for ActivePython-2.4.3.12 only >> 15MB whereas the older msi file for ActivePython-2.4.2.10 was 19MB? >> >> BTW, is that the prefered Python environment? > > Are you sure you are comparing the right packages? By my count: > > ActivePython-2.4.2.10-win32-x86.msi 19,053 KB > ActivePython-2.4.3.12-win32-x86.msi 19,237 KB > > Note that the Windows *64-bit* builds are smaller (around 15MB) > because they do not include PyWin32. Thanks. I didn't notice the file name was wrong until I tried to install it. Can I ask you about alternative environments? How do Active Python and IDLE from python.org compare? I'm just starting out with it and I know they run the same code but I don't want to have to change environments later. -- Reply in group, but if emailing add another zero, and remove the last word. From quentel.pierre at wanadoo.fr Sun Jun 25 05:42:29 2006 From: quentel.pierre at wanadoo.fr (Pierre Quentel) Date: 25 Jun 2006 02:42:29 -0700 Subject: Can you help me with the below code? Urgent! In-Reply-To: <1151226120.634245.97570@m73g2000cwd.googlegroups.com> References: <1151224178.479401.119620@r2g2000cwb.googlegroups.com> <1151225637.492538.122890@p79g2000cwp.googlegroups.com> <1151226120.634245.97570@m73g2000cwd.googlegroups.com> Message-ID: <1151228549.630209.28090@c74g2000cwc.googlegroups.com> gokcemutlu at gmail.com a ?crit : > Hello, > > You're right about it but this is a simple code which tells my problem. > I need actually the frame itself for states and unfortunately > copy.copy(frame) throws an exception. Pickling also doesn't work. Do > you have any other idea? > > Thanks, > > Gokce. > In your original post you said you wanted to store local variables, but it seems that you need to store more information than this : could you specify which ones ? Since you can't copy the stack frame, maybe you can copy only the attributes you need Pierre From jes at nl.demon.net Sat Jun 3 18:02:11 2006 From: jes at nl.demon.net (Jim Segrave) Date: Sat, 03 Jun 2006 22:02:11 -0000 Subject: wxpython wxgrid question References: <1149366330.999234.299880@u72g2000cwu.googlegroups.com> Message-ID: <12841n3lmt36v2a@corp.supernews.com> In article <1149366330.999234.299880 at u72g2000cwu.googlegroups.com>, wrote: >Hi, > > I am looking for example code that consists of just a frame and a >grid(10x2). The grid must fill the its parent even if the frame is >resized. This simple program makes a two element window, the lower half of which is a gridded set of labels which resize with the window. The important part is the columnconfigure() and rowconfigure() method calls on the container widget for the grid. See http://infohost.nmt.edu/tcc/help/pubs/tkinter/grid-config.html #!/usr/local/bin/python from Tkinter import * root = Tk() # create a frame (unused, but shared with gridded frame) f = Frame(height = 100) f.pack(expand = YES, fill = BOTH) # create a frame for a gridded display gf = Frame() gf.pack(expand = YES, fill = BOTH) # create a 3 x 4 array of labels, each with a different background # Make each row and column have equal weights, so they'll # grow and shrink together for row in range(3): gf.rowconfigure(row, weight = 1) for col in range(4): gf.columnconfigure(col, weight = 1) Label(gf, text = "Row: %d\nCol: %d" % (row, col), bg = "#%02x%02x%02x" % ((row * 4 + col) * 16, (row * 4 + col) * 16, (row * 4 + col) * 16), fg = "#ffffff" ).grid(row = row, column = col, sticky = NSEW) root.mainloop() -- Jim Segrave (jes at jes-2.demon.nl) From writeson at charter.net Wed Jun 14 20:35:09 2006 From: writeson at charter.net (writeson) Date: 14 Jun 2006 17:35:09 -0700 Subject: wxPython problems with Fedora Core 5 In-Reply-To: <1149317933.786386.304070@c74g2000cwc.googlegroups.com> References: <1149271626.481398.34440@h76g2000cwa.googlegroups.com> <1149317933.786386.304070@c74g2000cwc.googlegroups.com> Message-ID: <1150331709.388852.50960@u72g2000cwu.googlegroups.com> Frank, Thanks for the link, that solved the problem for me with FC5! That was a great help to me! Doug From sjmachin at lexicon.net Fri Jun 9 18:33:16 2006 From: sjmachin at lexicon.net (John Machin) Date: Sat, 10 Jun 2006 08:33:16 +1000 Subject: Most elegant way to generate 3-char sequence In-Reply-To: <1149889784.391965.271570@h76g2000cwa.googlegroups.com> References: <1149889784.391965.271570@h76g2000cwa.googlegroups.com> Message-ID: <4489F72C.7010101@lexicon.net> On 10/06/2006 7:49 AM, Rob Cowie wrote: > Hi all, > > I wish to generate a sequence of the form 'aaa', 'aab', aac'.... 'aba', > 'abb', 'abc' etc. all the way to 'zzz'. > > How would you construct a generator to acheive this? > > A simple, working but somewhat inelegant solution is... You're not wrong. > > alpha = ['a','b','c','d'] #shortened for brevity Hope you remember the alphabet correctly. Why type all that punctuation? Any reason this cruft is global (i.e. not local to the generator)? > alpha2 = ['a','b','c','d'] > alpha3 = ['a','b','c','d'] Hope you get the redundant copy/paste right. > > def generator(): > for char in alpha: Why stop at two spaces? One-space indentation is syntactically correct :-) > for char2 in alpha2: > for char3 in alpha3: > yield char + char2 + char3 > > x = generate() Did you meant "generator"? > x.next() # etc, etc, etc, > |>> def generator(): ... import string ... alpha = string.ascii_lowercase ... for char in alpha: ... for char2 in alpha: ... for char3 in alpha: ... yield char + char2 + char3 ... |>> x = generator() |>> the_lot = list(x) |>> len(the_lot) == 26 ** 3 True |>> [the_lot[i] for i in (0, 1, 25, 26, -27, -26, -1)] ['aaa', 'aab', 'aaz', 'aba', 'zyz', 'zza', 'zzz'] Cheers, John From steve at holdenweb.com Fri Jun 9 03:39:26 2006 From: steve at holdenweb.com (Steve Holden) Date: Fri, 09 Jun 2006 08:39:26 +0100 Subject: better Python IDE? Mimics Maya's script editor? In-Reply-To: <1149810048.765664.107820@i40g2000cwc.googlegroups.com> References: <1149810048.765664.107820@i40g2000cwc.googlegroups.com> Message-ID: warpcat wrote: > I've been scripting in Maya, via mel for years now. Recently learning > to Python, love it. Thing that's driving me nuts it the IDE. I'm > using PythonWin right now and trying to find something better, mainly > with this functionality: > > In Maya's mel script editor window, it's split into two sections. > Bottom window you can enter commands (where your script lives), top > window gives results. The thing I'm really used to is highlighting X# > of lines in the bottom window (little snippits from my script), and > executing that selection, with instant feedback of the results on top. > This really speeds my workflow. > It seems completely missing (so far) in Python's IDE. I have to copy > and paste from a script to the ide window to execute and see the > results, or I have to make a bunch of "buffer scripts" with just the > code snippetsI want to test in. Seems *really* clunky. > > Does anyone know of a scripting enviroment for Python that mimics what > Maya's script editor has? Much appreciated. > I don't know of anything that exhibits the exact behaviour you describe, but then again you might like to consider that i found your request very odd. I'm sure that way of testing code seems entirely natural to you, but I can honestly say that in almost ten years using Python it's not something I have ever wished for. You might also wish to reconsider your approach to the Python community. "PythonWin sucks" isn't my idea of how to win friends and influence people in a first posting to a usenet newsgroup. By and large we are a friendly bunch here, but you don't want to start off on the wrong foot :-) Take a look at DrPython (http://drpython.sourceforge.net/) - you might be able to script it to do what you want, and anyway it's more of a lightweight interface than PythonWin so you might find it less intrusive. [Irrelevant ramble: Man, SoureceForge really know how to screw a web site up. I'm guessing they think that the changes of the last year are "improvements". Boy are they wrong. What a mess!] regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From johnjsal at NOSPAMgmail.com Fri Jun 30 14:30:20 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 30 Jun 2006 18:30:20 GMT Subject: Module executed twice when imported! In-Reply-To: <1151534230.603274.144810@x69g2000cwx.googlegroups.com> References: <1151534230.603274.144810@x69g2000cwx.googlegroups.com> Message-ID: <05epg.2385$No6.49436@news.tufts.edu> Simon Forman wrote: > I don't get it either but there may be a clue in the docs for the > execfile() function > (http://docs.python.org/lib/built-in-funcs.html#l2h-24) > > "It is different from the import statement in that it does not use the > module administration --" Just after the above statement, it also says: "it reads the file unconditionally and does not create a new module." so perhaps that means that it isn't really being imported the second time, just that the contents are being executed? From g.brandl-nospam at gmx.net Thu Jun 29 04:52:43 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Thu, 29 Jun 2006 10:52:43 +0200 Subject: Bug reporting impossible In-Reply-To: References: Message-ID: Nick Maclaren wrote: > Currently logins are disabled to sourceforge.net, and (despite the > comments) it won't let me report a bug anonymously. Does anyone > know whether this is short or long term? I have a bug in 2.5 to > report - which has been there for a while and isn't overwhelmingly > critical and has been there for a while. > > Create a file called '' in your current directory containing > 'print "Oh, yeah?\n"' and then import a module that doesn't exist. > Don't include the single quotes. You should have said what the bug is. To save others reproducing this: you get a traceback akin to $ python Python 2.4.3 (#1, May 8 2006, 18:29:03) [GCC 3.4.6 (Gentoo 3.4.6-r1, ssp-3.4.5-1.0, pie-8.7.9)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import xyzzy Traceback (most recent call last): File "", line 1, in ? print "Oh, yeah?\n" ImportError: No module named xyzzy >>> The problem is that Python does not know whether a file name is bogus or an actual file. So it was assumed that names like "" or "" are safe enough to use them as subsitutes. I don't know whether this is worth fixing. Geor From max at alcyone.com Sun Jun 11 03:11:28 2006 From: max at alcyone.com (Erik Max Francis) Date: Sun, 11 Jun 2006 00:11:28 -0700 Subject: Xah Lee network abuse In-Reply-To: References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148495974.975395.12920@i40g2000cwc.googlegroups.com> <1149998343.493200.144990@h76g2000cwa.googlegroups.com> Message-ID: Philippa Cowderoy wrote: > It is. However, the onus is on the defendant to show that it's true, > rather than on the claimant to show that it's false. That also depends on the jurisdiction. > I assume the "he" > refers to Brandon? No, I was referring to the person who he was replying to, i.e., you. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Twenty-four hours a day, three-hundred sixty-five days a year as Secretary of Defense, I lived the Cold War. -- Robert S. McNamara From jstroud at ucla.edu Tue Jun 13 16:27:58 2006 From: jstroud at ucla.edu (James Stroud) Date: Tue, 13 Jun 2006 13:27:58 -0700 Subject: "groupby" is brilliant! In-Reply-To: References: <1150180151.643245.148210@y43g2000cwc.googlegroups.com> Message-ID: James Stroud wrote: > Frank Millman wrote: > >> Hi all >> >> This is probably old hat to most of you, but for me it was a >> revelation, so I thought I would share it in case someone has a similar >> requirement. >> >> I had to convert an old program that does a traditional pass through a >> sorted data file, breaking on a change of certain fields, processing >> each row, accumulating various totals, and doing additional processing >> at each break. I am not using a database for this one, as the file >> sizes are not large - a few thousand rows at most. I am using csv >> files, and using the csv module so that each row is nicely formatted >> into a list. >> >> The traditional approach is quite fiddly, saving the values of the >> various break fields, comparing the values on each row with the saved >> values, and taking action if the values differ. The more break fields >> there are, the fiddlier it gets. >> >> I was going to do the same in python, but then I vaguely remembered >> reading about 'groupby'. It took a little while to figure it out, but >> once I had cracked it, it transformed the task into one of utter >> simplicity. >> >> Here is an example. Imagine a transaction file sorted by branch, >> account number, and date, and you want to break on all three. >> >> ----------------------------- >> import csv >> from itertools import groupby >> from operator import itemgetter >> >> BRN = 0 >> ACC = 1 >> DATE = 2 >> >> reader = csv.reader(open('trans.csv', 'rb')) >> rows = [] >> for row in reader: >> rows.append(row) >> >> for brn,brnList in groupby(rows,itemgetter(BRN)): >> for acc,accList in groupby(brnList,itemgetter(ACC)): >> for date,dateList in groupby(accList,itemgetter(DATE)): >> for row in dateList: >> [do something with row] >> [do something on change of date] >> [do something on change of acc] >> [do something on change of brn] >> ----------------------------- >> >> Hope someone finds this of interest. >> >> Frank Millman >> > > I'm sure I'm going to get a lot of flac on this list for proposing to > turn nested for-loops into a recursive function, but I couldn't help > myself. This seems more simple to me, but for others it may be difficult > to look at, and these people will undoubtedly complain. > > > import csv > from itertools import groupby > from operator import itemgetter > > reader = csv.reader(open('trans.csv', 'rb')) > rows = [] > for row in reader: > rows.append(row) > > def brn_doer(row): > [doing something with brn here] > > def acc_doer(date): > [you get the idea] > > [etc.] > > doers = [brn_doer, acc_doer, date_doer, row_doer] > > def doit(rows, doers, i=0): > for r, alist in groupby(rows, itemgetter(i)): > doit(alist, doers[1:], i+1) > doers[0](r) > > doit(rows, doers, 0) > > Now all of those ugly for loops become one recursive function. Bear in > mind, its not all that 'elegant', but it looks nicer, is more succinct, > abstracts the process, and scales to arbitrary depth. Tragically, > however, it has been generalized, which is likely to raise some hackles > here. And, oh yes, it didn't answer exactly your question (which you > didn't really have). I'm sure I will regret this becuase, as you will > find, suggesting code on this list with additional utility is somewhat > discouraged by the vociferous few who make a religion out of 'import this'. > > Also, I still have no idea what 'groupby' does. It looks interesting > thgough, thanks for pointing it out. > > James > Forgot to test for stopping condition: def doit(rows, doers, i=0): for r, alist in groupby(rows, itemgetter(i)): if len(doers) > 1: doit(alist, doers[1:], i+1) doers[0](r) -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From eric_brunel at despammed.com Thu Jun 1 07:12:18 2006 From: eric_brunel at despammed.com (Eric Brunel) Date: Thu, 01 Jun 2006 13:12:18 +0200 Subject: Function mistaken for a method Message-ID: Hi all, I just stepped on a thing that I can't explain. Here is some code showing the problem: ----------------------------- class C: f = None def __init__(self): if self.f is not None: self.x = self.f(0) else: self.x = 0 class C1(C): f = int class C2(C): f = lambda x: x != 0 o1 = C1() print o1.x o2 = C2() print o2.x ----------------------------- Basically, I want an optional variant function across sub-classes of the same class. I did it like in C1 for a start, then I needed something like C2. The result is... surprising: 0 Traceback (most recent call last): File "func-vs-meth.py", line 18, in ? o2 = C2() File "func-vs-meth.py", line 5, in __init__ self.x = self.f(0) TypeError: () takes exactly 1 argument (2 given) So the first works and o1.x is actually 0. But the second fails because self is also being passed as the first argument to the lambda. Defining a "real" function doesn't help: the error is the same. My actual question is: why does it work in one case and not in the other? As I see it, int is just a function with one parameter, and the lambda is just another one. So why does the first work, and not the second? What 'black magic' takes place so that int is not mistaken for a method in the first case? -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From claird at lairds.us Sat Jun 24 21:55:56 2006 From: claird at lairds.us (Cameron Laird) Date: Sun, 25 Jun 2006 01:55:56 +0000 Subject: Python is fun and useful (was: Python is fun (useless social thread) ; -)) References: Message-ID: In article , Carl Trachte wrote: . . . >Yes. I was a production geologist in a copper mine in the mid 90's. Our >mine planning software vendor Mintec (www.mintec.com) had chosen it as >their API for programmatic access to the three dimensional geologic block >model and two dimensional polygons that defined geologic shapes on a level >bench or in vertical cross section. > >> >> Or did you just like what you saw and decided to learn it for fun? > >That too. I had been using Visual Basic. For what I was doing (mine >engineering), there was just a lot more functionality available in Python >and its external modules (numeric, for example). Organizing a lot of >engineering data dumped as text is easier in Python than it is in VB >(IMO), because of the way Python handles lists and dictionaries. > >> >> Also, how did you go about learning it? (i.e., like I described above, I >started with the main stuff then moved on to the different available >frameworks) > >I started with Mintec's mine planning software API, then realized that a >lot of stuff was easier in Python. VB was great for making GUI's quickly. > Python (Tkinter) is harder because you have to code your windows >(although once I got over that initial hump, it got a lot easier - there's >decent documentation for Tkinter on the web, and it doesn't cost a >thing!). > >My employer was good enough to send me to M. Lutz' 3 day course on Python >in Colorado. This was helpful. Up until that time I had been coding VB >in Python (a lot of it was "translating" code from one language to the >other). After that course I started to think in Python and make better >use of the features Python had (OO, exception handling, etc.). > >> >> Was there any necessity in the specifics you learned, or did you just >dabble in something (e.g. wxPython) for fun? > >As I mentioned with the Tkinter example above, there was almost always >necessity. Fortunately the stuff we do necessitates a lot of different >language features and modules. The datetime module was something I didn't >know about until I bought the latest version of the Python cookbook. The >thing is a huge productivity boost, especially for the stuff I do >(daily/monthly/yearly production reports). > >> >> Are there still some things you feel you need to learn or improve? > >Always. Always. Always. Extending to Fortran and C are things I'd like >to accomplish. There is a lot of old, but useful Fortran code around. If >you can marry it with Python instead of trying to rewrite it, that's a lot >of coding time (and money) saved. There are accounts of this sort of >thing out on the web, but I'm yet to accomplish it myself. Langtangen's >scientific Python book offers a start. I've got a copy and have read >through it, but I've got to work on some real examples before I have any >success with it. I'm not there yet. > >> >> Additional comments/complains here: :) > >Life's too short to use and enjoy everything Python's got to offer. :-) . . . Indeed. Your testimony deserves particular attention, I think, because I believe the applicability of Python and related techniques to process control, engineering programming, and so on, is vastly under-appreciated. Conventional wisdom in these domains sees Visual Basic, Visual C++, and Fortran as suitable vehicles. You've seen how limiting this is. For reasons that I can elaborate at more length later, I'd love to diffuse awareness of Python's potential in mining and other "real-world" industries. The Agile Control Forum is made for just such purposes. Although it's been rather quiet recently, that might change soon. It'd be great to have you tell your story in the ACF Wiki. From jj_frap at hotmail.com Sun Jun 4 18:15:20 2006 From: jj_frap at hotmail.com (jj_frap) Date: 4 Jun 2006 15:15:20 -0700 Subject: Max function question: How do I return the index of the maximum value of a list? Message-ID: <1149459320.802652.186930@i40g2000cwc.googlegroups.com> I'm new to programming in Python and am currently writing a three-card poker simulator. I have completed the entire simulator other than determining who has the best hand (which will be far more difficult than the aspects I've codes thus far)...I store each player's hand in a list of hand objects and I determine hand strength via a handstrength list with one element for each player. When I try to print the "winner" (I've not coded for kicker strength and ties yet) via the max function, it returns the maximum value in the list rather than the index associated with that value. How do I return the index? From sjmachin at lexicon.net Fri Jun 2 19:40:55 2006 From: sjmachin at lexicon.net (John Machin) Date: Sat, 03 Jun 2006 09:40:55 +1000 Subject: Initializing an attribute that needs the object In-Reply-To: References: <4480be5b$0$27367$626a54ce@news.free.fr> Message-ID: <4480CC87.8050006@lexicon.net> On 3/06/2006 9:17 AM, David Pratt **TOPPOSTED**: > Hi Bruno. This is certainly what I was missing. Thank you. I am afraid I > am behind the times with use of object. Will I only use object when I am > not subclassing? More precisely, don't use object when you are subclassing. > Where will I find a document that provides info on the > use of object in new style classes? > Other way up :-) A new-style class is one which inherits ultimately from the type that is called "object". class NewStyleClass(object): pass class OldStyleClass(): pass Docs are a bit ummmm ... See this: http://www.python.org/doc/newstyle/ HTH, John From andrew.arobert at gmail.com Thu Jun 8 05:25:18 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Thu, 08 Jun 2006 05:25:18 -0400 Subject: what are you using python language for? In-Reply-To: <4487c0cd$0$7763$7a628cd7@news.club-internet.fr> References: <4487c0cd$0$7763$7a628cd7@news.club-internet.fr> Message-ID: <128fr8g7aeh2r20@corp.supernews.com> I use python and the pymqi module to work with IBM WebSphere MQSeries and IBM WebSphere Message broker. From spam.noam at gmail.com Fri Jun 9 01:49:00 2006 From: spam.noam at gmail.com (spam.noam at gmail.com) Date: 8 Jun 2006 22:49:00 -0700 Subject: Allowing zero-dimensional subscripts References: <1149801040.936452.26270@i40g2000cwc.googlegroups.com> <1149807149.516004.48590@f6g2000cwb.googlegroups.com> Message-ID: <1149832139.948242.64160@f6g2000cwb.googlegroups.com> Hello, Terry Reedy wrote: > So I do not see any point or usefulness in saying that a tuple subcript is > not what it is. I know that a tuple is *constructed*. The question is, is this, conceptually, the feature that allows you to ommit the parentheses of a tuple in some cases. If we see this as the same feature, it's reasonable that "nothing" won't be seen as an empty tuple, just like "a = " doesn't mean "a = ()". However, if we see this as a different feature, which allows multidimensional subscript by constructing a tuple behind the scenes, constructing an empty tuple for x[] seems very reasonable to me. Since in some cases you can't have the parentheses at all, I think that x[] makes sense. Noam From tjreedy at udel.edu Thu Jun 8 22:15:37 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 8 Jun 2006 22:15:37 -0400 Subject: Allowing zero-dimensional subscripts References: <1149801040.936452.26270@i40g2000cwc.googlegroups.com> <1149807149.516004.48590@f6g2000cwb.googlegroups.com> Message-ID: wrote in message news:1149807149.516004.48590 at f6g2000cwb.googlegroups.com... > Terry Reedy wrote: >> > In a few more words: Currently, an object can be subscripted by a few >> > elements, separated by commas. It is evaluated as if the object was >> > subscripted by a tuple containing those elements. >> >> It is not 'as if'. 'a,b' *is* a tuple and the object *is* subcripted >> by a >> tuple. >> Adding () around the non-empty tuple adds nothing except a bit of noise. >> > > It doesn't necessarily matter, but technically, it is not "a tuple". Tell that to the compiler. Here the code again. >>> dis(compile('x[a,b]','','eval')) 0 0 LOAD_NAME 0 (x) 3 LOAD_NAME 1 (a) 6 LOAD_NAME 2 (b) 9 BUILD_TUPLE 2 12 BINARY_SUBSCR 13 RETURN_VALUE >>> dis(compile('x=a,b','','single')) 1 0 LOAD_NAME 0 (a) 3 LOAD_NAME 1 (b) 6 BUILD_TUPLE 2 9 STORE_NAME 2 (x) 12 LOAD_CONST 0 (None) 15 RETURN_VALUE The same exact code to build the tuple a,b. > The "1, 2" in "x[1, 2]" isn't evaluated according to the same rules as > in "x = 1, 2" >>> dis(compile('x[1,2]','','eval')) 0 0 LOAD_NAME 0 (x) 3 LOAD_CONST 2 ((1, 2)) 6 BINARY_SUBSCR 7 RETURN_VALUE >>> dis(compile('x=1,2','','single')) 1 0 LOAD_CONST 3 ((1, 2)) 3 STORE_NAME 0 (x) 6 LOAD_CONST 2 (None) 9 RETURN_VALUE Same exact tuple literal. The tuple rules are the same. >- for example, you can have "x[1, 2:3:4, ..., 5]", which > isn't a legal tuple outside of square braces - in fact, it even isn't > legal inside parens: "x[(1, 2:3:4, ..., 5)]" isn't legal syntax. Yes, slice and ellipsis literals are only valid directly inside brackets. And it is definitely worth knowing about them and that this is one place where a tuple cannot be parenthesized. But once they are accepted, the slice and ellipsis objects are members of the resulting tuple like any other. >>> dis(compile("x[1, 2:3:4, ..., 5]", '','eval')) 0 0 LOAD_NAME 0 (x) 3 LOAD_CONST 0 (1) 6 LOAD_CONST 1 (2) 9 LOAD_CONST 2 (3) 12 LOAD_CONST 3 (4) 15 BUILD_SLICE 3 18 LOAD_CONST 4 (Ellipsis) 21 LOAD_CONST 5 (5) 24 BUILD_TUPLE 4 27 BINARY_SUBSCR 28 RETURN_VALUE So I do not see any point or usefulness in saying that a tuple subcript is not what it is. Terry Jan Reedy From tactics40 at gmail.com Fri Jun 23 11:47:42 2006 From: tactics40 at gmail.com (tactics40 at gmail.com) Date: 23 Jun 2006 08:47:42 -0700 Subject: Opening a file with system default application Message-ID: <1151077662.598370.214490@c74g2000cwc.googlegroups.com> I'm writing a GUI application in Jython which takes a database text file and performs some operations on the data, finally spitting out a group of CSV files. I generate a log file and several CSV files and I thought it would be helpful if I could add a button the user could click on to automatically launch the log file or the CSV output files using the default text editor / spreadsheet editor on their system. Does Python (or Java, since I'm using jython) have a clean cut way to do this? From bj_666 at gmx.net Wed Jun 14 06:42:28 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 14 Jun 2006 12:42:28 +0200 Subject: About Threading - implementation References: Message-ID: In , Dara Durum wrote: > Under Python the threads are simulated by Python Interpreter as when > prev. setted pieces (interval) of the interpreted tokens are executed, > it is change to another "virtual" thread ? > > Or it was really create real threads, and they are figth for the > priority, and for the execution time ? Both. CPython creates real threads but only one of those can be active at a time if python bytecode is executed because of the `global interpreter lock` (GIL). Extensions written in C can release that lock unless they are accessing the interpreter "internals". For example blocking IO calls like `file.read()` release the lock. > And can I create REAL threads under Python (just like in Delphi), or > better if I use processes, not threads ? Depends on the use case. If your program is IO bound i.e. many threads waiting for blocking IO then just use Python threads. If your task is computational intensive then it may be better to use processes and some form of inter process communication. Ciao, Marc 'BlackJack' Rintsch From fredrik at pythonware.com Sat Jun 3 04:42:27 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 03 Jun 2006 10:42:27 +0200 Subject: image lib & Qt4 In-Reply-To: References: <1149173540.470829.34940@c74g2000cwc.googlegroups.com> <4e8haiF1dp2heU1@uni-berlin.de> <1149180814.585713.209640@i39g2000cwa.googlegroups.com> Message-ID: Fredrik Lundh wrote: >> To get better performance, you should be able to use PIL's tostring() >> method together with the QImage(buffer, width, height, depth, >> colortable, numColors, bitOrder) form of the QImage constructor. I've posted a simple ImageQt interface module for PIL and PyQt4 here: http://svn.effbot.python-hosting.com/stuff/sandbox/pil/ImageQt.py this interface handles 1, P, L, and RGB images efficiently. usage: im = Image.open(...) # or some other pil operation qim = ImageQt.toimage(im) # to access the QImage, use qim.image. e.g: label.setPixmap(QtGui.QPixmap.fromImage(qim.image)) note that the toimage() function returns a wrapper object, not a QImage instance. I didn't find a reliable way to subclass from QImage, nor any other way to attach custom attributes to an existing QImage object. if anyone knows how to do that, let me know. From michele.petrazzo at TOGLIunipex.it Thu Jun 1 04:04:28 2006 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Thu, 01 Jun 2006 08:04:28 GMT Subject: ctypes pointers and SendMessage In-Reply-To: <1149116010.351538.258990@g10g2000cwb.googlegroups.com> References: <1149116010.351538.258990@g10g2000cwb.googlegroups.com> Message-ID: Metalone wrote: > I would like to call > windll.user32.SendMessageA(hwnd, win32con.WM_COMMAND, wParam, lParam) > where > lParam represents a pointer to an object. and the others? > > And also convert this pointer back to an object reference inside of > wnd_proc > def wnd_proc(hwnd, msg, wParam, lParam): > > So something like this: > class X(Structure): > def __init__(self, x): > self.v = x > > What am I doing wrong? > I don't know if you want to create a "real" C structure. If yes this is the wrong method: >>> class X(Structure): ... _fields_ = [("x", c_int), ] ... >>> x1 = X(1) >>> x1.x 1 >>> http://starship.python.net/crew/theller/ctypes/tutorial.html -> Structures and Unions Michele From serge.orlov at gmail.com Fri Jun 23 21:08:26 2006 From: serge.orlov at gmail.com (Serge Orlov) Date: Fri, 23 Jun 2006 18:08:26 -0700 Subject: PEP 314 - requirements for Python itself In-Reply-To: <46370B82-C052-4C28-8EDA-0EC33085CC7C@mnot.net> References: <75C72D66-19F4-43AA-9120-09919076A4E5@mnot.net> <46370B82-C052-4C28-8EDA-0EC33085CC7C@mnot.net> Message-ID: On 6/23/06, Mark Nottingham wrote: > I was looking for some normal (hopefully, machine-readable) way to > indicate it so that people can figure out the version of Python > required before they download the package. I'm sure writing English text like "make sure you have python 2.4 before downloading this package" is not abnormal :) How do you expect to prevent users from downloading your package if they don't have python your package needs? It could be useful if there was a tool to silently download and install python, but I'm sure it is a pain to code and support such a tool, so nobody was crazy enough to do it. From python at hope.cz Tue Jun 6 07:01:44 2006 From: python at hope.cz (Lad) Date: 6 Jun 2006 04:01:44 -0700 Subject: How to add few pictures into one In-Reply-To: References: <1149511692.796038.155930@c74g2000cwc.googlegroups.com> <1149517433.880564.128350@h76g2000cwa.googlegroups.com> <1149529269.228019.120480@u72g2000cwu.googlegroups.com> <1149573892.526072.6770@i39g2000cwa.googlegroups.com> <1149580572.739202.110940@y43g2000cwc.googlegroups.com> <1149587802.895959.37210@f6g2000cwb.googlegroups.com> Message-ID: <1149591704.231602.158740@c74g2000cwc.googlegroups.com> Fredrik Lundh wrote: > Lad wrote: > > > Open a picture file( download it from internet) and write it in a > > result file( being open in binary mode). > > Then download another file and append to the result file. > > And so on... > > But is it possible? Will be the pictures in the result file seen > > well?? > > the internal structure of an image file is quite a bit more complicated > than the internal structure of a text file, so it's not very likely that > you would get very far with that approach. > > why not just put all the files in a directory, and use an image viewer > with collage or slideshow support ? > Fredrik, Thank you for your reply. I really would like to have ALL pictures in one file. So, what would be the easiest/best way how to do that? Thank you for your reply regards, L. From micklee74 at hotmail.com Mon Jun 26 08:52:20 2006 From: micklee74 at hotmail.com (micklee74 at hotmail.com) Date: 26 Jun 2006 05:52:20 -0700 Subject: automatic debugger? Message-ID: <1151326339.869650.278890@p79g2000cwp.googlegroups.com> hi is there something like an automatic debugger module available in python? Say if i enable this auto debugger, it is able to run thru the whole python program, print variable values at each point, or print calls to functions..etc...just like the pdb module, but now it's automatic. thanks From g.brandl-nospam at gmx.net Thu Jun 29 03:43:48 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Thu, 29 Jun 2006 09:43:48 +0200 Subject: Immutability In-Reply-To: References: <4Qj*cEjkr@news.chiark.greenend.org.uk> Message-ID: Steve Holden wrote: > Georg Brandl wrote: >> Nick Maclaren wrote: >> >>>In article , >>>"Fredrik Lundh" writes: >>>|> >>>|> identical? you only applied @property to one of the methods, and then you're >>>|> surprised that only one of the methods were turned into a property? >>> >>>I wasn't expecting EITHER to be turned INTO a property - I was expecting >>>both methods to be the same, but one would have non-default properties >>>attached to it. >> >> >> That's another sign that property isn't intended to be used as a decorator. >> Normally, decorators wrap functions with other functions. property doesn't >> return a function but a descriptor object. >> > OK, I still think the docs need updating, but to explain the above as > the reason *why* property's use as a decorator is not advised. Or is it > stylistically and semantically acceptable in the case of a read-only > property? I'm not the one to judge over that. > Would it make sense, in the single argument case, to default the doc > value to fget.__doc__ to support that use case, or should we just not > create read-only properties by using property as a decorator? This is actually already the case in 2.5. Georg From tactics40 at gmail.com Tue Jun 13 15:26:36 2006 From: tactics40 at gmail.com (tactics40 at gmail.com) Date: 13 Jun 2006 12:26:36 -0700 Subject: Tuple Syntax and () Message-ID: <1150226796.616272.223320@i40g2000cwc.googlegroups.com> I keep accidently trying to declare t-tuples as mytuple = (myitem) I know this doesn't work and that you need the trailing comma, but reading something online, I just came to realize.... the parenthesises don't have any special meaning in relation to tuples at all, do they? From manstey at csu.edu.au Mon Jun 26 19:02:42 2006 From: manstey at csu.edu.au (manstey) Date: 26 Jun 2006 16:02:42 -0700 Subject: list problem 4 newbie In-Reply-To: References: <1151302228.249512.277690@p79g2000cwp.googlegroups.com> Message-ID: <1151362962.386024.35520@m73g2000cwd.googlegroups.com> Thanks very much. Deepcopy works fine, as does reversed(b). I thought I needed the index number but I didn't. Duncan Booth wrote: > manstey wrote: > > > for index in reversed(range(0,len(a)-1)): > > if '75' in b[index][1]: > > b[index][1].remove('75') > > b[index][1].append('99') > > > > What on earth is all that messing around in the for loop intended to do? If > you want a range from len(a)-2 to 0 inclusive then just do it in range > directly (and did you really mean not to look at the last element?), if you > actually just wanted to iterate through b in reverse, then just iterate > through b in reverse: > > b = copy.deepcopy(a) > for element in reversed(b): > if '75' in element[1]: > element[1].remove('75') > element[1].append('99') From digitalorganics at gmail.com Mon Jun 26 13:19:00 2006 From: digitalorganics at gmail.com (digitalorganics at gmail.com) Date: 26 Jun 2006 10:19:00 -0700 Subject: Replace Whole Object Through Object Method In-Reply-To: References: <1151337453.804750.293180@b68g2000cwa.googlegroups.com> Message-ID: <1151342339.985517.104000@b68g2000cwa.googlegroups.com> Maric Michaud wrote: > Le lundi 26 juin 2006 17:57, digitalorganics at gmail.com a ?crit : > > How can an object replace itself using its own method? See the > > following code: > > > > class Mixin: > > def mixin(object, *classes): > > NewClass = type('Mixin', (object.__class__,) + classes, {}) > > newobj = NewClass() > > newobj.__dict__.update(object.__dict__) > > return newobj > > > > Variables in python are names, not the objects, and instances shouldn't know > nothing about how they are referenced. > > I guess what you want to do is, in fact, very simple somethig like : > > a = SomeClass() > a = a.some_method_wich_return_a_new_object() > > or : > > for k, v in globals().iteritems() : > if isinstance(v, SomeClass) : > globlals()[k] = v.some_method_wich_return_a_new_object() > > > > def isClass(object): > Don't mask builtin names. You mean "object"? The shadow/mask only exists within the scope of the function. But anyhow, point well taken. > > if 'classobj' in str(type(object)): > Why don't you test the type directly ? Thanks. > > return 1 > Python has boolean for clarity. Thanks. > > > elif "'type'" in str(type(object)): > > return 1 > > else: > > return 0 > should be : > > import types > > def isClass(object_) : > if isinstance(object_, type) : > return True # new style class > elif isinstance(object_, types.ClassType) : > return True # old-style class > else : return False > > or if you don't need to diferentiate the cases : > > def isClass(object_) : > return isinstance(object_, type) or \ > isinstance(object_, types.ClassType) Very clean! Thank you. > > > > > def listClasses(): > > classes = [] > > for eachobj in globals().keys(): > > if isClass(globals()[eachobj]): > > classes.append(globals()[eachobj]) > > print eachobj > > return classes > > > > def MixInto(Class, Mixin): > > if Mixin not in Class.__bases__: > > Class.__bases__ += (Mixin,) > > This doesn't work in most cases (with new style classes), better recreat a > type which inherit from Class and Mixin, or Class.__dict__ with > Mixin.__dict__. What doesn't work exactly? The whole purpose of the mixin is to add functionality to the class and hence to all its instances on the fly. Creating a new type would not achieve this, unless there's something I'm missing (a very real possibility!). And what do you mean doesn't work in most newstyleclass cases? Seems to be working just fine... > > > ------------------------------------------------------------------------ > > > > Okay, so the mixin function becomes part of whatever class I choose and > > hence its instances, but the problem is that the way I currently have > > it setup mixin() returns a new object, instead of replacing whatever > > class instance that calls it into that new object. I hope I'm making > > sense here. > > > > Basically what I need is for the method to be able to find out the name > > of the instance, then I can just go to the globals dictionary to do the > > replacement. Any answers my primary question though? > > > > Advance thanks to all who can help... > > -- > _____________ > > Maric Michaud > _____________ > > Aristote - www.aristote.info > 3 place des tapis > 69004 Lyon > Tel: +33 426 880 097 From tayss_temp2 at yahoo.com Fri Jun 30 06:43:53 2006 From: tayss_temp2 at yahoo.com (Tayssir John Gabbour) Date: 30 Jun 2006 03:43:53 -0700 Subject: Reddit broke - should have remained on Lisp? References: <1151626961.232761.255550@d56g2000cwd.googlegroups.com> <1151662301.891275.166300@d56g2000cwd.googlegroups.com> <1151662812.571023.205500@d56g2000cwd.googlegroups.com> Message-ID: <1151664233.843889.176100@m73g2000cwd.googlegroups.com> Kay Schluehr wrote: > Tayssir John Gabbour wrote: > > Supposedly, the Reddit team had a bit of remorse (though of course, we > > should take the following writeup with a grain of salt; maybe there are > > more in-depth sources online): > > "If we could do it all over again, we'd still be using Lisp. Probably." > > "Reddit: Stick with Lisp. If you want it done right, do it yourself- > > hosting- Avoid A+.net" > > http://notelab.infogami.com/startupschool2006 > > Please, since this is a Python+Lisp cross-thread and you seem to have > background info: can you explain why Lisp hackers have turned > themselves into Python newbies for Reddit impl. and finally complain > about the language switch? What was cause for their decision to use > Python in the first place? Hi Kay, The claim was that their Lisp implementation, CMUCL, had threading problems which regularly crashed their site. http://lemonodor.com/archives/001301.html Also, they had concerns about the user community's size (at least the one surrounding the free Common Lisp implementations). http://xach.livejournal.com/66285.html All right, serious criticism of Lisp is a joy to read, as we're a technical audience... but how serious was this criticism? Apparently the original big announcement of their switch was deleted from the blog (at least the links are dead and I can't find it in a few secs of googling), but I remember they promised to write up their experiences with Lisp to help others if enough people asked. I was among those who encouraged them to do this, but I haven't heard a word more about this writeup. This would've made their claims easier to verify. As it stands, I don't know if they just had weird glitches with shoddy hardware from their service provider, or whether they seriously reached out to the community so it could help them. And they didn't even offer newbies the benefit of a helpful, critical writeup. (If it is indeed true they didn't follow up on the writeup.) For that matter, a nasty side-effect is it prompts some to heavily criticize Python in the same loose manner, out of a defensive feeling. Tayssir From shejo284 at gmail.com Thu Jun 29 05:25:25 2006 From: shejo284 at gmail.com (Sheldon) Date: 29 Jun 2006 02:25:25 -0700 Subject: Numeric help! In-Reply-To: <1151540468.434688.242530@75g2000cwc.googlegroups.com> References: <1151510615.139278.167520@j72g2000cwa.googlegroups.com> <1151540468.434688.242530@75g2000cwc.googlegroups.com> Message-ID: <1151573125.651727.322660@i40g2000cwc.googlegroups.com> Hi Carl, My days as a student is over for the most part. I am learning python on my own and Numeric is not properly documented so I am learning by doing and copying from others. I thought about the problem and a solution another problem given to me earlier using "putmask" is the solution but there is a bug that I cannot figure out: ************************ index = 0 for z in range_va: wk = msgva # working arrary sattmp = sat_id # working array mask = where(equal(wk,z),1,0) # creating a mask of valid data pixs putmask(sattmp,mask==0,-999) # since zero is valid data, -999 is used instead rdata = compress(ravel(not_equal(sattmp,-999)),ravel(sattmp)) if sum(sum(rdata)) == 0: av = 0 else: av = average(rdata,axis=None) tmparray[0,index] = av tmparray[1,index] = z index += 1 print tmparray *********************************** But the tmparray is returning zeros as averages. When I try just one value for z everything works. I can't see where I going wrong. I am not using the original arrays, only the copies and when a new z is chosen then these are recreated. Care to help out with this? /Sheldon Carl Banks wrote: > Sheldon wrote: > > Hi, > > > > I have the following loop that I think can be written to run faster in > > Numeric. I am currently using Numeric. > > range_va = [60,61,62,63,64,65,66,67,68,69,70,71,72] > > main.xsize= 600 > > main.ysize= 600 > > #msgva is an (600x600) Numeric array with mutiple occurrences of the > > values in range_va > > #sat_id is an (600x600) Numeric array with values ranging from -2 to 2 > > for z in range_va: > > count = 0 > > mbias = 0 > > for i in range(main.xsize): > > for j in range(main.ysize): > > if msgva[i,j] == z: > > mbias += sat_id[i,j] # take the sum of the > > values > > count += 1 # count the occurrences > > tmp_array[0,index] = round(mbias/count,1) # store the mean > > tmp_array[1,index] = z > > index += 1 > > > > Any help would be greatly appreciated! > > I'm not sufficiently sure this isn't a homework problem, so here's a > partial answer. > > Your intuition is correct--there's almost always a faster way to do it > when you're cycling through Numeric array indices in a Python for loop. > Numeric and successors exist mostly to get rid of them. > > Given z, you can calculate mbias in one line: > > mbias = Numeric.sum( > Numeric.ravel(Numeric.where(msgva==z,sat_id,0))) > > Here, the Numeric.where function allows you to filter out entries: it > returns an array with the elements of sat_id, but only where the > corresponding element of msvga==z; otherwise the entry is zero. > Numeric.ravel flattens an multidimensional array into one dimension, > and, of course, Numeric.sum adds up all the elements in the array. > > How to get count and to work this into your loop are left as an > exercise. > > > Carl Banks From pc at p-cos.net Wed Jun 14 16:18:03 2006 From: pc at p-cos.net (Pascal Costanza) Date: Wed, 14 Jun 2006 22:18:03 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: <7zpshbsvjy.fsf@app-1.diku.dk> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> Message-ID: <4fb97sF1if8l6U1@individual.net> Torben ?gidius Mogensen wrote: > On a similar note, is a statically typed langauge more or less > expressive than a dynamically typed language? Some would say less, as > you can write programs in a dynamically typed language that you can't > compile in a statically typed language (without a lot of encoding), > whereas the converse isn't true. It's important to get the levels right here: A programming language with a rich static type system is more expressive at the type level, but less expressive at the base level (for some useful notion of expressiveness ;). > However, I think this is misleading, > as it ignores the feedback issue: It takes longer for the average > programmer to get the program working in the dynamically typed > language. This doesn't seem to capture what I hear from Haskell programmers who say that it typically takes quite a while to convince the Haskell compiler to accept their programs. (They perceive this to be worthwhile because of some benefits wrt correctness they claim to get in return.) Pascal -- 3rd European Lisp Workshop July 3 - Nantes, France - co-located with ECOOP 2006 http://lisp-ecoop06.bknr.net/ From barry.j.kelly at gmail.com Tue Jun 20 12:36:17 2006 From: barry.j.kelly at gmail.com (Barry Kelly) Date: Tue, 20 Jun 2006 17:36:17 +0100 Subject: __getattribute__ doesn't work on 'type' type for '__class__' Message-ID: <8k8g92tgqmhu70au13od2fn1ihut04sr0o@4ax.com> I'm running this version of Python: Python 2.4.3 (#1, May 18 2006, 07:40:45) [GCC 3.3.3 (cygwin special)] on cygwin I read in the documentation that these two expressions are interchangeable: x.__getattribute__('name') <==> x.name >From "pydoc __getattribute__": ---8<--- Help on method-wrapper object: __getattribute__ = class method-wrapper(object) | Methods defined here: | | __call__(...) | x.__call__(...) <==> x(...) | | __getattribute__(...) | x.__getattribute__('name') <==> x.name --->8--- Yet when I try this with the 'type' type, it doesn't work: ---8<--- >>> x.__class__.__class__ >>> x.__class__.__getattribute__('__class__') Traceback (most recent call last): File "", line 1, in ? TypeError: descriptor '__getattribute__' requires a 'int' object but received a 'str' --->8--- Why is this? -- Barry -- http://barrkel.blogspot.com/ From alanalan at newsgroup.nospam Thu Jun 1 14:00:42 2006 From: alanalan at newsgroup.nospam (A.M) Date: Thu, 1 Jun 2006 14:00:42 -0400 Subject: Member index in toples Message-ID: <_TFfg.2976$EF1.229574@news20.bellglobal.com> Hi, I have a tuple like this: T = ("One","Two","Three","Four") Is there any built-in way to find what is the index of "Two" withouot looping within the tuple? Is the same feature available for lists or dictionaries? Thank you, Alan From samschul at pacbell.net Sat Jun 3 00:40:55 2006 From: samschul at pacbell.net (sam) Date: 2 Jun 2006 21:40:55 -0700 Subject: Seg fault in python extension module In-Reply-To: <44810873.3050200@lexicon.net> References: <4480F004.7000602@lexicon.net> <1149305921.145967.248740@i39g2000cwa.googlegroups.com> <44810873.3050200@lexicon.net> Message-ID: <1149309655.287866.10380@i40g2000cwc.googlegroups.com> Sorry, From MethodObject.h the 4th parameter is usually documented as having a NULL, but is intended to be used for a documentation string that will be available to the user under the various GUI IDE's such as IDLE or PyWin32. I just wanted to point that out.. struct PyMethodDef { const char *ml_name; /* The name of the built-in function/method */ PyCFunction ml_meth; /* The C function that implements it */ int ml_flags; /* Combination of METH_xxx flags, which mostly describe the args expected by the C func */ const char *ml_doc; /* The __doc__ attribute, or NULL */ }; Sam Schulenburg John Machin wrote: > On 3/06/2006 1:38 PM, sam wrote: > > I recommend that you also replace the NULL after the METH_VARARGS with > > a valid documentations string such as: > > > > static PyMethodDef modglMethods[] = > > { > > { (char *)"glVertex4f", _wrap_glVertex4f, METH_VARARGS, "My > > Doc String"}, > > { NULL, NULL, 0, NULL } > > > > }; > > > > Lack of one is unlikely to have anything to do with the OP's segfault. > > |>>> repr(modgl.glVertex4f.__doc__) > 'None' > |>>> > > As to style, etiquette, and good citizenship in module extension > writing, it might be better to give him some references, rather than > mention just one point. > > Cheers, > John From emvee.bh at gmail.com Mon Jun 19 18:49:42 2006 From: emvee.bh at gmail.com (emvee bhian) Date: Mon, 19 Jun 2006 15:49:42 -0700 Subject: logging module ValueError: I/O operation on closed file Message-ID: <72db3eb70606191549u2fa34f6bu274a5e2c3e777e46@mail.gmail.com> getting the following error while using logging at random any idea what can cause this behaviour Traceback (most recent call last): File lib/python2.4/logging/__init__.py", line 737, in emit ValueError: I/O operation on closed file self.Log = logging.getLogger('MAIN') sFormat='%(asctime)s %(name)s %(levelname)s %(message)s' filer = logging.FileHandler('/tmp/log.log','a') filer.setLevel(logging.DEBUG) formatter = logging.Formatter(sFormat) filer.setFormatter(formatter) Erfiler = logging.FileHandler('/tmp/error.log','a') Erfiler.setLevel(logging.ERROR) Erfiler.setFormatter(formatter) #logging.getLogger('').addHandler(filer) self.Log.addHandler(filer) self.Log.addHandler(Erfiler) using the following in subsequent modules self.Log = logging.getLogger('MAIN.MODULE') self.Log.info("log the message") -------------- next part -------------- An HTML attachment was scrubbed... URL: From tim.peters at gmail.com Wed Jun 21 07:37:41 2006 From: tim.peters at gmail.com (Tim Peters) Date: Wed, 21 Jun 2006 07:37:41 -0400 Subject: Iteration over recursion? In-Reply-To: <1150873424.345733.165730@m73g2000cwd.googlegroups.com> References: <1150808045.539887.291180@i40g2000cwc.googlegroups.com> <1150873424.345733.165730@m73g2000cwd.googlegroups.com> Message-ID: <1f7befae0606210437q66f4f203na2788c84ff4bcb41@mail.gmail.com> [Kay Schluehr] > You might use a separate prime generator to produce prime factors. The > factorize algorithm becomes quite simple and configurable by prime > generators. Alas, yours was _so_ simple that it always takes time proportional to the largest prime factor of n (which may be n) instead of worst-case time proportional to sqrt(n). Repair that, and it's not quite so simple anymore. The speed of the sieve generator would also benefit a lot by never looking at even integers, beyond an initial "yield 2" ... the OP said he was looking for speed more than elegance, and they're not good buddies here ;-) > def eratosthenes(): > memo = {} > q = 2 > while True: > p = memo.pop(q, None) > if p is None: > yield q > memo[q*q] = q > else: > x = p + q > while x in memo: > x += p > memo[x] = p > q+=1 > > def factorize(n, sieve = eratosthenes): > if n <= 1: > return [n] > factors = [] > primes = sieve() > for q in primes: > while n % q == 0: > factors.append(q) > n //= q > if n == 1: > return factors At _some_ point you might think that's bound to be faster than only skipping multiples of 2 and 3, because it does fewer divisions. But to get to a particular prime p, the sieve there has to go around its outer loop about 3x as often as the trial() function goes around its inner loop, and grows a dict with about p/ln(p) entries (while the trial() function's memory use is constant), and those aren't free. Applied to 9999991**2 (constructed so that both functions take time proportional to sqrt(n)), on my box the factorize() function took 4x longer than trial() (approximately 16 seconds versus 4). Trial division isn't practical for such large inputs, but I picked the square of a "large" prime to give factorize() maximum advantage in skipping division attempts (by the time we get to a prime p, factorize() tries about p/ln(p) divisions, while trial() does about p/3; so trial() does about ln(p)/3 times as many divisions as factorize(): the larger the p we need, the larger that _factor_ gets). Alas, it appears that made the dict so big that cache faults on dict accesses more than wiped out the division advantage. At the smaller 999983**2, factorize() took only about 3.6x longer, despite losing some of its relative division advantage. In short, it's never what you think it is ;-) From pjb at informatimago.com Thu Jun 8 09:46:56 2006 From: pjb at informatimago.com (Pascal Bourguignon) Date: Thu, 08 Jun 2006 15:46:56 +0200 Subject: The Nature of the =?utf-8?Q?=E2=80=9CUnix_Philosophy=E2=80=9D?= References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1149080931.582431.95560@j55g2000cwa.googlegroups.com> <1149730552.161534.121350@i40g2000cwc.googlegroups.com> <4487d188$1@news.broadpark.no> <44882412$0$20779$ec3e2dad@news.usenetmonster.com> Message-ID: <878xo7sqsv.fsf@thalassa.informatimago.com> Frank Silvermann writes: > Nils O. Sel?sdal wrote: >> Xah Lee wrote: >>> The Nature of the ?Unix Philosophy? > [snip] > >> Perhaps you should take a peek at the ideas in Plan 9 from Bell Labs, >> which is a continuation of this philosophy, unlike the "modern" unix >> clones. > Is there an actual Plan 9? I'm only aware of the one from Outer > Space. frank No, there is no _actual_ Plan 9. The OS named "Plan 9" is named after the Outer Space one. -- __Pascal Bourguignon__ http://www.informatimago.com/ ATTENTION: Despite any other listing of product contents found herein, the consumer is advised that, in actuality, this product consists of 99.9999999999% empty space. From timr at probo.com Sat Jun 17 23:23:22 2006 From: timr at probo.com (Tim Roberts) Date: Sun, 18 Jun 2006 03:23:22 GMT Subject: wxPython question References: <1150466566.439285.304110@r2g2000cwb.googlegroups.com> Message-ID: diffuser78 at gmail.com wrote: > >I tried to follow wxPython Demo examples to understand it better. I >used wxGlade to generate my code from the GUI builder. > >When I try to see the code for Menu and Menubar I see a little mismatch >in the way functions are being used. > >For example, wxGlade produces code like this > >self.Action = wx.Menu() >self.AddComputer = wx.MenuItem(self.Action, wx.NewId(), _("Add >Computer"), "",wx.ITEM_NORMAL) >self.Action.AppendItem(self.AddComputer) >## Code end > >and in the demo it is gives as > >self.Action = wx.Menu() >Action.append(201, "Add Computer") ># Code end > >Can somebody please explain this discrepancy ? It's not really a "discrepancy". It's just that the latter example is a shortcut for the first. (Well, it would be a shortcut if you used "201" instead of "wx.NewId() in the first.) wxPython has, over the years, developed sensible shortcuts for many common operations. The GUI generators tend to use the "long" way, since that tends to be the original method that will work with any version. Also note that, in the first example, you are given a wx.MenuItem object to work with, should you need it. The second example hides it. It is rarely necessary to access a wx.MenuItem directly, so this is not usually an issue. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From aleax at mac.com Sat Jun 3 02:11:37 2006 From: aleax at mac.com (Alex Martelli) Date: Fri, 2 Jun 2006 23:11:37 -0700 Subject: An oddity in list comparison and element assignment References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> <1hg9nl6.xivwcd7n0j5N%aleax@mac.com> <1149277242.199765.213600@g10g2000cwb.googlegroups.com> <1hgbhhi.mcrge51cyj2isN%aleax@mac.com> Message-ID: <1hgbu61.1gtkkjh1aca3i8N%aleax@mac.com> wrote: > Alex Martelli wrote: > > [snip] > > Can somebody please shut down this bot? I think it's running out of Much as you might love for somebody to "shut me down", that (unfortunately, no doubt, from your viewpoint) is quite unlikely to happen. Although "making predictions is always difficult, especially about the future", the most likely course of events is that I shall continue for a while to survive, probably in tolerable health. BTW, and for your information: in modern Western society, publically wishing for some adversary's death is often considered somewhat uncouth and rude, except perhaps in times of war or similar extremities. Being aware of such social niceties and conventions may help: even were I to wish that somebody crushed you underfoot like the worm you are, I would avoid expressing such a wish in public, and likely in private too. Alex From jmdeschamps at gmail.com Wed Jun 28 21:06:58 2006 From: jmdeschamps at gmail.com (jmdeschamps at gmail.com) Date: 28 Jun 2006 18:06:58 -0700 Subject: USB In-Reply-To: References: Message-ID: <1151543218.224323.205190@j72g2000cwa.googlegroups.com> Gabriel wrote: > ?Alguien conoce alg?n m?dulo para python con el que se pueda tener > acceso a los puertos USB y que sea multiplataforma? > > -- > Gabriel Hola Gabriel, Voy... http://sourceforge.net/projects/pyusb (multiplataforma sin Windows) mas http://web.media.mit.edu/~dmerrill/sensor_network_applications/plug_howto.html otros http://libusb-win32.sourceforge.net/ (windows) Esperando ;-)) Jean-Marc From claird at lairds.us Tue Jun 13 11:27:10 2006 From: claird at lairds.us (Cameron Laird) Date: Tue, 13 Jun 2006 15:27:10 +0000 Subject: Making a Label that looks the same as a button. References: Message-ID: In article , Grayson, John wrote: > > > >Buttons can look like labels without the need to create another object - >just remove the >Command binding, set state to DISABLED and disabledforeground='same >color as NORMAL'... > >This demonstrates how to play with button styles: . . . John, as I read the original poster, Tkinter.DISABLED is *exactly* what he wants (although he might not realize it yet); I suspect there's no need at all for other styling. Are Button and Label styles truly identical except for disabledforeground? While I can't make the time now to research this for myself, it surprises me; I thought there were padding differences ... Your remark about the Command has me curious: why remove it? In terms of the original poster's description, what does this serve? I repeat my speculation that Tkinter.DISABLED will "do it all" for him. From writetoalok at googlemail.com Fri Jun 30 06:19:25 2006 From: writetoalok at googlemail.com (Alok) Date: 30 Jun 2006 03:19:25 -0700 Subject: Reddit broke - should have remained on Lisp? In-Reply-To: <1151628347.551890.48050@y41g2000cwy.googlegroups.com> References: <1151626961.232761.255550@d56g2000cwd.googlegroups.com> <1151627462.297352.205150@i40g2000cwc.googlegroups.com> <1151627924.322764.6040@y41g2000cwy.googlegroups.com> <1151628347.551890.48050@y41g2000cwy.googlegroups.com> Message-ID: <1151662765.178529.82670@75g2000cwc.googlegroups.com> Luis M. Gonz?lez wrote: > Alok wrote: > > I was merely describing my experience and inviting others' response > > about theirs. > > That's exactly what I'm doing. You misinterpret, I was talking about my experience with the site and inviting response from other people about their experience with the site. Now, I don't know much about python or lisp, but I have read about this web-site's history with the two programming languages. And hence I chose to post in comp.lang.lisp and comp.lang.python. Now if there were a reddit.technology.lisp or reddit.technology.python, and if they had the same traction as these usenet groups, then I could have posted there. But that was not an option was it. > > > Please don't misconstrue that as a blame on any language. > > I think it can be interpreted in many ways. Can you please explain what your interpretation is? > Now if you're not ready to read other people's oppinions, don't ask. > Now, I think you are unfairly prejudiced about my not wanting to read other people's opinion. I would rather have a 1000 acrid responses to something I write and learn from it, than post into a responseless vacuum. > > And of course, I disagree with your comments about ridicule etc. > > Ok. From alanalan at newsgroup.nospam Thu Jun 1 21:20:23 2006 From: alanalan at newsgroup.nospam (A.M) Date: Thu, 1 Jun 2006 21:20:23 -0400 Subject: Can Python format long integer 123456789 to 12,3456,789 ? References: <8oKfg.1621$Su3.139425@news20.bellglobal.com> Message-ID: Thanks for help. Is there any comprehensive library for number formatting available on the net? Alan From cdsmith at twu.net Tue Jun 27 13:50:03 2006 From: cdsmith at twu.net (Chris Smith) Date: Tue, 27 Jun 2006 11:50:03 -0600 Subject: What is Expressiveness in a Computer Language References: <7zy7vt1mz2.fsf@app-3.diku.dk> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <1151384511.223582.305760@m73g2000cwd.googlegroups.com> Message-ID: Dr.Ruud wrote: > > So it seems to me that we have this ideal point at which it is > > possible to write all correct or interesting programs, and impossible > > to write buggy programs. > > I think that is a misconception. Even at the idealest point it will be > possible (and easy) to write buggy programs. G?del! I agree. I never said that the ideal point is achievable... only that there is a convergence toward it. (In some cases, that convergence may have stalled at some equilibrium point because of the costs of being near that point.) -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation From pslana at gmail.com Wed Jun 21 06:49:15 2006 From: pslana at gmail.com (pierre_py) Date: 21 Jun 2006 03:49:15 -0700 Subject: wxStyledTextCtrl and sql syntax highlightning In-Reply-To: <44990576$0$7766$7a628cd7@news.club-internet.fr> References: <1150876325.128357.129460@p79g2000cwp.googlegroups.com> <44990576$0$7766$7a628cd7@news.club-internet.fr> Message-ID: <1150886955.112552.39630@p79g2000cwp.googlegroups.com> Hi. Thanks it works now .. i must reset the default styles with StyleClearAll and then set the styles apropriate again. Is there a way that the keyword list isn't case sensitive, as sql isn't. reg, Pierre jean-michel bain-cornu wrote: > > I have the following: > > self.__m_styled_text_ctrl = wxPython.stc.wxStyledTextCtrl( > > self, wx.NewId(), > > style=wxPython.wx.wxNO_FULL_REPAINT_ON_RESIZE) > > self.__m_styled_text_ctrl.SetLexer(wxPython.stc.wxSTC_LEX_SQL) > > self.__m_styled_text_ctrl.SetProperty("fold", "1") > > self.__m_styled_text_ctrl.SetMargins(0,0) > > self.__m_styled_text_ctrl.SetKeyWords(0, SQL_KEYWORDS) > Hi Pierre, > I'd like to do some tests with your stuff, but I'd appreciate to have a > working sample. Would you like to post it ? > Regards, > jm From rossberg at ps.uni-sb.de Wed Jun 21 11:52:54 2006 From: rossberg at ps.uni-sb.de (Andreas Rossberg) Date: Wed, 21 Jun 2006 17:52:54 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <0%Wlg.3521$MF6.947@tornado.socal.rr.com> <44992e6c$0$664$bed64819@news.gradwell.net> Message-ID: Joachim Durchholz wrote: >> >>> It's worth noting, too, that (in some sense) the type of an object >>> can change over time[*]. >> >> No. Since a type expresses invariants, this is precisely what may >> *not* happen. > > No. A type is a set of allowable values, allowable operations, and > constraints on the operations (which are often called "invariants" but > they are invariant only as long as the type is invariant). The purpose of a type system is to derive properties that are known to hold in advance. A type is the encoding of these properties. A type varying over time is an inherent contradiction (or another abuse of the term "type"). - Andreas From steven.bethard at gmail.com Fri Jun 30 23:36:24 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 30 Jun 2006 21:36:24 -0600 Subject: Concatenating strings In-Reply-To: <1151724825.477962.127160@h44g2000cwa.googlegroups.com> References: <1151724825.477962.127160@h44g2000cwa.googlegroups.com> Message-ID: <5amdnXYb37EqcDjZnZ2dnUVZ_vednZ2d@comcast.com> John Henry wrote: > I have a list of strings (some 10,000+) and I need to concatenate them > together into one very long string. The obvious method would be, for > example: > > alist=["ab","cd","ef",.....,"zzz"] > blist = "" > for x in alist: > blist += x > > But is there a cleaner and faster way of doing this? blist = ''.join(alist) STeVe From trentm at activestate.com Mon Jun 19 23:15:14 2006 From: trentm at activestate.com (Trent Mick) Date: Mon, 19 Jun 2006 20:15:14 -0700 Subject: Active Python versions In-Reply-To: References: <2hElg.41514$mF2.19600@bgtnsc04-news.ops.worldnet.att.net> <1150769349.111390.280450@y41g2000cwy.googlegroups.com> Message-ID: <44976842.60001@activestate.com> Tom Del Rosso wrote: > jmdeschamps at gmail.com typed > in news://1150769349.111390.280450 at y41g2000cwy.googlegroups.com, > >> Maybe the OP is refering to PythonWin editor (as compared to IDLE) >> which is in ActiveState's release but not in the Python.org release... >> makes for a very different subject, and hopefully for very different >> answer direction. > > Yes. I just wanted to know which programming environment is prefered by > regular users, maybe even one that I haven't heard of yet. Ah, the PythonWin IDE/Editor is part of PyWin32 -- which is included as a standard part of ActivePython. IDLE is also included in ActivePython, BTW. ActivePython just doesn't setup a shortcut in the Start Menu for it. You could add your own. As jean-marc suggests, you might want to search the python-list archives for peoples opinions on Python IDEs and editors. Also check out: http://wiki.python.org/moin/IntegratedDevelopmentEnvironments http://wiki.python.org/moin/PythonEditors ActiveState has a Python IDE called Komodo http://www.activestate.com/Products/Komodo/ which I work on (so I'm biased :). Trent -- Trent Mick trentm at activestate.com From jmbc at nospam.fr Wed Jun 21 04:33:07 2006 From: jmbc at nospam.fr (jean-michel bain-cornu) Date: Wed, 21 Jun 2006 10:33:07 +0200 Subject: How to truncate/round-off decimal numbers? In-Reply-To: <1150875897.866447.312150@g10g2000cwb.googlegroups.com> References: <1150875897.866447.312150@g10g2000cwb.googlegroups.com> Message-ID: <4499048f$0$7764$7a628cd7@news.club-internet.fr> > just a thought: if you *always* work with "floats" with two decimals, > you are in fact working with integers, but you represent them as a > floats - confusing for the internal representation. > > So why not work with int(float * 100) instead? This way you only have > to take care of roundoffs etc when dividing. And why won't you work with decimal module ? From onurb at xiludom.gro Tue Jun 27 08:20:39 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Tue, 27 Jun 2006 14:20:39 +0200 Subject: Python is fun (useless social thread) ;-) In-Reply-To: <1151345365.630616.14400@i40g2000cwc.googlegroups.com> References: <1150381872.958342.180420@p79g2000cwp.googlegroups.com> <44917776$1@nntp0.pdx.net> <4492c1c6$0$11008$626a54ce@news.free.fr> <1151345365.630616.14400@i40g2000cwc.googlegroups.com> Message-ID: <44a12298$0$8346$636a55ce@news.free.fr> BartlebyScrivener wrote: >>You know what are dicts, right ? That is, containers with keyword-access >>to values ? Then you probably have dicts with a known, defined >>structure, and functions working on it. What classes (and hence 00) >>gives you is a way to associate these functions with the dicts >>themselves. That is the big intuition about objects, the rest is just >>details. > > > Bruno, > > Ever seen this from Fuzzyman? It explicitly uses the dict comparison. > > http://www.voidspace.org.uk/python/articles/OOP.shtml#introduction Nope - and the site seems to be down actually. But thanks for the pointer anyway. > Thanks for the tip, Welcome to OO !-) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From grante at visi.com Sat Jun 3 11:06:16 2006 From: grante at visi.com (Grant Edwards) Date: Sat, 03 Jun 2006 15:06:16 -0000 Subject: integer to binary... References: <1149189570.376091.319890@j55g2000cwa.googlegroups.com> <127ugf9jgu7av18@corp.supernews.com> <4480a084$0$6172$626a54ce@news.free.fr> Message-ID: <12839b8doin7mff@corp.supernews.com> On 2006-06-02, Bruno Desthuilliers wrote: > Grant Edwards a ?crit : >> On 2006-06-01, nicolasg at gmail.com wrote: >> >> >>>does anyone know a module or something to convert numbers like integer >>>to binary format ? >> >> >> They _are_ in binary format. > > Not really. Yes, really. Otherwise the bitwise boolean operations you demonstrated wouldn't work as shown. >>>> (7).__class__ > >>>> dir((7)) > ['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', > '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', > '__floordiv__', '__getattribute__', '__getnewargs__', '__hash__', > '__hex__', '__init__', '__int__', '__invert__', '__long__', > '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', > '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', > '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', > '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', > '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', > '__rxor__', '__setattr__', '__str__', '__sub__', '__truediv__', '__xor__'] >>>> The fact that they impliment the xor operator is pretty much proof that integers are stored in binary format -- xor is only defined for binary numbers. -- Grant Edwards grante Yow! ... Blame it on the at BOSSA NOVA!!! visi.com From xivulon at gmail.com Fri Jun 2 09:17:50 2006 From: xivulon at gmail.com (ago) Date: 2 Jun 2006 06:17:50 -0700 Subject: win32com: how to connect to a specific instance of a running object? In-Reply-To: References: Message-ID: <1149254270.790703.145700@j55g2000cwa.googlegroups.com> Thanks, after some further digging I hit something... The following seems to do the trick: import win32gui WINDOW_CLASS = 'XLMAIN' WINDOW_TITLE = 'Microsoft Excel - MySpreadsheet.xls' hwindow = win32gui.FindWindow(WINDOW_CLASS,WINDOW_TITLE) Now the next question is: how do I use the window-handle returned? I would like to work with a com object like the one returned by win32com.client.Dispatch('ExcelApplication'). Any hint? PS I could also use win32ui instead win32gui, in this case I get a window object instead of an handle. But I still do not know how to transform it into a nice pythoncom excel object. From grahamd at dscpl.com.au Mon Jun 12 04:04:13 2006 From: grahamd at dscpl.com.au (grahamd at dscpl.com.au) Date: 12 Jun 2006 01:04:13 -0700 Subject: [mod_python] using nested blocks in psp References: <1150027597.236379.53290@j55g2000cwa.googlegroups.com> Message-ID: <1150099453.868939.187030@f6g2000cwb.googlegroups.com> cloc3 wrote: > I'm a newbie in python, and I'm fighting against nested blocks in psp. > Thats a little example with a funny behaviour: > [code] > >
> > > > > [/code] > In my intention, the for instruction have to run two operation: > first: the if instruction > second: to print the option tag on the html page. > > Instead, the real behaviour is depending on the result of the control > in the if: > if the control is true, the option tag is not printed, and the for > instruction goes to the successive step. > if the control is false, the option is correctly printed. > > I don't understand the reason of this behaviour. > Which is the right way to control the nested block instructions in psp? PSP as implemented by mod_python is fussy about how many spaces are used in indents. Use either 8 space or tab indents. If you don't want to do that, you will need to use comment hints to help PSP understand what level of indenting you are using. See: http://www.modpython.org/pipermail/mod_python/2005-May/018102.html Comment hints may still be needed in certain cases to turn off scopes even if 8 space or tab indents are needed so it is good to understand what they are about. Also ask further questions on mod_python user mailing list as you will in general get better responses there. Graham From girish at cse.iitb.ac.in Thu Jun 8 21:09:49 2006 From: girish at cse.iitb.ac.in (Girish Sahani) Date: Fri, 9 Jun 2006 06:39:49 +0530 (IST) Subject: How to generate k+1 length strings from a list of k lengthstrings? In-Reply-To: <1149780416.430558.251860@h76g2000cwa.googlegroups.com> References: <1149773165.890230.228960@g10g2000cwb.googlegroups.com> <1149780416.430558.251860@h76g2000cwa.googlegroups.com> Message-ID: <53975.10.209.4.2.1149815389.squirrel@10.105.1.3> Yes it is the former of course.Common elements could be in any order in both strings. Thanks Marc :)...though we need to add an if for checking the length of the string (k+1). > > Jon Clements wrote: >> Are you asking the question, "Which pairs of strings have one character >> different in each?", or "Which pairs of strings have a substring of >> len(string) - 1 in common?". >> >> Jon. > > I imagine it's the former because the latter is trivially easy, I mean > _really_ trivially easy. > > -- > http://mail.python.org/mailman/listinfo/python-list > From llosee at gmail.com Wed Jun 7 12:01:10 2006 From: llosee at gmail.com (Lou Losee) Date: Wed, 7 Jun 2006 12:01:10 -0400 Subject: help to install MySQL-python module In-Reply-To: <1149687465.4486d6a9e5c5e@webmail.unical.it> References: <1149687465.4486d6a9e5c5e@webmail.unical.it> Message-ID: On 6/7/06, ciccio at unical.it wrote: > > > Dear python users, > > I have an account on a Linux Cluster. I installed python version 2.3.5 on my > account. I need to install the module MySQL-python to interact with a MySQL > server already installed on the cluster. > However, I read the README file but running > > python setup.py build > > the system fails to build the module and gives me the following error: > > error: invalid Python installation: unable to > open /usr/local/lib/python2.3/config/Makefile (No such file or directory) > > How can I solve this problem? > > Thank you in advance > > Ernesto > Ernesto, Where did the install put Python - the obvious situation is that the Makefile is not where the install of MySQL-Python thinks it is. Lou -- Artificial Intelligence is no match for Natural Stupidity From onurb at xiludom.gro Tue Jun 13 04:55:19 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 13 Jun 2006 10:55:19 +0200 Subject: "parent" in a class __init__ def? In-Reply-To: <1150170367.294662.10330@y43g2000cwc.googlegroups.com> References: <1149999409.650251.251240@g10g2000cwb.googlegroups.com> <448d295c$0$19196$636a55ce@news.free.fr> <1150170367.294662.10330@y43g2000cwc.googlegroups.com> Message-ID: <448e7d78$0$5714$626a54ce@news.free.fr> akameswaran at gmail.com wrote: > bruno at modulix wrote: > >>akameswaran at gmail.com wrote: >> >>> Intuitively, the name lookup on >>>self.parent.foo would be faster than if you passed in the object in >>>question >> >> >>Each dot means doing a lookup in a namespace. The more dots, the more >>lookups. And lookups do have a cost. > > hmm, intuition may not be right in this case. > Lookups do have a cost - now I"m almost tempted to write and run a test > for this - but the cost of each lookup is also relative to the current > scope. A common "optimization" trick is to 'localize' references before a heavy loop, to avoid lookup cost, ie: def method(self, *args): dothis = self.dothis dothat = somemodule.somefunc CONST = othermodule.CONST # heavy processing loop here > I haven't looked over the implementation of the python > interpreter - but I would hope the lookup on self would be optimized > and trivial. It's certainly not trivial. Must take into account instance attributes (in __dict__ or __slots__), class attributes, inherited attributes, overriding descriptors, non-overriding descriptors, __getattr__, etc... The incredible felxibility of Python's object model comes with a cost. > The next relevant question would be is it cheaper to > lookup self.parent or to look up a method variable, The second - cf above. > which I supsect > would depend on the number of names in self vs. number of names in the > method. Namespaces are mostly built upon hashtables, so the number of names should be mostly irrelevant. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From digitalorganics at gmail.com Mon Jun 26 11:39:46 2006 From: digitalorganics at gmail.com (digitalorganics at gmail.com) Date: 26 Jun 2006 08:39:46 -0700 Subject: Get List of Classes In-Reply-To: References: <1151332257.564563.139040@u72g2000cwu.googlegroups.com> Message-ID: <1151336386.377824.134110@i40g2000cwc.googlegroups.com> Wow, more than I had asked for, thank you Tim! I ended up doing this: def isClass(object): if 'classobj' in str(type(object)): return 1 elif "'type'" in str(type(object)): return 1 else: return 0 def listClasses(): classes = [] for eachobj in globals().keys(): if isClass(globals()[eachobj]): classes.append(globals()[eachobj]) print eachobj return classes Tim Chase wrote: > > Is there a method or attribute I can use to get a list of > > classes defined or in-use within my python program? I tried > > using pyclbr and readmodule but for reason that is dogslow. > > Well, given that so much in python is considered a class, the > somewhat crude code below walks an object/module and emits > details regarding what's going on. I couldn't find any nice > method for determining if a variable referenced a module other > than checking to see if that item had both a "__file__" and a > "__name__" attribute. Likewise, the check for whether something > is an object is a bit crude. > > > >>> def inspect(thing, name = '', indent=0): > ... if hasattr(thing, "__file__") and hasattr(thing, "__name__"): > ... #assume it's a module > ... print "%sModule %s" % ("\t" * indent, thing.__name__) > ... for subthing in dir(thing): > ... objname = ".".join([name, > subthing]).lstrip(".") > ... inspect(eval(objname), > ... objname, indent+1) > ... elif isinstance(thing, object): > ... print "%s%s is an object" % ("\t" * indent, name) > ... > >>> import m1 > >>> # m1 is a junk module that references module "m2" and has > >>> # some junk classes in it > >>> inspect(m1, "m1") > Module m1 > m1.M1Class is an object > m1.M1ObjectClass is an object > m1.__builtins__ is an object > m1.__doc__ is an object > m1.__file__ is an object > m1.__name__ is an object > Module m2 > m1.m2.M2Class is an object > m1.m2.M2ObjectClass is an object > m1.m2.__builtins__ is an object > m1.m2.__doc__ is an object > m1.m2.__file__ is an object > m1.m2.__name__ is an object > > > > You could also filter out builtin object properties by wrapping > that last print statement in something like > > if not name.startswith("_"): print ... > > which might cut down on some of the noise. > > Just a few ideas. > > -tkc From rogue_pedro at yahoo.com Thu Jun 22 13:01:22 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 22 Jun 2006 10:01:22 -0700 Subject: Help req: Problems with MySQLdb References: <1150968147.565850.156870@u72g2000cwu.googlegroups.com> <1150969803.984843.111950@y41g2000cwy.googlegroups.com> Message-ID: <1150995682.162673.238130@u72g2000cwu.googlegroups.com> rodmc wrote: > Hi, > > Thanks for your email. Well I am kind of new to exceptions in Python, > but here is the code used below, as you can see it is somewhat basic. > Is there a way to display more information about the exception? > > Best, > > rod > Use the traceback module (See http://docs.python.org/lib/module-traceback.html for info on it.) import traceback try: db = MySQLdb.connect(host=DBSERVERIP, user="user", passwd="password", db="nuke") except: print "A database connection error has occurred" traceback.print_exc() return False else: pass #The rest of the program It's generally very difficult to figure out what's going wrong without the traceback in front of you. Also, try an empty string (i.e. "") as your hostname, it's shorthand for 'localhost'. Hope this helps, ~Simon From paul at boddie.org.uk Fri Jun 23 17:40:03 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 23 Jun 2006 14:40:03 -0700 Subject: code is data References: <44965f53$0$12743$636a55ce@news.free.fr> <4496b29f$0$27412$626a54ce@news.free.fr> <4496e9c9$0$14868$626a54ce@news.free.fr> <4fokj4F1ihat3U1@uni-berlin.de> <4497c20e$0$29656$636a55ce@news.free.fr> <4fpuh5F1i9bl1U1@uni-berlin.de> <4497d72d$0$30964$636a55ce@news.free.fr> <4fq5fkF1k346bU1@uni-berlin.de> <44982637$0$29812$626a54ce@news.free.fr> <1151013151.902103.32800@g10g2000cwb.googlegroups.com> Message-ID: <1151098803.791806.302740@i40g2000cwc.googlegroups.com> Anton Vredegoor wrote: > Paul Boddie wrote: > > > > I was going to write a long reply to one of your previous messages, but > > the above link references a project which may intersect with some of > > your expectations. Meanwhile, it should be noted that the availability > > Somehow I get the impression of getting away with my posts luckily, > while you now are duping other interested readers into not reading your > innermost feelings about this subject. Let's get it in the open, don't > spare me :-) I was just going to say that your Web application could have used XSLT more or less exclusively if the data arrives in XML (and obviously leaves in some kind of XML), provided you aren't doing exotic processing on the data. [...] > Well maybe this trick of vehemently denying the existence of something > on Usenet worked again, by materializing the thing as a reaction. My intention was to correct the perception that before a bunch of work was done on exposing the Python AST (the so-called "AST branch") there weren't any tools to get nice ASTs which could be used to generate code. Of course there are such tools, with the compiler module being in the standard library itself - not to be confused with the parser module which everyone seems to mention and about whose representation everyone seems to complain, but that's also obviously in the standard library too. I'm not sure about the ready availability of Python-to-Python transformers, though. I have made HTML "reports" of Python programs - annotated source code with type information in CSS-based pop-ups - and a plain text serialiser for the compiler module's AST wouldn't be as difficult as that. The hardest part of working with the compiler API would be in the modification of the AST, and perhaps it is in that area that the "AST branch" shows promise. [...] > Maybe a Python webserver could also emit pieces of javascript code by > getting them from a *Python* code library after translating Python > code on the fly? http://subway.python-hosting.com/file/crackajax/trunk/crackajax.py I personally don't go for this kind of thing, but people have given it some thought. Paul From alanmk at hotmail.com Thu Jun 8 05:49:06 2006 From: alanmk at hotmail.com (Alan Kennedy) Date: 8 Jun 2006 02:49:06 -0700 Subject: XML, JSON, or what? References: <1149749530.734275.181300@j55g2000cwa.googlegroups.com> Message-ID: <1149760146.136587.124710@h76g2000cwa.googlegroups.com> [Frank Millman] > I am writing a multi-user accounting/business application, which uses > sockets to communicate between server and client. The server contains > all the business logic. It has no direct knowledge of the client. I > have devised a simple message format to exchange information between > the two. > > At first, I used XML as a message format. Then I read the article that > recommended not using XML for Python-to-Python, so I changed it to a > pickled collection of Python objects. It works just as well. If you were just communicating python to python, I'd recommend Pyro, since it has all the socket management, etc, already taken care of. http://pyro.sourceforge.net > At present the client uses wxPython. One of my medium-term goals is to > write a web-based client. I don't think it will be easy to reproduce > all the functionality that I have at present, but I hope to get close. > I have not done any serious research yet, but I am pretty sure I will > use javascript on the client, to make it as universal as possible. If you're going to mix javascript client and python server, you definitely need something cross platform, like XML or JSON. > Ideally, the server should be able to handle a wxPython client or a web > client, without even knowing which one it is talking to. Obviously I > cannot use Pickle for this. So my question is, what is the ideal format > to use? I could go back to XML, or I could switch to JSON - I have read > a bit about it and it does not seem complicated. JSON is indeed (mostly) as simple as it looks: it fits your need very well. And you should be up and running with it very quickly. > My messages are not > very large (maximum about 2k so far for a complex screen layout) so I > don't think performance will be an issue. And parsing JSON will almost certainly be faster than parsing XML. You should easily be able to parse hundreds or maybe thousands of 2K JSON messages a second. And JSON generation and parsing is at least as well supported and robust as XML, in most languages. > I would rather make a decision now, otherwise I will have a lot of > changes to make later on. Does anyone have any recommendations? I'd go with JSON, for simplicity and portability. If you have any specific questions about it, ask. regards, -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From cdsmith at twu.net Fri Jun 23 22:25:36 2006 From: cdsmith at twu.net (Chris Smith) Date: Fri, 23 Jun 2006 20:25:36 -0600 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> Message-ID: I thought about this in the context of reading Anton's latest post to me, but I'm just throwing out an idea. It's certainly too fuzzy in my mind at the moment to consider it in any way developed. I'm sure it's just as problematic, if not more so, as any existing accounts of dynamic types. Here it is, anyway, just because it's a different way of seeing things. (I'll first point out here, because it's about to become significant, that contrary to what's been said several times, static type systems assign types to expressions rather than variables.) First of all, it's been pointed out several times that static typing assumes a static program, and that it becomes difficult to describe if the program itself is being modified as it is evaluated. The interesting thing that occurred to me earlier today is that for languages that are reducible to the lambda calculus at least, ALL programs are from some perspective self-modifying. Specifically, no single expression is ever evaluated more than once. When a statement is evaluated several times, that simply means that there is actually a more complex statement that, when it is evaluated, writes a new statement, which consists of a copy of itself, plus something else. Thus it makes little sense, from that perspective, to worry about the possibility that an expression might have a different type each time it's evaluated, and therefore violate static typing. It is never evaluated more than once. What if I were to describe a dynamically typed system as one in which expressions have types just as they do in a static type system, but in which programs are seen as self-modifying? Rather than limiting forms of recursion for well-typed programs to, say, the standard fixed-point operator and then assigning some special-purpose rule for it, we simply admit that the program is being modified as it is run. Type inference (and therefore checking) would need to be performed incrementally. When they do, the results of evaluating everything up to this point will have changed the type environment, providing more information than was previously known. The type environment for assigning types to an expression could still be treated statically at the time that the expression first comes into existence; but it would be different then from what it was at the beginning of the program. Of course, this is only a formal description of the meaning, and not a description of any kind of a reasonable implementation. However, this initially appears, on the surface, to take us some distance toward unifying dynamic types and static types. At least two interesting correlations just sort of "fall out". First, Marshall has observed (and I agree) that static and dynamic types form not different ways of looking at verifying correctness, but rather different forms of programming in the first place. It appears to be encouraging, then, that this perspective classifies static and dynamic types based on how we define the program rather than how we define the type checking. Second, type theory is sometimes concerned with the distinction between structural and nominal types and various hybrids. We've concerned ourself a good bit in this thread with exactly what kinds of "tags" or other runtime type notations are acceptable for defining a dynamically typed language. In this view, Smalltalk (or some simplification thereof wherein doesNotUnderstand is considered an error handling mechanism rather than a first-class part of the language semantics) would represent the dynamic version of structural types, whereas type "tagging" systems with a user-declared finite set of type tags would be the dynamic equivalent to nominal types. Just like in type theory, dynamic type systems can also have hybrids between structural and nominal types. Obviously, that has a lot of problems... some of the same ones that I've been complaining about. However, it has some interesting characteristics as well. If an expression is assumed to be different each time it is encountered, then type the type of "one" expression is easy to evaluate in the initial environment in which it occurs (for some well-defined order of evaluation). Now, to Anton's response, with admittedly rather liberal skimming (sorry!) to avoid my staying up all night thinking about this. Anton wrote: > It's obviously going to be difficult to formally pin down something that > is fundamentally informal. It's fundamentally informal because if > reasoning about the static properties of terms in DT languages were > formalized, it would essentially be something like a formal type system. We may be talking past each other, then, but I'm not particularly interested in the informal aspects of what makes up a type. I agree that formalizing the notion appears quite difficult, especially if my conjecture above were to become part of it. > However, there are some pretty concrete things we can look at. One of > them, which as I've mentioned elsewhere is part of what led me to my > position, is to look at what a soft type inferencer does. It takes a > program in a dynamically typed language, and infers a static type scheme > for it (obviously, it also defines an appropriate type system for the > language.) This has been done in both Scheme and Erlang, for example. > How do you account for such a feat in the absence of something like > latent types? There are undoubtedly any number of typing relations and systems of rules which can be assigned to any program in a dynamically typed language. I think the more interesting question is how these type inference systems choose between the limitless possibilities in a way that tends to be acceptable. I suspect that they do it by assuming certain kinds of type systems, and then finding them. I doubt they are going to find a type system in some language until the basics of that system have been fed to the software as something to look for. I'd be delighted to discover that I'm wrong. If nothing else, it would mean that applying these programs to significant amounts of Scheme and Erlang software would become an invaluable tool for doing research in type theory. > > Undoubtedly, some programmers sometimes perform reasoning about their > > programs which could also be performed by a static type system. > > I think that's a severe understatement. Yes, I agree. I did not intend the connotations that ended up there. In fact, I'd say that something like 90% (and yes, I just grabbed that number out of thin air) of reasoning performed by programmers about their programs could be performed by a static type system. > BTW, I notice you didn't answer any of the significant questions which I > posed to Vesa. So let me pose one directly to you: how should I rewrite > the first sentence in the preceding paragraph to avoid appealing to an > admittedly informal notion of type? I'll try to answer your question. My answer is that I wouldn't try. I would, instead, merely point out that the notion of type is informal, and that it is not necessarily even meaningful. The two possibilities that concern me are that either reasoning with types in this informal sense is just a word, which gets arbitrarily applied to some things but not others such that distinctions are made that have no real value, and that any sufficient definition of type-based reasoning is going to be broad enough to cover most reasoning that programmers ever do, once we start applying enough rigor to try to distinguish between what counts as a type and what doesn't. The fact that programmers think about types is not disputed; my concern is that the types we think about may not meaningfully exist. > Note, also, that I'm using the word > in the sense of static properties, not in the sense of tagged values. In the static sense of types, as I just wrote to Chris Uppal, I can then definitively assert at least the second of the two possibilities above. Every possible property of program execution is a type once the problem of how to statically check it has been solved. > For now, I'll stand on what I've written above. When I see if or how > that doesn't convince you, I can go further. To be clear, I am certainly convinced that people talk and think about types and also about other things regarding their programs which they do not call types. I am concerned only with how accurate it is to make that distinction, on something other than psychological grounds. If we are addressing different problems, then so be it. If however, you believe there is a type/non-type distinction that can be built on some logical foundation, then I'd love to hash it out. > > It is, nevertheless, quite appropriate to call the language "untyped" if > > I am considering static type systems. > > I agree that in the narrow context of considering to what extent a > dynamically typed language has a formal static type system, you can call > it untyped. OK. > However, what that essentially says is that formal type > theory doesn't have the tools to deal with that language, and you can't > go much further than that. As long as that's what you mean by untyped, > I'm OK with it. I can see that in a sense... yes, if a specific program has certain properties, then it may be possible to extend the proof-generator (i.e., the type checker) to be able to prove those properties. However, I remain inconvinced that the same is true of the LANGUAGE. Comments in this thread indicate to me that even if I could write a type-checker that checks correctness in a general-purpose programming language, and that language was Scheme, there would be Scheme programmers who would prefer not to use my Scheme+Types language because it would pester them until they got everything perfect before they could run their code, and Scheme would remain a separate dynamically typed (i.e., from a type theory perspective, untyped) language despite my having achieved all of the wildest dreams of the field of type theory. In that sense, I don't consider this a limitation of type theory. (Two notes: first, I don't actually believe that this is possible, since the descriptions people would give for "correct" are nowhere near so formal as the type theory that would try to check them; and second, I am not so sure that I'd want to use this new language either, for anything except applications in which bugs are truly life-threatening.) > Think of it like this: the more ambitious a language's type system is, > the fewer uncaptured static properties remain in the code of programs in > that language. However, there are plenty of languages with rather weak > static type systems. In those cases, code has more static properties > that aren't captured by the type system. Yes, I agree with this. > I'm pointing out that in many > of these cases, those properties resemble types, to the point that it > can make sense to think of them and reason about them as such, applying > the same sort of reasoning that an automated type inferencer applies. It often makes sense to apply the same sort of reasoning as would be involved in static type inference. I also agree that there are properties called types, which are frequently the same properties caught by commonly occurring type systems, and which enough developers already think of under the word "type" to make it worth trying to change that EXCEPT when there is an explicit discussion going on that touches on type theory. In that latter case, though, we need to be very careful about defining some group of things as not-types across the scope of all possible type systems. There are no such things a priori, and even when you take into account the common requirement that a type system is tractable, the set of things that are not-type because it's provably impossible to check them in polynomial time is smaller than the intuitive sense of that word. Essentially, this use of "type" becomes problematic when it is used to draw conclusions about the scope, nature, purpose, etc. of static types. This answers a good number of the following concerns. > > I see it as quite reasonable when there's an effort by several > > participants in this thread to either imply or say outright that static > > type systems and dynamic type systems are variations of something > > generally called a "type system", and given that static type systems are > > quite formally defined, that we'd want to see a formal definition for a > > dynamic type system before accepting the proposition that they are of a > > kind with each other. > > A complete formal definition of what I'm talking about may be impossible > in principle, because if you could completely formally define it, you'd > have a static type system. That may not actually be the case. Lots of things may be formally defined that would nevertheless be different from a static type system. For example, if someone did provide a rigorous definition of some category of type errors that could be recognized by some defined process as such, then the set of language features that detect and react to these errors could be defined as a type system. Chris Uppal just posted such a thing in a different part of this thread, and I'm unsure at this point whether it works or not. The problem with earlier attempts to define type errors in this thread is that they either tend to include all possible errors, or are distinguished by some nebulously defined condition such as being commonly thought of in some way by some set of human beings. > If that makes you throw up your hands, then all you're saying is that > you're unwilling to deal with a very real phenomenon that has obvious > connections to type theory, examples of which I've given above. That's > your choice, but at the same time, you have to give up exclusive claim > to any variation of the word "type". I really think it's been a while since I claimed any such thing... and even at the beginning, I only meant to challenge that use of type in comparing static and dynamic type systems. I am not so sure, though, about these obvious connections to type theory. Those connections may be, for example, some combination of the following rather uninteresting phenomena: 1. Type theory got the word "type" from somewhere a century ago, and the word has continued to be used in its original sense as well, and it just happens that despite the divergence of these uses, there remains some common ground between the two different meanings. or, 2. Many programmers approach type theory from the perspective of having some intuitive definition of a type in mind, and they tend to mix it in with a few of the ideas of type theory in their minds, and then go off and use the word in other contexts. > Terms are used in a context, and it's perfectly reasonable to call > something a "latent type" or even a "dynamic type" in a certain context > and point out connections between those terms and their cousins (or if > you insist, their completely unrelated namesakes) static types. Yes, I agree. I'm yet to be convinced that they are completely unrelated namesakes. I am actually trying to reconstruct such a thing. The problem is that, knowing how "type" is used in the static sense, I am forced to reject attempts that share only basic superficial similarities and yet miss the main point. > > I believe that's unacceptable for several reasons, but the most > > significant of them is this. It's not reasonable to ask anyone to > > accept that static type systems gain their essential "type system-ness" > > from the idea of having well-defined semantics. > > The definition of static type system is not in question. However, > realistically, as I pointed out above, you have to acknowledge that type > systems exist in, and are inextricably connected to, a larger, less > formal context. No, but it certainly seems that the reason behind calling them a "type system" is being placed very much in doubt. Simply saying static type system is horribly wrong, and I do it only to avoid inventing words wholesale... but I greatly regret the implication that it means "a type system, which happens to be static." In some senses, this is akin to describing a boat as "a floating platform". That may be somewhat accurate as a rough definition for someone who is familiar with platforms but not with boats. It's a terrible failure, though, in that it implies that being a platform is the important bit; where actually the important bit is that it floats! In fact, it may turn out that boats have very little to do with common platforms... for example, while some boats (barges) have many of the same properties that platforms do, there are whole other classes of boats, which are considerably more powerful than barges, that end up looking very little like a platform at all. If you press hard enough, I can be forced to admit that there is some kind of connection between platforms and floating platforms, because after all one has to stand on something while using a boat, right? Well, the important part of the phrase "static type" isn't "type" but "static." Without even having to undertake the dead-end task of deciding who's got the right to the word "type", let's assume that I should really be saying some other word, like boat. However, that word doesn't really exist, so I am stuck with "static type". I just have to be very careful about explaining that what I mean by type is completely different from what others mean by type. There is some overlap, which potentially arises from one of the uninteresting sources I've listed above, or maybe... just maybe... arises from some actual similarity that we haven't identified yet. But we still haven't identified it. This is very much the situation I see ourselves in. I very much want to agree with everyone's right to use the word "type", but then people keep saying things that seem to me to be clear misunderstandings that the important part is the "static", not the "type". When qualification is not needed Fundamentally, the important aspect of types, in the static sense, is that they are used in a formal, syntactic, tractable method for proving the absence of program behaviors. Even if it turns out that, in practice, all type systems contain mechanisms for solving a certain rigorously definable class of problems, that will not be part of the definition of types, when the word is used in the static sense. So we can search for a more formal similarity, or we can agree that it's incidentally true that they sometimes solve the same problems but also agree that it's pointless and misleading to ever talk about a "type system" without clarifying the usage either explicitly or by context. It remains incorrect to relax the degree of formality and talk about static types in an intuitive and undefinable way, because than they lose the entire property of being types at all. At that point, it's best to drop "static", which is not true anyway, and switch over to the other set of terminology where it makes sense to call them types. > There's a sense in which one can say that yes, the informal types I'm > referring to have an interesting degree of overlap with static types; > and also that static types do, loosely speaking, have the "purpose" of > formalizing the informal properties I'm talking about. Static types have the property of proving ANY properties of a program that may be proven. Certainly, research is pragmatically restricted to specific problems that are (1) useful and (2) solvable. Aside from that, I can't imagine any competent language designer building a type system, but rejecting some useful and solvable feature for the sole reason that he or she doesn't think of it as solving a type error. > But I hardly see why such an informal characterization should bother > you. It doesn't affect the definition of static type. I hope I've explained how it does affect the definition of a static type. > This is based on the assumption that all we're talking about is > "well-defined semantics". Indeed. My statement there will not apply if we find some formal definition of a dynamic type system that doesn't reduce to well-defined semantics once you remove the intuitive bits from it. -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation From avelldiroll at yahoo.fr Wed Jun 21 16:34:24 2006 From: avelldiroll at yahoo.fr (Avell Diroll) Date: Wed, 21 Jun 2006 22:34:24 +0200 Subject: OS specific command in Python In-Reply-To: References: <1150781429.090359.148560@c74g2000cwc.googlegroups.com> <44979b35$0$8390$626a54ce@news.free.fr> <1150823140.295590.307390@i40g2000cwc.googlegroups.com> <4498d973$0$25496$626a54ce@news.free.fr> Message-ID: <4499ad49$0$23551$626a54ce@news.free.fr> 3c273 wrote: > I was just trying to learn how to use .communicate() and all of the examples > I see have [0] after .communicate(). What is the significance of the [0]? From the Python Library Reference (http://docs.python.org/lib/node239.html), you learn that the method communicate() from the subprocess.Popen() class returns a tuple containing the standard output as first item and the standard error of the child process as second item. So the [0] in the example is for selecting the first item of the tuple ... #### from subprocess import * p1 = Popen(["dmesg"], stdout=PIPE) p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) output = p2.communicate()[0] ### is equivalent to : from subprocess import * p1 = Popen(["dmesg"], stdout=PIPE) p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) output_and_error = p2.communicate() output = output_and_error[0] ### or : from subprocess import * p1 = Popen(["dmesg"], stdout=PIPE) output=Popen(["grep","hda"],stdin=p1.stdout,stdout=PIPE).communicate()[0] ### or : from subprocess import * p1 = Popen(["dmesg"], stdout=PIPE) p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) (output, stderror) = p2.communicate() I hope it was useful ... From scott.daniels at acm.org Thu Jun 15 16:36:34 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Thu, 15 Jun 2006 13:36:34 -0700 Subject: list of polynomial functions In-Reply-To: References: <1150390140.459461.169900@i40g2000cwc.googlegroups.com> <4491AA55.7030200@tim.thechases.com> Message-ID: <4491c005$1@nntp0.pdx.net> Fredrik Lundh wrote: > Tim Chase wrote: >>> The `i` is the problem. It's not evaluated when the lambda >>> *definition* is executed but when the lambda function is >>> called. And then `i` is always == `n`. You have to >>> explicitly bind it as default value in the lambda definition: >>> >>> polys.append(lambda x, i=i: polys[i](x)*x) >>> >>> Then it works. >> >> Just to sate my curiosity, why can the lambda find "polys", but not >> find "i"? If what you're describing is the case, then it seems to me >> that the following code should work too: > > it's not that it cannot find it, it's that if you use a closure, i will > have the same value for all lambdas. > >> There's some subtle behavior here that I'm missing. > > lexical closures bind to names, default arguments bind to values. Just to be a bit more explicit: In code like: def make_polys(n): """Make a list of polynomial functions up to order n.""" p = lambda x: 1 polys = [p] for i in range(n): polys.append(lambda x: polys[i](x)*x) i=3 The lambda-defined functions will be called after the for loop is done, at which time the "i" (from the surrounding environment) will have a value of 3. Hope this makes it a bit clearer. --Scott David Daniels scott.daniels at acm.org From cvanarsdall at mvista.com Tue Jun 6 11:41:45 2006 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Tue, 06 Jun 2006 08:41:45 -0700 Subject: what are you using python language for? In-Reply-To: References: Message-ID: <4485A239.6060508@mvista.com> hacker1017 wrote: > im just asking out of curiosity. > We use python for somewhat complex build system which builds several versions of embedded Linux for multiple architectures (30+). Two particularly interested aspects of this build system involve simple cluster management utilities (utilities to help manage distribution of work across 70 machines) and we are currently developing a distributed execution framework. Some cool stuff if you ask me (I mean, i had better like it, its my job!) -carl -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From find at my.address.elsewhere Sat Jun 24 22:54:08 2006 From: find at my.address.elsewhere (Matthias Blume) Date: Sat, 24 Jun 2006 21:54:08 -0500 Subject: Saying "latently-typed language" is making a category mistake References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <86Qmg.10725$o4.1907@newsread2.news.pas.earthlink.net> <0neng.213767$8W1.1948@fe1.news.blueyonder.co.uk> Message-ID: David Hopwood writes: > Patricia Shanahan wrote: >> Vesa Karvonen wrote: >> ... >> >>> An example of a form of informal reasoning that (practically) every >>> programmer does daily is termination analysis. There are type systems >>> that guarantee termination, but I think that is fair to say that it is >>> not yet understood how to make a practical general purpose language, whose >>> type system would guarantee termination (or at least I'm not aware of >>> such a language). It should also be clear that termination analysis need >>> not be done informally. Given a program, it may be possible to formally >>> prove that it terminates. >> >> To make the halting problem decidable one would have to do one of two >> things: Depend on memory size limits, or have a language that really is >> less expressive, at a very deep level, than any of the languages >> mentioned in the newsgroups header for this message. > > I don't think Vesa was talking about trying to solve the halting problem. > > A type system that required termination would indeed significantly restrict > language expressiveness -- mainly because many interactive processes are > *intended* not to terminate. Most interactive processes are written in such a way that they (effectively) consist of an infinitely repeated application of some function f that maps the current state and the input to the new state and the output. f : state * input -> state * output This function f itself has to terminate, i.e., if t has to be guaranteed that after any given input, there will eventually be an output. In most interactive systems the requirements are in fact much stricter: the output should come "soon" after the input has been received. I am pretty confident that the f for most (if not all) existing interactive systems could be coded in a language that enforces termination. Only the loop that repeatedly applies f would have to be coded in a less restrictive language. From sven.suursoho at gmail.com Sat Jun 17 05:07:25 2006 From: sven.suursoho at gmail.com (sven.suursoho at gmail.com) Date: 17 Jun 2006 02:07:25 -0700 Subject: Iterating generator from C Message-ID: <1150535245.425994.72370@g10g2000cwb.googlegroups.com> Does messing with signal handlers and longjmp affect Python interpreter? I'm trying to find solution for problem, described in http://groups.google.com/group/comp.lang.python/browse_thread/thread/98cbae94ca4beefb/9d4d96fd0dd9fbc3 and came up with test application. It works well but i'm not sure it is ok for long-running python interpreter? #include #include #include const char *py_source = "def fn():\n" " yield 1\n"; jmp_buf env; enum _ { detect, no, yes } has_buggy_gen_iternext = detect; static sighandler_t old_abrt = SIG_DFL; void signal_handler (int sig) { if (sig == SIGABRT) longjmp(env, 1); } int main (int argc, char *argv[]) { Py_Initialize(); PyObject *globals = PyDict_New(); // insert function code into interpreter PyObject *code = PyRun_String(py_source, Py_file_input, globals, NULL); Py_DECREF(code); // compile call to the function code = Py_CompileString("fn()", "", Py_eval_input); // do call PyObject *gen = PyEval_EvalCode((PyCodeObject *)code, globals, NULL); gen = PyObject_GetIter((PyObject *)gen); // detect if we are using bad Python interpreter if (has_buggy_gen_iternext == detect) { if (setjmp(env) == 0) // first time, set signal handler old_abrt = signal(SIGABRT, signal_handler); else { // jumped here from signal handler -- bad Python has_buggy_gen_iternext = yes; signal(SIGABRT, old_abrt); } } if (has_buggy_gen_iternext == yes) printf("generators are disabled\n"); else { // iterate result PyObject *item; while ((item = PyIter_Next(gen))) { printf("> %ld\n", PyInt_AsLong(item)); Py_DECREF(item); } if (has_buggy_gen_iternext == detect) { // ok, restore old signal handler has_buggy_gen_iternext = no; signal(SIGABRT, old_abrt); } } Py_DECREF(gen); Py_DECREF(code); Py_DECREF(globals); Py_Finalize(); return 0; } From elcinturapartida at yahoo.es Tue Jun 27 17:06:46 2006 From: elcinturapartida at yahoo.es (el cintura partida) Date: Tue, 27 Jun 2006 23:06:46 +0200 (CEST) Subject: Event objects Threading on Serial Port on Win32 In-Reply-To: <91906ddf0606271257m5c7cc640k566bf621b448ee13@mail.gmail.com> Message-ID: <20060627210646.45490.qmail@web26011.mail.ukl.yahoo.com> Muchas gracias Gabriel por haberme informado, vos si que es un profesional de la programaci?n. Un saludo, David --- Gabriel escribi?: > David: > Tube el mismo problema que vos con el hilo del > ejemplo de pyserial. Me > paso que en Linux andaba bien, obvio, pero tenia un > peque?o > problemilla en Windows, tambi?n obvio. > > Lo solucione de la siguiente manera: > Asi es el codigo original de la funci?n > ComPortThread > > def ComPortThread(self): > """Thread that handles the incomming > traffic. Does the basic input > transformation (newlines) and generates > an SerialRxEvent""" > > while self.alive.isSet(): > #loop while alive event is true > if self.ser.inWaiting() != 0: > text = self.ser.read() > event = SerialRxEvent(self.GetId(), > text) > > self.GetEventHandler().AddPendingEvent(event) > > > solo tiene que agregarle el siguiente bucle antes > que nada: > while not self.alive.isSet(): > pass > > qued?ndote as? dicha funci?n... > > def ComPortThread(self): > """Thread that handles the incomming > traffic. Does the basic input > transformation (newlines) and generates > an SerialRxEvent""" > while not self.alive.isSet(): > pass > > while self.alive.isSet(): > #loop while alive event is true > if self.ser.inWaiting() != 0: > text = self.ser.read() > event = SerialRxEvent(self.GetId(), > text) > > self.GetEventHandler().AddPendingEvent(event) > > y listo... Con eso deber?a andar > Espero haber sido ?til > > -- > Gabriel > ______________________________________________ LLama Gratis a cualquier PC del Mundo. Llamadas a fijos y m?viles desde 1 c?ntimo por minuto. http://es.voice.yahoo.com From bdesth.quelquechose at free.quelquepart.fr Mon Jun 12 21:22:59 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 13 Jun 2006 03:22:59 +0200 Subject: [OT] Most elegant way to generate 3-char sequence In-Reply-To: <4489F72C.7010101@lexicon.net> References: <1149889784.391965.271570@h76g2000cwa.googlegroups.com> <4489F72C.7010101@lexicon.net> Message-ID: <448de39f$0$9607$636a55ce@news.free.fr> John Machin a ?crit : > On 10/06/2006 7:49 AM, Rob Cowie wrote: (snip) >> >> def generator(): >> for char in alpha: > > > Why stop at two spaces? One-space indentation is syntactically correct :-) I very often uses 2-spaces indent when posting here, to avoid problems with wrapping. From jurgenex at hotmail.com Fri Jun 9 02:25:29 2006 From: jurgenex at hotmail.com (Jürgen Exner) Date: Fri, 09 Jun 2006 06:25:29 GMT Subject: HOST - dreamhost.com / Liberality (Hosting, Basic Requirement) References: <4482CDDA.9060905@lazaridis.com> Message-ID: Ilias Lazaridis wrote: > crossposted to 5 groups, which are affected by this case. > [some random ramblings about a troll being silenced for the moment] And your article has exactly what relationship to Perl? *PLONK* jue From fredrik at pythonware.com Tue Jun 6 10:29:24 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 06 Jun 2006 16:29:24 +0200 Subject: capture video from camera In-Reply-To: <1149603488.012417.269760@j55g2000cwa.googlegroups.com> References: <1149598946.182874.121650@c74g2000cwc.googlegroups.com> <1149603488.012417.269760@j55g2000cwa.googlegroups.com> Message-ID: aljosa wrote: > i posted here to find out if anybody knows a better way to capture > video. what other requirements did you forget to mention ? From grante at visi.com Fri Jun 9 18:20:18 2006 From: grante at visi.com (Grant Edwards) Date: Fri, 09 Jun 2006 22:20:18 -0000 Subject: Most elegant way to generate 3-char sequence References: <1149889784.391965.271570@h76g2000cwa.googlegroups.com> Message-ID: <128jt12jo4glkb7@corp.supernews.com> On 2006-06-09, Rob Cowie wrote: > Hi all, > > I wish to generate a sequence of the form 'aaa', 'aab', aac'.... 'aba', > 'abb', 'abc' etc. all the way to 'zzz'. > > How would you construct a generator to acheive this? > > A simple, working but somewhat inelegant solution is... > > alpha = ['a','b','c','d'] #shortened for brevity > alpha2 = ['a','b','c','d'] > alpha3 = ['a','b','c','d'] > > def generator(): > for char in alpha: > for char2 in alpha2: > for char3 in alpha3: > yield char + char2 + char3 Why three separate lists? Why not alpha = ['a','b','c','d'] #shortened for brevity def generator(): for char in alpha: for char2 in alpha: for char3 in alpha: yield char + char2 + char3 -- Grant Edwards grante Yow! I think I am an at overnight sensation right visi.com now!! From g.brandl-nospam at gmx.net Mon Jun 5 14:22:22 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Mon, 05 Jun 2006 20:22:22 +0200 Subject: is it possible to find which process dumped core In-Reply-To: References: <1149514829.032643.193890@h76g2000cwa.googlegroups.com> Message-ID: Steve Holden wrote: > su wrote: >> to find which process dumped core at the promt we give >> >> $ file core.28424 >> >> core.28424: ELF 32-bit LSB core file of 'soffice.bin' (signal 11), >> Intel 80386, version 1 (SYSV), from 'soffice.bin' >> >> from this command we know 'soffice.bin' process dumped core. Now can i >> do the same using python i.e. finding which process dumped core? if so >> how can i do it? >> > Unfortunately, without some debugging, all you are likely to find is > that /usr/bin/python (or some other interpreter executable) dumped core. > > You'd have to poke around inside the core image to find out which file > was being executed when the interpreter failed. I think he didn't want to analyze a Python core dump. su: look into /usr/share/file/magic or whatever it's called on your box to see where "file" looks for the executable name. Georg From percivall at gmail.com Tue Jun 13 04:48:04 2006 From: percivall at gmail.com (Simon Percivall) Date: 13 Jun 2006 01:48:04 -0700 Subject: numeric/numpy/numarray In-Reply-To: References: Message-ID: <1150188484.888977.189510@y43g2000cwc.googlegroups.com> Bryan wrote: > hi, > > what is the difference among numeric, numpy and numarray? i'm going to start > using matplotlib soon and i'm not sure which one i should use. > > > this page says, "Numarray is a re-implementation of an older Python array module > called Numeric" > http://www.stsci.edu/resources/software_hardware/numarray > > this page says, "NumPy derives from the old Numeric code base and can be used as > a replacement for Numeric." > http://numeric.scipy.org/ > > i looked at the matplotlib examples today and if i remember correctly, the > examples didn't use numarray. > > so i'm a bit confused. > > thanks, > > bryan Look again at numeric.scipy.org, and this time: read the whole page, especially the section called "Older Array Packages". From Michael.Husmann at teleatlas.com Mon Jun 19 05:54:36 2006 From: Michael.Husmann at teleatlas.com (Michael Husmann) Date: Mon, 19 Jun 2006 11:54:36 +0200 Subject: memory-leak in pysqlite 2.3.0 ? Message-ID: <8289D4DDD352DF45B8DABD7D5852A59001C007FA@EUSRV-EXC1.eu.ta.global> After upgrading from pysqlite 2.0.5 to pysqlite 2.3.0 writing into a sqlite database increases memory consumption heavily. A similar program with Ruby and sqlite-ruby 1.1.0 does not affect memory consumption at all. Here a short example: ------------------------------- #!/usr/bin/env python import os from pysqlite2 import dbapi2 print dbapi2.version db = dbapi2.connect("bla.db") c = db.cursor() c.execute("create table b (c integer)") for i in xrange(10000000): c.execute("insert into b values (%d)" % i) ---------------------------------- System in use: Python 2.4.1, Sqlite3 3.3.6, Pysqlite 2.3.0 Regards, Michael From fredrik at pythonware.com Thu Jun 29 17:19:34 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 29 Jun 2006 23:19:34 +0200 Subject: style question In-Reply-To: References: <1151314163.701348.195370@u72g2000cwu.googlegroups.com> <1151314474.696043.201250@b68g2000cwa.googlegroups.com> Message-ID: Jorgen Grahn wrote: >> assuming fixed-pitch fonts isn't very Pythonic, though; to get reliable indentation >> no matter what font you're using, you can write [...] > > Since when? I've always coded, in all languages I've ever used[1], under the > assumption that the reader will view it with a fixed-pitch (or whatever the > proper term is) font. I assumed everyone else did, too. that's a popular myth. > (I like well-typeset code in print though. Bjarne Stroustrup uses an elegant > system for C++ code, where identifiers and strings are in Times italic, > operators in Courier, and so on.) the idea of printing everything in courier (or some other monospace font) is a rather new idea; if you read seventies stuff, the program code is often as carefully designed as the rest of the document. (for an indication that we might be moving back to nicely rendered code, see Sun's new Fortress language, which provides extraordinarily detailed control over how identifiers are rendered, including extensive support for Unicode and math notation. it also mandates the use of proportional fonts for things like identifiers and comments...) From g.brandl-nospam at gmx.net Thu Jun 29 14:07:45 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Thu, 29 Jun 2006 20:07:45 +0200 Subject: Immutability In-Reply-To: References: <4Qj*cEjkr@news.chiark.greenend.org.uk> Message-ID: Steve Holden wrote: > Georg Brandl wrote: >> Steve Holden wrote: > [...] >> >>>Would it make sense, in the single argument case, to default the doc >>>value to fget.__doc__ to support that use case, or should we just not >>>create read-only properties by using property as a decorator? >> >> >> This is actually already the case in 2.5. >> > Sorry, haven't had much time for python-checkins lately. I didn't want to offend you, I must know since I implemented it myself ;) > But this would > certainly argue that the decorator form for read-only properties is > accepted at some level. Yes, one could argue in this direction. I will ask on python-dev whether an official hint should be added to the documentation. Georg From cito at online.de Mon Jun 5 05:59:36 2006 From: cito at online.de (Christoph Zwerschke) Date: Mon, 05 Jun 2006 11:59:36 +0200 Subject: Python less error-prone than Java In-Reply-To: <4483E9C3.6090207@v.loewis.de> References: <1149424883.529756.13700@j55g2000cwa.googlegroups.com> <4483E9C3.6090207@v.loewis.de> Message-ID: Martin v. L?wis wrote: > In Python 2.4 and later, you could write > > def Distance(t1, t0, maxint=(1<<32)-1): > return (t1-t0) & maxint No, this function behaves differently. It never returns a negative value. The only difference in Python 2.4 is that 1<<32 was 0 before. -- Christoph From sreeram at tachyontech.net Fri Jun 9 13:47:06 2006 From: sreeram at tachyontech.net (K.S.Sreeram) Date: Fri, 09 Jun 2006 23:17:06 +0530 Subject: TypeError: unsubscriptable object In-Reply-To: <1149874726.470436.279200@i40g2000cwc.googlegroups.com> References: <1149874726.470436.279200@i40g2000cwc.googlegroups.com> Message-ID: <4489B41A.4070308@tachyontech.net> k.retheesh at gmail.com wrote: > print template % (ID, IID, Function[:10], Description[:10], > ErrorNumber, StatusCD) > TypeError: unsubscriptable object It means either 'Function' or 'Description' is not a sequence. Try inserting print statements to see what values they are. e.g: a = 2 a[:10] will give me an 'unsubscriptable object' Regards Sreeram -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 260 bytes Desc: OpenPGP digital signature URL: From gneuner2/ at comcast.net Mon Jun 19 06:11:15 2006 From: gneuner2/ at comcast.net (George Neuner) Date: Mon, 19 Jun 2006 06:11:15 -0400 Subject: What is Expressiveness in a Computer Language References: <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <2006061410510511272-raffaelcavallaro@pasdespamsilvousplaitmaccom> <2006061501423327544-raffaelcavallaro@pasdespamsilvousplaitmaccom> <2006061611492350073-raffaelcavallaro@pasdespamsilvousplaitmaccom> <2006061618250975249-raffaelcavallaro@pasdespamsilvousplaitmaccom> <7zhd2himme.fsf@app-3.diku.dk> Message-ID: On 19 Jun 2006 10:19:05 +0200, torbenm at app-3.diku.dk (Torben ?gidius Mogensen) wrote: >If you don't have definitions (stubs or complete) of the functions you >use in your code, you can only run it up to the point where you call >an undefined function. So you can't really do much exploration until >you have some definitions. Well in Lisp that just drops you into the debugger where you can supply the needed return data and continue. I agree that it is not something often needed. >I expect a lot of the exploration you do with incomplete programs >amount to the feedback you get from type inference. The ability to write functions and test them immediately without writing a lot of supporting code is _far_ more useful to me than type inference. I'm not going to weigh in on the static v dynamic argument ... I think both approaches have their place. I am, however, going to ask what information you think type inference can provide that substitutes for algorithm or data structure exploration. George -- for email reply remove "/" from address From martin.witte at gmail.com Fri Jun 9 10:24:07 2006 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 9 Jun 2006 07:24:07 -0700 Subject: Getting start/end dates given week-number In-Reply-To: References: Message-ID: <1149863047.066608.293970@i39g2000cwa.googlegroups.com> see the calendar faq http://www.faqs.org/faqs/calendars/faq/part3/, look especially in section 6.7. Tim Chase wrote: > I've been trying to come up with a good algorithm for determining > the starting and ending dates given the week number (as defined > by the strftime("%W") function). > > My preference would be for a Sunday->Saturday range rather than a > Monday->Sunday range. Thus, > > >>> startDate, stopDate = weekBoundaries(2006, 23) > > would yield a start-date of June 4, 2006 and an end-date of June > 10, 2006 in this hypothetical function (as strftime("%W") for > today, June 9th, 2006 returns 23). > > I've posted my first round of code below, but I'm having problems > with dates early in 2005, as the tests show. > > Any thoughts/improvements/suggestions would be most welcome. > > Thanks, > > -tkc > > > from datetime import date, timedelta > from time import strptime > DEBUG = False > tests = [ > #test date start end > (date(2006,1,1), (date(2006,1,1), date(2006,1,7))), > (date(2006,1,2), (date(2006,1,1), date(2006,1,7))), > (date(2006,1,3), (date(2006,1,1), date(2006,1,7))), > (date(2006,1,4), (date(2006,1,1), date(2006,1,7))), > (date(2006,1,5), (date(2006,1,1), date(2006,1,7))), > (date(2006,1,6), (date(2006,1,1), date(2006,1,7))), > (date(2006,1,7), (date(2006,1,1), date(2006,1,7))), > (date(2006,1,8), (date(2006,1,8), date(2006,1,14))), > (date(2005,1,1), (date(2004,12,26), date(2005,1,1))), > (date(2005,1,2), (date(2005,1,2), date(2005,1,8))), > ] > def weekBoundaries(year, week): > startOfYear = date(year, 1, 1) > now = startOfYear + timedelta(weeks=week) > # isoweekday() % 7 returns Sun=0 ... Sat=6 > sun = now - timedelta(days=now.isoweekday() % 7) > sat = sun + timedelta(days=6) > if DEBUG: > print "DEBUG: now = %s/%s" % (now, now.strftime("%a")) > print "DEBUG: sun = %s/%s" % (sun, sun.strftime("%a")) > print "DEBUG: sat = %s/%s" % (sat, sat.strftime("%a")) > return sun, sat > > for test, expectedResult in tests: > print "Testing %s" % test > year = test.year > # jigger it so that %W is Sun->Sat rather than Mon->Sun > weekNum = int((test + timedelta(days=1)).strftime("%W")) - 1 > results = weekBoundaries(year, weekNum) > passed = (expectedResult == results) > print "Week#%s: %s" % (weekNum, passed) > print "=" * 50 From ptmcg at austin.rr._bogus_.com Fri Jun 30 15:35:13 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 30 Jun 2006 19:35:13 GMT Subject: Regular Expression - old regex module vs. re module References: <1151607229.548737.145800@d56g2000cwd.googlegroups.com> <12aaigaohtou291@corp.supernews.com> <12aat51q5ubf1a3@corp.supernews.com> Message-ID: "Jim Segrave" wrote in message news:12aat51q5ubf1a3 at corp.supernews.com... > The poster was excluding escaped (with a '\' character, but I've just > looked up the Perl format statement and in fact fields always begin > with a '@', and yes having no digits on one side of the decimal point > is legal. Strings can be left or right justified '@<<<<', '@>>>>', or > centred '@||||', numerics begin with an @, contain '#' and may contain > a decimal point. Fields beginning with '^' instead of '@' are omitted > if the format is a numeric ('#' with/without decimal). I assumed from > the poster's original patterns that one has to worry about '@', but > that's incorrect, they need to be present to be a format as opposed to > ordinary text and there's appears to be no way to embed a '@' in an > format. It's worth noting that PERL does implicit float to int > coercion, so it treats @### the same for ints and floats (no decimal > printed). > > For the grisly details: > > http://perl.com/doc/manual/html/pod/perlform.html > > -- > Jim Segrave (jes at jes-2.demon.nl) > Ah, wunderbar! Some further thoughts... I can see that the OP omitted the concept of "@|||" centering, since the Python string interpolation forms only support right or left justified fields, and it seems he is trying to do some form of format->string interp automation. Adding centering would require not only composing a suitable string interp format, but also some sort of pad() operation in the arg passed to the string interp operation. I suspect this also rules out simple handling of the '^' operator as mentioned in the spec, and likewise for the trailing ellipsis if a field is not long enough for the formatted value. The '@' itself seems to be part of the field, so "@<<<<" would be a 5 column, left-justified string. A bare '@' seems to be a single string placeholder (meaningless to ask right or left justified :) ), since this is used in the doc's hack for including a "@" in the output. (That is, as you said, the original spec provides no mechanism for escaping in a '@' character, it has to get hacked in as a value dropped into a single character field.) The Perl docs say that fields that are too long are truncated. This does not happen in Python string interps for numeric values, but it can be done with strings (using the precision field). >>> print "%-10s" % string.ascii_uppercase ABCDEFGHIJKLMNOPQRSTUVWXYZ >>> print "%-10.10s" % string.ascii_uppercase ABCDEFGHIJ So if we were to focus on support for "@", "@>>>", "@<<<", "@###" and "@###.##" (with and without leading or trailing digits about the decimal) style format fields, this shouldn't be overly difficult, and may even meet the OP's requirements. (The OP seemed to also want some support for something like "@##.###****" for scientific notation, again, not a dealbreaker.) -- Paul From bdesth.quelquechose at free.quelquepart.fr Mon Jun 5 08:46:33 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 05 Jun 2006 14:46:33 +0200 Subject: check for dictionary keys In-Reply-To: <1149298230.864123.8320@u72g2000cwu.googlegroups.com> References: <1149298230.864123.8320@u72g2000cwu.googlegroups.com> Message-ID: <4483f80a$0$27349$626a54ce@news.free.fr> micklee74 at hotmail.com a ?crit : > hi > in my code, i use dict(a) to make to "a" into a dictionary , "a" comes > from user input, so my program does not know in the first place. Then > say , it becomes > > a = { '-A' : 'value1' , '-B' : "value2" , "-C" : "value3" , '-D' : > 'value4' } > > somewhere next in my code, i will check for these..: > > 1) -A and -B cannot exist together > 2) -A and -C cannot exist together > 3) -A and -B and -D cannot exist together > 4) and lots of other combinations to check for.... Looks like an option parser... If so, there's all you need in the standard lib (look for the optparse module). > > how can i efficiently check for the above? At first as i do simple > checks , i use if and else. > But as i began to check for more combinatoiuns, it gets messy.... First : use boolean logic (truth table, Kernaugh diagram, etc) to simplify things. As an example, rule #3 is useless - it's a subset of rule #1 (-A and -B and -D implies -A and -B). This should greatly reduce the number of needed tests. Then, write a simple rule system describing either valid inputs or invalid inputs (preferably the smallest set !-). FWIW, it can be as simple as a list of lambdas/error messages pairs, with lambdas being predicate taking dict keys as params: _RULES = [ (lambda keys : '-A' in keys and '-B' in keys, "can't have both options -A and -B"), (lambda keys : '-A' in keys and '-C' in keys, "can't have both options -A and -C"), # etc... ] def validate(options, rules): keys = options.keys() for predicate, message in rules: if not predicate(keys): raise ValueError(message) From rossberg at ps.uni-sb.de Wed Jun 21 12:50:35 2006 From: rossberg at ps.uni-sb.de (Andreas Rossberg) Date: Wed, 21 Jun 2006 18:50:35 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <0%Wlg.3521$MF6.947@tornado.socal.rr.com> <44992e6c$0$664$bed64819@news.gradwell.net> Message-ID: Vesa Karvonen wrote: > >>>Indeed, the ability to declare a new type that has the exact same >>>underlying representation and isomorphically identical operations but >>>not be the same type is something I find myself often missing in >>>languages. It's nice to be able to say "this integer represents vertical >>>pixel count, and that represents horizontal pixel count, and you don't >>>get to add them together." > >>Not counting C/C++, I don't know when I last worked with a typed >>language that does *not* have this ability... (which is slightly >>different from ADTs, btw) > > Would Java count? Yes, you are right. And there certainly are more in the OO camp. But honestly, I do not remember when I last had to actively work with one of them, including Java... :-) - Andreas From siona at chiark.greenend.org.uk Tue Jun 27 09:23:58 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 27 Jun 2006 14:23:58 +0100 (BST) Subject: Having problems with strings in HTML References: Message-ID: Lawrence D'Oliveiro wrote: > Kiana Toufighi wrote: > >>print ''' >>
>href="http://bbc.botany.utoronto.ca/ntools/cgi-bin/ntools_treeview_word.cgi?inp >>ut=&max=2&values_off=no&remove_bracket=no&show_line_nr=yes&show_link_out=yes >> [ ... ] ">GraphicalOutput >> ''' [ ... ] > >By the way, you _do_ realize that your "&" characters should be escaped >as "&", don't you? No they shouldn't. They part of the url, which is (IIRC) a CDATA attribute of the A element, not PCDATA. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From frithiof.jensen at die_spammer_die.ericsson.com Wed Jun 21 05:06:28 2006 From: frithiof.jensen at die_spammer_die.ericsson.com (Frithiof Andreas Jensen) Date: Wed, 21 Jun 2006 11:06:28 +0200 Subject: OT: wxPython GUI designer References: <1150661348.837969.46870@r2g2000cwb.googlegroups.com> Message-ID: "Don Taylor" wrote in message news:mailman.7224.1150765229.27775.python-list at python.org... > I find it easy to use sizers in > wxGlade. Just gave is a spin yesterday: How does on fix the size of layout; I can only manage to get sizers to distribute space evently amongst the fields, which is *not* what I want. From wmcneely at gmail.com Mon Jun 19 18:40:41 2006 From: wmcneely at gmail.com (Warren) Date: 19 Jun 2006 15:40:41 -0700 Subject: Does Running Python modules dump stuff on "C" drive? Message-ID: <1150756840.984382.234500@i40g2000cwc.googlegroups.com> I am running win2k pro and was wondering if writing python scripts or running modules dumps anything in the "C" drive? I have 3 partitions and run python on the 3rd one or "E"drive. My "C" drive is almost full and keeps loading up with stuff I don't want or need. Some of it I can find some not. So until I can get a new HD I need to keep weeding out the weeds! TIA. Warren From grante at visi.com Sun Jun 18 14:47:11 2006 From: grante at visi.com (Grant Edwards) Date: Sun, 18 Jun 2006 18:47:11 -0000 Subject: maximum integer length? References: <129asc2kok1o4b0@corp.supernews.com> Message-ID: <129b7tf4fkhq56@corp.supernews.com> On 2006-06-18, Grant Edwards wrote: >> Que? An integer is just a whole number without fraction. What are you >> talking about? > > He's talking about decimal digits. Each decimal digit takes up > 3.322 bits. A byte can hold about 2.4 digits. 400MB should be > able to hold an integer with about 1,010,000,000 decimal > digits. Oops. The real answer is 15/16 of that. I didn't realize that the integer representation only uses 15 of 16 bits. -- Grant Edwards grante at visi.com From robert.kern at gmail.com Thu Jun 22 12:51:17 2006 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 22 Jun 2006 11:51:17 -0500 Subject: OverflowError: math range error... In-Reply-To: <1150965908.354492.239230@i40g2000cwc.googlegroups.com> References: <1150965908.354492.239230@i40g2000cwc.googlegroups.com> Message-ID: Sheldon wrote: > Hi, > > I have a written a script that will check to see if the divisor is zero > before executing but python will not allow this: > > ?if statistic_array[0:4] > 0.0: > statistic_array[0,0:4] = > int(multiply(divide(statistic_array[0,0:4],statistic_array \ > [0,4]),10000.0))/100.0 > > Does anyone know why Python is complaining: > > "statistic_array[0,0:4] = > int(multiply(divide(statistic_array[0,0:4],statistic_array[0,4]),10000.0))/100.0 > > OverflowError: math range error" > > and how do I get around this problem? This stupid because there is a if > statement preventing this "dividing by zero". What kind of arrays are you using? If it's Numeric (and I think it is because numarray and numpy would throw an error at the if: statement), then your test is incorrect. Comparisons yield arrays of boolean values. When a Numeric boolean array is used as a truth value (like in an if: statement), then it will return True is *any* of the values are True. Use Numeric.alltrue(statistic_array[:4] > 0.0) instead. Both numarray and numpy throw an exception when one attempts to use arrays as truth values since the desired meaning (alltrue or sometrue) is ambiguous. -- 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 From mwilson-to at sympatico.ca Sun Jun 4 11:27:06 2006 From: mwilson-to at sympatico.ca (Mel Wilson) Date: Sun, 04 Jun 2006 11:27:06 -0400 Subject: carshing the interpreter in two lines In-Reply-To: <1149367261.176919.134090@y43g2000cwc.googlegroups.com> References: <1149343823.789918.210110@h76g2000cwa.googlegroups.com> <1149350854.072412.263920@f6g2000cwb.googlegroups.com> <1149367261.176919.134090@y43g2000cwc.googlegroups.com> Message-ID: sam wrote: > Mel: > Wow that book brings back memories. I scanned my copy to review the > subject covered, and came to the conclusion that mind reading > algorithms are the answer. > I gathered from somewhere (but not the index to Andrew Hodges' biography) that Turing was toying with an idea for "oracles", where a computation would be allowed to call out sometimes to a non-computational process to obtain some required result. Used maybe by interactive debugging programs. Cheers, Mel. > Mel Wilson wrote: [ ... ] >>Douglas Hofstadter's _Goedel, Escher, Bach: an Eternal Golden Braid_. [ ... ] >> "Contracrostipunctus". From wahab at chemie.uni-halle.de Sun Jun 18 04:54:01 2006 From: wahab at chemie.uni-halle.de (Mirco Wahab) Date: Sun, 18 Jun 2006 10:54:01 +0200 Subject: Extracting values from text file In-Reply-To: References: <20060617232543.9a0338fb.randhol+valid_for_reply_from_news@pvv.org> Message-ID: Thus spoke Dennis Lee Bieber (on 2006-06-18 06:29): > On Sun, 18 Jun 2006 03:12:23 +0200, Mirco Wahab > declaimed the following in comp.lang.python: >> - you have to explicitly instantiate a dictionary value >> (with 0) if/before you want in-place add to it (why is that?) > Uhm... Not quite... > ... > dict.get(key, default) > > returns the value associated by key, IFF key exists in the > dictionary, otherwise it returns the value defined for default. Thanks, Dennis, for your help on this part I bragged about. Now the extractor loop, according to your suggestion, can be written shorter: for rule in filter: k = re.search(r'\((.+)\)', rule) # pull out variable names ->k if k.group(1): # pull their values from text varname[k.group(1)] = varname.get(k.group(1), 0) + float( \ re.search( re.sub(r'\((.+)\)', varscanner, rule), \ example ).group(1) ) # use regex in modified 'rule' For the other issue I stumbled upon: - no DWIM-ism (do what I mean) on 'value' addition a = '1' a += '1.1111' print a will print 11.1111 and not 2.1111, as in 'dynamically typed', 'operator based' languages. (maybe the lack of a simple string-concatenation operator is the reason?) whereas: a = '1' a += 1.1111 print a will fail magnificently. These thing would come handy when working with text/table driven computations (as above) How could one approach these things without needing to get too explicitly about 'type conversions' (Python is supposed to be 'dynamically typed'?). Regards & thanks Mirco From mdudley at king-cart.com Sun Jun 4 12:23:29 2006 From: mdudley at king-cart.com (Marshall Dudley) Date: Sun, 04 Jun 2006 12:23:29 -0400 Subject: Installation Problem Message-ID: <44830900.155C7297@king-cart.com> I am trying to install python, but am having problems. I did what the README file said, and it created an executible code in the current directory as it said it would when I typed "make". It seemed to say to copy the executable over to the /usr/local directory, which I did. If I type ./python in the directory I did the make in I get: execonn# ./python Python 2.4.3 (#1, May 31 2006, 07:50:04) [GCC 2.95.4 20020320 [FreeBSD]] on freebsd4 Type "help", "copyright", "credits" or "license" for more information. >>> Which is I believe correct. But if I type /usr/local/python I get: Python 2.4.3 (#1, May 31 2006, 07:50:04) [GCC 2.95.4 20020320 [FreeBSD]] on freebsd4 Type "help", "copyright", "credits" or "license" for more information. >>> execonn# /usr/local/python Could not find platform independent libraries Could not find platform dependent libraries Consider setting $PYTHONHOME to [:] 'import site' failed; use -v for traceback Python 2.4.3 (#1, May 31 2006, 07:50:04) [GCC 2.95.4 20020320 [FreeBSD]] on freebsd4 Type "help", "copyright", "credits" or "license" for more information. >>> So nothing that tries to use it works. Any assistance would be appreciated. Thanks, Marshall From cdsmith at twu.net Tue Jun 27 02:06:02 2006 From: cdsmith at twu.net (Chris Smith) Date: Tue, 27 Jun 2006 00:06:02 -0600 Subject: What is Expressiveness in a Computer Language References: <7zy7vt1mz2.fsf@app-3.diku.dk> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <1151384511.223582.305760@m73g2000cwd.googlegroups.com> Message-ID: Marshall wrote: > Yes, an important question (IMHO the *more* important question > than the terminology) is what *programs* do we give up if we > wish to use static typing? I have never been able to pin this > one down at all. You'd need to clarify what you mean by "use static typing". Clearly, if you use forms of static typing that currently exist for Java, there's considerable limitation in expressiveness. If you mean a hypothetical "perfect" type system, then there would be no interesting programs you couldn't write, but such a system may not be possible to implement, and certainly isn't feasible. So it seems to me that we have this ideal point at which it is possible to write all correct or interesting programs, and impossible to write buggy programs. Pure static type systems try to approach that point from the conservative side. Pure dynamic systems (and I actually think that design-by-contract languages and such apply here just as well as type tagging) try to approach that point via runtime verification from the liberal side. (No, this has nothing to do with George Bush or Noam Chomsky... :) Either side finds that the closer they get, the more creative they need to be to avoid creating development work that's no longer commensurate with the gains involved (whether in safety or expressiveness). I think I am now convinced that the answer to the question of whether there is a class of type errors in dynamically checked languages is the same as the answer for static type systems: no. In both cases, it's just a question of what systems may be provided for the purposes of verifying (more or less conservatively or selectively) certain program properties. Type tags or other features that "look like" types are only relevant in that they encapsulate common kinds of constraints on program correctness without requiring the programmer to express those constraints in any more general purpose language. As for what languages to use right now, we are interestingly enough back where Xah Lee started this whole thread. All languages (except a few of the more extreme statically typed languages) are Turing complete, so in order to compare expressiveness, we'd need some other measure that considers some factor or factors beyond which operations are expressible. > There are also what I call "packaging" issues, such as > being able to run partly-wrong programs on purpose so > that one would have the opportunity to do runtime analysis > without having to, say, implement parts of some interface > that one isn't interested in testing yet. These could also > be solved in a statically typed language. (Although > historically it hasn't been done that way.) I'll note veryh briefly that the built-in compiler for the Eclipse IDE has the very nice feature that when a particular method fails to compile, it can still produces a result but replace the implementation of that method with one that just throws an Error. I've taken advantage of that on occasion, though it doesn't allow the same range of options as a language that will just go ahead and try the buggy operations. > The real question is, are there some programs that we > can't write *at all* in a statically typed language, because > they'll *never* be typable? I think there might be, but I've > never been able to find a solid example of one. This seems to depend on the specific concept of equivalence of programs that you have in mind. -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation From marshall.spight at gmail.com Sun Jun 25 14:35:04 2006 From: marshall.spight at gmail.com (Marshall) Date: 25 Jun 2006 11:35:04 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <1151199196.870389.81960@p79g2000cwp.googlegroups.com> Message-ID: <1151260503.976524.77060@b68g2000cwa.googlegroups.com> Chris F Clark wrote: > Chris F Clark (I) wrote: > > > I'm particularly interested if something unsound (and perhaps > > ambiguous) could be called a type system. I definitely consider such > > things type systems. > > "Marshall" wrote: > > > I don't understand. You are saying you prefer to investigate the > > unsound over the sound? > ... > > Again, I cannot understand this. In a technical realm, vagueness > > is the opposite of understanding. > > At the risk of injecting too much irrelevant philosophy into the > discussion, I will with great trepdiation reply. I agree this is OT, but I'm not sure about the source of trepidation. > First in the abstrtact: No, understanding is approximating. Agreed. > The world is inherently vague. Our understanding of the world is vague. The world itself is not at all vague. > We make false symbolic models of the world which > are consistent, but at some level they do not reflect reality, Yes... > because reality isn't consistent. What?! > Only by abtracting away the inherent > infinite amout of subtlety present in the real universe can we come to > comprehensible models. Sure. (Although I object to "infinite.") > Those models can be consistent, but they are > not the universe. The models in their consistency, prove things which > are not true about the real universe. Sure, sure, sure. None of these is a reaon to prefer the unsound over the sound. > Now in the concrete: In my work productivity is ultimately important. > Therefore, we live by the 80-20 rule in numerous variations. One of > ths things we do to achieve productivity is simplify things. In fact, > we are more interested in an unsound simplification that is right 80% > of the time, but takes only 20% of the effort to compute, than a > completely sound (100% right) model which takes 100% of the time to > compute (which is 5 times as long). We are playing the probabilities. What you are describing is using a precise mathematical function to approximate a different precise mathematical function. This argues for the value of approximation functions, which I do not dispute. But this does not in any way support the idea of vague trumping precise, informal trumping formal, or unsoundness as an end in itself. > It's not that we don't respect the sound underpining, the model which > is consistent and establishes certain truths. However, what we want > is the rule of thumb which is far simpler and approximates the sound > model with reasonable accuracy. In particular, we accept two types of > unsoundness in the model. One, we accept a model which gives wrong > answers which are detectable. We code tests to catch those cases, and > use a different model to get the right answer. Two, we accept a model > which gets the right answer only when over-provisioned. for example, > if we know a loop will occassionaly not converge in the n-steps that > it theoretically should, we will run the loop for n+m steps until the > approximation also converges--even if that requires allocating m extra > copies of some small element than are theoretically necessary. A > small waste of a small resource, is ok if it saves a waste of a more > critical resource--the most critical resource of all being our project > timeliness. ?es, I'm quite familiar with modelling, abstraction, approximation, etc. However nothing about those endevours suggests to me that unsoundness is any kind of goal. > Marshall's last point: > > > I flipped a coin to see who would win the election; it came > > up "Bush". Therefore I *knew* who was going to win the > > election before it happened. See the probem? > > Flipping one coin to determine an election is not playing the > probabilities correctly. You need a plausible explanation for why the > coin should predict the right answer and a track record of it being > correct. If you had a coin that had correctly predicted the previous > 42 presidencies and you had an explanation why the coin was right, > then it would be credible and I would be willing to wager that it > could also predict that the coin could tell us who the 44th president > would be. One flip and no explanation is not sufficient. (And to the > abstract point, to me that is all knowledge is, some convincing amount > of examples and a plausible explanation--anyone who thinks they have > more is appealing to a "knowledge" of the universe that I don't > accept.) I used a coin toss; I could also have used a psycic hotline. There is an explanation for why those things work, but the explanation is unsound. > Look at where that got Russell and Whitehead. Universal acclaim, such that their names will be praised for centuries to come? > I'm just trying to be "honest" about that fact and find ways to > compensate for my own failures. Limitation != failure. Marshal From johnzenger at gmail.com Fri Jun 23 16:07:17 2006 From: johnzenger at gmail.com (johnzenger at gmail.com) Date: 23 Jun 2006 13:07:17 -0700 Subject: hard to explain for a french ;-) References: <007b01c696c9$dc8c1a40$33067a37@d11610100.cpamalencon.cnamts.fr> <5f56302b0606231054u10743a95ke6768492519fa225@mail.gmail.com> Message-ID: <1151093237.406452.298750@r2g2000cwb.googlegroups.com> How about an effort to "compile" Python into JavaScript? Such an effort is underway for Scheme. http://www-sop.inria.fr/mimosa/personnel/Florian.Loitsch/scheme2js/ Tim Chase wrote: > > As explained in this thread > > http://mail.python.org/pipermail/python-list/2006-June/348241.html > > what you try to do will never work because your attempts are > > at using python on the client side and only javascript works > > for that purpose. > > Sounds like an opportunity to write JSPython...written in > JavaScript, akin to CPython (written in C), Jython (written in > Java), and PyPy (written in Python)...for those sick enough to > undertake such a freakish task... :) > > > No...that wouldn't be slow... > > > -tkc From penneys at bigfoot.com Tue Jun 27 03:49:33 2006 From: penneys at bigfoot.com (MrBlueSky) Date: 27 Jun 2006 00:49:33 -0700 Subject: What technologies should I use for my application manager? In-Reply-To: <1151307031.166916.232330@m73g2000cwd.googlegroups.com> References: <1151260635.570013.87210@b68g2000cwa.googlegroups.com> <1151307031.166916.232330@m73g2000cwd.googlegroups.com> Message-ID: <1151394573.819701.242240@c74g2000cwc.googlegroups.com> Thanks for the advice, Adam! Turbogears sounds like it does everything I want and looks like a great... except you've made me nervous with your comment on the instability of the Oracle API! Stability, good documentation and a wide user base are priorities. I was delighted by the quality of Tkinter in this regard. Am I wishing for the moon in hoping for the same quality in the framework I choose for this? Anyone else like to try and sell me on Zope or Django?! From bdesth.quelquechose at free.quelquepart.fr Mon Jun 5 08:30:06 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 05 Jun 2006 14:30:06 +0200 Subject: re beginner In-Reply-To: <4483665A.206@lexicon.net> References: <44834d62$0$6192$626a54ce@news.free.fr> <4483665A.206@lexicon.net> Message-ID: <4483f42e$0$5594$626a54ce@news.free.fr> John Machin a ?crit : > On 5/06/2006 10:38 AM, Bruno Desthuilliers wrote: > >> SuperHik a ?crit : >> >>> hi all, >>> (snip) >>> I have an old(er) script with the >>> following task - takes a string I copy-pasted and wich always has the >>> same format: >>> (snip) >>> >> def to_dict(items): >> items = items.replace('\t', '\n').split('\n') > > > In case there are leading/trailing spaces on the keys: There aren't. Test passes. (snip) > Fantastic -- at least for the OP's carefully copied-and-pasted input. That was the spec, and my code passes the test. > Meanwhile back in the real world, The "real world" is mostly defined by customer's test set (is that the correct translation for "jeu d'essai" ?). Code passes the test. period. > there might be problems with multiple > tabs used for 'prettiness' instead of 1 tab, non-integer values, etc etc. Which means that the spec and the customer's test set is wrong. Not my responsability. Any way, I refuse to change anything in the parsing algorithm before having another test set. > In that case a loop approach that validated as it went and was able to > report the position and contents of any invalid input might be better. One doesn't know what *will* be better without actual facts. You can be right (and, from my experience, you probably are !-), *but* you can be wrong as well. Until you have a correct spec and test data set on which the code fails, writing any other code is a waste of time. Better to work on other parts of the system, and come back on this if and when the need arise. Kind of reminds me of a former employer that paid me 2 full monthes to work on a very hairy data migration script (the original data set was so f... up and incoherent even a human parser could barely make any sens of it), before discovering than none of the users of the old system was interested in migrating that part of the data. Talk about a waste of time and money... Now FWIW, there's actually something else bugging me with this code : it loads the whole data set in memory. It's ok for a few lines, but obviously wrong if one is to parse huge files. *That* would be the first thing I would change - it takes a couple of minutes to do so no real waste of time, but it obviously imply rethinking the API, which is better done yet than when client code will have been written. My 2 cents.... From diffuser78 at gmail.com Thu Jun 15 11:43:36 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 15 Jun 2006 08:43:36 -0700 Subject: GUI in Python using wxGlade References: <1150380251.279150.73620@u72g2000cwu.googlegroups.com> Message-ID: <1150386216.365531.157690@g10g2000cwb.googlegroups.com> I am pasting my code. I created a small little GUI without any functionality as of yet. I wanted to ask few questions on that. [code] #!/usr/bin/env python # -*- coding: UTF-8 -*- # generated by wxGlade 0.4cvs on Thu Jun 15 10:51:12 2006 import wx class MyFrame(wx.Frame): def __init__(self, *args, **kwds): # begin wxGlade: MyFrame.__init__ kwds["style"] = wx.DEFAULT_FRAME_STYLE wx.Frame.__init__(self, *args, **kwds) self.panel_1 = wx.Panel(self, -1) # Menu Bar self.frame_1_menubar = wx.MenuBar() self.SetMenuBar(self.frame_1_menubar) self.File = wx.Menu() self.CreateNewConfigFile = wx.MenuItem(self.File, wx.NewId(), _("Create New Config File"), "", wx.ITEM_NORMAL) self.File.AppendItem(self.CreateNewConfigFile) self.OpenConfigFile = wx.MenuItem(self.File, wx.NewId(), _("Open Config File"), "", wx.ITEM_NORMAL) self.File.AppendItem(self.OpenConfigFile) self.EditConfigFile = wx.MenuItem(self.File, wx.NewId(), _("Edit Config File"), "", wx.ITEM_NORMAL) self.File.AppendItem(self.EditConfigFile) self.Close = wx.MenuItem(self.File, wx.NewId(), _("Close"), "", wx.ITEM_NORMAL) self.File.AppendItem(self.Close) self.Exit = wx.MenuItem(self.File, wx.NewId(), _("Exit"), "", wx.ITEM_NORMAL) self.File.AppendItem(self.Exit) self.frame_1_menubar.Append(self.File, _("File")) self.Action = wx.Menu() self.AddComputer = wx.MenuItem(self.Action, wx.NewId(), _("Add Computer"), "", wx.ITEM_NORMAL) self.Action.AppendItem(self.AddComputer) self.Shutdown = wx.MenuItem(self.Action, wx.NewId(), _("Shutdown..."), "", wx.ITEM_NORMAL) self.Action.AppendItem(self.Shutdown) self.ShutdownAll = wx.MenuItem(self.Action, wx.NewId(), _("Shutdown All"), "", wx.ITEM_NORMAL) self.Action.AppendItem(self.ShutdownAll) self.frame_1_menubar.Append(self.Action, _("Action")) self.Help = wx.Menu() self.Tutorial = wx.MenuItem(self.Help, wx.NewId(), _("Tutorial"), "", wx.ITEM_NORMAL) self.Help.AppendItem(self.Tutorial) self.AboutUs = wx.MenuItem(self.Help, wx.NewId(), _("About us"), "", wx.ITEM_NORMAL) self.Help.AppendItem(self.AboutUs) self.frame_1_menubar.Append(self.Help, _("Help")) # Menu Bar end self.frame_1_statusbar = self.CreateStatusBar(1, 0) self.__set_properties() self.__do_layout() # end wxGlade def __set_properties(self): # begin wxGlade: MyFrame.__set_properties self.SetTitle(_("Test")) self.SetSize((600, 450)) self.frame_1_statusbar.SetStatusWidths([-1]) # statusbar fields frame_1_statusbar_fields = [_("Test Application")] for i in range(len(frame_1_statusbar_fields)): self.frame_1_statusbar.SetStatusText(frame_1_statusbar_fields[i], i) # end wxGlade def __do_layout(self): # begin wxGlade: MyFrame.__do_layout sizer_1 = wx.BoxSizer(wx.VERTICAL) sizer_1.Add(self.panel_1, 1, wx.EXPAND, 0) self.SetAutoLayout(True) self.SetSizer(sizer_1) self.Layout() # end wxGlade # end of class MyFrame class MyApp(wx.App): def OnInit(self): wx.InitAllImageHandlers() frame_1 = MyFrame(None, -1, "") self.SetTopWindow(frame_1) frame_1.Show() return 1 # end of class MyApp if __name__ == "__main__": import gettext gettext.install("app") # replace with the appropriate catalog name app = MyApp(0) app.MainLoop() [/code] If I click on any of the items of the File Menu, say I click on "Open config File", I want a new windows to come up. My questions is when I create a new Frame/Windows in wxGlade, will it be wxFrame or wxMDI Frame......which one should I choose and why ? I am not completely aware of all the small tools that wxGlade gives and how to place them. Any kind of help is greatly appreciated. Thanks > Without having time to go into a full, the way to proceed with Glade > (unless I am mistaken) is to design each window independently of the > others, and to use a button press in one window to create an instance of > another type of window. From python.list at tim.thechases.com Fri Jun 30 09:41:14 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 30 Jun 2006 08:41:14 -0500 Subject: finding the last file created in a directory In-Reply-To: <200606301443.11201.> References: <200606301443.11201.> Message-ID: <44A529FA.9070402@tim.thechases.com> > I have a repeatedly running process, which always creates a > new logfile with an ending n+1. What I need is to find the > last file, the one with highest number at the end. The problem > is, that the max() method gives me a wrong answer. I tried to > convert the items in my list into integers using int(), but > that ends up with an error ValueError: invalid literal for > int(): The int() call should be passed only strings that are numeric...if you've got other bits of your filename in there (such as, in your code, the terminal period), it will likely choke on them with the above-mentioned ValueError. Presuming your filenames are of the form "fileXXXX.log" (adjustable by altering the 'filename' and 'suffix' variables) >>> filename = 'file' >>> suffix = '.log' >>> # create ourselves some sample filenames as one >>> # might get from globbing >>> filenames = ['%s%s%s' % (filename, i, suffix) for i in range(1,30, 7)] >>> filenames ['file1.log', 'file8.log', 'file15.log', 'file22.log', 'file29.log'] >>> # extract the maximum number from the list of file numbers: >>> max_file_number = max([int(s[len(filename):-len(suffix)]) for s in filenames]) >>> max_file_number 29 As you can see, it handles disjoint spans of file numbers, so even if you delete items in the middle, it should still find the max. There is a race condition in this in the event that you have multiple items attempting to write the file-name at hand. Thus, between the time you get the max_file_number+1, and you open the file, some other process might have created a file with that number. Use with caution accordingly. -tkc From duane at franz.com Tue Jun 27 11:53:44 2006 From: duane at franz.com (Duane Rettig) Date: Tue, 27 Jun 2006 08:53:44 -0700 Subject: What is Expressiveness in a Computer Language References: <7zy7vt1mz2.fsf@app-3.diku.dk> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <1151384511.223582.305760@m73g2000cwd.googlegroups.com> Message-ID: Ketil Malde writes: > "Marshall" writes: > >> There are also what I call "packaging" issues, such as >> being able to run partly-wrong programs on purpose so >> that one would have the opportunity to do runtime analysis >> without having to, say, implement parts of some interface >> that one isn't interested in testing yet. These could also >> be solved in a statically typed language. (Although >> historically it hasn't been done that way.) > > I keep hearing this, but I guess I fail to understand it. How > "partly-wrong" do you require the program to be? This conclusion is false. To be "wrong", whether partly or fully, a program needs to specifically not conform to the requirements that the programmer gives it. You are assuming that only a completed program can be right. Let me give a counterexample: Consider this part of a CL program: CL-USER(1): (defun foo (x) (declare (optimize speed (safety 0) (debug 0)) (fixnum x) ) (bar (the fixnum (1+ x)))) FOO CL-USER(2): This is of course not a complete program, because the function BAR is not yet defined. If I try to run it, it will of course get an error. But does that require then that I call this a "partly wrong" program? No, of course not; it is not a program; it is a function, and for my purposes it is completely correct (I've debugged it already :-) So what can we do with an incomplete program? Nothing? Well, no. Of course, we can't run it (or can we?). But even before talking about running the program, we can at least do some reasoning about it: 1. It seems to have some static type declarations (in a dynamic langiuage? oh my :-). 2. The 1+ operation limits the kinds of operations that would be acceptable, even in the absence of static type declarations. 3. The declarations can be ignored by the CL implementation, so #2 might indeed come into play. I ensured that the declarations would be "trusted" in Allegro CL, by declaring high speed and low safety. 4. I can compile this function. Note that I get a warning about the incompleteness of the program: CL-USER(2): (compile 'foo) Warning: While compiling these undefined functions were referenced: BAR. FOO NIL NIL CL-USER(3): 5. I can disassemble the function. Note that it is a complete function, despite the fact that BAR is undefined: CL-USER(3): (disassemble 'foo) ;; disassembly of # ;; formals: X ;; constant vector: 0: BAR ;; code start: #x406f07ec: 0: 83 c0 04 addl eax,$4 3: 8b 5e 12 movl ebx,[esi+18] ; BAR 6: b1 01 movb cl,$1 8: ff e7 jmp *edi CL-USER(4): 6. I can _even_ run the program! Yes, I get an error: CL-USER(4): (foo 10) Error: attempt to call `BAR' which is an undefined function. [condition type: UNDEFINED-FUNCTION] Restart actions (select using :continue): 0: Try calling BAR again. 1: Return a value instead of calling BAR. 2: Try calling a function other than BAR. 3: Setf the symbol-function of BAR and call it again. 4: Return to Top Level (an "abort" restart). 5: Abort entirely from this (lisp) process. [1] CL-USER(5): 7. But note first that I have many options, including retrying the call to BAR. What was this call to BAR? I can reason about that as well, by getting a backtrace: [1] CL-USER(5): :zoom Evaluation stack: (ERROR #) ->(BAR 11) [... EXCL::%EVAL ] (EVAL (FOO 10)) (TPL:TOP-LEVEL-READ-EVAL-PRINT-LOOP) (TPL:START-INTERACTIVE-TOP-LEVEL # # ...) [1] CL-USER(6): 8. If I then define BAR, with or without compiling it, and then take that option to retry the call: [1] CL-USER(6): (defun bar (x) (1- x)) BAR [1] CL-USER(7): :cont 10 CL-USER(8): Hmm, I was able to complete the program dynamically? Who ever heard of doing that? :-) > During development, I frequently sprinkle my (Haskell) program with > 'undefined' and 'error "implement later"' - which then lets me run the > implemented parts until execution hits one of the 'undefined's. Why do it manually? And what do you do when you've hit the undefined? Start the program over? > The "cost" of static typing for running an incomplete program is thus > simply that I have to name entities I refer to. I'd argue that this > is good practice anyway, since it's easy to see what remains to be > done. Good practice, yes, but why not have the language help you to practice it? -- Duane Rettig duane at franz.com Franz Inc. http://www.franz.com/ 555 12th St., Suite 1450 http://www.555citycenter.com/ Oakland, Ca. 94607 Phone: (510) 452-2000; Fax: (510) 452-0182 From sjmachin at lexicon.net Wed Jun 28 20:52:40 2006 From: sjmachin at lexicon.net (John Machin) Date: Thu, 29 Jun 2006 10:52:40 +1000 Subject: locating strings approximately In-Reply-To: <6e8360ad0606281707w10d7f0ch9636c9e80a9cbe3@mail.gmail.com> References: <1151537334.900487.322980@75g2000cwc.googlegroups.com> <44A31824.8000504@lexicon.net> <6e8360ad0606281707w10d7f0ch9636c9e80a9cbe3@mail.gmail.com> Message-ID: <44A32458.5080706@lexicon.net> On 29/06/2006 10:07 AM, BBands wrote: > On 6/28/06, John Machin wrote: >> On 29/06/2006 9:28 AM, BBands wrote: >> > I'd like to see if a string exists, even approximately, in another. For >> > example if "black" exists in "blakbird" or if "beatles" exists in >> > "beatlemania". The application is to look though a long list of songs >> > and return any approximate matches along with a confidence factor. I >> > have looked at edit distance, but that isn't a good choice for finding >> > a short string in a longer one. >> >> There is a trivial difference between the traditional >> distance-matrix-based Levenshtein algorithm for edit distance and the >> corresponding one for approximate string searching. Ditto between >> finite-state-machine approaches. Ditto between modern bit-bashing >> approaches. >> >> > I have also explored >> > difflib.SequenceMatcher and .get_close_matches, but what I'd really >> > like is something like: >> > >> > a = FindApprox("beatles", "beatlemania") >> > print a >> > 0.857 >> > >> > Any ideas? >> >> You got no ideas from googling "approximate string search python"??? > > Yes, many including agrepy and soundex in addition to those I > mentioned already, but none seem really handy at approximately looking > up smaller strings in larger ones. I also note that this has been the > topic of prior discussion without resolutiuon. > > jab It helps if you tell all that you've done. Otherwise people will tell you to do what you've done already :-) It helps if you reply on-list so that others can see. You may get better answers sooner. I have to vanish now. Will check back tonight. Cheers, John agrepy = approximate-grep-python -- why doesn't that suit you? From jo at durchholz.org Thu Jun 22 15:59:21 2006 From: jo at durchholz.org (Joachim Durchholz) Date: Thu, 22 Jun 2006 21:59:21 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <0%Wlg.3521$MF6.947@tornado.socal.rr.com> <44992e6c$0$664$bed64819@news.gradwell.net> Message-ID: Andreas Rossberg schrieb: > Joachim Durchholz wrote: >>> >>>> It's worth noting, too, that (in some sense) the type of an object >>>> can change over time[*]. >>> >>> No. Since a type expresses invariants, this is precisely what may >>> *not* happen. >> >> No. A type is a set of allowable values, allowable operations, and >> constraints on the operations (which are often called "invariants" but >> they are invariant only as long as the type is invariant). > > The purpose of a type system is to derive properties that are known to > hold in advance. That's just one of many possible purposes (a noble one, and the most preeminent one in FPLs I'll agree any day, but it's still *not the definition of a type*). > A type is the encoding of these properties. A type > varying over time is an inherent contradiction (or another abuse of the > term "type"). No. It's just a matter of definition, essentially. E.g. in Smalltalk and Lisp, it does make sense to talk of the "type" of a name or a value, even if that type may change over time. I regard it as a highly dubious practice to have things change their types over their lifetime, but if there are enough other constraints, type constancy may indeed have to take a back seat. Regards, Jo From david at boddie.org.uk Sat Jun 10 17:35:00 2006 From: david at boddie.org.uk (David Boddie) Date: 10 Jun 2006 14:35:00 -0700 Subject: convert .pdf files to .txt files References: <1149945556.411580.143850@j55g2000cwa.googlegroups.com> Message-ID: <1149975300.823378.76780@g10g2000cwb.googlegroups.com> Davor wrote: > Hi, my name is david. > I need to read information from .pdf files and convert to .txt files, > and I have to do this on python, > I have been looking for libraries on python and the pdftools seems to > be the solution, but I do not know how to use them well, > this is the example that I found on the internet is: [...] > for n_page in range (1, (n_pages+1)): > print "Page", n_page > page = doc.read_page (n_page) > contents = page.read_contents ().contents > text.extend (contents_to_text (contents)) > > print "".join (text) > > the problem is that on some pdf?s it generates join words and In > spanish the "acentos" > in words like: "cami?n" goes to --> cami/86n or > "IMPLEMENTACI?N" -----> "IMPLEMENTACI?" give strange > characters pdftools just extracts the textual data in the file and stores it in Text instances - it doesn't try to interpret or decode the text. I'd like to fix the library so that it does try and decode the text properly and put it into unicode strings, but I don't have the time right now. Remember that text can be stored in PDF files in many different ways, and that the text cannot always be extracted in its original form. > if someone knows how to use the pdftools and can help me it makes me > very happy. > > Another thing is that I can see the letters readden from .pdf on the > screen, but I do not know how to create a file and save this > information inside the file a .txt You need to do something like this: f = open("myfilename", "w").write("".join (text)) > Sorry for my english. Don't worry about it. It's much better than my Spanish will ever be. Sorry I couldn't give you more help with this. You may find that the other tools mentioned by people in this thread will do what you need better than pdftools can at the moment. David From laurent.pointal at limsi.fr Fri Jun 2 04:26:28 2006 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Fri, 02 Jun 2006 10:26:28 +0200 Subject: Python for Visual Basic or C# programmers In-Reply-To: References: Message-ID: A.M a ?crit : > Hi, > > > > I am trying to find the equivalent functions such as vb's str or asc in > Python. Is there any resource that help me to find these kinds of functions > in Python faster? I've written the PQRC for that purpose: http://www.limsi.fr/Individu/pointal/python/pqrc/ A+ Laurent. From aleax at mac.com Sat Jun 3 20:07:48 2006 From: aleax at mac.com (Alex Martelli) Date: Sat, 3 Jun 2006 17:07:48 -0700 Subject: Python less error-prone than Java References: <1149378739.429512.26310@f6g2000cwb.googlegroups.com> Message-ID: <1hgd8qo.8h0orqhpo6bcN%aleax@mac.com> Simon Percivall wrote: ... > with static typing. The equivalent in Python would have been if an > overflow exception was raised when the int got too big. It might have > been that way, typing or no typing. Indeed, it _used_ to be that way -- STILL says...: exception OverflowError Raised when the result of an arithmetic operation is too large to be represented. This cannot occur for long integers (which would rather raise MemoryError than give up). Because of the lack of standardization of floating point exception handling in C, most floating point operations also aren't checked. For plain integers, all operations that can overflow are checked except left shift, where typical applications prefer to drop bits than raise an exception. Actually, the docs are obsolete on this point, and an int becomes a long when that's necessary: >>> sys.maxint+1 2147483648L but, this operation _would_ have raised OverflowError in old-enough versions of Python (not sure exactly when the switch happened...). Alex From k.retheesh at gmail.com Thu Jun 8 17:44:36 2006 From: k.retheesh at gmail.com (k.retheesh at gmail.com) Date: 8 Jun 2006 14:44:36 -0700 Subject: ValueError: too many values to unpack Message-ID: <1149803076.552465.137150@j55g2000cwa.googlegroups.com> Hi, I am very new to pyton, during my adventures journey I got the following error message which am not able to solve, can somebody help me. I was trying to format my output in a readable way, Compare results in tblItem ________________________________________________________________________________ 71 records found in pctrsqlstage case9125 71 records found in qa-sql2\pctr case9126 Database counts match: True -------------------------------------------------------------------------------- 71 unique records found in pctrsqlstage case9125 71 unique records found in qa-sql2\pctr case9126 56 records were different Type, FileType, Item, Hash, Path, Size, CullCd, Ext, DtCr, DtLMd, DtLAc Traceback (most recent call last): File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "Q:\PythonScripts\InventoryCompareCase.py", line 234, in ? main() File "Q:\PythonScripts\InventoryCompareCase.py", line 117, in main for (Type,FileType,Item,Hash,Path,Size,CullCd,Ext,DtCr,DtLMd,DtLAc) in infoDiffs : ValueError: too many values to unpack Thanks Retheesh From rogue_pedro at yahoo.com Wed Jun 28 18:37:10 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 28 Jun 2006 15:37:10 -0700 Subject: Module executed twice when imported! References: Message-ID: <1151534230.603274.144810@x69g2000cwx.googlegroups.com> Michael Abbott wrote: > It seems to be an invariant of Python (insofar as Python has invariants) > that a module is executed at most once in a Python session. I have a > rather bizzare example that breaks this invariant: can anyone enlighten > me as to what is going on? > > --- test.py --- > import imptest > execfile('subtest.py', dict(__name__ = 'subtest.py')) > --- imptest.py --- > print 'Imptest imported' > --- subtest.py --- > import imptest > --- > > $ python test.py > Imptest imported > Imptest imported > $ > > Hmm. If the value __name__ is omitted from the dictionary, or if its > value doesn't match at least 'subtest.' then the message is printed only > once (for example, passing dict(__name__='subtest') produces one > "imported" message). > > This happens with both python 2.4 and 2.3. I don't get it. I don't get it either but there may be a clue in the docs for the execfile() function (http://docs.python.org/lib/built-in-funcs.html#l2h-24) "It is different from the import statement in that it does not use the module administration --" I don't know why the globals dict you're passing in would change the behavior though. Hopefully someone else can enlighten us both. Peace, ~Simon From fredrik at pythonware.com Wed Jun 7 12:30:07 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 07 Jun 2006 18:30:07 +0200 Subject: 10GB XML Blows out Memory, Suggestions? In-Reply-To: <1149694031.712812.304940@u72g2000cwu.googlegroups.com> References: <1149594519.098115.8980@u72g2000cwu.googlegroups.com> <4eleh3F1eguosU1@uni-berlin.de> <1149648187.891942.258300@i40g2000cwc.googlegroups.com> <1149694031.712812.304940@u72g2000cwu.googlegroups.com> Message-ID: fuzzylollipop wrote: > dependes on the CODE and the SIZE of the file, in this case > processing 10GB of file, unless that file is heavly encrypted or > compressed will, the process will be IO bound PERIOD! so the fact that for token, node in pulldom.parse(file): pass is 50-200% slower than for event, elem in ET.iterparse(file): if elem.tag == "item": elem.clear() when reading a gigabyte-sized XML file, is due to an unexpected slowdown in the I/O subsystem after importing xml.dom? > I work with TeraBytes of files, and all our Python code is just as fast > as equivelent C code for IO bound processes. so how large are the things that you're actually *processing* in your Python code? megabyte blobs or 100-1000 byte records? or even smaller things? From anton at appsolutions.com Sun Jun 25 14:11:22 2006 From: anton at appsolutions.com (Anton van Straaten) Date: Sun, 25 Jun 2006 18:11:22 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: <1151224844.569347.167420@r2g2000cwb.googlegroups.com> References: <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150904134.520639.71070@b68g2000cwa.googlegroups.com> <1151056505.908723.162580@u72g2000cwu.googlegroups.com> <1151171007.230666.235430@r2g2000cwb.googlegroups.com> <1151224844.569347.167420@r2g2000cwb.googlegroups.com> Message-ID: rossberg at ps.uni-sb.de wrote: >>>In this context, the term "latently-typed language" refers to the >>>language that a programmer experiences, not to the subset of that >>>language which is all that we're typically able to formally define. > > > That language is not a subset, if at all, it's the other way round, but > I'd say they are rather incomparable. That is, they are different > languages. The "subset" characterization is not important for what I'm saying. The fact that they are different languages is what's important. If you agree about that, then you can at least understand which language I'm referring to when I say "latently-typed language". Besides, many dynamically-typed languages have no formal models, in which case the untyped formal model I've referred to is just a speculative construct. The language I'm referring to with "latently-typed language" is the language that programmers are familiar with, and work with. >>That is starting to get a bit too mystical for my tastes. > > > I have to agree. > > \sarcasm One step further, and somebody starts calling C a "latently > memory-safe language", because a real programmer "knows" that his code > is in a safe subset... And where he is wrong, dynamic memory page > protection checks will guide him. That's a pretty apt comparison, and it probably explains how it is that the software we all use, which relies so heavily on C, works as well as it does. But the comparison critiques the practice of operating without static guarantees, it's not a critique of the terminology. Anton From robert.kern at gmail.com Tue Jun 6 11:31:44 2006 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 06 Jun 2006 10:31:44 -0500 Subject: Vectorization In-Reply-To: <0Efhg.18184$0v4.13198@tornado.texas.rr.com> References: <1149595753.611358.189070@i39g2000cwa.googlegroups.com> <0Efhg.18184$0v4.13198@tornado.texas.rr.com> Message-ID: Paul McGuire wrote: > "RonnyM" wrote in message > news:1149595753.611358.189070 at i39g2000cwa.googlegroups.com... > >>Hi! >> >>Need to vectorize this, but do not have a clue. >> >>a = n*m matrix >>x and y are n and m vectors >> >>Suggestions? >> >>def fill(a, x, y): >> for i in range(1,a.shape[0]): >> xp = x[i] >> for j in range(a.shape[1]): >> yp = y[j] >> a[i,j] = sin(xp*yp)*exp(-xp*yp) + a[i-1,j] >> return a >> >>Thanks in advance, >> >>Ronny Mandal > > Something like this, but the first row in a is never modified, is this > correct? > > Note: this is a brute force Python attempt at a matrix, using a list of > lists. Look also at the array and numarray modules. The array module doesn't do matrices, and numarray is deprecated. Please point new users to numpy, instead. http://numeric.scipy.org/ Since the OP seems to already be using one of Numeric/numarray/numpy, (given "a.shape"), I would suggest that he ask the question on the appropriate mailing list: https://lists.sourceforge.net/lists/listinfo/numpy-discussion I won't attempt an answer until the OP answers about the first row. -- 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 From fredrik at pythonware.com Thu Jun 15 08:20:52 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 15 Jun 2006 14:20:52 +0200 Subject: umask option for tarfile extract References: <200606151442.13111.faik@pardus.org.tr> Message-ID: Faik Uygur wrote: > While extracting a tar file, is there a way to give an umask option for > creating the non-existing upper directories of the file within the tar > archive. os.umask From gbsuar at gmail.com Wed Jun 28 21:46:03 2006 From: gbsuar at gmail.com (Gabriel) Date: Wed, 28 Jun 2006 22:46:03 -0300 Subject: Icono en wxpython In-Reply-To: <91906ddf0606281609l17753eaexf12dd3b22433c514@mail.gmail.com> References: <91906ddf0606281609l17753eaexf12dd3b22433c514@mail.gmail.com> Message-ID: <91906ddf0606281846s74f6200cybb8fd292cfdec132@mail.gmail.com> Hola: He echo un programa en wxpython. Se trata de un programa para desarrollos con microcontroladores como PIC's etc. en cuanto a transmisi?n RS232 se refiere. El programa es GNU y quiero publicarlo pronto pero no se como poner el ?cono a la ventana y al archivo en si... ?Alguien puede darme una mano con esto? Otra cosa ?d?nde puedo publicar el programa una vez que este terminado? Desde ya muchas gracias -- Gabriel From grante at visi.com Thu Jun 8 09:19:27 2006 From: grante at visi.com (Grant Edwards) Date: Thu, 08 Jun 2006 13:19:27 -0000 Subject: Select hangs after some reads References: <1149737234.816833.177710@j55g2000cwa.googlegroups.com> <1149764138.868847.326250@i39g2000cwa.googlegroups.com> Message-ID: <128g8uvi6aj4240@corp.supernews.com> On 2006-06-08, alsmeirelles at gmail.com wrote: > Well, actually I?m using a very simple protocol wich sends only > strings ended by newline. I need to send 3 chunks of information and a > newline after them. On the reader side I make 3 readline(), this way I > wouldn?t have to care about this problem, but maybe that?s where I?m > falling. If that?s the case, I?ll have to use a more complex > protocol. You can't use readline() with select(). Select tells you whether recv() called on the underlying socket will block or not. What's probably happening is that all of the data has been read from the underlying socket and is being held in a buffer waiting to be read by readline(). The Select call has no way of knowing about that buffered data. As far as it's concerned there's no more data left to read, so it block until the socket is closed. -- Grant Edwards grante Yow! My mind is a potato at field... visi.com From duane at franz.com Fri Jun 23 18:39:46 2006 From: duane at franz.com (Duane Rettig) Date: Fri, 23 Jun 2006 15:39:46 -0700 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150902275.129780.50260@p79g2000cwp.googlegroups.com> <1150918629.818145.143220@y41g2000cwy.googlegroups.com> <4fv081F1jh4ifU1@individual.net> <1150967543.947096.72840@g10g2000cwb.googlegroups.com> <4fv84rF1kp06kU1@individual.net> <1150988625.527780.148710@c74g2000cwc.googlegroups.com> <4g22l7F1j8p4mU1@individual.net> <1151081129.290382.297530@r2g2000cwb.googlegroups.com> Message-ID: Darren New writes: > Marshall wrote: >> I can't see how you'd call + on a and b if you think they might >> not be numbers. > > Now substitute "<" for "+" and see if you can make the same argument. :-) Sure. Properly extended to handle strings, "abc" < "def" might return true. -- Duane Rettig duane at franz.com Franz Inc. http://www.franz.com/ 555 12th St., Suite 1450 http://www.555citycenter.com/ Oakland, Ca. 94607 Phone: (510) 452-2000; Fax: (510) 452-0182 From johnzenger at gmail.com Fri Jun 16 13:57:01 2006 From: johnzenger at gmail.com (johnzenger at gmail.com) Date: 16 Jun 2006 10:57:01 -0700 Subject: Cross-site scripting (XSS) defense Message-ID: <1150480621.563312.134500@c74g2000cwc.googlegroups.com> Is there a module (or, better yet, sample code) that scrubs user-entered text to remove cross-site scripting attacks, while also allowing a small subset of HTML through? Contemplated application: a message board that allows people to use , , and so on, but does not allow any javascript, vbscript, or other nasties. From max at alcyone.com Wed Jun 7 14:12:14 2006 From: max at alcyone.com (Erik Max Francis) Date: Wed, 07 Jun 2006 11:12:14 -0700 Subject: CENSORSHIP - Django Project (Schema Evolution Support) In-Reply-To: <6asd825u537kpp2aurhaeo1i41f61akbd6@4ax.com> References: <4486B9FB.9030804@lazaridis.com> <4ent10F1f9d3gU1@uni-berlin.de> <6asd825u537kpp2aurhaeo1i41f61akbd6@4ax.com> Message-ID: Rene Pijlman wrote: > Wikipedia always tells the Absolute Truth, because if it doesn't, we can > edit it and fix it right away. Tell that to John Seigenthaler. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Too much agreement kills a chat. -- Eldridge Cleaver From cito at online.de Sat Jun 3 21:49:23 2006 From: cito at online.de (Christoph Zwerschke) Date: Sun, 04 Jun 2006 03:49:23 +0200 Subject: Python less error-prone than Java In-Reply-To: <4nj9l3-hgn.ln1@lairds.us> References: <4nj9l3-hgn.ln1@lairds.us> Message-ID: Cameron Laird wrote: > So, here's my summary: Python's a nice language--a very nice one. > It's safer to use than Java in many ways. Python's typing is > STRICTER than Java's, but it's also dynamic, so people get to argue > for decades about which is a better model. Anyone who thinks typing > is a first-order determinant of code quality is making a big mistake > though, anyway. Yes, sorry. It has nothing to do with strict, but with static typing. And I should not have chosen such a general subject line (I just meant to be funny, but sounded more like a troll). I had just noticed that the direct translation of that Java program to Python would not have that subtle bug and found that this was worth mentioning. -- Christoph From tommy04 at gmail.com Tue Jun 6 22:30:37 2006 From: tommy04 at gmail.com (Tommy B) Date: 6 Jun 2006 19:30:37 -0700 Subject: pysqlite error: Database locked? Message-ID: <1149647436.911324.176630@c74g2000cwc.googlegroups.com> I'm currently working on a casino script for an IRC bot. I was going to make a flat file database, but I decided to make it sqlite after some suggestions. I'm using pysqlite. http://pastebin.com/764315 < Source. The lines that have @@ (pastebin doesn't like me) in front of them are important. ERROR 2006-06-06T22:20:34 Uncaught exception in ['diceroll']. Traceback (most recent call last): File "G:\Python24\Lib\site-packages\supybot\callbacks.py", line 1170, in _call Command self.callCommand(command, irc, msg, *args, **kwargs) File "G:\Python24\Lib\site-packages\supybot\utils\python.py", line 62, in g f(self, *args, **kwargs) File "G:\Python24\Lib\site-packages\supybot\callbacks.py", line 1156, in callCommand method(irc, msg, *args, **kwargs) File "G:\Python24\Lib\site-packages\supybot\commands.py", line 906, in newf f(self, irc, msg, args, *state.args, **state.kwargs) File "G:\Python24\Scripts\plugins\Casino\plugin.py", line 160, in diceroll money_file_update(msg.nick, wager) File "G:\Python24\Scripts\plugins\Casino\plugin.py", line 43, in money_file_update cur2.execute('UPDATE players SET cash = ' + str(newcash) + ' WHERE name = \' ' + user + '\'') OperationalError: database is locked ERROR 2006-06-06T22:20:34 Exception id: 0x486de ' + user + '\'') OperationalError: database is locked ERROR 2006-06-06T22:20:34 Exception id: 0x486de That's the error. From find at my.address.elsewhere Mon Jun 26 11:17:39 2006 From: find at my.address.elsewhere (Matthias Blume) Date: Mon, 26 Jun 2006 10:17:39 -0500 Subject: What is Expressiveness in a Computer Language [off-topic] References: <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150908952.804184.218990@r2g2000cwb.googlegroups.com> <1150991074.705803.211570@m73g2000cwd.googlegroups.com> <1151244628.566060.40500@p79g2000cwp.googlegroups.com> <1151252226.104247.62960@b68g2000cwa.googlegroups.com> <1151257480.183097.165640@b68g2000cwa.googlegroups.com> Message-ID: David Hopwood writes: > Matthias Blume wrote: >> I agree with Bob Harper about safety being language-specific and all >> that. But, with all due respect, I think his characterization of C is >> not accurate. > [...] >> AFAIC, C is C-unsafe by Bob's reasoning. > > Agreed. > >> Of course, C can be made safe quite easily: >> >> Define a state "undefined" that is considered "safe" and add a >> transition to "undefined" wherever necessary. > > I wouldn't say that was "quite easy" at all. > > C99 4 #2: > # If a "shall" or "shall not" requirement that appears outside of a constraint > # is violated, the behavior is undefined. Undefined behavior is otherwise > # indicated in this International Standard by the words "undefined behavior" > # *or by the omission of any explicit definition of behavior*. [...] > > In other words, to fix C to be a safe language (compatible with Standard C89 > or C99), you first have to resolve all the ambiguities in the standard where > the behaviour is *implicitly* undefined. There are a lot of them. Yes, if you want to make the transition system completely explict, it won't be easy. I was thinking of a catch-all rule that says: transition to "undefined" unless specified otherwise. (Note that I am not actually advocating this approach to making a language "safe". For practical purposes, C is unsafe. (And so is C++.)) From Bulkan at gmail.com Tue Jun 27 01:09:57 2006 From: Bulkan at gmail.com (placid) Date: 26 Jun 2006 22:09:57 -0700 Subject: HTTP server In-Reply-To: <1151283779.491178.146890@c74g2000cwc.googlegroups.com> References: <1151134073.393065.187500@c74g2000cwc.googlegroups.com> <1151162732.819264.190560@i40g2000cwc.googlegroups.com> <1151241369.138325.173690@r2g2000cwb.googlegroups.com> <1151253325.924054.95100@c74g2000cwc.googlegroups.com> <1151282086.450972.128790@r2g2000cwb.googlegroups.com> <1151283779.491178.146890@c74g2000cwc.googlegroups.com> Message-ID: <1151384997.776795.134050@c74g2000cwc.googlegroups.com> Simon Forman wrote: > ... > > > > Awesome! Glad to hear it. > > ... > > > > Thanks for the help. I got it to work now. > > > > You're welcome. I'm glad I could help you. :-D > Im having trouble with the following code for handling GET requests from a client to my HTTP server. What i want to do is restrict access only to a folder and contents within this folder. But when trying to open files (text files) i get file not found error from send_head() method of SimpleHTTPServer. The reason behind this is when opening the file the path to the file is only C:\file.txt when it should be C:\folder\file.txt. And when i remove the code that checks if path contains "txt" it works (i can access files without errors). Any help will be greatly appreciated! def list_directory(self, path): """Helper to produce a directory listing (absent index.html). Return value is either a file object, or None (indicating an error). In either case, the headers are sent, making the interface the same as for send_head(). """ f = StringIO() p = self.translate_path(self.path) if p.find("txt") == -1: f.write("httpserver.py: Access Denied" ) f.write("

httpserver.py: Access Denied

" ) else: try: list = os.listdir(path) except os.error: self.send_error(404, "No permission to list directory") return None list.sort(key=lambda a: a.lower()) displaypath = cgi.escape(urllib.unquote(self.path)) f.write("Directory listing for %s\n" % displaypath) f.write("

Directory listing for %s

\n" % displaypath) f.write("
\n
From steve at holdenweb.com Thu Jun 8 11:14:28 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 08 Jun 2006 16:14:28 +0100 Subject: how to switch from os.tmpnam to os.tmpfile In-Reply-To: <1149777877.945829.25390@h76g2000cwa.googlegroups.com> References: <1149773439.534989.54450@i40g2000cwc.googlegroups.com> <1149777877.945829.25390@h76g2000cwa.googlegroups.com> Message-ID: Harold Fellermann wrote: > Maric Michaud wrote: > >>Le Jeudi 08 Juin 2006 15:30, Harold Fellermann a ?crit : >> >>>to os.tmpfile() which is supposed to be safer, but I do not know how to >>>get >>>the path information from the file object returned by tmpfile(). any >>>clues? >> >>There is no path for tmpfile, once it's closed, the file and its content are >>lost. from the doc : >>" The file has no directory entries associated with it and will be >>automatically deleted once there are no file descriptors for the file." >> >>You must maintain a reference to it in your program untill you don't need it >>anymore. > > > I am doing so. But still, I need its path. To give you some context: > I have an app built on Tk that uses gnuplot behind the scenes. > My application creates a temporary file where which gnuplot writes its > results to (using the tkcanvas terminal). Later, I load the contents of > that file into the a tk canvas. I don't care about the temporary file > after my app is closed, so I have its reference all the time. But I > need > its path to tell both gnuplot and tk where to read/write data to/from. > > class PlotWindow(Tk.Canvas) : > def plot(self,commands) : > tmp = os.tmpnam() > gnuplot = subprocess.Popen( > "gnuplot", shell=True, > stdin=subprocess.PIPE, stdout=file(tmp,"w") > ) > stdout,stderr = gnuplot.communicate(""" > set terminal tkcanvas interact > set output "%s" > """ % tmp + commands) > assert not stderr > self.tk.call("source",tmp) > self.tk.call("gnuplot",self._w) > > Of course, I could just use matplotlib or Gnuplot.py but the problem > is not necessary enough to make any refacturing. If there is no way > to use os.tmpfile(), I just go ahead with the security warning. Its > only > a small personal app, anyway. Looks like the only way you could handle this is using inherited file descriptors between processes and have Gnuplot write to its standard output. In other words, build a pipeline like the shell does. Of course this only works if the process that has the handle on the temp file is the same one that starts Gnuplot, but it looks from your code like that's the case. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From pc at p-cos.net Mon Jun 19 14:40:05 2006 From: pc at p-cos.net (Pascal Costanza) Date: Mon, 19 Jun 2006 20:40:05 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <4fo19aF1jsudeU1@individual.net> Message-ID: <4fo9c6F1k7pesU1@individual.net> Chris Smith wrote: > Pascal Costanza wrote: >> Types can be represented at runtime via type tags. You could insist on >> using the term "dynamically tagged languages", but this wouldn't change >> a lot. Exactly _because_ it doesn't make sense in a statically typed >> setting, the term "dynamically typed language" is good enough to >> communicate what we are talking about - i.e. not (static) typing. > > Okay, fair enough. It's certainly possible to use the same sequence of > letters to mean two different things in different contexts. The problem > arises, then, when Torben writes: > > : That's not really the difference between static and dynamic typing. > : Static typing means that there exist a typing at compile-time that > : guarantess against run-time type violations. Dynamic typing means > : that such violations are detected at run-time. > > This is clearly not using the word "type" to mean two different things > in different contexts. Rather, it is speaking under the mistaken > impression that "static typing" and "dynamic typing" are varieties of > some general thing called "typing." In fact, the phrase "dynamically > typed" was invented to do precisely that. My argument is not really > with LISP programmers talking about types, by which they would mean > approximately the same thing Java programmers mean by "class." My point > here concerns the confusion that results from the conception that there > is this binary distinction (or continuum, or any other simple > relationship) between a "statically typed" and a "dynamically typed" > language. There is an overlap in the sense that some static type systems cover only types as sets of values whose correct use could as well be checked dynamically. Yes, it's correct that more advanced static type systems can provide more semantics than that (and vice versa). Pascal -- 3rd European Lisp Workshop July 3 - Nantes, France - co-located with ECOOP 2006 http://lisp-ecoop06.bknr.net/ From find at my.address.elsewhere Tue Jun 20 11:53:19 2006 From: find at my.address.elsewhere (Matthias Blume) Date: Tue, 20 Jun 2006 10:53:19 -0500 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <1150809118.677124.142230@u72g2000cwu.googlegroups.com> <1150815461.210286.53120@r2g2000cwb.googlegroups.com> Message-ID: "Rob Thorpe" writes: > Andreas Rossberg wrote: >> Rob Thorpe wrote: >> >> >> >>>No, that isn't what I said. What I said was: >> >>>"A language is latently typed if a value has a property - called it's >> >>>type - attached to it, and given it's type it can only represent values >> >>>defined by a certain class." >> >> >> >>"it [= a value] [...] can [...] represent values"? >> > >> > ??? >> >> I just quoted, in condensed form, what you said above: namely, that a >> value represents values - which I find a strange and circular definition. > > Yes, but the point is, as the other poster mentioned: values defined by > a class. > For example, in lisp: > "xyz" is a string, #(1 2 3) is an array, '(1 2 3) is a list, 45 is a > fixed-point number. > Each item that can be stored has a type, no item can be stored without > one. The types can be tested. Most dynamic typed languages are like > that. Your "types" are just predicates. > Compare this to an untyped language where types cannot generally be > tested. You mean there are no predicates in untyped languages? >> They all have - the whole purpose of a type system is to ensure that any >> expression of type T always evaluates to a value of type T. > > But it only gaurantees this because the variables themselves have a > type, the values themselves do not. Of course they do. > Most of the time the fact that the > variable they are held in has a type infers that the value does too. > But the value itself has no type, in a C program for example I can take > the value from some variable and recast it in any way I feel and the > language cannot correct any errors I make because their is no > information in the variable to indicate what type it is. Casting in C takes values of one type to values of another type. >> So when you >> look at type systems formally then you certainly have to assign types to >> values, otherwise you couldn't prove any useful property about those >> systems (esp. soundness). > > Yes, but indirectly. No, this is usually done very directly and very explicitly. From bnblazer at gmail.com Thu Jun 22 08:05:41 2006 From: bnblazer at gmail.com (Brian) Date: 22 Jun 2006 05:05:41 -0700 Subject: upgrading python on virtual hosting server Message-ID: <1150977941.571479.257890@g10g2000cwb.googlegroups.com> Hello, I have a dedicated linux server with several virtual domains on it. These domains are chrooted for security. I need to upgrade python and be able to have it available for all accounts. I am also concerned that I may muck up some of the server processes that use python. Can someone tell me: 1) Where should I do the install? 2) How do I make sure that the new version is available to all users? 3) What do I need to do to make sure that current services can use the new version? Thank you, Brian From onurb at xiludom.gro Thu Jun 22 12:41:50 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Thu, 22 Jun 2006 18:41:50 +0200 Subject: VPW: T-Shirt design contest In-Reply-To: References: Message-ID: <449ac850$0$13584$626a54ce@news.free.fr> Brian Quinlan wrote: > Bruno Desthuilliers submitted this really cool rant/essay/something from > Tim Lesher that I hadn't seen before. I think that the original source is: > > http://apipes.blogspot.com/2005/01/choose-python.html > (snip) > I think that it might be a bit long to put on a T-Shirt but it is > definitely cool :-) I do have the (A4 format) printout of the PDF version on the wall, and it would definitively fit the back of a T-shirt !-) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From maric at aristote.info Tue Jun 6 02:28:42 2006 From: maric at aristote.info (Maric Michaud) Date: Tue, 6 Jun 2006 08:28:42 +0200 Subject: Again, Downloading and Displaying an Image from the Internet in Tkinter In-Reply-To: <1149556130.667899.199470@j55g2000cwa.googlegroups.com> References: <1149555597.559051.162590@i39g2000cwa.googlegroups.com> <1149556130.667899.199470@j55g2000cwa.googlegroups.com> Message-ID: <200606060828.43738.maric@aristote.info> Le Mardi 06 Juin 2006 03:08, Dustan a ?crit?: > > I should probably also mention, the only reason I downloaded the image > to a file was because I don't know of any other way to do it. I feel no > need to save the image to my hard drive. using PIL, there is something like this (untested) : (assuming you have put your image data in a file-like object, ie. a StringIO, named self._dled_img) Label(self.frame, image=TkImage(Image.open(self._dled_img))) -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From skip at pobox.com Fri Jun 9 14:59:39 2006 From: skip at pobox.com (skip at pobox.com) Date: Fri, 9 Jun 2006 13:59:39 -0500 Subject: Pychecker In-Reply-To: References: Message-ID: <17545.50459.246874.166801@montanaro.dyndns.org> Rick> I think you're asking a lot from pychecker. Rick> kop = 1 Rick> koi = 2 Rick> if True: Rick> koo = 3 Rick> What would you like pychecker to report? I thing the OP was hoping for a "not used" error, but it can only reasonably do that within a function, which it does do: pyc.py:2: Local variable (kop) not used pyc.py:3: Local variable (koi) not used pyc.py:6: Local variable (koo) not used At the module level it doesn't know that the suspect object isn't accessed from another module. Skip From torbenm at app-3.diku.dk Mon Jun 19 06:03:29 2006 From: torbenm at app-3.diku.dk (=?iso-8859-1?q?Torben_=C6gidius_Mogensen?=) Date: 19 Jun 2006 12:03:29 +0200 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> Message-ID: <7zy7vt1mz2.fsf@app-3.diku.dk> "Rob Thorpe" writes: > Torben ?gidius Mogensen wrote: > > "Rob Thorpe" writes: > > > > > Torben ?gidius Mogensen wrote: > > > > Indeed. So use a language with type inference. > > Well, for most purposes that's the same as dynamic typing since the > compiler doesn't require you to label the type of your variables. That's not really the difference between static and dynamic typing. Static typing means that there exist a typing at compile-time that guarantess against run-time type violations. Dynamic typing means that such violations are detected at run-time. This is orthogonal to strong versus weak typing, which is about whether such violations are detected at all. The archetypal weakly typed language is machine code -- you can happily load a floating point value from memory, add it to a string pointer and jump to the resulting value. ML and Scheme are both strongly typed, but one is statically typed and the other dynamically typed. Anyway, type inference for statically typed langauges don't make them any more dynamically typed. It just moves the burden of assigning the types from the programmer to the compiler. And (for HM type systems) the compiler doesn't "guess" at a type -- it finds the unique most general type from which all other legal types (within the type system) can be found by instantiation. > I > occasionally use CMUCL and SBCL which do type inference, which is > useful at improving generated code quality. It also can warn the > programmer if they if they reuse a variable in a context implying that > it's a different type which is useful. > > I see type inference as an optimization of dynamic typing rather than a > generalization of static typing. But I suppose you can see it that way > around. Some compilers for dynamically typed languages will do a type analysis similar to type inference, but they will happily compile a program even if they can't guarantee static type safety. Such "type inference" can be seen as an optimisation of dynamic typing, as it allows the compiler to omit _some_ of the runtime type checks. I prefer the term "soft typing" for this, though, so as not to confuse with static type inference. Soft typing can give feedback similar to that of type inference in terms of identifying potential problem spots, so in that respect it is similar to static type inference, and you might get similar fast code development. You miss some of the other benefits of static typing, though, such as a richer type system -- soft typing often lacks features like polymorphism (it will find a set of monomorphic instances rather than the most general type) and type classes. Torben From ldo at geek-central.gen.new_zealand Thu Jun 22 04:47:50 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 22 Jun 2006 20:47:50 +1200 Subject: How to generate all permutations of a string? References: Message-ID: In article , "Girish Sahani" wrote: > I want to generate all permutations of a string. def permute(Seq) : """generator which yields successive permutations of the elements of Seq.""" if len(Seq) == 0 : yield () else : for i in range(0, len(Seq)) : for rest in permute(Seq[:i] + Seq[i + 1:]) : yield (Seq[i],) + rest #end for #end for #end if #end permute From cdsmith at twu.net Mon Jun 19 23:26:54 2006 From: cdsmith at twu.net (Chris Smith) Date: Mon, 19 Jun 2006 21:26:54 -0600 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> Message-ID: Joe Marshall wrote: > They *do* have a related meaning. Consider this code fragment: > (car "a string") My feeling is that this code is obviously wrong. It is so obviously wrong, in fact, that the majority of automated error detection systems, if written for Lisp, would probably manage to identify it as wrong at some point. This includes the Lisp runtime. So far, I haven't mentioned types. > A string is *not* a valid argument to CAR. Ask anyone why and > they will tell you `It's the wrong type.' Indeed, they will. We're assuming, of course that they know a little Lisp... otherwise, it may be entirely reasonable for someone to expect that (car "a string") is 'a' and (cdr "a string") is " string"... but I'll ignore that, even though I haven't yet convinced myself that it's not relevant to why this is colloquially considered a type error. I believe that in this sense, the 'anyone' actually means "type" in the sense that you mean "type". The fact that a static type system detects this error is somewhat coincidental (except for the fact that, again, any general error-detection scheme worth its salt probably detects this error), and orthogonal to whether it is considered a type error by our hypothetical 'anyone'. > Both `static typing' and `dynamic typing' (in the colloquial sense) are > strategies to detect this sort of error. I will repeat that static typing is a strategy for detecting errors in general, on the basis of tractable syntactic methods. There are some types of errors that are easier to detect in such a system than others... but several examples have been given of problems solved by static type systems that are not of the colloquial "It's the wrong type" variety that you mention here. The examples so far have included detecting division by zero, or array bounds checking. Other type systems can check dimensionality (correct units). Another particularly interesting example may be the following from Ocaml: let my_sqrt x = if x < 0.0 then None else Some(sqrt(x));; Then, if I attempt to use my_sqrt in a context that requires a float, the compiler will complain about a type violation, since the type of the expression is "float option". So this is a type error *in Ocaml*, but it's not the kind of thing that gets intuitively classified as a type error. In fact, it's roughly equivalent to a NullPointerException at runtime in Java, and few Java programmers would consider a NullPointerException to be somehow "actually a type error" that the compiler just doesn't catch. In this case, when the error appears in Ocaml, it appears to be "obviously" a type error, but that's only because the type system was designed to catch some class of program errors, of which this is a member. > It's hardly mythical. (car "a string") is obviously an error and you > don't need a static type system to know that. Sure. The question is whether it means much to say that it's a "type error". So far, I'd agree with either of two statements, depending on the usage of the word "type": a) Yes, it means something, but Torben's definition of a static type system was wrong, because static type systems are not specifically looking for type errors. or b) No, "type error" just means "error that can be caught by the type system", so it is circular and meaningless to use the phrase in defining a kind of type system. > I mean that this has been argued time and time again in comp.lang.lisp > and probably the other groups as well. My apologies, then. It has not been discussed so often in any newsgroup that I followed up until now, though Marshall has now convinced me to read comp.lang.functional, so I might see these endless discussions from now on. > In fact, we become rather confused when you say `a > correctly typed program cannot go wrong at runtime' because we've seen > plenty of runtime errors from code that is `correctly typed'. Actually, I become a little confused by that as well. I suppose it would be true of a "perfect" static type system, but I haven't seen one of those yet. (Someone did email me earlier today to point out that the type system of a specification language called LOTOS supposedly is perfect in that sense, that every correctly typed program is also correct, but I've yet to verify this for myself. It seems rather difficult to believe.) Unless I suddenly have some kind of realization in the future about the feasibility of a perfect type system, I probably won't make that statement that you say confuses you. > > An attempt to generalize the definition of "type" from programming > > language type theory to eliminate the requirement that they are > > syntactic in nature yields something meaningless. Any concept of > > "type" that is not syntactic is a completely different thing from > > static types. > > Agreed. That is why there is the qualifier `dynamic'. This indicates > that it is a completely different thing from static types. If we agree about this, then there is no need to continue this discussion. I'm not sure we do agree, though, because I doubt we'd be right here in this conversation if we did. This aspect of being a "completely different thing" is why I objected to Torben's statement of the form: static type systems detect type violations at compile time, whereas dynamic type systems detect type violations at runtime. The problem with that statement is that "type violations" means different things in the first and second half, and that's obscured by the form of the statement. It would perhaps be clearer to say something like: Static type systems detect some bugs at compile time, whereas dynamic type systems detect type violations at runtime. Here's one interesting consequence of the change. It is easy to recognize that static and dynamic type systems are largely orthogonal to each other in the sense above. Java, for example (since that's one of the newsgroups on the distribution list for this thread), restricting the field of view to reference types for simplicity's sake, clearly has both a very well-developed static type system, and a somewhat well- developed dynamic type system. There are dynamic "type" errors that pass the compiler and are caught by the runtime; and there are errors that are caught by the static type system. There is indeed considerable overlap involved, but nevertheless, neither is made redundant. In fact, one way of understanding the headaches of Java 1.5 generics is to note that the two different meanings of "type errors" are no longer in agreement with each other! > We're all rubes here, so don't try to educate us with your > high-falutin' technical terms. That's not my intention. -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation From bijsterblokit at hccnet.nl Mon Jun 12 08:34:14 2006 From: bijsterblokit at hccnet.nl (Jan Bijsterbosch) Date: Mon, 12 Jun 2006 14:34:14 +0200 Subject: Very nice python IDE (windows only) References: <1149694235.741274.325200@u72g2000cwu.googlegroups.com> <1149701880.540109.10100@y43g2000cwc.googlegroups.com> <1149704292.676501.138530@h76g2000cwa.googlegroups.com> Message-ID: <448d5f3d$0$815$3a628fcd@textreader.nntp.hccnet.nl> Hello ago, Bernard, "ago" schreef in bericht news:1149704292.676501.138530 at h76g2000cwa.googlegroups.com... > > Bernard Lebel wrote: >> Not me. I'll probably sound pedantic but >> - the editor text looks awful, changing the editor options had no effect >> at all >> - there is no network access of UNC paths other than through File > >> Open and Python Paths..... all of my code is on a network location >> - expanding and collapsing directories is done with a transition >> effect.... that drives me nuts > > You can certainly change the font of the editor (Tools>Options>Editor > Options>Display>Editor Font>Font), not to be confused with the font of > the Gutter which only changes the font inside the left bar (i.e. for > line numbers). Admittedly there are not too many fonts to choose from. Furthermore the full source of the editor is available in the Delphi python VCL components package as an example from the same site. If you're a happy owner of Delphi, you just can change everything to your liking and recompile...;-)) Greetings from sunny Amsterdam, Jan From luismgz at gmail.com Thu Jun 29 20:31:02 2006 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 29 Jun 2006 17:31:02 -0700 Subject: Reddit broke - should have remained on Lisp? In-Reply-To: <1151626961.232761.255550@d56g2000cwd.googlegroups.com> References: <1151626961.232761.255550@d56g2000cwd.googlegroups.com> Message-ID: <1151627462.297352.205150@i40g2000cwc.googlegroups.com> Alok wrote: > While posting a comment on http://www.reddit.com I got an error page > with the following curious statement on it. > > "reddit broke (sorry)" > "looks like we shouldn't have stopped using lisp..." > > See screenshot at > http://photos1.blogger.com/blogger/1773/1980/1600/reddit-broke.jpg > > Whether they truly repent not using lisp or otherwise, their site > appears to be 3 times slower ... > > Alok I don't know if this is true or not, but blaming a language for a poor development is a little bit ridiculous... From nmm1 at cus.cam.ac.uk Thu Jun 15 10:16:47 2006 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 15 Jun 2006 14:16:47 GMT Subject: Numerics, NaNs, IEEE 754 and C99 References: <12904mjhl493t49@corp.supernews.com> <1290aik50hmk94a@corp.supernews.com> <4490329e$0$12356$636a55ce@news.free.fr> <12917f6jp7u90f8@corp.supernews.com> <44912058$0$29674$636a55ce@news.free.fr> <1292p7s46ef5off@corp.supernews.com> Message-ID: In article <1292p7s46ef5off at corp.supernews.com>, Grant Edwards writes: |> On 2006-06-15, Nick Maclaren wrote: |> |> > Hence, the SAFE approach is to make the inverse of all zeros a |> > NaN. |> |> OK. You're right. I'm wrong about what my Python programs |> should do. |> |> In any case, that ship sailed. And sank, spawning a zillion lifeboats heading in different directions :-) |> Maybe you can argue convincingly that theoretically your |> approach is better than IEEE 754. You're not going to get the |> standard changed. You're not going to get all of the computers |> on the planet re-worked. Making Python incompatible with IEEE |> 754 is a bad idea. No, that is wrong, on many counts. Firstly, a FAR more common assumption is that integers wrap in twos' complement - Python does not do that. Secondly, it is NOT incompatible with IEEE 754, which is a pure hardware standard. All it does is to trap the exception and take appropriate action (as permitted by that standard). Thirdly, virtually no hardware sticks strictly to IEEE 754, and no language that I know of has EVER attempted to make it the strict basis for its arithmetic model. Fourthly, I am not proposing to change any hardware, and could even provide a Python option to deliver mathematically incorrect results when you want them. Regards, Nick Maclaren. From Dennis.Benzinger at gmx.net Thu Jun 29 15:19:30 2006 From: Dennis.Benzinger at gmx.net (Dennis Benzinger) Date: Thu, 29 Jun 2006 21:19:30 +0200 Subject: Problem with sets and Unicode strings In-Reply-To: References: <44a17d05$1@news.uni-ulm.de> <44a19d55$2@news.uni-ulm.de> <44a2b2cc$2@news.uni-ulm.de> <4gfr58F1mijo5U2@uni-berlin.de> <44a41e06$1@news.uni-ulm.de> Message-ID: <44a427c0$1@news.uni-ulm.de> Robert Kern wrote: > Dennis Benzinger wrote: >> Ok, I understand. >> But isn't it a (minor) problem that using a set like this: >> >> # -*- coding: UTF-8 -*- >> >> FIELDS_SET = set(("F?cher", )) >> >> print u"F?cher" in FIELDS_SET >> print u"F?cher" == "F?cher" >> >> shadows the error of not setting sys.defaultencoding()? > > You can't set the default encoding. If you could, then scripts that run > on your machine wouldn't run on mine. > [...] As Serge Orlov wrote in one of his posts you _can_ set the default encoding (at least in site.py). See Bye, Dennis From sonja.coussell at gmail.com Thu Jun 15 12:42:30 2006 From: sonja.coussell at gmail.com (sonjaa) Date: 15 Jun 2006 09:42:30 -0700 Subject: memory leak problem with arrays In-Reply-To: References: <1150317325.614389.14770@i40g2000cwc.googlegroups.com> <1150349112.780025.289480@i40g2000cwc.googlegroups.com> Message-ID: <1150389750.360090.123430@c74g2000cwc.googlegroups.com> Fredrik Lundh wrote: > wrote: > > After doing this I see that iterative counters used to collect occurrences > > and nested loop counters (ii & jj) as seen in the code example below > > are the culprits with the worst ones over 1M: > > > > for ii in xrange(0,40): > > for jj in xrange(0,20): > > try: > > nc = y[a+ii,b+jj] > > except IndexError: nc = 0 > > > > if nc == "1" or nc == "5": > > news = news +1 > > if news == 100: > > break > > else: > > pass > > y[a+ii,b+jj] = 4 > > else: > > pass > > what's "y" in this example ? > > "y" is a 500x500 array. From john.hsu at sovereign.co.nz Thu Jun 15 02:13:59 2006 From: john.hsu at sovereign.co.nz (JH) Date: 14 Jun 2006 23:13:59 -0700 Subject: Regular Expression pattern group Message-ID: <1150352039.497654.256490@r2g2000cwb.googlegroups.com> Hi I am a fussy learner. Could someone explain to me why the following inconsistency exists between methods? How can it be justified if it is considered all right? There are three groups in pattern. However, match object shows 3 groups in collection, but group has to be indexed from one because the m.group(0) is the implicit group for whole pattern. Are these just some things to remember? "Group counting is from one". >>> p = sre.compile('abc(.(.).)d(ef)') >>> s 'xxxabc???defxxx' >>> m = p.search(s) >>> m.groups() ('???', '?', 'ef') >>> m.group(0) 'abc???def' >>> m.group(1) '???' >>> m.group(2) '?' >>> m.group(3) 'ef' >>> m.group(4) Traceback (most recent call last): File "", line 1, in -toplevel- m.group(4) IndexError: no such group >>> p.findall(s) [('???', '?', 'ef')] >>> From gry at ll.mit.edu Mon Jun 19 14:56:14 2006 From: gry at ll.mit.edu (gry at ll.mit.edu) Date: 19 Jun 2006 11:56:14 -0700 Subject: Seeking regex optimizer In-Reply-To: <1150650439.651839.38180@y41g2000cwy.googlegroups.com> References: <1150650439.651839.38180@y41g2000cwy.googlegroups.com> Message-ID: <1150743374.422647.39850@f6g2000cwb.googlegroups.com> Kay Schluehr wrote: > I have a list of strings ls = [s_1,s_2,...,s_n] and want to create a > regular expression sx from it, such that sx.match(s) yields a SRE_Match > object when s starts with an s_i for one i in [0,...,n]. There might > be relations between those strings: s_k.startswith(s_1) -> True or > s_k.endswith(s_1) -> True. An extreme case would be ls = ['a', 'aa', > ...,'aaaa...ab']. For this reason SRE_Match should provide the longest > possible match. In a very similar case I used a simple tree of dictionaries, one node per letter, to represent the strings. This naturally collapses cases like ['a','aa','aaa']. Then a recursive function finds the desired prefix. This was WAY faster than the "re" module for large n (tradeoff point for me was n~1000). It requires a bit more coding, but I think it is the natural data structure for this problem. As others have suggested, you should first try the most naive implementation before making a hard optimization problem out of this. > Is there a Python module able to create an optimized regex rx from ls > for the given constraints? > > Regards, > Kay From fredrik at pythonware.com Tue Jun 6 10:01:35 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 06 Jun 2006 16:01:35 +0200 Subject: Again, Downloading and Displaying an Image from the Internet in Tkinter In-Reply-To: <1149601541.489425.248880@y43g2000cwc.googlegroups.com> References: <1149555597.559051.162590@i39g2000cwa.googlegroups.com> <1149556130.667899.199470@j55g2000cwa.googlegroups.com> <1149563528.127044.32210@y43g2000cwc.googlegroups.com> <1149601541.489425.248880@y43g2000cwc.googlegroups.com> Message-ID: Dustan wrote: > Ok, that worked (was it plain w or the writelines/readlines that messed > it up?). the plain "w"; very few image files are text files. > But Tkinter still can't find the image. I'm getting an error > message: > > TclError: image "C:\Documents and [pathname snipped]" doesn't exist > > If it makes a difference, I'm on a Windows XP machine, and don't have > to go cross-platform. the "image" option takes a PhotoImage object, not a file name: http://effbot.org/tkinterbook/photoimage.htm note that the built-in PhotoImage type only supports a few image formats; to get support for e.g. PNG and JPEG, you can use PIL which ships with it's own PhotoImage replacement: http://effbot.org/imagingbook/imagetk.htm From cjbottaro at alumni.cs.utexas.edu Mon Jun 26 17:32:53 2006 From: cjbottaro at alumni.cs.utexas.edu (Christopher J. Bottaro) Date: Mon, 26 Jun 2006 16:32:53 -0500 Subject: getting POST vars from BaseHTTPRequestHandler Message-ID: Hi, I can't for the life of me figure out how to get the post vars when using basehttpserver. Here's my code: class MyHandler(BaseHTTPRequestHandler): def do_POST(self): print self.path, self.command if self.rfile: print self.rfile.read() else: print 'no data' server = HTTPServer(('', 80), MyHandler) server.serve_forever() When I make a post, it just hangs (in self.rfile.read()). Thanks for the help. From runlevelten at gmail.com Mon Jun 19 12:53:14 2006 From: runlevelten at gmail.com (Ten) Date: Mon, 19 Jun 2006 17:53:14 +0100 Subject: Getting output from external programs... In-Reply-To: References: <4495B759.4040002@gmail.com> Message-ID: <200606191753.14544.runlevelten@gmail.com> On Monday 19 June 2006 03:44, Cameron Laird wrote: > In article , > Ten wrote: > > >You can do this in various ways, ranging from the very simple and not very > > good > > > >from commands import getoutput > > > >x=getoutput(command) > > > > > >- to your more common and better popens. > > > >ie: > > > >import popen2 > > > >(stdOut, stdIn) = popen2.popen4(command) > > > >x=stdOut.readlines() > > > >- asynchronously if appropriate. > > > >How are you running the command at the moment? > > . > . > . > Why deprecate commands.getoutput()? Are you merely > observing that it's applicable in fewer circumstances? Absolutely so. Commands.getoutput is simple, quick and useful, just less versatile. Maybe "not very good" is a pretty vague, almost emotive-sounding way of putting it. My bad. :-) Cheers, Ten -- There are 10 types of people in this world, those who understand binary, and those who don't. From mikem76 at gmail.com Wed Jun 7 18:05:34 2006 From: mikem76 at gmail.com (mikem76 at gmail.com) Date: 7 Jun 2006 15:05:34 -0700 Subject: How do I get the process id when starting a process using os.popen2 or os.popen3 on linux? Message-ID: <1149717934.308699.166930@i39g2000cwa.googlegroups.com> Is there a way to get the process id when starting a process using os.popen2 or os.popen3 on linux? Mike From rpdooling at gmail.com Tue Jun 20 23:10:19 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 20 Jun 2006 20:10:19 -0700 Subject: Python is fun (useless social thread) ;-) In-Reply-To: <4492c1c6$0$11008$626a54ce@news.free.fr> References: <1150381872.958342.180420@p79g2000cwp.googlegroups.com> <44917776$1@nntp0.pdx.net> <4492c1c6$0$11008$626a54ce@news.free.fr> Message-ID: <1150859419.772118.140080@p79g2000cwp.googlegroups.com> >>> You know what are dicts, right ? That is, containers with >>> keyword-access to values ? Then you probably have dicts >>> with a known, defined structure, and functions working on >>> it. What classes (and hence 00) gives you is a way to >>> associate these functions with the dicts themselves. That >>> is the big intuition about objects, the rest is just >>> details. You bet. I have lots of these. Especially a large dictionary that is kind of an application and site launcher. I type "l clp" at the command line, and l.py runs a function def launch(obj), which grabs the key "clp" whose value is this site address, and I'm browsing clp. Kind of like favorites with no mouse. Or another dictionary with applications. Same way. They work fine. I guess they aren't complex enough to require classes yet? I appreciate the tips. I'll do a couple tutorials and read my books and then come back with any OO questions. Thanks Bruno and Luis. rd From fredrik at pythonware.com Wed Jun 28 12:14:34 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 28 Jun 2006 18:14:34 +0200 Subject: Immutability References: <4Qj*cEjkr@news.chiark.greenend.org.uk> <44a2a956$0$29814$626a54ce@news.free.fr> Message-ID: Bruno Desthuilliers wrote: >> class fred : >> @property >> def joe (self) : >> print "Inside /joe\n" > > > properties dont work properly on old-style classes (lookup 'new-style > classes' on python.org, in the documentation menu), hence the strange > behaviour you observe. property getters work just fine on old-style classes (setters and deleters don't work, but that's not what he's using). From simon at xiano.co.uk Wed Jun 28 09:46:54 2006 From: simon at xiano.co.uk (Bowen) Date: 28 Jun 2006 06:46:54 -0700 Subject: MySQLdb not updating rows In-Reply-To: References: <1151500514.817456.65510@d56g2000cwd.googlegroups.com> Message-ID: <1151502414.717043.234520@d56g2000cwd.googlegroups.com> Thanks for that, it appears it was the db.commit() that sorted it out.....lesson learnt :) From marshall.spight at gmail.com Fri Jun 23 12:28:42 2006 From: marshall.spight at gmail.com (Marshall) Date: 23 Jun 2006 09:28:42 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: <1151053730.887911.256200@u72g2000cwu.googlegroups.com> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150908952.804184.218990@r2g2000cwb.googlegroups.com> <1150991074.705803.211570@m73g2000cwd.googlegroups.com> <1151053730.887911.256200@u72g2000cwu.googlegroups.com> Message-ID: <1151080122.252066.106740@i40g2000cwc.googlegroups.com> Rob Thorpe wrote: > David Hopwood wrote: > > The term "dynamically typed" is well used and understood. The term > untyped is generally associated with languages that as you put it "have > no memory safety", it is a pejorative term. "Latently typed" is not > well used unfortunately, but more descriptive. > > Most of the arguments above describe a static type system then follow > by saying that this is what "type system" should mean, and finishing by > saying everything else should be considered untyped. This seems to me > to be an effort to associate dynamically typed languages with this > perjorative term. I can believe that someone, somewhere out there might have done this, but I can't recall ever having seen it. In any event, the standard term for memory safety is "safety", not "untyped." Further, anyone who was interested in actually understanding the issues woudn't be doing what you describe. And if you did find someone who was actively doing this I would say "never attribute to malice what can adequately be explained by stupidity." Marshall From fredrik at pythonware.com Wed Jun 7 06:39:24 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 07 Jun 2006 12:39:24 +0200 Subject: Bug in list comprehensions? In-Reply-To: <1149675723.118917.276940@j55g2000cwa.googlegroups.com> References: <1149675723.118917.276940@j55g2000cwa.googlegroups.com> Message-ID: Iain King wrote: > I'm guessing I'm the one confused here... but I'm confused! What's > going on? reading the documentation may help: /.../ the elements of the new list are those that would be produced by considering each of the for or if clauses a block, nesting from left to right, and evaluating the expression to produce a list element each time the innermost block is reached. the clauses nest from left to right, not from right to left, so "[x for x in y for y in beta]" is equivalent to out = [] for x in y: for y in beta: out.append(x) From 3dbernard at gmail.com Mon Jun 5 16:09:00 2006 From: 3dbernard at gmail.com (Bernard Lebel) Date: Mon, 5 Jun 2006 16:09:00 -0400 Subject: GUI Program Error In-Reply-To: <920hg.2238$No6.47697@news.tufts.edu> References: <1149536396.375285.319390@y43g2000cwc.googlegroups.com> <920hg.2238$No6.47697@news.tufts.edu> Message-ID: <61d0e2b40606051309p56539c33q87591336ce3fd9f0@mail.gmail.com> On 6/5/06, John Salerno wrote: > What is dir(), btw? Is it a class for creating the application? [Bernard] In your Python documentation, dir() is described in the built-in functions (section 2.1) as well as the tutorial, in the "Modules" section (chapter 6). Unless you were being sarcastic? ;-) Bernard From claudio.grondi at freenet.de Tue Jun 27 08:17:03 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Tue, 27 Jun 2006 14:17:03 +0200 Subject: How do you use this list ? In-Reply-To: References: Message-ID: Bo Yang wrote: > Hi everyone , > I have join this list for about 4 months , and everyday I receive > hundreds of > mails . There is no means to read all of them , so I just read something > interesting > for me . But if so , there are too much mails pile up in my inbox , I > want to ask > how do you use this list , reading every mail come in or just read what > you think > interesting ? > > Thank you ! > > > Best Regard ! I am using a newsreader capable of showing posting in their threads in a hierarchical view. I read entire messages only if I mean the topic is of interest to me, if I have spotted something interesting in the first lines of a posting or if I mean, that I can immediately help writing a reply without much efforts on my side what is the case when the answer pops up in my mind already as I see the question. It was the topic "How do you use this list?" what attracted my attention so I looked into the content of your posting and decided to reply. My advice: download e.g. Thunderbird and use it as a newsreader instead of getting through not by thread and date structured piles of emails. I actually go through each single posting spending at least a second on each (sometimes a bit faster, sometimes much slower). This gives an effort of about 10 minutes of very concentrated work towards selection of interesting postings for detailed reading on a day with a huge traffic of around 600 new postings. Over years of reading I improved much the speed of perception at first glance if a posting or a thread is in my eyes worth to read it in detail. As I also in between know who writes here the best quality replies I usually read carefully all the details in postings of such authors skipping from reading another postings in same thread. Hope this helps. Claudio From 4daniel at gmail.com Thu Jun 29 21:21:51 2006 From: 4daniel at gmail.com (Daniel) Date: 29 Jun 2006 18:21:51 -0700 Subject: decimal by default In-Reply-To: <1hhnr9n.74ctg51k4vtc0N%aleax@mac.com> References: <1151547269.842597.319600@y41g2000cwy.googlegroups.com> <1hhnr9n.74ctg51k4vtc0N%aleax@mac.com> Message-ID: <1151630511.634906.3940@p79g2000cwp.googlegroups.com> Alex Martelli wrote: > What about: > > c = compile(thestring, thestring, '') > > cc = new.code( ...all args from c's attributes, except the 5th > one, constants, which should instead be: > decimalize(c.co_consts)...) Wow, what an elegant solution! I had no hope that it would be this simple. I always wondered what compile() was useful for and now I know at least one thing. I'll try it out tomorrow. Thanks a lot Alex! ~ Daniel From steve at holdenweb.com Tue Jun 27 12:32:06 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 27 Jun 2006 17:32:06 +0100 Subject: [W2k, wxPython 2.6.1.0] - MDISashDemo bug? In-Reply-To: References: Message-ID: <44A15D86.20209@holdenweb.com> w.p. wrote: > w.p. wrote: > >>When i run MDISashDemo and maximize main frame, minimize and maximize >>again - LayoutMDIFrame in OnSize dont work more... >>Why? >> >>I need this feature for main MDI frame with toolbar and statusbar with >>panels&sizers&bitmapbuttons :) >> >>Windows 2000, wxPython 2.6.1.0 >> >>w.p. >> > > When i add this code: > > self.Bind(wx.EVT_ACTIVATE, self.OnActivate) > > and > > def OnActivate(self, event): > if event.GetActive(): > wx.LayoutAlgorithm().LayoutMDIFrame(self) > > all is ok. > > Small improvement in demo :) > Well done! Do you know how to feed this information on to the developers (probably Robin Dunn)? All such changes are valuable. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From grante at visi.com Tue Jun 6 11:38:56 2006 From: grante at visi.com (Grant Edwards) Date: Tue, 06 Jun 2006 15:38:56 -0000 Subject: what are you using python language for? References: Message-ID: <128b8cg1d0p7uce@corp.supernews.com> At the moment, I'm using it for 1) Enginerring/scientific data analysis and visualization. 2) Serial communication test programs. 3) Small utilities for embedded software development (processing map and hex files). 4) Miscellaneous other stuff like grabbing all of the comic strips I like every day and putting them on a local web page so I can read them all in one place, deleting all of the virus-laden e-mails that Postini catches, etc. -- Grant Edwards grante Yow! Is this BOISE?? at visi.com From jbellis at gmail.com Mon Jun 12 23:05:23 2006 From: jbellis at gmail.com (Jonathan Ellis) Date: 12 Jun 2006 20:05:23 -0700 Subject: Very nice python IDE (windows only) In-Reply-To: <1149694235.741274.325200@u72g2000cwu.googlegroups.com> References: <1149694235.741274.325200@u72g2000cwu.googlegroups.com> Message-ID: <1150167923.112598.194230@u72g2000cwu.googlegroups.com> ago wrote: > I have just discovered Python Scripter by Kiriakos Vlahos and it was a > pleasant surprise. I thought that it deserved to be signalled. It is > slim and fairly fast, with embedded graphical debugger, class browser, > file browser... If you are into graphical IDEs you are probably going > to enjoy it. Windows only unfortunately. > > http://mmm-experts.com/Products.aspx?ProductId=4 Not to rain on anyone's parade, but I'd recommend using an IDE that isn't based on an obviously dead-end platform. (PyScripter is written in Delphi.) -Jonathan From rpdooling at gmail.com Sat Jun 17 21:42:04 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 17 Jun 2006 18:42:04 -0700 Subject: python texts? References: <4493cb7c$1@nntp0.pdx.net> Message-ID: <1150594924.379710.220840@g10g2000cwb.googlegroups.com> >> I'd say P.E.R. is terser, going for >> density and brevity, while the Nutshell is a bit more elaborative >> on what it covers. The choice between Martelli and Beazley is, I >> suspect, one of your learning style. Yes, sometimes Beazley is too terse if you're reading about something for the first time. But he's the best when you need to freshen your knowledge on a module or function you used three months ago. When in doubt, get both Beazley & Martelli. And follow with the Cookbook. Note the Martelli Nutshell is coming out in a new edition in early July. You can preorder. http://tinyurl.com/pkczm rd From Serge.Orlov at gmail.com Tue Jun 13 15:04:09 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 13 Jun 2006 12:04:09 -0700 Subject: embedded python and windows multi threading, can't get it to work References: <1150222300.661239.5870@u72g2000cwu.googlegroups.com> Message-ID: <1150225449.316019.173070@f6g2000cwb.googlegroups.com> freesteel wrote: > I am trying to run a python programme embedded from C++. I want to run > the same python code concurrently in several threads. I read the manual > on embedding, especially chapter 8, and searched for relevant info on > google all afternoon, but I can't get this to work. What am I doing > wrong? I use python2.4 and vc++7 (.net). The first thread seems to work > okay, the 2nd thread crashes, but the exception information is not very > useful: > (An unhandled exception of type 'System.NullReferenceException' > occurred in pyembed_test.exe Running one iterpreter in more than one thread is not supported. You need to create one interpreter per thread using Py_NewInterpreter (don't forget to read "Bugs and caveats" paragraph). I hope you also realize the interpreters won't share objects. From cito at online.de Sun Jun 4 05:12:09 2006 From: cito at online.de (Christoph Zwerschke) Date: Sun, 04 Jun 2006 11:12:09 +0200 Subject: Python less error-prone than Java In-Reply-To: References: <1149378739.429512.26310@f6g2000cwb.googlegroups.com> Message-ID: >> Simon Percivall wrote: >>> First: It's perfectly simple in Java to create a binary sort that >>> sorts all arrays that contain objects; so wrong there. >> My point was that the *same* Java source example, directly converted to >> Python would *automatically* accept all kinds of arrays. > > And the same code converted to SML would automatically work on all > kinds of arrays and SML is statically typed. It's a language issue, > not a typing issue. Ok, here the point was that Java has *explicit* static typing. SML is not a procedural language and uses *implicit* static typing. Therefore it shares some of the benefits of dynamically typed languages such as Python. However, an SML version of the program would probably still have the same bug as the Java version, right? >> No need to make any extra efforts. >> By the way, how would you do it in Java? With >> function overloading? I would not call that perfectly simple. > > Since Java doesn't allow function overloading that clearly can't be > the way. J2SE 5.0 allows generic classes and functions that operate > on generic containers. There are some gotchas, but it's not drastically > more complex than the original int-only java code. Java doesn't allow function overloading? That would be new to me. Or did you just want to nitpick that it should be more properly called "method overloading" in Java? And as you already said, there are some gotchas and you would have to wrap int and long etc. I still would not call that perfectly simple, as it is in Python. -- Christoph From bumtool at yahoo.com Fri Jun 9 10:13:43 2006 From: bumtool at yahoo.com (kilnhead) Date: 9 Jun 2006 07:13:43 -0700 Subject: UltraEdit and Python In-Reply-To: References: Message-ID: <1149862423.290740.204520@c74g2000cwc.googlegroups.com> Check out the following link: http://gurno.com/adam/python_wordfile.txt gregory diaczok wrote: > How do I sent up Ultra Edit to work w/ Python? > > How do I get Ultra Edit to run a Python script currently in the edit window > and supply results? > > I can't figure out how to get Ultra Edit to invoke the Python debugger to > allow stepping through a Python script and view each line reults? > > How do I set pause / break points in Ultra Edit for a Python script? > > -- > Thanks, > Greg > > gdiaczok at verizon.net From walterigo at yahoo.com Sat Jun 10 16:39:47 2006 From: walterigo at yahoo.com (walterigo at yahoo.com) Date: 10 Jun 2006 13:39:47 -0700 Subject: autocomplete Message-ID: <1149971987.225379.290100@h76g2000cwa.googlegroups.com> hello. I have been working all too hard trying to figure out how to get TextCtrlAutoComplete.py to start another word after it finishes the last word. I want it to start the autocomplete process all over again after it finishes the autocomplete process. I have striped down the program to a smaller version than the orginal. it now works in a multiline wx.textctrl box. belive that the program only needs one or two lines to complete the taks and start all over again. here is a copy of the code ''' wxPython Custom Widget Collection 20060207 Written By: Edward Flick () Michele Petrazzo (michele -=dot=- petrazzo -=at=- unipex -=dot=- it) Will Sadkin (wsadkin-=at=- nameconnector -=dot=- com) Copyright 2006 (c) CDF Inc. ( http://www.cdf-imaging.com ) Contributed to the wxPython project under the wxPython project's license. ''' import wx import sys import wx.lib.mixins.listctrl as listmix class myListCtrl(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin): def __init__(self, parent, ID=-1, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0): wx.ListCtrl.__init__(self, parent, ID, pos, size, style) listmix.ListCtrlAutoWidthMixin.__init__(self) class TextCtrlAutoComplete (wx.TextCtrl, listmix.ColumnSorterMixin ): def __init__ ( self, parent, choices = None, showHead=False, dropDownClick=True, colFetch=-1, colSearch=0, hideOnNoMatch=True, selectCallback=None, entryCallback=None, matchFunction=None, **therest) : ''' Constructor works just like wx.TextCtrl except you can pass in a list of choices. You can also change the choice list at any time by calling setChoices. ''' if therest.has_key('style'): therest['style']=wx.TE_PROCESS_ENTER | therest['style'] else: therest['style']=wx.TE_PROCESS_ENTER wx.TextCtrl.__init__(self,parent,-1,'',size=(500,500),style=wx.TE_MULTILINE) #wx.TextCtrl.__init__(self, parent, **therest ) self._hideOnNoMatch = hideOnNoMatch self._selectCallback = selectCallback self._matchFunction = matchFunction self._screenheight = wx.SystemSettings.GetMetric( wx.SYS_SCREEN_Y ) #sort variable needed by listmix self.itemDataMap = dict() #widgets self.dropdown = wx.PopupWindow( self ) #Control the style flags = wx.LC_REPORT | wx.LC_SINGLE_SEL | wx.LC_SORT_ASCENDING if not (showHead) : flags = flags | wx.LC_NO_HEADER #Create the list and bind the events self.dropdownlistbox = myListCtrl( self.dropdown, style=flags, pos=wx.Point( 0, 0) ) gp = self while ( gp != None ) : gp = gp.GetParent() self.Bind( wx.EVT_TEXT , self.onEnteredText, self ) self.Bind( wx.EVT_KEY_DOWN , self.onKeyDown, self ) self.dropdownlistbox.Bind(wx.EVT_LEFT_DCLICK, self.onListDClick) def onListDClick(self, evt): self._setValueFromSelected() def onEnteredText(self, event): text = event.GetString() #print('onEnterdText text: ',text) if self._entryCallback: self._entryCallback() if not text: # control is empty; hide dropdown if shown: if self.dropdown.IsShown(): self._showDropDown(False) event.Skip() return found = False choices = self._choices for numCh, choice in enumerate(choices): if self._matchFunction and self._matchFunction(text, choice): found = True elif choice.lower().startswith(text.lower()) : found = True if found: self._showDropDown(True) item = self.dropdownlistbox.GetItem(numCh) toSel = item.GetId() self.dropdownlistbox.Select(toSel) break if not found: self.dropdownlistbox.Select(self.dropdownlistbox.GetFirstSelected(), False) if self._hideOnNoMatch: self._showDropDown(False) self._listItemVisible() event.Skip () def onKeyDown ( self, event ) : """ Do some work when the user press on the keys: up and down: move the cursor left and right: move the search """ skip = True sel = self.dropdownlistbox.GetFirstSelected() visible = self.dropdown.IsShown() KC = event.GetKeyCode() if KC == wx.WXK_DOWN : if sel < (self.dropdownlistbox.GetItemCount () - 1) : self.dropdownlistbox.Select ( sel+1 ) self._listItemVisible() self._showDropDown () skip = False elif KC == wx.WXK_UP : if sel > 0 : self.dropdownlistbox.Select ( sel - 1 ) self._listItemVisible() self._showDropDown () skip = False if visible : if event.GetKeyCode() == wx.WXK_RETURN : self._setValueFromSelected() skip = False if event.GetKeyCode() == wx.WXK_ESCAPE : self._showDropDown( False ) skip = False if skip : event.Skip() def onListItemSelected (self, event): self._setValueFromSelected() event.Skip() def onClickToggleDown(self, event): self._lastinsertionpoint = self.GetInsertionPoint() event.Skip () def onClickToggleUp ( self, event ) : if ( self.GetInsertionPoint() == self._lastinsertionpoint ) : self._showDropDown ( not self.dropdown.IsShown() ) event.Skip () # -- Interfaces methods def SetChoices(self, choices): #Sets the choices available in the popup wx.ListBox. #The items will be sorted case insensitively. self._choices = choices flags = wx.LC_REPORT | wx.LC_SINGLE_SEL | wx.LC_SORT_ASCENDING | wx.LC_NO_HEADER self._updateDataList(self._choices) self.dropdownlistbox.InsertColumn(0, "") for num, colVal in enumerate(self._choices): index = self.dropdownlistbox.InsertImageStringItem(sys.maxint, colVal, -1) self.dropdownlistbox.SetStringItem(index, 0, colVal) self.dropdownlistbox.SetItemData(index, num) self._setListSize() # there is only one choice for both search and fetch if setting a single column: self._colSearch = 0 self._colFetch = -1 def SetSelectCallback(self, cb=None): self._selectCallback = cb def SetEntryCallback(self, cb=None): self._entryCallback = cb #-- Internal methods def _setValueFromSelected( self ) : ''' Sets the wx.TextCtrl value from the selected wx.ListCtrl item. Will do nothing if no item is selected in the wx.ListCtrl. ''' sel = self.dropdownlistbox.GetFirstSelected() if sel > -1: if self._colFetch != -1: col = self._colFetch else: col = self._colSearch itemtext = self.dropdownlistbox.GetItem(sel, col).GetText() if self._selectCallback: dd = self.dropdownlistbox values = [dd.GetItem(sel, x).GetText() for x in xrange(dd.GetColumnCount())] self._selectCallback( values ) self.SetValue (itemtext) self.SetInsertionPointEnd () self.SetSelection ( -1, -1 ) self._showDropDown ( False ) def _showDropDown ( self, show = True ) : ''' Either display the drop down list (show = True) or hide it (show = False). ''' if show : size = self.dropdown.GetSize() width, height = self . GetSizeTuple() x, y = self . ClientToScreenXY ( wx.CentreX+6, wx.CentreY+6 ) if size.GetWidth() != width : size.SetWidth(width) self.dropdown.SetSize(size) self.dropdownlistbox.SetSize(self.dropdown.GetClientSize()) if (y + size.GetHeight()) < self._screenheight : self.dropdown . SetPosition ( wx.Point(x, y) ) else: self.dropdown . SetPosition ( wx.Point(x, y - height - size.GetHeight()) ) self.dropdown.Show ( show ) def _listItemVisible( self ) : ''' Moves the selected item to the top of the list ensuring it is always visible. ''' toSel = self.dropdownlistbox.GetFirstSelected () if toSel == -1: return self.dropdownlistbox.EnsureVisible( toSel ) def _updateDataList(self, choices): #delete, if need, all the previous data if self.dropdownlistbox.GetColumnCount() != 0: self.dropdownlistbox.DeleteAllColumns() self.dropdownlistbox.DeleteAllItems() #and update the dict if choices: for numVal, data in enumerate(choices): self.itemDataMap[numVal] = data #print("data is %s",data) else: numVal = 0 self.SetColumnCount(numVal) def _setListSize(self): choices = self._choices longest = 0 for choice in choices : longest = max(len(choice), longest) #longest += 3 itemcount = min( len( choices ) , 7 ) + .5 charheight = self.dropdownlistbox.GetCharHeight() charwidth = self.dropdownlistbox.GetCharWidth() self.popupsize = wx.Size( charwidth*longest, charheight*itemcount ) self.dropdownlistbox.SetSize ( self.popupsize ) self.dropdown.SetClientSize( self.popupsize ) class test: def __init__(self): args = dict() args["selectCallback"] = self.selectCallback self.dynamic_choices = [ 'hello world', 'abandon', 'acorn', 'acute', 'adore', 'aegis', 'ascertain', 'asteroid', 'beautiful', 'bold', 'classic', 'daring', 'dazzling', 'debonair', 'definitive', 'effective', 'elegant', 'http://python.org', 'http://www.google.com', 'fabulous', 'fantastic', 'friendly', 'forgiving', 'feature', 'sage', 'scarlet', 'scenic', 'seaside', 'showpiece', 'spiffy', 'www.wxPython.org', 'www.osafoundation.org' ] app = wx.PySimpleApp() frm = wx.Frame(None,-1,"Test", style=wx.CLEAR |wx.DEFAULT_FRAME_STYLE ) panel = wx.Panel(frm) self._ctrl = TextCtrlAutoComplete(panel, **args) self.onBtDynamicChoices(self.onBtDynamicChoices) frm.Show() app.MainLoop() def onBtDynamicChoices(self, event): self._ctrl.SetChoices(self.dynamic_choices) self._ctrl.SetEntryCallback(self.setDynamicChoices) def match(self, text, choice): t = text.lower() c = choice.lower() #print('The Value is %S',choice) return c.startswith(t) def setDynamicChoices(self): if wx.EVT_KEY_DOWN == ' ': print "Space bar pressed" text = self._ctrl.GetValue().lower() choices = [choice for choice in self.dynamic_choices if self.match(text, choice)] self._ctrl.SetChoices(choices) #print('The Value is %S',text) def selectCallback(self, values): """ Simply function that receive the row values when the user select an item """ print "Select Callback called...:", values self.wordCheck(values) def wordCheck(self,values): pass #print"Word to check:",values if __name__ == "__main__": test() From brian at sweetapp.com Tue Jun 13 12:09:25 2006 From: brian at sweetapp.com (Brian Quinlan) Date: Tue, 13 Jun 2006 18:09:25 +0200 Subject: Vancouver Python Workshop - Talk submission reminder Message-ID: <448EE335.8060605@sweetapp.com> What's New? =========== The deadline for submitting a talk or tutorial for the Vancouver Python Workshop is fast approaching. Talks will be accepted until Friday June 16th. To submit a talk, see: http://www.vanpyz.org/conference/talksubmission.html About the Vancouver Python Workshop =================================== The conference will begin with keynote addresses on August 4st by Guido van Rossum [1], Jim Hugunin [2], and Ian Cav?n [3]. Further talks (and tutorials for beginners) will take place on August 5th and 6th. The Vancouver Python Workshop is a community organized and designed for both the beginner and for the experienced Python programmer with: * tutorials for beginning programmers * advanced lectures for Python experts * case studies of Python in action * after-hours social events * informative keynote speakers * tracks on multimedia, Web development, education and more More information see: http://www.vanpyz.org/conference/ or contact Brian Quinlan at: brian at sweetapp.com Vancouver ========= In addition to the opportunity to learn and socialize with fellow Pythonistas, the Vancouver Python Workshop also gives visitors the opportunity to visit one of the most extraordinary cities in the world [4]. For more information about traveling to Vancouver, see: http://www.vanpyz.org/conference/vancouver.html http://www.tourismvancouver.com http://en.wikipedia.org/wiki/Vancouver Important dates =============== Talk proposals accepted: May 15th to June 15th Early registration (discounted): May 22nd to June 30th Normal registration: from July 1st Keynotes: August 4th Conference and tutorial dates: August 5th and 6th [1] Guido van Rossum (Google) is the inventor of Python and has managed its growth and development for more than a decade. Guido was awarded the Free Software Foundation Award in 2002 and Dr.Dobb's 1999 Excellence in Programming Award. Guido works at Google and spends half of his time on Python. [2] Jim Hugunin (Microsoft) is the creator of numerous innovations that take Python into new application domains. Jim's most recent project, IronPython integrates Python into Microsoft's .NET runtime. Jim's previous project, Jython is Python for the Java runtime and was the second production-quality implementation of Python. Before that, Jim's Numeric Python adapted Python to the needs of number crunching applications. Jim works at Microsoft adapting the .NET runtime to the needs of dynamic languages like Python. [3] Ian Cav?n is the primary developer of the Lowry Digital Images motion picture restoration system. This Python and Zope-based system has been used to restore over 150 motion pictures. Highlights include Citizen Kane, Sunset Boulevard and both the Indiana Jones and Star Wars trilogies. While Ian was Chief Scientist at Lowry Digital, his rack of computers grew from a few Macintoshes on his desktop to over six hundred Macintosh and Linux servers - at one point earning Lowry the title as the second biggest installation of parallel processing Maintoshes in the world. In 2005, Lowry Digital Images was acquired by DTS (the famous movie audio company) and renamed DTS Digital Images. The motion picture restoration system has been discussed in publications as diverse as IEEE Spectrum, USA Today, the BBC NEWS, the New York Times and Apple.com. Ian has been a Python enthusiast since 1999. [4] http://news.bbc.co.uk/2/hi/business/2299119.stm Cheers, Brian From timx at nospam.dev.null Fri Jun 30 01:32:39 2006 From: timx at nospam.dev.null (Tim X) Date: Fri, 30 Jun 2006 15:32:39 +1000 Subject: Reddit broke - should have remained on Lisp? References: <1151626961.232761.255550@d56g2000cwd.googlegroups.com> <1151627462.297352.205150@i40g2000cwc.googlegroups.com> Message-ID: <87fyhn2op4.fsf@tiger.rapttech.com.au> "Luis M. Gonz?lez" writes: > Alok wrote: >> While posting a comment on http://www.reddit.com I got an error page >> with the following curious statement on it. >> >> "reddit broke (sorry)" >> "looks like we shouldn't have stopped using lisp..." >> >> See screenshot at >> http://photos1.blogger.com/blogger/1773/1980/1600/reddit-broke.jpg >> >> Whether they truly repent not using lisp or otherwise, their site >> appears to be 3 times slower ... >> >> Alok > > > I don't know if this is true or not, but blaming a language for a poor > development is a little bit ridiculous... > Although I'd like to agree with you and the principal is sound, unfortunately it does not always hold in the real world. In the years I've been programming, there have certainly been situations in which a poorly implemented or poorly designed language has made developing reliable software near impossible. Admittedly this is not as common as it was in the 80s when you had lots of companies developing their own "better" languages for certain domains and there were a lot of 4GLs promising the world, it is still possible to have a situation in which a development fails because of a poorly chosen language. Actually, I've just remember the introduction to PCL where Peter talks about his fathers experience with lisp in the 80s. In this example, choosing lisp saved a development project which was looking very much like it was going to be a complete failure. If do something like selecting a different language saves a development project, isn't it also reasonable to suggest that the converse could be true and that selecting the wrong language could have a negative impact on development? Tim -- tcross (at) rapttech dot com dot au From mrcsparker at gmail.com Wed Jun 14 00:18:25 2006 From: mrcsparker at gmail.com (mrcsparker at gmail.com) Date: 13 Jun 2006 21:18:25 -0700 Subject: TONIGHT! Lisp group beerfest in NYC, PyCells to be discussed In-Reply-To: <2QBjg.497$Yq7.348@fe12.lga> References: <2QBjg.497$Yq7.348@fe12.lga> Message-ID: <1150258705.113102.199690@y41g2000cwy.googlegroups.com> Ken Tilton wrote: > The royal We has just learned that His Kennyness will be honoring the > boozehounds of LispNYC with His Presence tonight (deets below). > > He will come bearing Celtk and news of PyCells, though the top billing > tonight goes to SoC student Extraordinaire Samantha Kleinberg. > > kenzo > > > Please join us for our next meeting on Tuesday, June 13th from 7:00 > > to 9:00 at Westside Brewery. > > > > With Summer of Code being here, this is a great opportunity to talk and > > drink regarding the students and their projects! > > > > Hope to see you there! > > > > > > > > Directions: > > > > Westside Brewery in the VIP room > > 340 Amsterdam Ave. > > (On the West side of Amsterdam Ave., 76th-77th) > > > > Directions by subway: 1-2-3-9 (the red line) to 72nd or 79th and > > Broadway. From 72nd, walk up Amsterdam (not Broadway). From 79th, walk > > east one long block to Amsterdam and turn right/south. > > > > Directions by car: 79th street exit from west side highway, down West > > End Ave or Broadway to 76th, turn left and one or two blocks to > > Amsterdam. > > -- > Cells: http://common-lisp.net/project/cells/ > > "I'll say I'm losing my grip, and it feels terrific." > -- Smiling husband to scowling wife, New Yorker cartoon Why are all of the cool Lisp things up north? No Lispers down south? From bearophileHUGS at lycos.com Fri Jun 23 05:11:02 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 23 Jun 2006 02:11:02 -0700 Subject: map() return of flat tuple list In-Reply-To: References: <1151017077.211517.47940@u72g2000cwu.googlegroups.com> Message-ID: <1151053862.812545.43500@g10g2000cwb.googlegroups.com> Mirco: >He, this looks more like Haskell than like Python (for me, it looks awful ;-) Maybe this is more readable: ar = [[3,3,3,3], [3,3,3,1], [3,3,4,3]] print sorted( [(r,c) for r,row in enumerate(ar) for c in xrange(len(row))], key=lambda (r,c): ar[r][c] )[0] I don't know if operator.itemgetter can be used here, I think it's too much complex. With python 2.5 you can probably simplify it a little (and speed it up) with something like: print min( [ (r,c) for r,row in enumerate(ar) for c in xrange(len(row)) ], key=lambda (r,c): arr[r][c] ) Bye, bearophile From shejo284 at gmail.com Sun Jun 25 14:54:40 2006 From: shejo284 at gmail.com (Sheldon) Date: 25 Jun 2006 11:54:40 -0700 Subject: array manipulation without for loops In-Reply-To: <1151256882.568752.118970@b68g2000cwa.googlegroups.com> References: <1151251578.463273.24370@m73g2000cwd.googlegroups.com> <1151253182.496596.185420@r2g2000cwb.googlegroups.com> <1hhhes5.1hw0kbeniihqiN%aleax@mac.com> <1151254570.730665.298450@r2g2000cwb.googlegroups.com> <1hhhg1j.11oc03fuoikz8N%aleax@mac.com> <1151256882.568752.118970@b68g2000cwa.googlegroups.com> Message-ID: <1151261680.379790.185440@u72g2000cwu.googlegroups.com> The following script (using your function) raised no exception so it worked! Elegant Alex, thanx. res = equalize_arrays(msgtmp,ppstmp,255) # class (ppstmp,msgtmp) = res.equalize() # class method for i in range(int(main.xsize)): for j in range(int(main.ysize)): if msgtmp[i,j] == 255 and ppstmp[i,j] != 255: raise "equalize error!" if ppstmp[i,j] == 255 and msgtmp[i,j] != 255: raise "equalize error!" I read up on the putmask function and I don't understand this part: >>> print x [10 1 30 3 50] >>> putmask(x, [1,0,1,0,1], [-1,-2]) >>> print x [-1 1 -1 3 -1] Can you explain why the -2 didn't factor in? /Sheldon Sheldon wrote: > Hi Alex, > > I will code this in a little while and get back to you. Terrific! I saw > this function but I skipped over it without realizing what it could do. > > The Numeric doc is not very good and I am just getting into Python so > your book sounds great especially since it covers Numeric. I will look > into it when I get back to work tomorrow. > > Bye for now, > Sheldon > > Alex Martelli wrote: > > > Sheldon wrote: > > > > > Alex, > > > > > > I am using Numeric and have created 3 arrays: zero((1215,1215),Float) > > > Two arrays are compared and one is used to hold the mean difference > > > between the two compared arrays. Then I compare 290 or 340 pairs of > > > arrays. I know that memory is a problem and that is why I don't open > > > all of these arrays at the same time. I cannot install Numpy due to my > > > working conditions. Sorry I should have made it clear that is was > > > Numeric I was working with. > > > > It's OK, even if the hard-core numeric-python people are all > > evangelizing for migration to numpy (for reasons that are of course > > quite defensible!), I think it's quite OK to stick with good old Numeric > > for the moment (and that's exactly what I do for my own personal use!). > > > > So, anyway, I'll assume you mean your 1215 x 1215 arrays were created by > > calling Numeric.zeros, not "zero" (with no trailing s) which is a name > > that does not exists in Numeric. > > > > Looking back to your original post, let's say that you have two such > > arrays, a and b, both 1215x1215 and of Numeric.Float type, and the > > entries of each array are all worth 1, 2, or 255 (that's how I read your > > original post; if that's not the case, please specify). We want to > > write a function that alters both a and b, specifically setting to 255 > > all entries in each array whose corresponding entries are 255 in the > > other array. > > > > Now that's pretty easy -- for example: > > > > import Numeric > > > > def equalize(a, b, v=255): > > Numeric.putmask(a, b==v, v) > > Numeric.putmask(b, a==v, v) > > > > if __name__ == '__main__': > > a = Numeric.zeros((5,5), Numeric.Float) > > b = Numeric.zeros((5,5), Numeric.Float) > > a[1,2]=a[2,1]=b[3,4]=b[0,2]=255 > > a[3,0]=a[0,0]=1 > > b[0,3]=b[4,4]=2 > > print "Before:" > > print a > > print b > > equalize(a, b) > > print "After:" > > print a > > print b > > > > > > brain:~/pynut alex$ python ab.py > > Before: > > [[ 1. 0. 0. 0. 0.] > > [ 0. 0. 255. 0. 0.] > > [ 0. 255. 0. 0. 0.] > > [ 1. 0. 0. 0. 0.] > > [ 0. 0. 0. 0. 0.]] > > [[ 0. 0. 255. 2. 0.] > > [ 0. 0. 0. 0. 0.] > > [ 0. 0. 0. 0. 0.] > > [ 0. 0. 0. 0. 255.] > > [ 0. 0. 0. 0. 2.]] > > After: > > [[ 1. 0. 255. 0. 0.] > > [ 0. 0. 255. 0. 0.] > > [ 0. 255. 0. 0. 0.] > > [ 1. 0. 0. 0. 255.] > > [ 0. 0. 0. 0. 0.]] > > [[ 0. 0. 255. 2. 0.] > > [ 0. 0. 255. 0. 0.] > > [ 0. 255. 0. 0. 0.] > > [ 0. 0. 0. 0. 255.] > > [ 0. 0. 0. 0. 2.]] > > brain:~/pynut alex$ > > > > Of course I'm using tiny arrays here, for speed of running and ease of > > display and eyeball-checking, but everything should work just as well in > > your case. Care to check and let us know? > > > > Numeric has pretty good documentation (numpy's is probably even better, > > but it is not available for free, so I don't know!), and if you don't > > find that documentation sufficient you might want to have a look to my > > book "Python in a Nutshell" which devotes a chapter to Numeric (it also > > is not available for free, but you can get a subscription to O'Reilly's > > Safari online-books repository, which is free for the first two weeks, > > and lets you look at many books including Python in a Nutshell -- if you > > don't want to pay monthly subscription fees, make sure you cancel your > > trial subscription before two weeks have passed!!!). > > > > I strongly recommend that, in some way or other, you DO get a taste of > > the huge amount of functionality that Numeric provides for you -- with > > the size of computational tasks you're talking about, an investment of > > 2-3 hours spent becoming deeply familiar with everything Numeric offers > > may well repay itself in savings of ten times as much execution time, > > and what other investments offer such ROI as 1000%?-) > > > > > > Alex From bdesth.quelquechose at free.quelquepart.fr Thu Jun 1 19:45:36 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 02 Jun 2006 01:45:36 +0200 Subject: Using print instead of file.write(str) In-Reply-To: References: Message-ID: <447f4c9a$0$6174$626a54ce@news.free.fr> A.M a ?crit : > Hi, > > > I found print much more flexible that write method. Can I use print instead > of file.write method? > f = open("/path/to/file") print >> f, "this is my %s message" % "first" f.close() To print to stderr: import sys print >> sys.stderr, "oops" FWIW, you and use string formating anywhere, not only in print statements: s = "some %s and % formating" % ("nice", "cool") print s You can also use "dict formating": names = {"other": "A.M.", "me" : "bruno"} s = "hello %(other)s, my name is %(me)s" % names From gandalf at designaproduct.biz Fri Jun 30 05:57:55 2006 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Fri, 30 Jun 2006 11:57:55 +0200 Subject: No error while sending via TCP Socket In-Reply-To: <44A4F4D9.6060606@designaproduct.biz> References: <1151659739.850068.287190@d56g2000cwd.googlegroups.com> <44A4F4D9.6060606@designaproduct.biz> Message-ID: <44A4F5A3.5080103@designaproduct.biz> Laszlo Nagy ?rta: > Ben Sizer ?rta: > >> Martin B?rkle wrote: >> >> >>> I have writen a programm using TCP sockets. After i get the connection >>> to another socket I cut the Ethernet cable. Then I send a message. >>> The program doesnt raise any exception. Can somebody tell me why and >>> give me a hint how to get an exception >>> >>> >> Have you tried waiting 30 seconds or so? The connection may just take a >> while to time out. >> >> > I'm not sure if this will help him. He told that the program doesn't > raise an exception. I suppose this also means that socket.send() was > successful. If his program does not want to send or receive anything > else, then he will not get an exception. Otherwise if socket.send() > blocks his program, then you are right Another idea: probably his message is too small to fit one TCP packet. socket.send() succeeds, but the TCP packet is not sent out. By the time the packet driver tries to send out the (short) TCP packet, the socket.send() call is not active, so it cannot raise an exception. Laszlo From paddy3118 at netscape.net Thu Jun 15 15:43:54 2006 From: paddy3118 at netscape.net (Paddy) Date: 15 Jun 2006 12:43:54 -0700 Subject: a good programming text editor (not IDE) References: <_xgkg.2317$No6.48542@news.tufts.edu> Message-ID: <1150400634.065474.14810@h76g2000cwa.googlegroups.com> John Salerno wrote: > I know there's a request for a good IDE at least once a week on the ng, > but hopefully this question is a little different. I'm looking for > suggestions for a good cross-platform text editor (which the features > for coding, such as syntax highlighting, etc.) but not a full IDE with > all the fancy jazz (GUI developer, UML diagrams, etc.). > > Ideally, it would be something I could even put on a flash drive and > move from computer to computer, but this isn't necessary. Just something > I can immediately use in either Windows or Linux (or Mac, if necessary). > Hi John, I am yet another user of (g)vim. The good thing about gvim is that for normal editing, a lot can be done from the drop-down menus. You need to get hold of a list of the vim commands to learn and what to learn first (anyone?), as there is a huge amount of functionality in vim, and you can do a lot with a little. Personally, I have never done more than poke at the edges of the internal scripting of vim as I prefer: :%!gawk 'awk one liner' Which sends text to the external shell for processing by another command (in this case gawk) Gvim on windows is a life-saver for me as I have files with different line terminators from my unix work, and it opens those. The only thing I miss in gvim is a mode that would try to display HTML to say the degree that the lynx/links browsers do. (http://artax.karlin.mff.cuni.cz/~mikulas/links/, http://lynx.browser.org/). From gherron at islandtraining.com Wed Jun 14 12:28:23 2006 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 14 Jun 2006 09:28:23 -0700 Subject: Numerics, NaNs, IEEE 754 and C99 In-Reply-To: <4490329e$0$12356$636a55ce@news.free.fr> References: <12904mjhl493t49@corp.supernews.com> <1290aik50hmk94a@corp.supernews.com> <4490329e$0$12356$636a55ce@news.free.fr> Message-ID: <44903927.3060502@islandtraining.com> Christophe wrote: > Grant Edwards a ?crit : > >> The division by zero trap is really annoying. In my world the >> right thing to do is to return Inf. >> > > Your world is flawed then, this is a big mistake. NaN is the only > aceptable return value for a division by zero. > Sorry, but this is not true. The IEEE standard specifies (plus or minus) infinity as the result of division by zero. This makes sense since such is the limit of division by a quantity that goes to zero. The IEEE standard then goes on to define reasonable results for arithmetic between infinities and real values. The production of, and arithmetic on, infinities is a choice that any application may want allow or not. Gary Herron From g.brandl-nospam at gmx.net Wed Jun 28 15:32:12 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Wed, 28 Jun 2006 21:32:12 +0200 Subject: Immutability In-Reply-To: References: <4Qj*cEjkr@news.chiark.greenend.org.uk> Message-ID: Nick Maclaren wrote: > In article , > "Fredrik Lundh" writes: > |> > |> identical? you only applied @property to one of the methods, and then you're > |> surprised that only one of the methods were turned into a property? > > I wasn't expecting EITHER to be turned INTO a property - I was expecting > both methods to be the same, but one would have non-default properties > attached to it. That's another sign that property isn't intended to be used as a decorator. Normally, decorators wrap functions with other functions. property doesn't return a function but a descriptor object. Georg From bucodi at yahoo.fr.invalid Mon Jun 19 03:52:11 2006 From: bucodi at yahoo.fr.invalid (Rony Steelandt) Date: Mon, 19 Jun 2006 09:52:11 +0200 Subject: Change value of element in list References: Message-ID: > Hi, > > I'm doing python tutorial, >> http://docs.python.org/tut/node5.html > > and I have these, > > lists = ['spam', 'eggs', 100, 1234] > lists[2] = lists[2] + 23 > > I expected this, > lists = ['spam', 'eggs', 123, 1234] > > but got this, > lists = ['spam', 'eggs', 100, 1234] > > What's my problem here ? > > I have Fedora C5 with python2.4. > > Thanks. > > O Plameras Don't think so Microsoft Windows XP [version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp. C:\Documents and Settings\Administrateur>python Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> list=['spam','egg',100,1234] >>> list ['spam', 'egg', 100, 1234] >>> list[2]=list[2]+23 >>> list[2] 123 >>> list ['spam', 'egg', 123, 1234] >>> Rony -- --- Rony Steelandt BuCodi rony dot steelandt (at) bucodi dot com Visit the python blog at http://360.yahoo.com/bucodi From johnjsal at NOSPAMgmail.com Tue Jun 6 09:48:34 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 06 Jun 2006 13:48:34 GMT Subject: follow-up to FieldStorage In-Reply-To: <4484b428$0$29635$636a55ce@news.free.fr> References: <4484b428$0$29635$636a55ce@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > John Salerno a ?crit : >> If I want to get all the values that are entered into an HTML form and >> write them to a file, is there some way to handle them all at the same >> time, or must FieldStorage be indexed by each specific field name? > > AFAIK, FieldStorage is a somewhat dict-like object, but I'm not sure it > supports the whole dict interface. At least, it does support keys(), so > you should get by with: > > for k in fs.keys(): > print >> myfile, k, ":", fs[k] > > But reading the doc may help... Thanks. The cgi docs don't seem to get into too much detail, unless I wasn't thorough enough. But your method seems like it might work well if I can't find something after another read through. From julius.welby at gmail.com Wed Jun 21 12:43:00 2006 From: julius.welby at gmail.com (jwelby) Date: 21 Jun 2006 09:43:00 -0700 Subject: returning index of minimum in a list of lists In-Reply-To: <1150901648.832039.165590@b68g2000cwa.googlegroups.com> References: <1150901648.832039.165590@b68g2000cwa.googlegroups.com> Message-ID: <1150908180.024084.259700@p79g2000cwp.googlegroups.com> def minIndexFinder(seq): mins = [] listIndex = 0 result = [] for item in seq: mins.append([listIndex,min(item),item.index(min(item))]) listIndex += 1 lowest = min([x[1] for x in mins]) for item in mins: if item[1] == lowest: result.append([item[0], item[2]]) return result A bit more verbose, but maybe slightly more readable?? I probably should have used enumerate like Paul did. For the index of the *first* (or only) occurence of the minimum value in a list of numbers you can just use: seq.index(min(seq)) From cfc at shell01.TheWorld.com Sat Jun 24 15:34:54 2006 From: cfc at shell01.TheWorld.com (Chris F Clark) Date: 24 Jun 2006 15:34:54 -0400 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> Message-ID: Chris Smith writes: > I thought about this in the context of reading Anton's latest post to > me, but I'm just throwing out an idea. I wrote: > I think there is some sense of convergence here. Apologies for following-up to my own post, but I forgot to describe the convergence. The convergence is there is something more general that what type theorists talk about when discussing types. Type theory is an abstraction and systemization of reasoning about types. This more general reasoning doesn't need to be sound, it just needs to be based aound "types" and computations. My own reasoning uses such an unsound system. It has clear roots in sound reasoning, and I wish I could make it sound, but.... In any case, dynamic tagging helps support my unsound reasoning by providing evidence when I have made an error. I hope this makes it less mystical for Marshall. -Chris From kernel1983 at gmail.com Mon Jun 12 23:54:05 2006 From: kernel1983 at gmail.com (kernel1983) Date: 12 Jun 2006 20:54:05 -0700 Subject: PIL show moves focus In-Reply-To: <1150147037.584482.120180@y43g2000cwc.googlegroups.com> References: <1150147037.584482.120180@y43g2000cwc.googlegroups.com> Message-ID: <1150170845.062611.322880@f6g2000cwb.googlegroups.com> Is the console necessary? if not, you can easily disable the console by rename the ext to .pyw elbertlev at hotmail.com wrote: > Hi! > > I have an application where images (jpeg) have to be annotated by an > operator. I use PIL like: > > import Image > im = Image.open(Path) > im.show() > raw_input(Path + ':') > .... > > Python runs in a console window. Then show starts some application (in > my case "Windows picture and FAX viewer") and the picture goes to this > application window. > Then operator enteres the annotation as prompted by raw_input. So far > so good. I understand, that the approach is very minilalistic, but > suffisient for what has to be done. > > Unfortunatelly after im.show focus moves to thw "Windows picture ..." > and stays there until I move it back using the mouse. > > Question: is there any way of returning the input focus to the console > window? From aisaac0 at verizon.net Thu Jun 1 12:32:03 2006 From: aisaac0 at verizon.net (David Isaac) Date: Thu, 01 Jun 2006 16:32:03 GMT Subject: argmax References: Message-ID: <7EEfg.16123$lN5.4994@trnddc04> Thanks for all the replies. A couple of comments. 1. I think the usefulness of an argmax built-in can be assessed by looking at other languages (and e.g. at numpy). So I do not buy the "not needed" argument as presented. More like "haven't got around to it," I'm thinking. 2. The particular use case this time is strategy choice. The desired strategy (i.e., index) is the one with the highest payoff. 3. Thanks to George, and to Peter for noticing a subtle difference in the implementations. Alan Isaac From david.nospam.hopwood at blueyonder.co.uk Sun Jun 25 11:22:32 2006 From: david.nospam.hopwood at blueyonder.co.uk (David Hopwood) Date: Sun, 25 Jun 2006 15:22:32 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150908952.804184.218990@r2g2000cwb.googlegroups.com> <1150991074.705803.211570@m73g2000cwd.googlegroups.com> Message-ID: Joachim Durchholz wrote: > Andreas Rossberg schrieb: > >> Luca Cardelli has given the most convincing one in his seminal >> tutorial "Type Systems", where he identifies "typed" and "safe" as two >> orthogonal dimensions and gives the following matrix: >> >> | typed | untyped >> -------+-------+---------- >> safe | ML | Lisp >> unsafe | C | Assembler >> >> Now, jargon "dynamically typed" is simply untyped safe, while "weakly >> typed" is typed unsafe. > > Here's a matrix how most people that I know would fill in with terminology: > > | Statically | Not | > | typed | statically | > | | typed | > ---------+--------------+-------------+ > typesafe | "strongly | Dynamically | > | typed" | typed | > | (ML, Pascal) | (Lisp) | Pascal, in most of its implementations, isn't [memory] safe; it's in the same box as C. > ---------+--------------+-------------+ > not | (no common | "untyped" | > typesafe | terminology) | | > | (C) | (Assembly) | > ---------+--------------+-------------+ I have to say that I prefer the labels used by Cardelli. > (Terms in quotes are challenged on a regular basis, or rarely if ever > applied.) > > With the above terminology, it becomes clear that the opposite if > "(statically) typed" isn't "statically untyped", but "not statically > typed". "Statically typed" and "dynamically typed" aren't even > opposites, they just don't overlap. > > Another observation: type safeness is more of a spectrum than a clearcut > distinction. Even ML and Pascal have ways to circumvent the type system, Standard ML doesn't (with just the standard basis; no external libraries, and assuming that file I/O cannot be used to corrupt the language implementation). > and even C is typesafe unless you use unsafe constructs. > IOW from a type-theoretic point of view, there is no real difference > between their typesafe and not typesafe languages in the "statically > typed" column; the difference is in the amount of unsafe construct usage > in practial programs. It is quite possible to design languages that have absolutely no unsafe constructs, and are still useful. -- David Hopwood From ben.hamilton at gmail.com Fri Jun 23 03:53:43 2006 From: ben.hamilton at gmail.com (ben.hamilton at gmail.com) Date: 23 Jun 2006 00:53:43 -0700 Subject: Help req: Problems with MySQLdb In-Reply-To: <1150968147.565850.156870@u72g2000cwu.googlegroups.com> References: <1150968147.565850.156870@u72g2000cwu.googlegroups.com> Message-ID: <1151049223.556754.216830@p79g2000cwp.googlegroups.com> for x in range(self.MAX_CRAWL_THREADS+1): self.con.append( [MySQLdb.connect(host,username,passwor,database,PORT),0]) PORT is an extra argument you might not have perhaps rodmc wrote: > I have written an application that connects to a database on a remote > machine which uses MySQLdb 1.2.0. The application works perfectly when > connecting to the database from a remote machine, however when it > attempts to connect to a database on the same machine a connection > error is generated. I have attached what little info I can below. > > DBSERVERIP = "1.2.3.4" > db = MySQLdb.connect(host=DBSERVERIP, user="user", passwd="password", > db="nuke") > --- it refuses to connect on the above line and the exception is caught > and a message displayed. > > I have tried changing the server IP to "localhost" or the hostname, > however the same problem arises. > > Information: Python 2.3.5, MySQLdb 1.2.0, MySQL 5.0.21 and Windows 2K > pro. > > I would be grateful for any help with this problem. > > Kind regards, > > rod Also not catching exceptions is a bad idea (crash thud) for long term programs short term testing its possible it could be good. From rhcarvalho at gmail.com Sat Jun 10 20:16:41 2006 From: rhcarvalho at gmail.com (rhcarvalho at gmail.com) Date: 10 Jun 2006 17:16:41 -0700 Subject: Algorithm for Labels like in Gmail Message-ID: <1149985001.668803.121260@c74g2000cwc.googlegroups.com> Hello there! I'm trying to make a simple Contact Manager using python (console only), however i'm having trouble implementing a division by "Groups" or "Labels" just like in Gmail. I don't have any real code to post because all i got now is a raw TXT file holding the names and phones of my contacts. The only idea I could figure out until now seems too weak, so that's why i'm asking for help. I thought of making a separate list (in a text file) holding all the possible groups, where each group hold the names of the contacts. Then if i access a group, i'll be able to see all contacts related to that group. On the other hand, i'll also need to attach to the contact instance a list of every group it is present. I think it's a bad idea because it seems to be very easy to get things messed up. Like I can get things corrupted or bad linked, and i'll always need to run functions to check all the realations between contact names and groups... I like the way i can "label" emails on Gmail, does anyone know how I can implement such kind of feature? What's the best/broadly used algorithm? Sorry for the long message, and thanks in advance Rodolfo Carvalho From no at spam.net Fri Jun 9 15:28:49 2006 From: no at spam.net (No) Date: Fri, 9 Jun 2006 14:28:49 -0500 Subject: UltraEdit and Python References: Message-ID: I'm replying to me... In article , no at spam.net says... > In article , gdiaczok at verizon.net says... > > How do I sent up Ultra Edit to work w/ Python? > > > > How do I get Ultra Edit to run a Python script currently in the edit window > > and supply results? > > > > I can't figure out how to get Ultra Edit to invoke the Python debugger to > > allow stepping through a Python script and view each line reults? I had intended to insert my reply above this paragraph. My reply below DOESN'T allow stepping, just "run and view results". > > Menu/Advanced/Tool Configuration: (Command tab) > > Menu Item Name: Python > Command Line: "C:\Program Files\python24\python.exe" %F > Working Directory: C:\ > > > Menu/Advanced/Tool Configuration: (Options tab) > > Program Type: Dos Program > > > Menu/Advanced/Tool Configuration: (Output tab) > > Command Output (DOC Commands): Output to List Box, Capture Output > Replace selected text with: No Replace > > > (This is with UltraStudio. Should be the same/similar in UltraEdit.) > > > > > > How do I set pause / break points in Ultra Edit for a Python script? > > > > If you find out, let me know by posting here... > > -Rob > > From balckraven at gmail.com Tue Jun 6 08:47:00 2006 From: balckraven at gmail.com (Raven) Date: 6 Jun 2006 05:47:00 -0700 Subject: cxFreeze executable linked to /usr/lib/libpython2.3.so Message-ID: <1149598020.587434.85080@j55g2000cwa.googlegroups.com> Hi, I compiled a python script using cxFreeze because I need a standalone application, while the Windows version runs without any python installation the linux version of the executable is linked to libpython2.3.so.1.0 => /usr/lib/libpython2.3.so.1.0 thus the end user have to install python 2.3 in order to run the binary. I would like to know if it's possible, using cxFreeze to create a binary that is not linked to any python system library, for example by putting the library in the directory where the binary file is located. Thank Ale From shejo284 at gmail.com Thu Jun 22 04:45:08 2006 From: shejo284 at gmail.com (Sheldon) Date: 22 Jun 2006 01:45:08 -0700 Subject: OverflowError: math range error... Message-ID: <1150965908.354492.239230@i40g2000cwc.googlegroups.com> Hi, I have a written a script that will check to see if the divisor is zero before executing but python will not allow this: ?if statistic_array[0:4] > 0.0: statistic_array[0,0:4] = int(multiply(divide(statistic_array[0,0:4],statistic_array \ [0,4]),10000.0))/100.0 Does anyone know why Python is complaining: "statistic_array[0,0:4] = int(multiply(divide(statistic_array[0,0:4],statistic_array[0,4]),10000.0))/100.0 OverflowError: math range error" and how do I get around this problem? This stupid because there is a if statement preventing this "dividing by zero". Sincerely, Sheldon From jes at nl.demon.net Thu Jun 1 18:53:43 2006 From: jes at nl.demon.net (Jim Segrave) Date: Thu, 01 Jun 2006 22:53:43 -0000 Subject: grouping a flat list of number by range References: <1149196642.001466.53990@c74g2000cwc.googlegroups.com> <1149201416.196975.123370@c74g2000cwc.googlegroups.com> Message-ID: <127urvnrbvjgr07@corp.supernews.com> In article <1149201416.196975.123370 at c74g2000cwc.googlegroups.com>, Paddy wrote: >=== interv2 === >>>> def interv2(inlist): >... for i,val in enumerate(inlist): >... if i==0: >... tmp = val >... elif val != valinc: >... yield [tmp, valinc] >... tmp = val >... valinc = val+1 >... yield [tmp, valinc] >... >>>> list(interv2(inlist)) >[[3, 4], [6, 9], [12, 14], [15, 16]] > >=== END interv2 === This doesn't actually run, changing it to make it do so: def interv2(inlist): tmp = valinc = 0 for i,val in enumerate(inlist): if i==0: tmp = val valinc = val + 1 elif val != valinc: yield [tmp, valinc] tmp = val valinc = val+1 yield [tmp, valinc] it now works, but returns [0, 0] when passed an empty list, when it should return nothing at all -- Jim Segrave (jes at jes-2.demon.nl) From fredrik at pythonware.com Wed Jun 28 13:33:24 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 28 Jun 2006 19:33:24 +0200 Subject: web Develop question In-Reply-To: <1151514841.490454.284770@i40g2000cwc.googlegroups.com> References: <1151514841.490454.284770@i40g2000cwc.googlegroups.com> Message-ID: gerkarcher at gmail.com wrote: > I' m new to python ...and I would like to ask you , wich is the best > template for developing dinamic generated pages using python ? > > I would like to use something easy to install and develop like php ? > tags and with a lots of features . > > thanks in advance and sorry for this silly question . for a start, look under "templating engines" on this page: http://wiki.python.org/moin/WebProgramming (hint: googling for stuff works pretty well, too ;-) From tayss_temp2 at yahoo.com Fri Jun 30 06:11:41 2006 From: tayss_temp2 at yahoo.com (Tayssir John Gabbour) Date: 30 Jun 2006 03:11:41 -0700 Subject: Reddit broke - should have remained on Lisp? References: <1151626961.232761.255550@d56g2000cwd.googlegroups.com> Message-ID: <1151662301.891275.166300@d56g2000cwd.googlegroups.com> Alok wrote: > "reddit broke (sorry)" > "looks like we shouldn't have stopped using lisp..." > > See screenshot at > http://photos1.blogger.com/blogger/1773/1980/1600/reddit-broke.jpg > > Whether they truly repent not using lisp or otherwise, their site > appears to be 3 times slower ... Hi Alok, Supposedly, the Reddit team had a bit of remorse (though of course, we should take the following writeup with a grain of salt; maybe there are more in-depth sources online): "If we could do it all over again, we'd still be using Lisp. Probably." "Reddit: Stick with Lisp. If you want it done right, do it yourself- hosting- Avoid A+.net" http://notelab.infogami.com/startupschool2006 The Reddit owners offered to write up their Lisp experiences. Did they? If not, then of course we have no real ability to verify their claims. (Particularly given that companies are far too secretive to let us actually go there and evaulate their claims for ourselves.) The problem was illustrated by Dvorak's admission that he skillfully antagonized the Apple world to drive traffic; I don't know how much Reddit was helped by this little soap opera, if at all, but these are problems. http://www.youtube.com/watch?v=SAWDYaWAVQQ Tayssir From bdesth.quelquechose at free.quelquepart.fr Thu Jun 22 19:24:23 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 23 Jun 2006 01:24:23 +0200 Subject: Quick Question In-Reply-To: <1151006076.949700.130110@u72g2000cwu.googlegroups.com> References: <1151006076.949700.130110@u72g2000cwu.googlegroups.com> Message-ID: <449af684$0$12370$626a54ce@news.free.fr> xkenneth a ?crit : > I want to be able to cycle through an array and print something in > hexadecimal. Such as this > thisArray = ["AF","0F","5F"] > for x in range(len(thisArray)): > print "\x" + thisArray[x] > > However python chokes on the escaped identifier, how can I get around > this? Either by escaping the backslash: print "\\x" or by using a raw string: print r"\x" From david.huard at gmail.com Wed Jun 21 00:50:50 2006 From: david.huard at gmail.com (David Huard) Date: Wed, 21 Jun 2006 04:50:50 +0000 (UTC) Subject: How to override the doc of an object instance. Message-ID: Hi, I'm not really sure about the right terminology, but here is my question, boiled down to this code: class widget (object): """This is a widget.""" def __init__(self): self._x = None def fget(self): return self._x def fset(self, value): self._x = value print self._x, 'Ok' x = property(fget = fget, fset = fset, doc= "It prints") print widget.x.__doc__ w = widget() w.x = 5 print w.x.__doc__ I would like the last statement to print the doc string that I specified in property, instead of the docstring for an int. The goal is to have ipython print that string with the command w.x? So the user knows what this attribute does, and how he can set it. Is this possible ? Thanks, David Huard From robin at NOSPAMreportlab.com Sat Jun 24 10:37:48 2006 From: robin at NOSPAMreportlab.com (Robin Becker) Date: Sat, 24 Jun 2006 14:37:48 +0000 Subject: Kamaelia 0.4.0 RELEASED - Faster! More Tools! More Examples! More Docs! ;-) In-Reply-To: <4499c9de$0$69378$ed2619ec@ptn-nntp-reader01.plus.net> References: <4499c9de$0$69378$ed2619ec@ptn-nntp-reader01.plus.net> Message-ID: <449D4E3C.8080508@jessikat.plus.net> Michael wrote: > Hi! > > > (OK, slightly silly subject line :) > > I'm extremely pleased to say - Kamaelia 0.4.0 has been released! > ....... Windows users might see problems with the attempt at importing libc.so.6 in the Axon Scheduler. I changed the lines at line 44 of scheduler.py to something like this try: from ctypes import cdll try: libc = cdll.LoadLibrary("/lib/libc.so.6") except: raise ImportError sched_yield = libc.sched_yield except ImportError: def sched_yield(): pass as I have ctypes, but no libc.so.6 I get a Windows error from the statement libc = cdll.LoadLibrary("/lib/libc.so.6") This allows somethings to run eg AxonVisualiser.py --navelgaze but I'm not sure if the results are really unaffected by not having a real yielder. The diagram appears, but doesn't seem to settle down. -- Robin Becker From jo at durchholz.org Wed Jun 21 10:17:14 2006 From: jo at durchholz.org (Joachim Durchholz) Date: Wed, 21 Jun 2006 16:17:14 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> Message-ID: Matthias Blume schrieb: > Joachim Durchholz writes: > >> Matthias Blume schrieb: >>> Joachim Durchholz writes: >>> >>>> Matthias Blume schrieb: >>>>> Perhaps better: A language is statically typed if its definition >>>>> includes (or ever better: is based on) a static type system, i.e., a >>>>> static semantics with typing judgments derivable by typing rules. >>>>> Usually typing judgmets associate program phrases ("expressions") with >>>>> types given a typing environment. >>>> This is defining a single term ("statically typed") using three >>>> undefined terms ("typing judgements", "typing rules", "typing >>>> environment"). >>> This was not meant to be a rigorous definition. >> Rigorous or not, introducing additional undefined terms doesn't help >> with explaining a term. > > I think you missed my point. My point was that a language is > statically typed IF IT IS DEFINED THAT WAY, i.e., if it has a static > type system that is PART OF THE LANGUAGE DEFINITION. The details are > up to each individual definition. Well, that certainly makes more sense to me. Regards, Jo From utabintarbo at gmail.com Wed Jun 14 15:52:44 2006 From: utabintarbo at gmail.com (utabintarbo) Date: 14 Jun 2006 12:52:44 -0700 Subject: determining file type In-Reply-To: <1150276935.270798.5550@i40g2000cwc.googlegroups.com> References: <1150276935.270798.5550@i40g2000cwc.googlegroups.com> Message-ID: <1150314764.014651.102620@c74g2000cwc.googlegroups.com> http://www.demonseed.net/~jp/code/magic.py From m.yanowitz at kearfott.com Thu Jun 1 08:31:34 2006 From: m.yanowitz at kearfott.com (Michael Yanowitz) Date: Thu, 1 Jun 2006 08:31:34 -0400 Subject: Tkinter - changing existing Dialog? In-Reply-To: <447ED790.20101@lexicon.net> Message-ID: Hello: I have a Tkinter GUI Dialog with many buttons and labels and text widgets. What I would like to do is, can I: 1) Disable/deactivate/hide a button, text widget that is already drawn (and of course the opposite enable/activate/show it)? 2) Change the text of a label or button that is already drawn? based on actions taken by the user. Can it be done without destroying the present dialog or the objects in it and creating a new one? Sorry for what probably is such a trivial and basic question. I just can't find the answer or know what the technical term for what I want to do is to search for it myself. Thanks in advance: Michael Yanowitz From python.list at tim.thechases.com Mon Jun 26 11:56:37 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 26 Jun 2006 10:56:37 -0500 Subject: Get List of Classes In-Reply-To: <200606261746.37706.maric@aristote.info> References: <1151332257.564563.139040@u72g2000cwu.googlegroups.com> <449FFC7E.2010600@tim.thechases.com> <200606261746.37706.maric@aristote.info> Message-ID: <44A003B5.3040603@tim.thechases.com> >> I couldn't find any nice method for determining if a >> variable referenced a module other than checking to see if >> that item had both a "__file__" and a "__name__" attribute. > > Why not : > > In [8]: import types, sys > > In [9]: isinstance(sys, types.ModuleType) > Out[9]: True Yes...this is the best way to do it. I hadn't explored (or even noticed, before your reply) the "types" module, which seems to have a large toolset for doing exactly what I wanted to. Thanks! A good programming language has users asking "how did I miss that?" rather than "why can't I make it do what I want?". Yet another feather in Python's cap. -tkc From p.o.bengtsson at gmail.com Wed Jun 14 05:36:44 2006 From: p.o.bengtsson at gmail.com (P-O Bengtsson) Date: Wed, 14 Jun 2006 11:36:44 +0200 Subject: Test tool - Design advise needed Message-ID: Hello I am new at this list, looking forward to be a part of it. I am trying to write a application with the functionality to record mouse and key events, and then another functionality to replay earlier recorded events. It is meant to be used for testing of other applications/WebPages. I started of with tk to catch mouse and key event. So far no worries. But I decided that I would like to use wxpython instead. But I can not find a way to catch the necessary event while using wxpython. For the playback function I have been thinking about using ctypes and access windll.user32 to move the cursor. And it should be possible to send key and mousebutton event from windll as well I guess(?) Is there any approach to catch user events from wxpyton? Am I on the right track here? Is it a good ide to access windll for my replay, or is there any better approach? Thanks in advance /P-O -------------- next part -------------- An HTML attachment was scrubbed... URL: From maxerickson at gmail.com Fri Jun 2 13:19:03 2006 From: maxerickson at gmail.com (Max Erickson) Date: Fri, 2 Jun 2006 17:19:03 +0000 (UTC) Subject: Package References: Message-ID: I'm no expert, but your post made me curious. It appears that __all__ has the effect of ensuring that from test import * picks up test1, but doesn't go any further than that. from test.test1.test2 import * should cause test3 to be imported. max From brochu121 at gmail.com Mon Jun 5 13:21:29 2006 From: brochu121 at gmail.com (david brochu jr) Date: Mon, 5 Jun 2006 13:21:29 -0400 Subject: Starting New Process Message-ID: <9583ed900606051021xbcc2cceo6fefb0bdd134ed06@mail.gmail.com> try os.spawn() using the os module -------------- next part -------------- An HTML attachment was scrubbed... URL: From onurb at xiludom.gro Fri Jun 23 09:39:57 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Fri, 23 Jun 2006 15:39:57 +0200 Subject: Specifing arguments type for a function In-Reply-To: <1151065595.089436.214710@i40g2000cwc.googlegroups.com> References: <200606201328.02784.maric@aristote.info> <1150804645.542646.38570@g10g2000cwb.googlegroups.com> <449afb64$0$16558$636a55ce@news.free.fr> <1151020127.152656.26860@m73g2000cwd.googlegroups.com> <9cum92trvgb271b776l2lg4rdfj3ed951g@4ax.com> <1151042100.731065.19510@r2g2000cwb.googlegroups.com> <1151065595.089436.214710@i40g2000cwc.googlegroups.com> Message-ID: <449bef2e$0$1628$636a55ce@news.free.fr> George Sakkis wrote: > Dennis Lee Bieber wrote: > >>On 22 Jun 2006 22:55:00 -0700, "George Sakkis" >>declaimed the following in comp.lang.python: >> >> >> >>>Ok, I'll try once more: What does __setitem__ have to do with >>>**iterability**, not mutability or indexability ? I was commenting on >>>Maric's post that although some objects are typically iterable, they >>>are often treated as atomic by some/many/most applications (e.g. >>>strings). It's not rocket science. >>> >> >> And the absence of the setitem would indicate such an object -- it >>may be iterable in terms of retrieving subparts, but atomic WRT >>modification. >> >> That, at least, is how I interpreted the introduction of the test... > > > Applications that don't need to treat strings as iterables of > characters wouldn't do so even if strings were mutable. Atomicity has > to do with whether something is considered to be composite or not, not > whether it can be modified. Sure. Do you have any generic solution for this ? -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From andrea.gavana at gmail.com Tue Jun 20 05:15:05 2006 From: andrea.gavana at gmail.com (Andrea Gavana) Date: Tue, 20 Jun 2006 10:15:05 +0100 Subject: [PIL]: Image size in runtime Message-ID: Hello NG, sorry if the message is not strictly Python-related, but it is fantastically impossible to send post to Image-SIG. I am using PIL to load and display some pictures (via wxPython) in a GUI. I have added the ability for the user to change the linear dimensions of the image (in pixels) and the quality of the image in order for the image to be saved in another file. I was wondering if is there a way to know in advance, based on the pixel dimensions specified by the user and by the image quality, which file size (in bytes) I will obtain for the new image (approximatively). Is there a way to obtain such result without actually saving the image? Thanks for any hint. Andrea. "Imagination Is The Only Weapon In The War Against Reality." http://xoomer.virgilio.it/infinity77/ From deets at nospam.web.de Sat Jun 17 08:18:33 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 17 Jun 2006 14:18:33 +0200 Subject: any subway experiences References: <1150533811.911621.112430@y41g2000cwy.googlegroups.com> Message-ID: <4fia8pF1isv0dU1@uni-berlin.de> The berlin subway is great - especially during the worldcup the sheer amount of people from all over the world makes things interesting. HTH, Diez From writeson at charter.net Fri Jun 2 14:07:06 2006 From: writeson at charter.net (writeson) Date: 2 Jun 2006 11:07:06 -0700 Subject: wxPython problems with Fedora Core 5 Message-ID: <1149271626.481398.34440@h76g2000cwa.googlegroups.com> Hi all, I'm trying to use wxPython from a fairly new installation of Fedora Core 5. I installed wxPython using yum -y install wxPython and that all seemed to work fine. However, when I run Python and do this: import wx I get this: Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.4/site-packages/wx/__init__.py", line 45, in ? from wxPython import wx File "/usr/lib/python2.4/site-packages/wxPython/__init__.py", line 20, in ? import wxc ImportError: /usr/lib/libwx_gtk2-2.4.so.0: undefined symbol: pango_x_get_context Anyone have any ideas what's going on and what I can do to fix this? Thanks in advance, Doug From mhellwig at xs4all.nl Thu Jun 29 08:09:26 2006 From: mhellwig at xs4all.nl (Martin P. Hellwig) Date: Thu, 29 Jun 2006 14:09:26 +0200 Subject: Python 2.4 tutorial In-Reply-To: References: Message-ID: <44a3c2f9$0$31650$e4fe514c@news.xs4all.nl> subramanian2003 wrote: > Hello All, > > From where I can get the detailed python 2.4 tutorial(other than python.org). > > Thanks, > Subramanian. > > If you're willing to pay for it you can read many python books online at: http://safari.oreilly.com Although I like a paper version more (and most books are in my possession) but I still use it quite frequently. -- mph From grante at visi.com Thu Jun 15 11:08:30 2006 From: grante at visi.com (Grant Edwards) Date: Thu, 15 Jun 2006 15:08:30 -0000 Subject: Numerics, NaNs, IEEE 754 and C99 References: <12904mjhl493t49@corp.supernews.com> <1290aik50hmk94a@corp.supernews.com> <4490329e$0$12356$636a55ce@news.free.fr> <12917f6jp7u90f8@corp.supernews.com> <44912058$0$29674$636a55ce@news.free.fr> <1292p7s46ef5off@corp.supernews.com> Message-ID: <1292tvei30ahhd4@corp.supernews.com> On 2006-06-15, Nick Maclaren wrote: >|> Making Python incompatible with IEEE |> 754 is a bad idea. > > No, that is wrong, on many counts. > > Firstly, a FAR more common assumption is that integers wrap in twos' > complement - Python does not do that. It used to, and I sure wish there was still a way to get that behavior back. Now I have to do all sorts of bitwise ands that I didn't use to. > Secondly, it is NOT incompatible with IEEE 754, which is a > pure hardware standard. All it does is to trap the exception > and take appropriate action (as permitted by that standard). There are two allowed (selectable?) behaviors for 1/0: trap and Inf. > Thirdly, virtually no hardware sticks strictly to IEEE 754, > and no language that I know of has EVER attempted to make it > the strict basis for its arithmetic model. All the HW and libraries I've used returned Inf for 1/0. > Fourthly, I am not proposing to change any hardware, IMO, having Python's FP results disagree with common HW FP results would be a pretty bad thing. > and could even provide a Python option to deliver > mathematically incorrect results when you want them. As long as I can get IEEE 754 results, that's cool. I'd prefer if Python just let the HW do it's thing when possible. -- Grant Edwards grante Yow! How do I get HOME? at visi.com From fredrik at pythonware.com Wed Jun 7 12:58:59 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 07 Jun 2006 18:58:59 +0200 Subject: printing backslash In-Reply-To: <1149698793.422979.148770@i40g2000cwc.googlegroups.com> References: <1149698793.422979.148770@i40g2000cwc.googlegroups.com> Message-ID: micklee74 at hotmail.com wrote: > i want to print something like this > > |\| > > first i tried it as string > > a = "|\|" > > it prints ok > > but when i put it to a list > > a = ["|\|"] > > it gives me '|\\|'. if you want to print "|\|", why are you printing the list? > there are 2 back slashes...i only want one.. there's only one in the string; the other one is added by the list- to-string conversion. if you print the *list item* instead, only one backslash is printed. the correct way to add a single backslash to a string is to write *two* backslashes in the string literal, like this: "|\\|" this results in a 3-character string, which is printed as |\|, but is echoed back as '|\\|' by the repr() operator (which is used by the interactive prompt, and the list-to-string conversion, among others). >>> s = "|\\|" >>> s # implicit repr '|\\|' >>> print s |\| >>> len(s) 3 >>> print repr(s) '|\\|' >>> print str(s) |\| >>> x = [s] >>> x # implicit repr ['|\\|'] >>> print x[0] |\| From sjmachin at lexicon.net Tue Jun 6 07:27:53 2006 From: sjmachin at lexicon.net (John Machin) Date: Tue, 06 Jun 2006 21:27:53 +1000 Subject: check for dictionary keys In-Reply-To: <44855b2c$0$10988$626a54ce@news.free.fr> References: <1149298230.864123.8320@u72g2000cwu.googlegroups.com> <4483f80a$0$27349$626a54ce@news.free.fr> <4484d5ee$1@news.eftel.com> <44855b2c$0$10988$626a54ce@news.free.fr> Message-ID: <448566b9@news.eftel.com> On 6/06/2006 8:38 PM, bruno at modulix wrote: > John Machin wrote: >> On 5/06/2006 10:46 PM, Bruno Desthuilliers wrote: >> >>> micklee74 at hotmail.com a ?crit : >>> >>>> hi >>>> in my code, i use dict(a) to make to "a" into a dictionary , "a" comes >>>> from user input, so my program does not know in the first place. Then >>>> say , it becomes >>>> >>>> a = { '-A' : 'value1' , '-B' : "value2" , "-C" : "value3" , '-D' : >>>> 'value4' } >>>> >>>> somewhere next in my code, i will check for these..: >>>> >>>> 1) -A and -B cannot exist together >>>> 2) -A and -C cannot exist together >>>> 3) -A and -B and -D cannot exist together >>>> 4) and lots of other combinations to check for.... >>> >>> Looks like an option parser... If so, there's all you need in the >>> standard lib (look for the optparse module). >>> >>>> how can i efficiently check for the above? At first as i do simple >>>> checks , i use if and else. >>>> But as i began to check for more combinatoiuns, it gets messy.... >>> >>> First : use boolean logic (truth table, Kernaugh diagram, etc) to >>> simplify things. As an example, rule #3 is useless - it's a subset of >>> rule #1 (-A and -B and -D implies -A and -B). This should greatly >>> reduce the number of needed tests. >> >> Good idea, but doesn't scale well. > > Does it need to scale ? If there are lot of rules and frequently > changing, yes, automating the process will be a good idea - but if it's > about a program options, just using one's brain might be enough. At > least it forces one to think about what's going on... > >> Simple code can weed out redundant >> rules, > > Simple code can weed out redundant *simple* rules !-) > > (snip) > >>> Then, write a simple rule system describing either valid inputs or >>> invalid inputs (preferably the smallest set !-). FWIW, it can be as >>> simple as a list of lambdas/error messages pairs, with lambdas being >>> predicate taking dict keys as params: >>> >>> >>> _RULES = [ >>> (lambda keys : '-A' in keys and '-B' in keys, >>> "can't have both options -A and -B"), >>> (lambda keys : '-A' in keys and '-C' in keys, >>> "can't have both options -A and -C"), >>> # etc... >>> ] >>> >> The evil HR director won't let the PHB pay me on a per LOC basis, so >> I've had to come up with a compact table-driven approach :-) > > I'm my own evil HR director and PHB !-) You must have some interesting conversations with yourself !-) > > Don't like table-driven programming, John ? I love table-driven programming. You seem to misunderstand; In this case the "bad combos" list *is* the table. > > This solution takes very few lines, and while it's surely not a > full-blown rule engine, it's at least reasonably flexible. > > (Not to say it's better than yours - it's of course a matter of > effective use case). > [snip] > > Nice code - but how does it handle more complex predicates ? Seems you > can only deal with 'and' rules here. More complex predicates are not in the OP's spec ... this is a defence I learned from somebody in this newsgroup recently :-) > "Doesn't scale well", you > said ?-) I understand 'scale' to relate to size, not to complexity. Cheers, John From steve at holdenweb.com Fri Jun 9 03:40:59 2006 From: steve at holdenweb.com (Steve Holden) Date: Fri, 09 Jun 2006 08:40:59 +0100 Subject: Python Class for Apache log analysis In-Reply-To: <1149813289.467298.6110@j55g2000cwa.googlegroups.com> References: <1149813289.467298.6110@j55g2000cwa.googlegroups.com> Message-ID: And80 wrote: > Hi all, > I am looking for a python package that I could employ to analyze > Apache's log files in real time. Of course I already have found some > scripts, but most of them are outdated (python1.5), while others are > simply impossible to use for a custom application. I was looking for > something reliable, flexible and not to much outdated... > Are you saying that a Python 1.5 script won't work on recent Pythons, or just that the scripts, being old, don't meet your requirements? The log file format is old enough that you might find the old scripts are fine. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From aljosa.mohorovic at gmail.com Tue Jun 6 09:02:26 2006 From: aljosa.mohorovic at gmail.com (aljosa) Date: 6 Jun 2006 06:02:26 -0700 Subject: capture video from camera Message-ID: <1149598946.182874.121650@c74g2000cwc.googlegroups.com> i'm trying to capture video from camera/webcam using python. so far i haven't found any library that would allow me to do that. cross-platform solution related to SDL/pygame would be nice but a simple solution to capture video under windows is ok. Aljosa Mohorovic From sramaswamy at gmail.com Thu Jun 29 23:59:36 2006 From: sramaswamy at gmail.com (sramaswamy at gmail.com) Date: 29 Jun 2006 20:59:36 -0700 Subject: How to get indices of a two dimensional list Message-ID: <1151639976.664310.183620@x69g2000cwx.googlegroups.com> I have a list x = [0] * 2 x = x * [2] x[1,1] = 7 This gives me the x value [[0,0] [0,0] [0,0] [0,7]] I want to get the indices of the value 7. i.e. something like i = a.index(max(a)) gives me '1' This only gives me the index in one dimension. Is there any method by which I can get (1,1) as the answer. Thanks in advance. From claird at lairds.us Sat Jun 24 20:58:10 2006 From: claird at lairds.us (Cameron Laird) Date: Sun, 25 Jun 2006 00:58:10 +0000 Subject: Absolute noob to Linux programming needs language choice help References: <1150854682.904891.274480@c74g2000cwc.googlegroups.com> <1hhdlmq.xxmlwo27govgN%aleax@mac.com> Message-ID: <2m31n3-q81.ln1@lairds.us> In article <1hhdlmq.xxmlwo27govgN%aleax at mac.com>, Alex Martelli wrote: > wrote: > >> Hey guys, >> >> I am absolutely new to Linux programming, with no w######s programming >> experience except a small amount of C++ console apps. >> Reasonably new to Linux, BSD etc, got good sound networking base of >> knowledge and dont have any problem working the command line etc. >> >> I want to learn a language that I can use in my networking duties that >> is most likely to be of use to me. I have a few choices I can think of >> being: . . . >Python, Perl, and a third language you have not mentioned, Ruby, are >very high level, and each is suitable for just about the same range of >programming (almost any programming, except very low-level;-). The . [more true and pertinent obser- vations] . . Tcl is also in this category. Even with Alex expanding the discussion to encompass Ruby, I wouldn't mention Tcl--except that the original questioner explicitly mentioned "networking duties". While his intent is ambiguous, it deserves to be said that, just as Alex has written, all four of these languages are rough equivalents, differing as much in subjective feel as objective functionality, but that 1. Tcl, with its emphasis on event programming, codes multi-processing TCP servers more com- pactly than the other three; 2. Tcl is the extension language for Cisco's IOS and several other networking products; 3. Tcl-based Scotty is the single most mature SNMP suite any of the four languages have produced; 4. There's the whole BEEP story; and 5. Tcl-based Expect has a special role in system administration and network manage- ment. There's plenty to read on all these subjects, if you have an interest. might be a place to start. From joncle at googlemail.com Tue Jun 20 11:20:27 2006 From: joncle at googlemail.com (Jon Clements) Date: 20 Jun 2006 08:20:27 -0700 Subject: Iteration over recursion? In-Reply-To: <1150808045.539887.291180@i40g2000cwc.googlegroups.com> References: <1150808045.539887.291180@i40g2000cwc.googlegroups.com> Message-ID: <1150816827.826028.114740@h76g2000cwa.googlegroups.com> MTD wrote: > Hello all, > (snip) > I've been told that iteration in python is generally more > time-efficient than recursion. Is that true? (snip) AFAIK, in most languages it's a memory thing. Each time a function calls itself, the 'state' of that function has to be stored somewhere so that it may continue, as was, when the recursive function returns. Therefore, you can effectively think of it as creating N many objects which don't start getting released until the very last nested call returns. This (depending on the stack size and implementation etc...) may force several memory allocations. Then of course, as it starts going back 'upwards' (towards the initiator of the recursive call that is), the garbage collector may kick in freeing memory... Depending on return values, iterating will just require space for the returned value from each function in term (which in most cases - I would imagine fits on the stack), so although it's doing effectively the same thing, it's doing so with less memory. I probably haven't explained too well, and I may not even be right. So take with a pinch of salt. All the best, Jon. From antroy at gmail.com Tue Jun 13 13:06:38 2006 From: antroy at gmail.com (Ant) Date: 13 Jun 2006 10:06:38 -0700 Subject: Is there a better way of accessing functions in a module? Message-ID: <1150218398.443615.304880@p79g2000cwp.googlegroups.com> I have the following code which works fine for running some tests defined within a module: def a_test(): print "Test A" def b_test(): print "Test B" if __name__ == "__main__": tests = ["%s()" % x for x in dir() if x.endswith("test")] for test in tests: eval(test) But this feels like a hack... Is there a cleaner way for accessing the functions of the current module similar to the __dict__ attribute of classes? i.e. a way to access the local symbol table? From jiguorui at gmail.com Sun Jun 18 02:15:09 2006 From: jiguorui at gmail.com (jiguorui at gmail.com) Date: 17 Jun 2006 23:15:09 -0700 Subject: setting cookies in quixote Message-ID: <1150611309.104331.144300@u72g2000cwu.googlegroups.com> # I write a quixote demo like this: equest = get_request() request.response.set_cookie('usr_name', 'Jim', path='/') request.response.set_cookie('usr_id', '1', path='/') #but only usr_name can be setted successfully, and usr_id is none. Why ? Help me ! Thanks From paddy3118 at netscape.net Sat Jun 17 12:51:20 2006 From: paddy3118 at netscape.net (Paddy) Date: 17 Jun 2006 09:51:20 -0700 Subject: a good programming text editor (not IDE) References: <_xgkg.2317$No6.48542@news.tufts.edu> <1150406662.900552.46650@u72g2000cwu.googlegroups.com> <1150533881.540254.270400@i40g2000cwc.googlegroups.com> Message-ID: <1150563080.448650.38090@g10g2000cwb.googlegroups.com> Hi 63q2o4i02 :-) Cream is a package built on top of vim that presents a more "Windows friendly" face to the vim/gvim editor. It is avaiable for Windows and Linux and might give you a single editor that you can use on more platforms, but maybe you might like the interface better. It does syntax hilighting for Python and code foding. http://cream.sourceforge.net/ - Paddy. From janencarl at aznex.net Mon Jun 26 00:37:35 2006 From: janencarl at aznex.net (Jane & Carl) Date: Sun, 25 Jun 2006 21:37:35 -0700 Subject: Python is fun and useful (was: Python is fun (useless social thread) ; -)) References: Message-ID: <00c301c698da$3ff151b0$e718140a@carlkbvm67868l> > I believe the applicability of Python and related techniques to > process control, engineering programming, and so on, is vastly > under-appreciated. Conventional wisdom in these domains sees > Visual Basic, Visual C++, and Fortran as suitable vehicles. > You've seen how limiting this is. > > For reasons that I can elaborate at more length later, I'd love > to diffuse awareness of Python's potential in mining and other > "real-world" industries. The Agile Control Forum http://www.engcorp.com/acf/RecentChanges > is made for just > such purposes. Although it's been rather quiet recently, that > might change soon. It'd be great to have you tell your story > in the ACF Wiki. > -- > http://mail.python.org/mailman/listinfo/python-list > Thanks! I'll have a look at the Agile Control Forum. I get some pushback sometimes for using Python instead of VBA/Excel at work. But my old department just sent two engineers for training with M. Lutz. So there's hope. All in all, I think Python is a pretty good choice for science, engineering, and process control. As you pointed out "coventional" wisdom sometimes doesn't have the last, or the correct word on things. Pythonistas of the engineering world, unite! (or something like that) From imcsee at gmail.com Wed Jun 14 13:51:04 2006 From: imcsee at gmail.com (imcs ee) Date: Thu, 15 Jun 2006 01:51:04 +0800 Subject: prog1 | prog2 . How not to make prog2 block if not piped? In-Reply-To: <1150306815.394154.130250@h76g2000cwa.googlegroups.com> References: <1150297984.798904.229730@h76g2000cwa.googlegroups.com> <1150306815.394154.130250@h76g2000cwa.googlegroups.com> Message-ID: yeah, forget my post ,it;s useless. sorry for my thoughtless On 14 Jun 2006 10:40:15 -0700, riquito at gmail.com wrote: > > imcs ee ha scritto: > > > do u really need read something even when you run the scripts2.py directly? > > why not just change script2.py to > > #script2.py > > if __name__ == "__main__": > > x=sys.stdin.read() > > print 'passed' > > else: > > print 'passed from else branch' > > > > is it what you want? or anything i misunderstand. > > it won't do. clever btw. > Script2 is not a module, it's a program that _could_ receive input via > pipe. > > -- > http://mail.python.org/mailman/listinfo/python-list > From garabik-news-2005-05 at kassiopeia.juls.savba.sk Wed Jun 14 02:35:20 2006 From: garabik-news-2005-05 at kassiopeia.juls.savba.sk (garabik-news-2005-05 at kassiopeia.juls.savba.sk) Date: Wed, 14 Jun 2006 06:35:20 +0000 (UTC) Subject: python-dev Summary for 2006-05-01 through 2006-05-15 References: Message-ID: This summary is tagged as being in ISO-8859-1 encoding: Content-Type: text/plain; charset=ISO-8859-1; format=flowed However, it really is in UTF-8, which results in this mojibake: > > Martin v. L??wis and Marc-Andre Lemburg discussed how to include both -- ----------------------------------------------------------- | 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! From christoph.hieronymus at geo.uu.se Mon Jun 19 07:56:20 2006 From: christoph.hieronymus at geo.uu.se (Chris Hieronymus) Date: Mon, 19 Jun 2006 13:56:20 +0200 Subject: Passing data to system command In-Reply-To: <1150666037.974563.25610@i40g2000cwc.googlegroups.com> References: <1150666037.974563.25610@i40g2000cwc.googlegroups.com> Message-ID: Hi, Holy mackerel, this really works; thanks a lot, guys. I played around a little bit with the suggestions by faulkner and hdante and pieced together the following script. I like this very much because I can write a bunch of data to the pipe, rather than making one big string containing perhaps several thousand lines of x-y pairs. I've tested the script for up to 100,000 data pairs and it works; passing a single string with that many lines to the psxy command generally leads to problems (?), I'm told... For any other newbie's out there that are trying to use python and GMT together: The script uses GMT's psxy command (with the required arguments), generates some x-y data (just a sine function), and writes each x-y pair as a string to the pipe. This should work equally for any other GMT-commands. I'm still trying to work out some of the details myself; I don't understand, yet, what exactly the command "communicate" does; but it seems to be needed. chris ================================================================= #! /usr/bin/python from subprocess import Popen, PIPE from math import * from os import system psfile = 'output1.ps' cmd = 'psxy -R0/100/0/10 -JX10 -B10/1' my_output = file(psfile, 'w') p1 = Popen(cmd,stdin = PIPE,stdout=my_output,shell=True) for i in range(10000): x = float(i)/100.0 y = 4.*sin(x/10.)+5.0 msg = str(x)+" "+str(y)+"\n" p1.stdin.write(msg) p1.communicate() my_output.close() cmd = 'gv '+psfile print cmd p2 = Popen(cmd,shell=True) p2.communicate() ================================================================= On Jun 18, 2006, at 11:27 PM, hdante wrote: > Should be like this: > > from subprocess import Popen, PIPE > > my_output = file('output1.ps', 'w') > p1 = Popen(["psxy"], stdin = PIPE, stdout=my_output) > p1.stdin.write(my_format(array)) > p1.communicate() > my_output.close() > > I've never used that, though, please tell us if it worked. > > Chris Hieronymus wrote: >> Hi, >> >> I have a bunch of x-y data contained in an array. I would like to >> plot the data using an >> external program (psxy in GMT). The plotting program takes x-y >> couples as standard >> input. How do I get the data into the system call? I used to do >> things in csh and awk, >> i.e., something like >> >> awk '{; print $1, $2}' filename | psxy > options> >! output.ps >> >> The reason I'm trying to use python is because the manipulations are >> getting too cumbersome >> in awk. Now I have all the manipulations done in python, but I'm >> missing that last step. >> >> I've tried various things with os.system, popen, and subprocess, but >> so far without success. >> Does anyone know how to do this? >> >> chris >> >> >> --------------------------------------------------------------------- >> --- >> ------------------------------------------- >> Christoph >> Hieronymus >> christoph.hieronymus at geo.uu.se >> Associate >> Professor >> phone: (+46) 18-471 2383 >> Uppsala >> University >> fax: (+46) 18-501 110 >> Dept. of Earth Sciences (Geophysics) >> Villav?gen 16 >> SE-752 36 Uppsala, Sweden > > -- > http://mail.python.org/mailman/listinfo/python-list ------------------------------------------------------------------------ ------------------------------------------- Christoph Hieronymus christoph.hieronymus at geo.uu.se Associate Professor phone: (+46) 18-471 2383 Uppsala University fax: (+46) 18-501 110 Dept. of Earth Sciences (Geophysics) Villav?gen 16 SE-752 36 Uppsala, Sweden From sjmachin at lexicon.net Sun Jun 18 18:06:44 2006 From: sjmachin at lexicon.net (John Machin) Date: Mon, 19 Jun 2006 08:06:44 +1000 Subject: Seeking regex optimizer In-Reply-To: <1150662655.541745.174430@u72g2000cwu.googlegroups.com> References: <1150650439.651839.38180@y41g2000cwy.googlegroups.com> <1150662655.541745.174430@u72g2000cwu.googlegroups.com> Message-ID: <4495ce73$1@news.eftel.com> On 19/06/2006 6:30 AM, Paddy wrote: > Kay Schluehr wrote: >> I have a list of strings ls = [s_1,s_2,...,s_n] and want to create a >> regular expression sx from it, such that sx.match(s) yields a SRE_Match >> object when s starts with an s_i for one i in [0,...,n]. There might >> be relations between those strings: s_k.startswith(s_1) -> True or >> s_k.endswith(s_1) -> True. Kay, what is the relevance of one string being a suffix of another? I don't see how that could affect the outcome. An extreme case would be ls = ['a', 'aa', >> ...,'aaaa...ab']. For this reason SRE_Match should provide the longest >> possible match. >> >> Is there a Python module able to create an optimized regex rx from ls >> for the given constraints? Optimised with respect to what? speed? ease of construction? I presume that you will ensure that the members of the list are unique. Note that the Python regex engine will consider each candidate in Paddy's solution left to right until it gets a match or reaches the end (that's why the reverse sort is needed to get longest possible match). This is worst-case O(N) where N is the total of the lengths of all the strings in your list. As far as I can see, this is the only basic solution (modulo one or two twiddles -- see below) using Python's re. You could possibly consider producing "zzz|foo(?:bar)?|aaa" instead of "zzz|foobar|foo|aaa" -- but whether that would run sufficiently faster to offset the cost of construction is anybody's guess. How many strings in your list? Average/maximum length? Likelihood of ls[i].startswith(ls[j]) == True? unicode or str? Your requirements are rather constrained: "sx.match(s) yields a SRE_Match object" ... why do you need this? Surely all you need is matched_len (which may be zero) such that s[:matched_len] is the matched prefix. I would have thought the way to approach this would be a simple character-by-character tree/trie-driven lookup. This would be worst case O(n) where n is the length of the longest string in your list. There may well be a Python-callable gadget for this on the net somewhere. Google "Danny Yoo ahocorasick" for a Python-callable solution to a similar but more complex problem. A cheap hack using Python's re: divide the problem according to first character: prefix_dict_match = { 'a': re.compile('alpaca|alligator').match, 'f': re.compile('foobar|foo').match, 'z': re.compile('zoo|zebra').match, } if s and s[0] in prefix_dict_match: match_obj = prefix_dict_match[s[0]](s) else: match_obj = None >> >> Regards, >> Kay > > A start would be: > regexp = "^(" + "|".join(sorted(ls, reverse=True)) + ")" > But the above does not work if you have special characters in your > strings. Paddy, fixing that problem, and "optimising" by removing the redundant ^() metacharacters: regexp = "|".join(map(re.escape, sorted(ls, reverse=True))) Hoping some of this helps, Regards, John From nmm1 at cus.cam.ac.uk Wed Jun 28 03:37:05 2006 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 28 Jun 2006 07:37:05 GMT Subject: Immutability Message-ID: The way that I read it, Python allows only values (and hence types) to be immutable, and not class members. The nearest approach to the latter is to use the name hiding conventions. Is that correct? Regards, Nick Maclaren. From ms at cerenity.org Sat Jun 24 13:30:06 2006 From: ms at cerenity.org (Michael) Date: Sat, 24 Jun 2006 18:30:06 +0100 Subject: Kamaelia 0.4.0 RELEASED - Faster! More Tools! More Examples! More Docs! ; -) References: <4499c9de$0$69378$ed2619ec@ptn-nntp-reader01.plus.net> <449D4E3C.8080508@jessikat.plus.net> Message-ID: <449d763a$0$69376$ed2619ec@ptn-nntp-reader01.plus.net> Robin Becker wrote: > Michael wrote: >> I'm extremely pleased to say - Kamaelia 0.4.0 has been released! > Windows users might see problems with the attempt at importing libc.so.6 > in the Axon Scheduler. > > I changed the lines at line 44 of scheduler.py to something like this [ .. patch .. ] Many thanks! Yes, this issue has also been raised on the Kamaelia mailing list in the past couple of days by Stefan Rank (he had a solution based on using win32.Sleep(0,0) which calls SleepEx[1]). I'm planning on an Axon 1.5.1 release shortly to deal with this issue. [1] http://www-128.ibm.com/developerworks/eserver/library/es-MigratingWin32toLinux.html?ca=dgr-lnxw09CPP2LinuxPower#N10364 I've got three options - I can either take the approach you've suggested, the approach suggested on the list (which is to call win32.Sleep(0,0), or actually remove this code from the scheduler completely. I'm actually most tempted by the final option, largely because this code was added in an earlier release as a way of making Axon & the scheduler more system friendly. Since we've now effectively gone from a busy wait loop to a scheduler that /can/ sleep waiting for threads [2] this means that code can be a lot more system friendly by default. [2] For example, rather than calling select with a timeout of zero in the main thread, it's now called with a timeout of 5s in a thread, which wakes up the scheduler when there's something to do. The pygame code does the same trick... That said, there is still whole chunks of code that busy run (such as the physics simulation, so I'm torn. Do I take the code you put forward, the solution put forward on the the list which I can't really check (since I don't have a windows box to test with right now (I will on Monday though)), or yank it out. I suppose the "correct" thing is to put your solution into Axon 1.5.1 - to get rid of the failure, and then to test Stefan's solution locally. My hesitation with regard to Stefan's solution is simply the fact that I don't tend to do a huge amount of coding under windows, and hence have greater concern there as a result. I'll get a release out with that fix either today or tomorrow, and then roll up Stefan's more detailed fix into the 1.5.2 release along with anything else that crops up over the next few days (hopefully nothing, but you never know). > This allows somethings to run eg > > AxonVisualiser.py --navelgaze > > but I'm not sure if the results are really unaffected by not having a > real yielder. The diagram appears, but doesn't seem to settle down. I don't think the AxonVisualiser would be particularly affected by this - any wobbling you'll see there is probably more down to the simple physics model the visualiser uses not having sufficient dampening for the layout you see. (The physics model was apparently originally written by Matt for a lava lamp simulator, but has turned out to be incredibly useful as a simple layout tool :-) A little bit of manual assistance to spread things out can sometimes help it settle down though :) > whoops, forgot to say thanks as I think this is very nice work You're very welcome. If you have any other suggestions/ideas for improvement they'd be very welcome :-) Personally, I think some of the most fun stuff right now being done by new people with it is coming from 2 of our summer of code students. One, Thomas, is working on 3D components (eg putting pygame components into a PyOpenGL display). The other is doing bittorrent related work, but has also written a webserver and IRC bot - both pretty much from scratch (at the protocol level) over the past month. (The other two students are working on encryption ideas for tools for communications - eg encrypted VoIP type things) Thomas's work (3D) is discussed here: http://thfsoc.blogspot.com/ Ryan's code (Bit Torrent, webserver/client, IRC bot) is sitting here: * http://kamaelia.cvs.sourceforge.net/kamaelia/Sketches/RJL/ Thanks for the bug fix/kind words! Regards, Michael. From tdelaney at avaya.com Mon Jun 5 17:29:28 2006 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Tue, 6 Jun 2006 07:29:28 +1000 Subject: Which exceptions are recommended to me handled? Message-ID: <2773CAC687FD5F4689F526998C7E4E5F074383@au3010avexu1.global.avaya.com> Fredrik Lundh wrote: > Delaney, Timothy (Tim) wrote: > >> The most important problem here is that you've lost the stack trace from >> the original exception. > > which, in many cases, is a good thing, especially if you replace "int" > with a call to some low-level support library. if I call API "foo" to > open a data file of some kind, I'm not necessarily interested in an > "unsubscriptable error" exception on line 129 in barpath.py, nor is it > helping me figure out what's wrong in my program. I always prefer to have the stack trace, since it *is* useful to me to figure out what is wrong with my program (or possibly, the library I'm using). > or do you expose internal implementation details to your end users > too, to make sure they don't lose any information? No - but I do log any errors, with stack traces, and as much useful data as possible. That way it's more likely that I can get a useful bug report (they send the log file). Replacing an exception *may* not get in the way if you're wrapping a single statement in the exception. I can't think of another case where it would not get in the way. Chained exceptions change this somewhat, because you don't lose the original information. Tim Delaney From gbsuar at gmail.com Tue Jun 27 15:57:33 2006 From: gbsuar at gmail.com (Gabriel) Date: Tue, 27 Jun 2006 16:57:33 -0300 Subject: Event objects Threading on Serial Port on Win32 Message-ID: <91906ddf0606271257m5c7cc640k566bf621b448ee13@mail.gmail.com> David: Tube el mismo problema que vos con el hilo del ejemplo de pyserial. Me paso que en Linux andaba bien, obvio, pero tenia un peque?o problemilla en Windows, tambi?n obvio. Lo solucione de la siguiente manera: Asi es el codigo original de la funci?n ComPortThread def ComPortThread(self): """Thread that handles the incomming traffic. Does the basic input transformation (newlines) and generates an SerialRxEvent""" while self.alive.isSet(): #loop while alive event is true if self.ser.inWaiting() != 0: text = self.ser.read() event = SerialRxEvent(self.GetId(), text) self.GetEventHandler().AddPendingEvent(event) solo tiene que agregarle el siguiente bucle antes que nada: while not self.alive.isSet(): pass qued?ndote as? dicha funci?n... def ComPortThread(self): """Thread that handles the incomming traffic. Does the basic input transformation (newlines) and generates an SerialRxEvent""" while not self.alive.isSet(): pass while self.alive.isSet(): #loop while alive event is true if self.ser.inWaiting() != 0: text = self.ser.read() event = SerialRxEvent(self.GetId(), text) self.GetEventHandler().AddPendingEvent(event) y listo... Con eso deber?a andar Espero haber sido ?til -- Gabriel From sekhon.hari at googlemail.com Tue Jun 27 10:54:55 2006 From: sekhon.hari at googlemail.com (Hari Sekhon) Date: Tue, 27 Jun 2006 15:54:55 +0100 Subject: Unbound Local error? How? In-Reply-To: <4gcuanF1m5nl5U1@uni-berlin.de> References: <4gcuanF1m5nl5U1@uni-berlin.de> Message-ID: <44A146BF.9000801@gmail.com> Diez B. Roggisch wrote: > Hari Sekhon wrote: > > >> import re >> re_regexname = re.compile('abc') >> >> ..... >> ..... various function defs >> ..... >> >> def func1(): >> ... >> func2() >> ... >> >> def func2(): >> if re_regexname.match('abc'): >> >> >> if __name__ == '__main__': >> func1() >> > > > The above clearly is not what you have. See the attached version of the > above that works. So - go check for a typo or something like that. > > Diez > ------------------------------------------------------------------------ > > import re > re_regexname = re.compile('abc') > > def func1(): > func2() > > def func2(): > if re_regexname.match('abc'): > print " whohoo!" > > if __name__ == '__main__': > func1() > you're right, it wasn't that, I was trying to locally override a regex object as follows: re_somepattern = re.compile('abc') re_someotherpattern = re.compile('def') def func(): if somecondition: re_somepattern = re_someotherpattern re_somepattern.match('something') not sure how to override this the way I want, it'd be quite messy if I had to do huge if blocks to handle this inside the other code blocks that use this re_somepattern.match() or perhaps I'm going about this all wrong.... -h -------------- next part -------------- An HTML attachment was scrubbed... URL: From jjlee at reportlab.com Fri Jun 23 20:32:47 2006 From: jjlee at reportlab.com (John J. Lee) Date: Sat, 24 Jun 2006 00:32:47 GMT Subject: urllib2 OpenerDirector question on usage. References: <1150892942.290474.185890@p79g2000cwp.googlegroups.com> Message-ID: <87r71ffl5b.fsf@reportlab.com> "Ant" writes: > I am using urllib2 as a part of a web testing tool. One of the things I > am testing is the effect of two different people perforing the same > actions on the website - do they interfer with each other or not. > > So to emulate this, I essentially have the following function: > > def get_opener(): > policy = cookielib.DefaultCookiePolicy(rfc2965=True) > cj = cookielib.CookieJar(policy) > return urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) > > Now am I right in thinking that since I am creating a separate > CookieJar for each opener, then creating two openers and using one for > each hypothetical user will achieve this effect - i.e. sessions will be > separate from each other in the app, since the openers will return > different session cookies back to the server. Yes. As far as cookies are concerned, anyway (and assuming you're not sharing cookies by e.g. loading and saving from a single file, obviously). Presumably the two users will also be separate login users too (i.e. have separate usernames and passwords -- or other credentials). John From piet at cs.uu.nl Fri Jun 2 08:07:23 2006 From: piet at cs.uu.nl (Piet van Oostrum) Date: Fri, 02 Jun 2006 14:07:23 +0200 Subject: New to Python: Do we have the concept of Hash in Python? References: Message-ID: >>>>> "A.M" (AM) wrote: >AM> This is my 1st day that I am seriously diving into Python and I have >AM> to finish this application by the end of today. Are you serious? -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From timr at probo.com Sat Jun 24 01:57:06 2006 From: timr at probo.com (Tim Roberts) Date: Sat, 24 Jun 2006 05:57:06 GMT Subject: Trouble including Python.h References: <1151099498.381282.64590@b68g2000cwa.googlegroups.com> Message-ID: "Marcelo Gosling" wrote: > >Hi, everyone. > >This is on WinXP SP2, with Python 2.4.3 and DJGPP gcc 4.1.0. > >I'm having trouble including Python.h in a C file. The following C >code: > >#include "Python.h" > >int main() >{ > return 0; >} > >when compiled with "gcc -I..\Python2.4\include\", gives more than 1000 >lines of errors, beginning with: > >c:/documents and settings/marcelo.gosling/my >documents/djgpp/bin/as.exe: BFD 2.16.1 assertion fail >../../bfd/coff-i386.c:576 >c:/documents and settings/marcelo.gosling/my >documents/djgpp/tmp/ccACtxBR.s: Assembler messages: >c:/documents and settings/marcelo.gosling/my >documents/djgpp/tmp/ccACtxBR.s:28: Error: cannot represent relocation >type BFD_RELOC_386_PLT32 >In file included from ../../Python2.4/include/Python.h:74, > from example_wrap.c:112: >../../Python2.4/include/pymem.h: In function '__declspec': >../../Python2.4/include/pymem.h:51: error: expected declaration >specifiers before '__declspec' >../../Python2.4/include/pymem.h:52: error: expected declaration >specifiers before '__declspec' __declspec is a Microsoft extension. Are you trying to build the Visual C++ source with gcc? -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From webraviteja at gmail.com Tue Jun 20 18:13:08 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 20 Jun 2006 15:13:08 -0700 Subject: code is data In-Reply-To: <1150772934.314520.165200@p79g2000cwp.googlegroups.com> References: <1150574111.415068.255900@p79g2000cwp.googlegroups.com> <1150606118.456390.262620@y41g2000cwy.googlegroups.com> <1150626424.563673.175060@c74g2000cwc.googlegroups.com> <1150650852.275956.249340@p79g2000cwp.googlegroups.com> <1150658597.272001.171840@r2g2000cwb.googlegroups.com> <1150772934.314520.165200@p79g2000cwp.googlegroups.com> Message-ID: <1150841588.382821.218340@i40g2000cwc.googlegroups.com> > Or... maybe to be more specific, the hard work later on goes into > *code*. If you are enhancing your model, you do so with methods on the > model classes, and those methods don't effect the DSL, they are just > "code". You create some raw XML in the beginning, but quickly it's > just a matter of gluing those pieces together, using functions instead > of DSLs, and that's just "code". > That doesn't look that much better. How do you create it > programmatically? I know how to pass a variable to > CharField(maxlength=200); can I pass a variable to "char length 200" > just as easily? Can I use **kw? Can I read it from a CSV file and > construct the class that way? Maybe, but only by recreating all the > native patterns that I can infer easily looking at the Django class. I am looking at it from the cognitive perspective. You are looking at it from the compiler perspective. I think you are talking about full blown DSLs like SQL which try to be self contained for a given domain. The ones I am referring are only thin layers on Python. > Words are great. Python is light on symbols, and that is good. Agreed. When I came to Python from Perl, I loved the clean syntax. Scalars, arrays, hashes occur too frequently in Perl code that using symbols to denote them causes more noise than cognitive assistance. On the other hand, using symbols to denote an occational special construct is helpful (as in decorators). > Even the Lisps stick to an incredibly homogenous syntax (far more > homogeneous than Python) to make macros feel familiar. Yes! The parser friendly, "everything is a list" syntax does help. I did consider that to be an essential feature to enable dynamic macros. However I changed my mind when I saw Logix macro syntax. > Constrained context is a step backward! How do you add methods? How > do you do looping? How do you write *code*? If you aren't going to > allow those things, then just make a parser and build the structure > from the file, and make it a DSL implemented entirely external to > Python. That's completely okay, though in my experience it's not very > satisfying for something like a model definition (see MiddleKit for an > example of an ORM that doesn't use Python code). I agree that constrained context is a step back in terms flexibility. But it is a strategic step backwards, in this case to trade for representational benefits. The extent of constraints is a judgement call. And proof of utility can only be emperical. However I think that you are seeing my sample differently than I meant it. I did not mean to create a special syntax file that would be parsed as a text file such that it would loose all the benefits of Python. It is just a thin layer over Python code for specific representational benefits. Kay Schluehr does a good job of identifying it as such in his reply. From cdsmith at twu.net Sun Jun 25 13:30:23 2006 From: cdsmith at twu.net (Chris Smith) Date: Sun, 25 Jun 2006 11:30:23 -0600 Subject: Saying "latently-typed language" is making a category mistake References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <449c5b85$0$656$bed64819@news.gradwell.net> Message-ID: Chris Uppal wrote: > It seems to me that most (all ? by definition ??) kinds of reasoning where we > want to invoke the word "type" tend to have a form where we reduce values (and > other things we want to reason about) to equivalence classes[*] w.r.t the > judgements we wish to make, and (usually) enrich that structure with > more-or-less stereotypical rules about which classes are substitutable for > which other ones. So that once we know what "type" something is, we can > short-circuit a load of reasoning based on the language semantics, by > translating into type-land where we already have a much simpler calculus to > guide us to the same answer. > > (Or representative symbols, or... The point is just that we throw away the > details which don't affect the judgements.) One question: is this more specific than simply saying that we use predicate logic? A predicate divides a set into two subsets: those elements for which the predicate is true, and those for which it is false. If we then apply axioms or theorems of the form P(x) -> Q(x), then we are reasoning from an "equivalence class", throwing away the details we don't care about (anything that's irrelevant to the predicate), and applying stereotypical rules (the theorem or axiom). I don't quite understand what you mean by substituting classes. -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation From michael at araneidae.co.uk.invalid Fri Jun 30 17:28:31 2006 From: michael at araneidae.co.uk.invalid (Michael Abbott) Date: Fri, 30 Jun 2006 22:28:31 +0100 Subject: Import bug: Module executed twice when imported! References: Message-ID: In article , Jean-Paul Calderone wrote: > Set __name__ to 'subtest' as it would be if you had really imported > subtest and the import system will correctly name the modules, causing > imptest to be imported only once. Ach. I get it now. From python.list at tim.thechases.com Wed Jun 14 10:45:55 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 14 Jun 2006 09:45:55 -0500 Subject: newbe: tuple In-Reply-To: <9583ed900606140718w2ddf1d9k5257de94c431e165@mail.gmail.com> References: <9583ed900606140718w2ddf1d9k5257de94c431e165@mail.gmail.com> Message-ID: <44902123.7080306@tim.thechases.com> > ip = socket.gethostbyaddr(socket.gethostname()) > > ip then becomes a tuple and takes on three values. I am trying to pull the > value of ip[2] which when printed displays: > ['10.5.100.17']. > > I want this ip that is being returned, but I would like it as a string, > without the [' and ']. Any idea how I would trim this down? Well, what you're getting back is the list of possible IP addresses for your machine. The "['w.x.y.z']" is simply the repr() of that list. A single machine can have multiple IP addresses, so ip[2] returns them as a list. You can either use ip_addresses = ip[2] my_ip_address = ip_addresses[0] # this is the same as # my_ip_address = ip[2][0] # only slightly clearer to read or your code can graciously accomodate them the way they were designed for: for ip_address in ip_addresses: print ip_address This allows you to deal with the possibility that the machine has more than one IP address assigned to it. I'm not at my OpenBSD box, but it's got at least three interfaces in it, and each one has its own IP address assigned to it. I presume that ip[2] would return a list of three strings in its case, something like ['192.168.3.14', '10.3.14.15', '172.16.3.14'] HTH, -tkc From alanmk at hotmail.com Thu Jun 8 10:05:53 2006 From: alanmk at hotmail.com (Alan Kennedy) Date: 8 Jun 2006 07:05:53 -0700 Subject: XML, JSON, or what? References: <1149749530.734275.181300@j55g2000cwa.googlegroups.com> <1149755672.088330.42610@h76g2000cwa.googlegroups.com> Message-ID: <1149775553.462335.143500@h76g2000cwa.googlegroups.com> [Ant] >> I'd favour JSON if the data structures are simple personally. XML is >> comparatively speaking a pain to deal with, where with JSON you can >> simply eval() the data and you have a Python dictionary at your >> disposal. [Steve] > Modulo any security problems that alert and malicious users are able to > inject into your application. Simply using eval() uncritically on > whatever comes down the pipe is a train wreck waiting to happen. Yes, evaling JSON, or any other text coming from the web, is definitely a bad idea. But there's no need for eval: there are safe JSON codecs for python, http://cheeseshop.python.org/pypi?%3Aaction=search&description=json And one for javascript, http://www.json.org/js.html http://www.json.org/json.js And most other languages you're likely to come across. http://www.json.org/ regards, -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From brian at sweetapp.com Mon Jun 26 13:36:10 2006 From: brian at sweetapp.com (Brian Quinlan) Date: Mon, 26 Jun 2006 19:36:10 +0200 Subject: VPW: Talk schedule available Message-ID: <44A01B0A.9090906@sweetapp.com> What's New? =========== The talk schedule for the Vancouver Python Workshop is now available: http://www.vanpyz.org/conference/talkschedule.html This years line-up might be even stronger than in 2004, so check it out! About the Vancouver Python Workshop =================================== The conference will begin with keynote addresses on August 4st by Guido van Rossum [1] and Jim Hugunin [2]. Further talks (and tutorials for beginners) will take place on August 5th and 6th. Ian Cav?n [3] will give the closing address. The Vancouver Python Workshop is a community organized and designed for both the beginner and for the experienced Python programmer with: * tutorials for beginning programmers * advanced lectures for Python experts * case studies of Python in action * after-hours social events * informative keynote speakers * tracks on multimedia, Web development, education and more More information see: http://www.vanpyz.org/conference/ or contact Brian Quinlan at: brian at sweetapp.com Vancouver ========= In addition to the opportunity to learn and socialize with fellow Pythonistas, the Vancouver Python Workshop also gives visitors the opportunity to visit one of the most extraordinary cities in the world [4]. For more information about traveling to Vancouver, see: http://www.vanpyz.org/conference/vancouver.html http://www.tourismvancouver.com http://en.wikipedia.org/wiki/Vancouver Important dates =============== Talk proposals accepted: May 15th to June 15th Early registration (discounted): May 22nd to June 30th Normal registration: from July 1st Keynotes: August 4th Conference and tutorial dates: August 5th and 6th [1] Guido van Rossum (Google) is the inventor of Python and has managed its growth and development for more than a decade. Guido was awarded the Free Software Foundation Award in 2002 and Dr.Dobb's 1999 Excellence in Programming Award. Guido works at Google and spends half of his time on Python. [2] Jim Hugunin (Microsoft) is the creator of numerous innovations that take Python into new application domains. Jim's most recent project, IronPython integrates Python into Microsoft's .NET runtime. Jim's previous project, Jython is Python for the Java runtime and was the second production-quality implementation of Python. Before that, Jim's Numeric Python adapted Python to the needs of number crunching applications. Jim works at Microsoft adapting the .NET runtime to the needs of dynamic languages like Python. [3] Ian Cav?n is the primary developer of the Lowry Digital Images motion picture restoration system. This Python and Zope-based system has been used to restore over 150 motion pictures. Highlights include Citizen Kane, Sunset Boulevard and both the Indiana Jones and Star Wars trilogies. While Ian was Chief Scientist at Lowry Digital, his rack of computers grew from a few Macintoshes on his desktop to over six hundred Macintosh and Linux servers - at one point earning Lowry the title as the second biggest installation of parallel processing Maintoshes in the world. In 2005, Lowry Digital Images was acquired by DTS (the famous movie audio company) and renamed DTS Digital Images. The motion picture restoration system has been discussed in publications as diverse as IEEE Spectrum, USA Today, the BBC NEWS, the New York Times and Apple.com. Ian has been a Python enthusiast since 1999. [4] http://news.bbc.co.uk/2/hi/business/2299119.stm http://edition.cnn.com/2006/BUSINESS/06/15/btn.cities/index.html Cheers, Brian From flaus.a at wanadoo.fr Sat Jun 17 18:00:40 2006 From: flaus.a at wanadoo.fr (flaus.a at wanadoo.fr) Date: 17 Jun 2006 15:00:40 -0700 Subject: Standard Yes / No Windows Dialog box creation Message-ID: <1150581640.385143.83410@y41g2000cwy.googlegroups.com> I found a way to create "Open File" or "Open Folder" windows dialog boxes, but not to create an easier Yes / No dialog box... Maybe someone has a solution for this? From fredrik at pythonware.com Fri Jun 16 15:24:35 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 16 Jun 2006 21:24:35 +0200 Subject: Problem on win xp and run time error In-Reply-To: References: Message-ID: Michele Petrazzo wrote: > just found in this moment that my applications stop to work with win xp > and receive this error: > > """ > This application has requested the Runtime to terminate it in an unusual > way. Please contact the application's support team for more information. > """ > > (Note that the same application [python source code + py2exe] with > python 2.3.x work well!) > > With a little google search I found that this is a win xp sp2 problem > *without* apparently solution :( > > http://support.microsoft.com/kb/884538/en-us > > I see that the page says: > """ > This problem may occur when you use the /GR and the /MD compiler switches > """ hint 1: the use of "may" in that sentence is intentional. hint 2: python 2.4 wasn't built with Visual C++ 6.0 (but python 2.3 was) hint 3: on Windows, this message is displayed when the "abort" function is called (including when an assert fails): http://msdn2.microsoft.com/en-us/library/k089yyh0.aspx the python interpreter will call abort() when it stumbles upon a fatal error (Py_FatalError), or when an internal assertion fails. when this happens, the program will print a "Fatal Python error" message to both stderr and the debug console before it calls abort. From steve at holdenweb.com Thu Jun 15 12:33:43 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 15 Jun 2006 17:33:43 +0100 Subject: GUI in Python using wxGlade In-Reply-To: <1150386216.365531.157690@g10g2000cwb.googlegroups.com> References: <1150380251.279150.73620@u72g2000cwu.googlegroups.com> <1150386216.365531.157690@g10g2000cwb.googlegroups.com> Message-ID: diffuser78 at gmail.com wrote: > I am pasting my code. I created a small little GUI without any > functionality as of yet. I wanted to ask few questions on that. > [lots of code ...] > > If I click on any of the items of the File Menu, say I click on "Open > config File", I want a new windows to come up. > > My questions is when I create a new Frame/Windows in wxGlade, will it > be wxFrame or wxMDI Frame......which one should I choose and why ? > > I am not completely aware of all the small tools that wxGlade gives and > how to place them. > > > Any kind of help is greatly appreciated. > As I already said I'm a bit to busy to help with specifics right now. Two places you might go for help: 1: http://www.holdenweb.com/PyConTX2006/wxPythonIntro.pdf The introductory tutorial I gave at PyCon TX 2006 2: Email to wxPython-users-help at lists.wxwidgets.org There's a fairly friendly community who will take your code as evidence you are trying to help yourself and explain the basics as necessary. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From sambo at void.com Thu Jun 15 00:53:52 2006 From: sambo at void.com (Sambo) Date: Thu, 15 Jun 2006 00:53:52 -0400 Subject: split with "*" in string and ljust() puzzles In-Reply-To: <1150343803.705236.292650@r2g2000cwb.googlegroups.com> References: <1150330131.466322.135350@i40g2000cwc.googlegroups.com> <1150343803.705236.292650@r2g2000cwb.googlegroups.com> Message-ID: George Sakkis wrote: > Serge Orlov wrote: > > >>Sambo wrote: >> >>>I have just (finally) realized that it is splitting and removing >>>on single space but that seams useless, and split items >>>1 and 2 are empty strings not spaces?? >> >>What is useless for you is worth $1,000,000 for somebody else ;) >>If you have comma separated list '1,,2'.split(',') naturally returns >>['1', '', '2']. I think you can get what you want with a simple regexp. > > > No need for regexp in this case, just use None to specify one or more > whitespace chars as delimiter: line.split(None,3) > > George > AHA! Thank You. From pc at p-cos.net Fri Jun 23 16:23:44 2006 From: pc at p-cos.net (Pascal Costanza) Date: Fri, 23 Jun 2006 22:23:44 +0200 Subject: Saying "latently-typed language" is making a category mistake In-Reply-To: <449c1f4c$0$662$bed64819@news.gradwell.net> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <86Qmg.10725$o4.1907@newsread2.news.pas.earthlink.net> <4g251pF1knc6tU1@individual.net> <4g28s6F1k9npnU1@individual.net> <4g2e1bF1kmiteU1@individual.net> <449c1f4c$0$662$bed64819@news.gradwell.net> Message-ID: <4g30ugF1l571tU1@individual.net> Chris Uppal wrote: > Pascal Costanza wrote: > >> Sorry, obviously I was far from being clear. ACL2 is not >> Turing-complete. All iterations must be expressed in terms of >> well-founded recursion. > > How expressive does that end up being for real problems ? I mean obviously in > some sense it's crippling, but how much of a restiction would that be for > non-accademic programming. I don't know your definition of "real problem" ;), but ACL2 is definitely used in industrial settings. See http://www.cs.utexas.edu/users/moore/publications/how-to-prove-thms/intro-to-acl2.pdf Pascal -- 3rd European Lisp Workshop July 3 - Nantes, France - co-located with ECOOP 2006 http://lisp-ecoop06.bknr.net/ From mystilleef at gmail.com Wed Jun 7 04:03:59 2006 From: mystilleef at gmail.com (mystilleef) Date: 7 Jun 2006 01:03:59 -0700 Subject: what are you using python language for? References: Message-ID: <1149667439.765508.146830@i40g2000cwc.googlegroups.com> Desktop application development From hdante at gmail.com Sun Jun 18 16:54:54 2006 From: hdante at gmail.com (hdante) Date: 18 Jun 2006 13:54:54 -0700 Subject: Simple script to make .png thumbnails from .zip archive... References: <1150660266.413889.217280@c74g2000cwc.googlegroups.com> Message-ID: <1150664094.345764.280030@u72g2000cwu.googlegroups.com> Hi, I don't know zipfile by heart, but python official documentation is always good ( docs.python.org ). You need a loop in the file list like this: for file in zip: process(file) Unfortunatelly, there are too many ways to create a thumbnail from an image. I'll cite one, using the "python image" external module, that I've found to be very easy: import Image def process(file): try: image = Image.open(file) image.thumbnail ((128,128), Image.ANTIALIAS) image.save (file + '.thumb.png') except: print 'Skipping file', file Links: http://docs.python.org/lib/lib.html - Python Library Reference http://www.pythonware.com/library/pil/handbook/image.htm - The Image Module K P S wrote: > Hi. > I'm looking for a small script that will take a .zip archive and pull > the first .jpg from the archive and convert it to a .png. > > The reason for this is I want to have tuhmbnails for these archives in > nautilus under gnome. I would like something similar to the following > code, which will pull a thumbnail from an openoffice.org (oasis) > document. What I want is a little more involved, I guess, since I > don't know the name of the file (for the zip.read command), and I need > to convert the file from .jpg to .png once I get it. Any help would be > appreciated. Including a pointer to a web page of a manual with > examples. :-) > > #!/usr/bin/python > > import zipfile > import sys > import gnomevfs > > inURL=gnomevfs.get_local_path_from_uri(sys.argv[1]) > outURL=sys.argv[2] > > zip=zipfile.ZipFile(inURL,mode="r") > picture=zip.read("Thumbnails/thumbnail.png") > thumbnail=open(outURL,"w") > thumbnail.write(picture) > thumbnail.write("/n") > zip.close() > thumbnail.close() From newz at bearfruit.org Mon Jun 26 12:01:27 2006 From: newz at bearfruit.org (Matthew Nuzum) Date: Mon, 26 Jun 2006 11:01:27 -0500 Subject: Pygame.draw challenge is over! In-Reply-To: <200606261053.50740.richard@pyweek.org> References: <200606261053.50740.richard@pyweek.org> Message-ID: Hey, just a quick note... when I visit http://pyweek.org I get a message that the site is not configured. www.pyweek.org works as expected. When I received this e-mail my e-mail client made pyweek.org clickable which is how I noticed the problem. On 6/25/06, richard at pyweek.org wrote: > It was quite successful too! Download the submissions from the pyweek.org > site: > > http://media.pyweek.org/static/pgd-200606.zip > > Congratulations to all who participated! > > > Richard > > -- > Visit the PyWeek website: > http://www.pyweek.org/ > -- > http://mail.python.org/mailman/listinfo/python-announce-list > > Support the Python Software Foundation: > http://www.python.org/psf/donations.html > -- Matthew Nuzum www.bearfruit.org From johnjsal at NOSPAMgmail.com Thu Jun 15 09:50:07 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 15 Jun 2006 13:50:07 GMT Subject: Python is fun (useless social thread) ;-) Message-ID: I have to say, I'm having a very enjoyable time learning and using Python. I spent a year playing around with C# and I feel like I learned/know less about it than I do about Python from just the past couple of months. Of course it's easier, but there's just something about it that makes me keep coming back to it and try to think of new ways to use it. Lately I've started to branch away from the "core" Python and I started learning internet/cgi programming, then a little with mysqldb (which involved a detour into learning some MySQL query commands), and now I'm fiddling with wxPython. My next goal is PyGame. So out of curiosity, I'm just wondering how everyone else came to learn it. If you feel like responding, I'll ask my questions for easy quoting: Did you have to learn it for a job? Or did you just like what you saw and decided to learn it for fun? Also, how did you go about learning it? (i.e., like I described above, I started with the main stuff then moved on to the different available frameworks) Was there any necessity in the specifics you learned, or did you just dabble in something (e.g. wxPython) for fun? Are there still some things you feel you need to learn or improve? Additional comments/complains here: :) From juergen.huber at kirchnersoft.com Fri Jun 30 06:47:44 2006 From: juergen.huber at kirchnersoft.com (Juergen Huber) Date: Fri, 30 Jun 2006 12:47:44 +0200 Subject: delete first line in a file References: <44a4f854$0$12942$91cee783@newsreader02.highway.telekom.at> Message-ID: <44a50151$0$12935$91cee783@newsreader02.highway.telekom.at> Fredrik Lundh wrote: > Juergen Huber wrote: > >> i am a dummy user in python and new in this programming language and >> so there will be questions, that?s for you no problem! i never have >> before programmed in any language! sorry for this! i hope you will >> help me, that i also could the basics in this language! and later >> many more, so i hope ! :) >> >> the first question for me in this newsgroup will be the follow one: >> >> - is there a way to delete in a csv-file the first line?! > > in general, modern file systems can only remove and add stuff at the > end of a > file, so the only way to do this is to rewrite the entire file. > > (you can either load the entire file, fix it up, and write it out > again, or copy the file to a new file, skipping the first line or > row). > > ok...i thought as much, that i have to copy this file! how will i do that?! how will i fix this file => delete the first line?! with which commands could i do that?! thanks From jon+usenet at unequivocal.co.uk Wed Jun 21 06:26:53 2006 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: 21 Jun 2006 10:26:53 GMT Subject: What's the best way to wrap a whole script in try..except? References: Message-ID: In article , Hari Sekhon wrote: > I want to wrap a whole script in try ... except. What is the best way of > doing this? You could do this maybe: import sys def excepthook(exc_type, exc_value, tb): import modules_needed_to_notify_exception ... sys.excepthook = excepthook import modules_needed_by_script ... From dgparks at gmail.com Sun Jun 18 12:21:56 2006 From: dgparks at gmail.com (Devon G. Parks) Date: 18 Jun 2006 09:21:56 -0700 Subject: Tetris Message-ID: <1150647716.792057.283860@u72g2000cwu.googlegroups.com> I've been searching google and this group for a while now for a good tutorial on making a Tetris-style game in Python. I hear Tetris is a good starting point, and although I am fairly new to programming I think I would learn best if I had some code to experiment with because without a tutorial I have no idea where to start. If you know of a tutorial that is specific to this game please let me know where to find it. From rschroev_nospam_ml at fastmail.fm Sun Jun 18 08:06:03 2006 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sun, 18 Jun 2006 12:06:03 GMT Subject: Which compiler will Python 2.5 / Windows (Intel) be built with? In-Reply-To: <4494953f$1@nntp0.pdx.net> References: <1150367139.495114.148550@g10g2000cwb.googlegroups.com> <44917535$1@nntp0.pdx.net> <1150391891.130185.4640@f6g2000cwb.googlegroups.com> <4492414C.10505@v.loewis.de> <1150444191.618761.22810@c74g2000cwc.googlegroups.com> <4494424f$1@nntp0.pdx.net> <4494953f$1@nntp0.pdx.net> Message-ID: Scott David Daniels schreef: > I musunderstood you. I thought you were advocating that Python itself > be built on gcc, obviating many compiler access issues. That wouldn't > work because gcc cannot, by itself (as I understand it) get to all the > nooks and crannies a windows developer may need to traverse. I know I > just repeated my argument here against a strawman, but that was really > for other readers, not for you. I'm not actively advocating it since I realize I don't know enough about all the pros and cons, but yes, I would like for Python and other open source projects to use gcc even on Windows. It gives me an uneasy feeling when you can't use the source (apart from just reading it) of open source projects without depending on the whims of a third party. As an example, look what happened to the Linux kernel and Bitkeeper. One might argue that Microsoft is not really a third party since the whole Windows platform is made by them, but the problems are the same: as far as I understand, Visual Studio Express 2003 is no longer available, and the 2005 version is not binary compatible. In my case, I'm even unable to uninstall any modern Microsoft compiler since AFAICT they all require XP SP2 and I'm stuck with SP1 on my laptop since SP2 conflicts with the touchpad driver resulting in Windows blocking on booting, but that only effects me (I hope) and is something for a whole other rant. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From onurb at xiludom.gro Wed Jun 7 05:10:14 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 07 Jun 2006 11:10:14 +0200 Subject: Writing to a certain line? In-Reply-To: <1149630414.246008.270720@f6g2000cwb.googlegroups.com> References: <1149576072.168354.14470@f6g2000cwb.googlegroups.com> <44854184$0$29904$636a55ce@news.free.fr> <1149630414.246008.270720@f6g2000cwb.googlegroups.com> Message-ID: <448697f7$0$10260$626a54ce@news.free.fr> Tommy B wrote: > bruno at modulix wrote: (snip) >>import os >>old = open("/path/to/file.txt", "r") >>new = open("/path/to/new.txt", "w") >>for line in old: >> if line.strip() == "Bob 62" >> line = line.replace("62", "66") >> new.write(line) >>old.close() >>new.close() >>os.rename("/path/to/new.txt", "/path/to/file.txt") >> (snip) > > Umm... I tried using this method and it froze. Infiinite loop, I'm > guessing. Wrong guess - unless, as Fredrik suggested, you have an infinite disk with an infinite file on it. If so, please share with, we would be *very* interested !-) Seriously : a for loop can only become an infinite loop if the iterable is infinite. AFAIK, file objects (created from regular files on a standard filesystem) are definitively not infinite. Problem is elsewhere. But since you prefered to guess - instead of providing relevant informations - we just can't help. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From fredrik at pythonware.com Wed Jun 21 11:29:59 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 21 Jun 2006 17:29:59 +0200 Subject: memory error with zipfile module In-Reply-To: References: <446e07ab$0$12795$636a55ce@news.free.fr> <1148072514.207383.26370@j55g2000cwa.googlegroups.com> <446e51e6$0$6831$636a55ce@news.free.fr> Message-ID: Hari Sekhon wrote: > Is it me or is having to use os.system() all the time symtomatic of a > deficiency/things which are missing from python as a language? it's you. From intemelion at libero.it Wed Jun 14 06:36:56 2006 From: intemelion at libero.it (Quacker) Date: 14 Jun 2006 03:36:56 -0700 Subject: Quacker Message-ID: <1150281416.125684.301290@p79g2000cwp.googlegroups.com> Very interesting! From wahab at chemie.uni-halle.de Sun Jun 18 11:46:43 2006 From: wahab at chemie.uni-halle.de (Mirco Wahab) Date: Sun, 18 Jun 2006 17:46:43 +0200 Subject: Extracting values from text file In-Reply-To: <20060618133459.2a56f781.randhol+valid_for_reply_from_news@pvv.org> References: <20060617232543.9a0338fb.randhol+valid_for_reply_from_news@pvv.org> <20060618133459.2a56f781.randhol+valid_for_reply_from_news@pvv.org> Message-ID: Thus spoke Preben Randhol (on 2006-06-18 13:34): > On Sun, 18 Jun 2006 10:54:01 +0200 > Mirco Wahab wrote: >> - no DWIM-ism (do what I mean) on 'value' addition > > But you don't add two values. you add two strings. If you > want numbers you must convert the strings. Why? At least - if its obvious, what I want. > Yes, but how can Python know that you want to add to > numbers and not concate two strings? The programming language should make some rules regarding its operators and their meaning. Compare: # want to add NUMBERS ('1' + '1.1111'/1.1111 = 2.1111) # # in python in perl # a1 = int( '1' ) $a1 = '1'; a1 += float( '1.1111' ) $a1 += '1.1111'; print a1 print $a1; a2 = int( '1' ) $a2 = '1'; a2 += 1.1111 $a2 += 1.1111; print a2 print $a2; # want to add strings ('1' . '1.1111'/1.1111 = 11.1111) # b1 = '1' $b1 = '1'; b1 += '1.1111'; $b1 .= '1.1111'; print b1 print $b1; b2 = '1' $b2 = '1'; b2 += str( 1.1111 ) $b2 .= 1.1111; print b2 print $b2; You see the picture? Pythons designer made the same mistake as the Java/Javascript designer - they use the _same_ operator (+) for number _addition_ and string _concatenation_, which is, imho, cumbersome. If you have an operator with meaning "add numbers" (+) and one for "add strings" (.), the language could then do the obvious for you. Why would one go from C/C++ to "dynamical typed" things, if he has to be so explicit on easy things? Of course, you will get along with it, you 'learn' the corresponding 'python-phrases' that do specific things, you get used to it. But if you come, like me, from elsewhere, there is sometimes something to rant on ;-) I really try to get into it (Python), but I'm, in such cases, more or less shocked - and try express that , but I'm not interested in 'language supremacy' discussions and the like. BTW.: what exactly did you try to solve? What would be a 'complete example' where the parser has to chew on? Regards Mirco From xivulon at gmail.com Wed Jun 7 14:03:11 2006 From: xivulon at gmail.com (ago) Date: 7 Jun 2006 11:03:11 -0700 Subject: Matplotlib 0.87.2 incompatible with numpy 0.9.8 Message-ID: <1149703391.093311.36440@f6g2000cwb.googlegroups.com> I was not able to make matplotlib 0.87.2 work with numpy 0.9.8 (there is an error in multiarray.pyd that crashes python). I have noticed that there is a new version 0.87.3, but I was waiting for the windows egg/exe version for python 2.4. I tried to compile from sources with little luck. Does the version 0.87.3 fix the problem? When will the egg/exe be released? From sonal.patankar at 3i-infotech.com Mon Jun 12 02:16:59 2006 From: sonal.patankar at 3i-infotech.com (sonal.patankar at 3i-infotech.com) Date: 11 Jun 2006 23:16:59 -0700 Subject: How to link foreign keys & primary keys using python? In-Reply-To: <1149862607.820399.224260@c74g2000cwc.googlegroups.com> References: <1149856668.055162.209650@u72g2000cwu.googlegroups.com> <1149862607.820399.224260@c74g2000cwc.googlegroups.com> Message-ID: <1150093019.057974.29650@j55g2000cwa.googlegroups.com> MTD wrote: > Your post is confusing. Here is my advice: investigate the use of > dictionaries. Dictionaries can allow you to define data in the form { > key:data }, e.g. > > { area_code : area_data } > > { (area_code,school_code) : school_data } > > { (school_code,student_code) : student_data } Thanx Mr. Marc... I am surely investigating the dictionaries... but the problem is that I have to use the existing code... and thas what is creating problems for me... :( From mumarathe at gmail.com Tue Jun 6 14:32:20 2006 From: mumarathe at gmail.com (Manish Marathe) Date: Tue, 6 Jun 2006 11:32:20 -0700 Subject: problem using logging module in python Message-ID: <7c8a9a970606061132m2f1bd5d7q5bfacb15b8baab60@mail.gmail.com> Python Experts every where!! I am having a problem using the logging utility in Python using the logging module from the std. lib. I have written a class SPFLogger which actually should be creating a new logger if one already does not exist. I have given the class I wrote in the end. The problem I am facing is: I am creating 2/3 object of this class SPFLogger in 2/3 other classes of mine having different logger name and the handler they will be using. Although the logs are going in a single file which means the logging.getLogger(name) function is getting the same logger which was created earlier and not creating a new logger with new handler. Eventhough the logs are going in a single file the loggers names used are different which I am passing as an argument. So for example if I do this first in the init method of class A: obj1 = SPFLogger ("A", "A.log") logger1 = obj.getLogger() logger1.info("Message A") ----> Goes in A.log with logger name A now class A calls class B so in the init method of class B I have: obj2 = SPFLogger ("B", "B.log") logger2 = obj.getLogger() logger2.info("Message B") ----> still goes in A.log with logger name B .. Is there something that needs to be done to handle this? Below is the code for SPFLogger class -- Manish Marathe SpikeSource, Inc. http://developer.spikesource.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From onurb at xiludom.gro Sat Jun 24 08:26:20 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Sat, 24 Jun 2006 14:26:20 +0200 Subject: Python web server In-Reply-To: <1151146727.087240.264800@r2g2000cwb.googlegroups.com> References: <1151146727.087240.264800@r2g2000cwb.googlegroups.com> Message-ID: <449d2f6d$0$1628$636a55ce@news.free.fr> arvind wrote: > When I run the script Which one ? And how ? > on server, Which one ? > only HTML part gets executed. HTML executed ??? > But the python code appears as it is on the screen in the text format. > How to run the CGI script on web server using Python2.4.3? Depends on your web server. But there's very probably all the needed documention somewhere, and I'm pretty confident google will find it. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From vasudevram at gmail.com Thu Jun 8 13:55:52 2006 From: vasudevram at gmail.com (vasudevram) Date: 8 Jun 2006 10:55:52 -0700 Subject: Request new feature suggestions for my PDF conversion toolkit - xtopdf Message-ID: <1149789349.974338.242080@i39g2000cwa.googlegroups.com> Hi all, I had created this open source project - xtopdf - http://sourceforge.net/projects/xtopdf - some time ago. It's a toolkit to help with conversion of other file formats to PDF. The current tools in xtopdf are available as both end-user command-line tools, and as a library (in both procedural and object-oriented versions) for use by developers in their own apps. Its written in Python (needs V2.2 or higher) and uses the open source version of the Reportlab toolkit (http://www.reportlab.org - needs V1.17 or higher) for the PDF generation. Initially I had included support for plain text and .DBF (XBase) files as input formats. The current version of xtopdf is 1.0 and is in a stable state. Recently I've added support for CSV and ODBC as input formats (still to be uploaded to the site, after some cleanup, refactoring and testing). I also have a few other related enhancements / extensions which I'm working on, and will mention on this group after getting at least a proof-of-concept working. Meanwhile, please give your suggestions for additional features or input formats for xtopdf. I can't promise to implement all (or any) of them - depends on the feasibility, how easy or difficult I find it, and so on, but will consider all reasonable suggestions seriously and see if I can implement some of them. I'd also welcome comments on the xtopdf code itself, from people who know Python well. I wrote it soon after learning a little Python, so it may not be written in a very Pythonic or idiomatic style. As I go along, I plan to incorporate more Pythonic style of doing things into the code, including stuff like new-style classes, generators/yield, etc. - anything that makes sense and seems appropriate, not just for the sake of adding it. I'll create a Credits page in the xtopdf tarball and site, and give due credit to anyone who suggests features, input formats, or code improvements (or reports bugs:-). Thanks! ---------------------------------------------------------------------------?------------------------------------------------------ Vasudev Ram ---------------------------------------------------------------------------?------------------------------------------------------ Personal site: http://www.geocities.com/vasudevram Open source projects: http://sourceforge.net/projects/xtopdf - tools for conversion of other file formats to PDF http://sourceforge.net/projects/xtopdf - tools for conversion of other file formats to RTF Profile and way to contact me: http://www.gojobby.com/Jobby/Resume/?user=454 Blog on software innovation: http://jugad.livejournal.com ---------------------------------------------------------------------------?------------------------------------------------------ From antroy at gmail.com Thu Jun 8 12:11:10 2006 From: antroy at gmail.com (Ant) Date: 8 Jun 2006 09:11:10 -0700 Subject: XML, JSON, or what? In-Reply-To: <1149775553.462335.143500@h76g2000cwa.googlegroups.com> References: <1149749530.734275.181300@j55g2000cwa.googlegroups.com> <1149755672.088330.42610@h76g2000cwa.googlegroups.com> <1149775553.462335.143500@h76g2000cwa.googlegroups.com> Message-ID: <1149783070.457652.150850@u72g2000cwu.googlegroups.com> > Yes, evaling JSON, or any other text coming from the web, is definitely > a bad idea. > > But there's no need for eval: there are safe JSON codecs for python, Fair enough. And I should imagine that the codecs are still much faster and easier to use than XML for the same purpose. For my purposes, the JSON is pushed out to the web from our Java web-app, and eval'd in the test scripts which screen scrape the JSON structure from the web page - no danger in this case for me. But yes - I wouldn't be eval'ing random 'JSON' code from the web :-) From 1gentle.giant at gmail.com Sun Jun 25 03:55:59 2006 From: 1gentle.giant at gmail.com (1gentle.giant at gmail.com) Date: 25 Jun 2006 00:55:59 -0700 Subject: Make Microsoft angry! Message-ID: <1151222159.511522.181810@c74g2000cwc.googlegroups.com> Make Microsoft angry! How? Click here and find out: http://xthost.info/browser/index.htm From fuzzyman at gmail.com Mon Jun 5 10:19:39 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 5 Jun 2006 07:19:39 -0700 Subject: Python to C converter In-Reply-To: <1149513389.922653.272900@u72g2000cwu.googlegroups.com> References: <1149506038.843016.298470@c74g2000cwc.googlegroups.com> <1149513389.922653.272900@u72g2000cwu.googlegroups.com> Message-ID: <1149517179.095435.266060@j55g2000cwa.googlegroups.com> gene tani wrote: > Rene Pijlman wrote: > > praveenkumar.117 at gmail.com: > > >I have an application return in python. I want this to be > > >converted to C. > > > > http://www.python.org/doc/faq/general/#can-python-be-compiled-to-machine-code-c-or-some-other-language > > > > http://pyfaq.infogami.com/can-python-be-compiled-to-machine-code-c-or-some-other-language > shd probably mention Shedskin, boost, ctypes, any others? The PyPy LLVM backend will compile Python code to C. Also Pyrex can do a bit more than just integrate C with Python, AFAIK it *can* compile some Python to C - although with very little speed advantage if you don't use native C types. Fuzzyman http://www.voidspace.org.uk/python/index.shtml From rbonvall at gmail.com Sun Jun 18 15:54:57 2006 From: rbonvall at gmail.com (Roberto Bonvallet) Date: Sun, 18 Jun 2006 15:54:57 -0400 Subject: code is data In-Reply-To: <1150606118.456390.262620@y41g2000cwy.googlegroups.com> References: <1150574111.415068.255900@p79g2000cwp.googlegroups.com> <1150606118.456390.262620@y41g2000cwy.googlegroups.com> Message-ID: <1908cb6b0606181254q2299637dy78666021be3e45d8@mail.gmail.com> Ravi Teja said: > I *like* 1..5 (ada, ruby) instead of range(5). If I had macros, I would > have done it myself for *my* code. You can write your own preprocessor to handle things like that. -- Roberto Bonvallet From dnew at san.rr.com Thu Jun 22 12:06:56 2006 From: dnew at san.rr.com (Darren New) Date: Thu, 22 Jun 2006 16:06:56 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150892256.591282.43880@u72g2000cwu.googlegroups.com> Message-ID: John W. Kennedy wrote: > 360-family assembler, yes. 8086-family assembler, not so much. And Burroughs B-series, not at all. There was one "ADD" instruction, and it looked at the data in the addresses to determine whether to add ints or floats. :-) -- Darren New / San Diego, CA, USA (PST) My Bath Fu is strong, as I have studied under the Showerin' Monks. From maric at aristote.info Thu Jun 22 06:24:08 2006 From: maric at aristote.info (Maric Michaud) Date: Thu, 22 Jun 2006 12:24:08 +0200 Subject: How to generate all permutations of a string? In-Reply-To: <53564.10.209.4.1.1150963627.squirrel@10.105.1.3> References: <53564.10.209.4.1.1150963627.squirrel@10.105.1.3> Message-ID: <200606221224.09340.maric@aristote.info> Le Jeudi 22 Juin 2006 10:07, Girish Sahani a ?crit?: > Hi guys, > I want to generate all permutations of a string. I've managed to > generate all cyclic permutations. Please help :) > Here is mine, maybe more versatile : def permute(iterable) : if len(iterable) == 1 : yield iterable else : next = permute(iterable[1:]) for i in next : if isinstance(iterable[0], basestring) : elt = iterable.__class__(iterable[0]) else : elt = iterable.__class__((iterable[0],)) for j, k in enumerate(i) : yield i[0:j] + elt + i[j:] yield i + elt In [2]: list(permute((1, 2, 3))) Out[2]: [(1, 2, 3), (2, 1, 3), (2, 3, 1), (1, 3, 2), (3, 1, 2), (3, 2, 1)] In [3]: list(permute('abc')) Out[3]: ['abc', 'bac', 'bca', 'acb', 'cab', 'cba'] In [4]: list(permute('aba')) Out[4]: ['aba', 'baa', 'baa', 'aab', 'aab', 'aba'] In [5]: set(permute('aba')) Out[5]: set(['aba', 'aab', 'baa']) In [6]: list(permute([1, 3, 3])) Out[6]: [[1, 3, 3], [3, 1, 3], [3, 3, 1], [1, 3, 3], [3, 1, 3], [3, 3, 1]] In [7]: set(permute([1, 3, 3])) # warning --------------------------------------------------------------------------- exceptions.TypeError Traceback (most recent call last) /home/maric/ TypeError: list objects are unhashable In [8]: set(permute((1, 3, 3))) Out[8]: set([(3, 3, 1), (3, 1, 3), (1, 3, 3)]) regards, -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From riteshsarraf at gmail.com Fri Jun 30 04:53:54 2006 From: riteshsarraf at gmail.com (Ritesh Raj Sarraf) Date: 30 Jun 2006 01:53:54 -0700 Subject: optparse multiple arguments In-Reply-To: <1151657119.837675.213700@p79g2000cwp.googlegroups.com> References: <1151657119.837675.213700@p79g2000cwp.googlegroups.com> Message-ID: <1151657634.348133.291340@x69g2000cwx.googlegroups.com> Ritesh Raj Sarraf wrote: > Hi, > > I'm having some minor problems with optparse. I'm just worried that > someone shouldn't say that multiple argument feature isn't implemented > in optpartse. > > How to tackle multiple arguments to an option ? > As far as I dug, I've found that >1 arguments are being ignored. > > parser.add_option("", "--my-option", dest="my_option", action="store", > type="string") > > Now if someone uses it as: > ./foo --my-option a b c > > I want somehow to store all the three arguments but my_option stores > only "a" while ignoring b and c. > I just noticed that the args variable is holding values b and c. the args variables comes from: (options, args) = parser.parse_args() I guess I only need to figure out now is why args isn't storing argument "a" also... Ritesh From victimorcrime at yahoo.com Fri Jun 2 18:41:53 2006 From: victimorcrime at yahoo.com (RJ) Date: Fri, 2 Jun 2006 18:41:53 -0400 Subject: beginner code problem Message-ID: <2006060218415316807-victimorcrime@yahoocom> I'm trying to teach myself Python (probably running into the old dog new tricks issue) and I'm trying to start with the very basics to get a handle on them. I'm trying to write code to get the computer to flip a coin 100 times and give me the output of how many times heads and tails. After solving a few syntax errors I seem to be stuck in an endless loop and have to kill python. A few times I would get it to print 'heads 0 (or 1) times and tails 1 (or 0) times' 100 times. Here's the code I wrote: import random flip = random.randrange(2) heads = 0 tails = 0 count = 0 while count < 100: if flip == 0: heads += 1 else: tails += 1 count += 1 print "The coin landed on heads", heads, 'times ' \ "and tails", tails, 'times' From sreeram at tachyontech.net Mon Jun 19 23:14:36 2006 From: sreeram at tachyontech.net (K.S.Sreeram) Date: Tue, 20 Jun 2006 08:44:36 +0530 Subject: [OT] code is data In-Reply-To: References: <44965f53$0$12743$636a55ce@news.free.fr> <4496b29f$0$27412$626a54ce@news.free.fr> Message-ID: <4497681C.3030900@tachyontech.net> Fredrik Lundh wrote: > because lots of people know how to describe XML transformations, and > there are plenty of tools that implement such transformations efficiently ? > > why would XML be inefficient ? XML Transformations (XSLT) would *certainly* be an overkill here. They've invented a whole new declarative programming language, and we certainly don't need that when we've got Python! :) XML by itself feels completely out of place in this context. What we need is, just a flexible, easy to manipulate, in-memory tree structure (AST) for the Python source. Regards Sreeram -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 260 bytes Desc: OpenPGP digital signature URL: From pc at p-cos.net Fri Jun 23 07:39:53 2006 From: pc at p-cos.net (Pascal Costanza) Date: Fri, 23 Jun 2006 13:39:53 +0200 Subject: What is a type error? In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <7i3mg.204167$8W1.155367@fe1.news.blueyonder.co.uk> <44992e6c$2$664$bed64819@news.gradwell.net> <%Igmg.464974$xt.353729@fe3.news.blueyonder.co.uk> <4fv0v3F1kipa6U1@individual.net> Message-ID: <4g2289F1kv8htU1@individual.net> Chris Smith wrote: > Pascal Costanza wrote: >> What about this: You get a type error when the program attempts to >> invoke an operation on values that are not appropriate for this operation. >> >> Examples: adding numbers to strings; determining the string-length of a >> number; applying a function on the wrong number of parameters; applying >> a non-function; accessing an array with out-of-bound indexes; etc. > > Hmm. I'm afraid I'm going to be picky here. I think you need to > clarify what is meant by "appropriate". No, I cannot be a lot clearer here. What operations are appropriate for what values largely depends on the intentions of a programmer. Adding a number to a string is inappropriate, no matter how a program behaves when this actually occurs (whether it continues to execute the operation blindly, throws a continuable exception, or just gets stuck). > If you mean "the operation will > not complete successfully" as I suspect you do, then we're closer... No, we're not. You're giving a purely technical definition here, that may or may not relate to the programmer's (or "designer's") understanding of the domain. Pascal -- 3rd European Lisp Workshop July 3 - Nantes, France - co-located with ECOOP 2006 http://lisp-ecoop06.bknr.net/ From michael.f.ellis at gmail.com Thu Jun 1 16:40:34 2006 From: michael.f.ellis at gmail.com (michael.f.ellis at gmail.com) Date: 1 Jun 2006 13:40:34 -0700 Subject: An oddity in list comparison and element assignment In-Reply-To: <447f152f@nntp0.pdx.net> References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> <447f152f@nntp0.pdx.net> Message-ID: <1149194434.528648.148860@u72g2000cwu.googlegroups.com> Yes (unless I was testing the assertion that the second envelope did not contain counterfeits of the first) Scott David Daniels wrote: > Would you say that envelope containing five $100 bills is equal to > an envelope containing five $100 bills with different serial numbers? From gene.tani at gmail.com Thu Jun 8 09:22:53 2006 From: gene.tani at gmail.com (gene tani) Date: 8 Jun 2006 06:22:53 -0700 Subject: Extended zip() for lists In-Reply-To: References: Message-ID: <1149772973.297794.68720@i39g2000cwa.googlegroups.com> Florian Reiser wrote: > Hello, > > I have 4 lists: a, b, c and d > Out of this 4 lists I want to build a table (e.g. list of lists): > > a|b|c|d > --------------------------- > a1|b1|c1|d1 > a1|b2| |d2 > > You see: the lists are not equally sized. > Is there a command which fills up the shorter lists with blanks? > Like an enhanced zip() command, maybe? > map(None, list1, list2, list3) http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/410687 From davecook at nowhere.net Sun Jun 25 05:03:16 2006 From: davecook at nowhere.net (Dave Cook) Date: Sun, 25 Jun 2006 09:03:16 GMT Subject: Entity GUI tool? References: Message-ID: On 2006-06-22, icebear wrote: > Ubuntu Drake comes with or allows you to install something called "entity" > which sounds like it ought to be the world's ultimate Python GUI tool. Looks like it only supports gtk 1.2. Dave Cook From wesleyhenwood at hotmail.com Tue Jun 27 23:29:30 2006 From: wesleyhenwood at hotmail.com (Wesley Henwood) Date: 27 Jun 2006 20:29:30 -0700 Subject: import chains Message-ID: <1151465370.186805.21070@x69g2000cwx.googlegroups.com> I have a program which uses a combination of MFC multithreading, python multithreading, and extended and embedded python. This works: >From the C++ app, call python script A within a MFC thread. Script A imports module 2 which imports module 3. Module 3 is a c++ extension, the code for which is within in C++ app. This does not: Everthing the same, only Script A imports module 1 which imports module 2 which imports module 3. I get very strange behavior - the script thread seems to give an exit code and yet still be running. When the thread exists for sure I get another exit signal. In short, it is exibiting unpredictable behavior. It seems that it can handle the double import. But the triple import is too much. However no error messages are produced. I have scanned comp.lang.python and the net and there are many posts about nesting/import problems. They all deal with slighly different cases but I think they are perhaps related. Is this basically the same issue? From digitalorganics at gmail.com Mon Jun 26 10:30:57 2006 From: digitalorganics at gmail.com (digitalorganics at gmail.com) Date: 26 Jun 2006 07:30:57 -0700 Subject: Get List of Classes Message-ID: <1151332257.564563.139040@u72g2000cwu.googlegroups.com> Is there a method or attribute I can use to get a list of classes defined or in-use within my python program? I tried using pyclbr and readmodule but for reason that is dogslow. Thanks in advance.... DigiO From bigodines at gmail.com Mon Jun 5 09:58:42 2006 From: bigodines at gmail.com (bigodines) Date: 5 Jun 2006 06:58:42 -0700 Subject: Simple question In-Reply-To: <1149514734.312783.122520@i40g2000cwc.googlegroups.com> References: <1149514734.312783.122520@i40g2000cwc.googlegroups.com> Message-ID: <1149515922.260243.225040@i40g2000cwc.googlegroups.com> SOLVED, thanks for your time. :) bigodines wrote: > Hi guys! > > I'm a complete newbie in Python and I'm trying to make a small software > to watch my network. It will be a simple snmpget report for a specific > machine. > > I would like to make a small program in python to be runed with > crontrab that will store the whole output in a txt file. I know its not > a big deal, but i've no background in python :) > > basically i would like to know how to: > > 1 - execute a command in the server > 2 - write the whole output into a file. > > best regards, > Matheus From Geibel at Vision-Comp.com Wed Jun 21 12:17:46 2006 From: Geibel at Vision-Comp.com (Roland Geibel) Date: Wed, 21 Jun 2006 18:17:46 +0200 Subject: Porting python to a TI Processor (C64xx) Message-ID: Dear all. We want to make python run on DSP processors (C64xx family of TI). I've already tried to ask mickey at vanille.de (about his "Python for arm-Linux"), but didn't get an answer so far. Neither could I find it in the Python tree at sourceforge. Any hints welcome Roland Geibel Geibel at vision-comp.com From faulkner612 at comcast.net Tue Jun 20 19:29:08 2006 From: faulkner612 at comcast.net (faulkner) Date: 20 Jun 2006 16:29:08 -0700 Subject: Problem Py2exe pygtk and Pil In-Reply-To: <44987851$0$29874$636a55ce@news.free.fr> References: <44987851$0$29874$636a55ce@news.free.fr> Message-ID: <1150846148.550072.194350@m73g2000cwd.googlegroups.com> read the py2exe docs. py2exe should put everything a new user should need in the dist directory. if it doesn't, copy the libraries [be they .pyc or .pyd or .dll] that py2exe missed into dist. i know for a fact that py2exe is intelligent with the gtk libraries, so check if the PIL libraries are in the dist directory. thomas carpentier wrote: > Hello, > > I have created a program with a GUI ( glade). In this script I call the > Python Imaging Library. > > I have developped this program onto linux, but il would like export it > on Windows, however I have a problem with py2exe. If the new user has > not python and library(PIL, GLADE) installed, it doesn't work. I don't > know how integrate library into my setup. > > Thank you for your help. > > Thomas From kydavis77 at gmail.com Mon Jun 26 13:37:53 2006 From: kydavis77 at gmail.com (kydavis77 at gmail.com) Date: 26 Jun 2006 10:37:53 -0700 Subject: Beginner Programmer Question In-Reply-To: <1151343383.139891.219270@u72g2000cwu.googlegroups.com> References: <1151342733.742416.180370@r2g2000cwb.googlegroups.com> <1151343383.139891.219270@u72g2000cwu.googlegroups.com> Message-ID: <1151343473.722970.251360@r2g2000cwb.googlegroups.com> kydavis77 at gmail.com wrote: > Claudio Grondi wrote: > > kydavis77 at gmail.com wrote: > > > I am doing alot of reading and trying to teach myself how to program. > > > I can not figure out how to make "Write a program that continually > > > reads in numbers from the user and adds them together until the sum > > > reaches 100." this work. If someone could show me the correct code so i > > > can learn from that it would be much appreciated. Thanks > > > > > Isn't it your homework? > > Why can't you figure it out? > > What have you tried? > > > > Claudio > > I am doing alot of reading, and the problem didnt come with an answer. > I dont understand how to get it to continually input numbers and add > all those together #Add up to 100 program #What number are you adding up to? bigone = 100 number = input("Whats the first number?") number2 = input ("Whats the second number?") nu3 = number+number2 while nu3 < bigone: print ("Not there yet, next number please") print "Finally there!" thats what i thought maybe it was...but after the first two numbers it just continually scrolls on the screen with finally there From jeremiah.bess at gmail.com Fri Jun 23 18:16:01 2006 From: jeremiah.bess at gmail.com (Network Ninja) Date: 23 Jun 2006 15:16:01 -0700 Subject: Clearing pythonwin environment In-Reply-To: <449c4071$1@nntp0.pdx.net> References: <1151012168.838694.235610@c74g2000cwc.googlegroups.com> <449c4071$1@nntp0.pdx.net> Message-ID: <1151100961.103470.141790@i40g2000cwc.googlegroups.com> Scott David Daniels wrote: > keep = set(['__builtins__', '__doc__', '__name__', > 'pywin', 'keep', 'item', 'globs']) # Faster to test > globs = globals() > for item in dir(): > if item not in keep: > del globs[item] > del globs, item This did not work, it gave an error saying "NameError: name 'globs' is not defined". However, Steven's del globals()[item] did the trick perfectly. Thanks a million for the replies, both of you. So can you explain the [] after globals()? How does that work? The help docs don't mention anything about that in the function. From thorley at gmail.com Fri Jun 30 12:27:36 2006 From: thorley at gmail.com (thorley at gmail.com) Date: 30 Jun 2006 09:27:36 -0700 Subject: python for windows internet filter / firewall In-Reply-To: References: <1151590961.464723.249360@p79g2000cwp.googlegroups.com> Message-ID: <1151684855.966099.297980@i40g2000cwc.googlegroups.com> Thanks for a detailed reply. > Firewall and filter are two things totally separated! Sorry for being to general. I want to create a filter like dansgaurdian. I was thinking of it also as a firewall because is restricts traffic on a port based on content, but you're correct, they aren't the same thing at all. > Take a look at wipfw (wipfw.sf.net) that do what you want Thanks for the tip I'll check it out. > And for windows. Why? All that work with networking (and not only that) work better with > *nix OS! Yes you are correct again. I am infact working on linux right now, and it is my os of choice. How ever I need to deploy this on M$win :( > win32COM for do what? My knowledge of COM is miniscule, but I assumed it has a low level interface for packet filtering. > You can do it in not so difficult manner: > Take twisted and its proxy class, make some outline code (for filter the > pages) and enjoy! (work also on win) Proxy would be an easy way, but I wanted to do it at a lower level. Thanks again. --matthew From bj_666 at gmx.net Mon Jun 19 11:46:03 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 19 Jun 2006 17:46:03 +0200 Subject: crawlers in python with graphing? References: Message-ID: In , bryan rasmussen wrote: > It should hopefully be as high level as Wget, not download the pages > but just follow the links, and output graphs. How do you get at the links without downloading the page!? Ciao, Marc 'BlackJack' Rintsch From feel.energetic at gmail.com Fri Jun 2 06:21:07 2006 From: feel.energetic at gmail.com (feel_energetic) Date: 2 Jun 2006 03:21:07 -0700 Subject: how to define a static field of a given class In-Reply-To: <448009b7$0$12763$636a55ce@news.free.fr> References: <1149239221.045268.6170@g10g2000cwb.googlegroups.com> <448009b7$0$12763$636a55ce@news.free.fr> Message-ID: <1149243667.724683.80090@g10g2000cwb.googlegroups.com> thanks for all of your replies I did this before I posted the subject but got (NameError: global name 'startTime' is not defined) the most important thing i didn't know is "the static field should be referred with the qualifier ClassName" it's a little different from C++ :) (the static field can directly referred without the ClassName) From nmm1 at cus.cam.ac.uk Wed Jun 21 03:38:05 2006 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 21 Jun 2006 07:38:05 GMT Subject: Iteration over recursion? References: <1150808045.539887.291180@i40g2000cwc.googlegroups.com> <1150873424.345733.165730@m73g2000cwd.googlegroups.com> Message-ID: In article <1150873424.345733.165730 at m73g2000cwd.googlegroups.com>, "Kay Schluehr" writes: |> |> You might use a separate prime generator to produce prime factors. The |> factorize algorithm becomes quite simple and configurable by prime |> generators. For demonstration purposes I use the eratosthenes sieve. That is a good point. The differences between iteration and recursion are well-understood (by some people, at least), but the difference between those two and generators is not. I have mixed feelings whether they are a good idea or not, largely because I have never seen a language that provides a declaration to guarantee that a generator is 'clean'. And an unclean generator (e.g. one with side-effects) is a most revolting object, from a software engineering (including validation) point of view. One good example of this is streaming input (I/O). Traditional, clean streaming input can be implemented efficiently and with good error diagnostics. The unclean C- and POSIX-like streaming input can't be, or at least only one of the two can be provided at once. Regards, Nick Maclaren. From peter.mosley at talk21.com Mon Jun 12 08:07:23 2006 From: peter.mosley at talk21.com (peter) Date: 12 Jun 2006 05:07:23 -0700 Subject: PIL problem after installation References: <1149954516.785869.160700@i40g2000cwc.googlegroups.com> <1150093465.553355.50410@f14g2000cwb.googlegroups.com> Message-ID: <1150114043.051948.134390@f14g2000cwb.googlegroups.com> I had similar problems a couple of months back when I was teaching myself Tkinter and PIL. I wrote up my experiences here:- http://www.aqzj33.dsl.pipex.com/how_i_learned_tkinter/contents.htm If you look at the section on Images you will see how I eventually solved it (with bucket loads of help from this forum) Good luck Peter From apardon at forel.vub.ac.be Fri Jun 16 06:08:35 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 16 Jun 2006 10:08:35 GMT Subject: Which compiler will Python 2.5 / Windows (Intel) be built with? References: <1150367139.495114.148550@g10g2000cwb.googlegroups.com> <44917535$1@nntp0.pdx.net> <1150391891.130185.4640@f6g2000cwb.googlegroups.com> <4491b9e1$1@nntp0.pdx.net> <1150406005.948538.188950@h76g2000cwa.googlegroups.com> Message-ID: Op 2006-06-15, Fredrik Lundh schreef : > meyer at mesw.de wrote: > >> I'm not sure how that backs the point you made. Infact, you're saying >> that people accepted that Python 2.4 was compiled with VS2003 because >> VC6 could not longer be bought. How is that different from the current >> situation where the VS2003 toolkit cannot longer be downloaded and it >> is at least becoming increasingly difficult to buy versions of VS2003? >> You also seem to imply that there is a large group of people that want >> you to stay with VS2003 for compiling Python 2.5. > > what part of "Python 2.4 is built with VC2003 and everyone who's ever > built Windows stuff for Python 2.4 already has it" do you have trouble > understanding ? What about new people who would be interested in building Window stuff for Python? If I understand the situation correctly, people who want to take up, writing C-extentions on windows now, may not be able to do so, because they can't find a compatible compilor for the moment. -- Antoon Pardon From steve at holdenweb.com Mon Jun 5 07:44:20 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 05 Jun 2006 12:44:20 +0100 Subject: An oddity in list comparison and element assignment In-Reply-To: <1149186735.650036.62670@i39g2000cwa.googlegroups.com> References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> <127u81kdf70ch8d@corp.supernews.com> <1149186735.650036.62670@i39g2000cwa.googlegroups.com> Message-ID: <44841914.7080701@holdenweb.com> michael.f.ellis at gmail.com wrote: > Yes. You stated it quite precisely. I believe l1==l2 should always > return True and l1==l3 should always be False. (unless l3 is reassigned > as l3=l1). Your idea of a separate operator for 'all elements have > numerically equal values at the moment of comparision' is a good one. > For want of a better name, it could be called DeepCopyEquality(a,b) and > would be equivalent to a byte-by-byte comparison of two distinct > regions in memory created by a deep copies of a and b. > I suspect the word you are grasping for is "isomorphic", since your complaint appears to be that two non-isomorphic lists can compare as equal. He then later said: > Considering the number of new programmers who get bit by automatic > coercion, I wish Dennis Ritchie had made some different choices when he > designed C. But then I doubt he ever dreamed it would become so wildly > successful. > So he designed it badly because he didn't anticipate its ubiquity? Give me a break. Every language designer regrets some of their decisions: it's almost a given for design of any kind, since one makes compromises without realising that they are compromises until usage reveals them. > Being a curmudgeon purist I'd actually prefer it if Python raised a > TypeError on float vs integer comparisons. > That's taking purity just a little too far for my taste. Looking at how this thread developed (if such an unedifying process can be described as "development") I hope you'll phrase future posts a little more carefully. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From cito at online.de Mon Jun 5 08:37:14 2006 From: cito at online.de (Christoph Zwerschke) Date: Mon, 05 Jun 2006 14:37:14 +0200 Subject: finding file In-Reply-To: <1149510738.569437.242050@f6g2000cwb.googlegroups.com> References: <1149510738.569437.242050@f6g2000cwb.googlegroups.com> Message-ID: su wrote: > could someone help me on how can i restrict > my code to search the file in the current dir only Use os.listdir(). -- Christoph From marc.t.davies at gmail.com Thu Jun 8 06:34:29 2006 From: marc.t.davies at gmail.com (MTD) Date: 8 Jun 2006 03:34:29 -0700 Subject: How to generate k+1 length strings from a list of k length strings? In-Reply-To: References: Message-ID: <1149762869.692025.164140@c74g2000cwc.googlegroups.com> Try this: def k2k1(string1, string2): for c in string1: string2 = string2.replace(c,"",1) if len(string2) == 1: string1 += string2 return string1 print k2k1("abcd", "ebcd") From thn at mail.utexas.edu Tue Jun 6 11:28:44 2006 From: thn at mail.utexas.edu (Thomas Nelson) Date: 6 Jun 2006 08:28:44 -0700 Subject: calling functions style question In-Reply-To: <1149607410.719487.213110@h76g2000cwa.googlegroups.com> References: <1149607410.719487.213110@h76g2000cwa.googlegroups.com> Message-ID: <1149607724.239875.241070@h76g2000cwa.googlegroups.com> The difference becomes clear when you import your program into another program (or the command line python editor). __name__!='__main__' when you import, so the functions will not be called if they're inside the block. This is why you see this block so often at the end of scripts; so that the script runs its main functions when called as a standalone program, but you can also import the code and do something with it without setting off those functions. THN Brian wrote: > I just have a basic style question here. Suppose you have the program: > > def foo1(): > do something > > def foo2() > do something else > > Assume that you want to call these functions at execution. Is it more > proper to call them directly like: > > foo1() > foo2() > > or in an if __name__ == "__main__": ? > > Both will execute when the script is called directly, I was just > wondering if there is a preference, and what the pros and cons to each > method were. > > Thanks, > Brian From dnew at san.rr.com Sun Jun 25 20:08:25 2006 From: dnew at san.rr.com (Darren New) Date: Mon, 26 Jun 2006 00:08:25 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150908952.804184.218990@r2g2000cwb.googlegroups.com> <1150991074.705803.211570@m73g2000cwd.googlegroups.com> <1151244628.566060.40500@p79g2000cwp.googlegroups.com> <1151252226.104247.62960@b68g2000cwa.googlegroups.com> Message-ID: Gabriel Dos Reis wrote: > I would suggest you give more thoughts to the claims made in > http://www.seas.upenn.edu/~sweirich/types/archive/1999-2003/msg00298.html I'm not sure I understand this. Looking at "Example 2", where C is claimed to be "C-safe", he makes two points that I disagree with. First, he says Unix misimplements the operations semantics of C. It seems more like Unix simply changes the transition system such that programs which access unmapped memory are terminal. Second, he says that he hasn't seen a formal definition of C which provides precide operational semantics. However, the language standard itself specified numerous "undefined" results from operations such as accessing unallocated memory, or even pointing pointers to unallocated memory. So unless he wants to modify the C standard to indicate what should happen in such situations, I'm not sure why he thinks it's "safe" by his definition. There is no one "q" that a "p" goes to based on the language. He's confusing language with particular implementations. He seems to be saying "C is safe, oh, except for all the parts of the language that are undefined and therefore unsafe. But if you just clearly defined every part of C, it would be safe." It would also seem to be the case that one could not say that a program "p" is either terminal or not, as that would rely on input, right? gets() is "safe" as long as you don't read more than the buffer you allocated. What's the difference between "safe" and "well-defined semantics"? (Ignoring for the moment things like two threads modifying the same memory at the same time and other such hard-to-define situations?) -- Darren New / San Diego, CA, USA (PST) Native Americans used every part of the buffalo, including the wings. From serge.orlov at gmail.com Wed Jun 21 19:24:20 2006 From: serge.orlov at gmail.com (Serge Orlov) Date: Wed, 21 Jun 2006 16:24:20 -0700 Subject: Python at compile - possible to add to PYTHONPATH In-Reply-To: <1150930496.559207.73320@m73g2000cwd.googlegroups.com> References: <1150930496.559207.73320@m73g2000cwd.googlegroups.com> Message-ID: On 21 Jun 2006 15:54:56 -0700, rh0dium wrote: > Hi all, > > Can anyone help me out. I would like to have python automatically look > in a path for modules similar to editing the PYTHONPATH but do it at > compile time so every user doesn't have to do this.. > > Soo... > > I want to add /foo/bar to the PYTHONPATH build so I don't have to add > it later on. Is there a way to do this? You don't need to recompile python. Just change sys.path before all import statements. From heikki at osafoundation.org Fri Jun 2 15:18:23 2006 From: heikki at osafoundation.org (Heikki Toivonen) Date: Fri, 02 Jun 2006 12:18:23 -0700 Subject: ANN: M2Crypto 0.16beta1 Message-ID: I am happy to announce the first beta of the M2Crypto 0.16 release. Please give these bits a spin and report any problems. I will be making new betas once a week (or more often if needed) until regressions are fixed. I expect the final 0.16 bits will be out by the end of June 2006. Highlights: - All known memory leaks fixed - All known regressions fixed - Added --openssl option to build command which can be used to specify where OpenSSL is installed, by Matt Rodriguez - ECDSA signatures and ECDH key agreement, requires OpenSSL 0.9.8+, by Arno Bakker - Added sha224, sha256, sha384 and sha512, by Larry Bugbee - Added serialNumber, SN, surname, GN and givenName fields to X509_Name, by Martin Paljak - And various other improvements and bugfixes, see CHANGES file Requirements: * Python 2.3 or newer * OpenSSL 0.9.7 or newer o Some optional new features will require OpenSSL 0.9.8 or newer * SWIG 1.3.24 or newer Get it while it's hot from M2Crypto homepage: http://wiki.osafoundation.org/bin/view/Projects/MeTooCrypto -- Heikki Toivonen From osv at javad.com Thu Jun 1 06:53:32 2006 From: osv at javad.com (Sergei Organov) Date: Thu, 01 Jun 2006 14:53:32 +0400 Subject: Watching serial port activity. References: <1148955873.334359.47860@u72g2000cwu.googlegroups.com> <127ncut3mpadoc5@corp.supernews.com> <1148962019.355956.124420@38g2000cwa.googlegroups.com> <127oj612scnl8a0@corp.supernews.com> <1148998176.105881.156310@g10g2000cwb.googlegroups.com> <127olia8pnldl90@corp.supernews.com> <127rccueg04oie5@corp.supernews.com> Message-ID: Grant Edwards writes: > On 2006-05-31, Sergei Organov wrote: > >> It seems that sniff on a real tty device could be implemented using the >> same technique strace uses to intercept and show syscalls, though I'm >> not aware of any sniffer application that does it. > > Using strace you can indeed trace read/write calls on user-specified > file descriptors. I've actually meant to take strace in source code and modify it for particular purpose. The fact that it almost can do it in unmodified form is quite impressive though. > Figuring out which file descriptors to trace is the tricky part. Provided I have port name, say, /dev/ttyM0, and have running application: osv at osv ~$ fuser /dev/ttyM0 /dev/ttyM0: 5134 osv at osv ~$ ls -l /proc/5134/fd | grep /dev/ttyM0 lrwx------ 1 osv osv 64 2006-05-29 15:33 8 -> /dev/ttyM0 osv at osv ~$ so I need to track fd #8 of the process with pid 5134. Guess one can attach to a running process as gdb does it. Alternatively, if the process to be sniffed sporadically opens/closes the port at run-time, it is required to track open()/close() syscalls as well as read()/write() ones, I think. Overall, seems not that trivial but doable. -- Sergei. From greg.ewing at canterbury.ac.nz Tue Jun 27 19:56:55 2006 From: greg.ewing at canterbury.ac.nz (Greg Ewing) Date: Wed, 28 Jun 2006 11:56:55 +1200 Subject: [Pyrex] pyrex functions to replace a method (Re: replace a method in class: how?) In-Reply-To: <44A11564.9030009@bryant.edu> References: <44A06A6B.6010200@bryant.edu> <44A11564.9030009@bryant.edu> Message-ID: <44A1C5C7.4090007@canterbury.ac.nz> Brian Blais wrote: > I have found a very similar problem trying to replace a method using a > function defined in pyrex. Functions defined in Pyrex are C-implemented functions, which don't trigger the method binding magic when you access them through a class. The same thing happens if you try to use a built-in function as a method. What *should* work is to define the method inside a class in Pyrex (plain class, not extension type) and extract it out of the class's __dict__. That's because Pyrex pre-wraps a function defined in a class in an unbound method object before putting it in the class. I have suggested that builtin functions should be given the same method-binding behaviour as interpreted functions. The idea wasn't rejected out of hand, but I don't think anything has been done about it yet. -- Greg From cowie.rob at gmail.com Mon Jun 19 15:55:53 2006 From: cowie.rob at gmail.com (Rob Cowie) Date: 19 Jun 2006 12:55:53 -0700 Subject: Calling every method of an object from __init__ Message-ID: <1150746953.156851.92820@r2g2000cwb.googlegroups.com> Hi all, Is there a simple way to call every method of an object from its __init__()? For example, given the following class, what would I replace the comment line in __init__() with to result in both methods being called? I understand that I could just call each method by name but I'm looking for a mechanism to avoid this. class Foo(object): def __init__(self): #call all methods here def test(self): print 'The test method' def hello(self): print 'Hello user' Thanks, Rob C From claird at lairds.us Wed Jun 14 12:48:57 2006 From: claird at lairds.us (Cameron Laird) Date: Wed, 14 Jun 2006 16:48:57 +0000 Subject: convert floats to their 4 byte representation References: <1150297093.191223.152330@c74g2000cwc.googlegroups.com> <44902b7c$1@nntp0.pdx.net> <1150301012.403651.198440@g10g2000cwb.googlegroups.com> Message-ID: In article <1150301012.403651.198440 at g10g2000cwb.googlegroups.com>, godavemon wrote: >I've been a member for a while but I had no idea how helpful this form >is. I had a one hour meeting and when I came back there were 4 >replies. Thanks for your help! > > >Scott David Daniels wrote: >> godavemon wrote: >> > I need to take floats and dump out their 4 byte hex representation. . . . >> import array >> >> def eights(number, swap=False): >> data = array.array('d', [number]) >> if swap: >> data.byteswap() >> return ' '.join(hexx(ord(char), 2) for char in data.tostring()) >> >> def fours(number, swap=False): >> data = array.array('f', [number]) >> if swap: >> data.byteswap() >> return ' '.join(hexx(ord(char), 2) for char in data.tostring()) . . . I want to reinforce and refine a bit of what's been written. comp.lang.python *is* unusually useful. Note, by the way, that, among the four replies you first found, ALL FOUR were accurate and pertinent. In a world where a discussion group is better-than- average when *one* out of four of its replies is trustworthy, clp rates high. Please be aware that "their ... hex representation" is ambiguous. At the very least, you need to be sensitive--as perhaps you already are--to the possibility that a float's (or double's) representation in memory is hardware-dependent (and, depending on what you mean, potentially dependent on the version of Python implementation). If you pursue this area, you'll want to be on the look-out for "IEEE 754", the standard which ... well, is most standard . From eval.apply at gmail.com Mon Jun 19 15:56:29 2006 From: eval.apply at gmail.com (Joe Marshall) Date: 19 Jun 2006 12:56:29 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> Message-ID: <1150746989.489702.26290@i40g2000cwc.googlegroups.com> Chris Smith wrote: > > Knowing that it'll cause a lot of strenuous objection, I'll nevertheless > interject my plea not to abuse the word "type" with a phrase like > "dynamically typed". Allow me to strenuously object. The static typing community has its own set of terminology and that's fine. However, we Lisp hackers are not used to this terminology. It confuses us. *We* know what we mean by `dynamically typed', and we suspect *you* do, too. > This cleaner terminology eliminates a lot of confusion. Hah! Look at the archives. > This isn't just a matter of preference in terminology. No? > If types DON'T mean a compile-time method for proving the > absence of certain program behaviors, then they don't mean anything at > all. Nonsense. From claird at lairds.us Sun Jun 25 12:49:30 2006 From: claird at lairds.us (Cameron Laird) Date: Sun, 25 Jun 2006 16:49:30 +0000 Subject: error with string (beginner) References: <1151240297.725336.305960@i40g2000cwc.googlegroups.com> Message-ID: In article <1151240297.725336.305960 at i40g2000cwc.googlegroups.com>, Alex Pavluck wrote: >Hello. I get the following error with the following code. Is there >something wrong with my Python installation? > >code: >import types >something = input("Enter something and I will tell you the type: ") > >if type(something) is types.IntType: > print "you entered an integer" >elif type(something) is types.StringType: > print "you entered a string" > >error: >String: Source for exec/eval is unavailable > There are several things wrong--'least three distinct ones, by my count. What version of Python do you believe you're using? What input do you enter at the "Enter something ..." prompt? I suspect you're going to have happier results all around when you replace "input" with "raw_input". I encourage you to read the documenta- tion for each. From ask at me Tue Jun 20 20:13:13 2006 From: ask at me (alf) Date: Tue, 20 Jun 2006 20:13:13 -0400 Subject: dynamic inheritance In-Reply-To: <44892d3a$0$5594$626a54ce@news.free.fr> References: <_IidnWMwvOnfRBXZnZ2dneKdnZydnZ2d@comcast.com> <44892d3a$0$5594$626a54ce@news.free.fr> Message-ID: <_sCdnYfsraI5AQXZnZ2dnUVZ_o-dnZ2d@comcast.com> bruno at modulix wrote: > > *But* you'd probably better tell us about the problem you're trying to > solve. Since in Python, inheritance is mostly about implementation (ie: > not needed for subtyping), your problem would probably be best solved > with composition/delegation, for which Python offers a good support: > I did not think about any particular problem, just thought it would be cool to abstract out the base class. In fact you can do that in C++ (to some extend) using templates and parameterizing the base class. regards, a. From bignose+hates-spam at benfinney.id.au Thu Jun 15 21:32:45 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 16 Jun 2006 11:32:45 +1000 Subject: Need Help comparing dates References: <1150419503.224684.320550@c74g2000cwc.googlegroups.com> <87hd2llwpf.fsf@benfinney.id.au> Message-ID: <87d5d9lwaq.fsf@benfinney.id.au> Ben Finney writes: > colincolehour at gmail.com writes: > > I am new to Python and am working on my first program. I am trying > > to compare a date I found on a website to todays date. The problem I > > have is the website only shows 3 letter month name and the date. > > Example: Jun 15 > > The 'datetime' module in the standard library will do the job of > creating date objects that can be compared. > > > > Construct a date from arbitrary values with datetime.date(), get the > current date with datetime.date.today(). The objects returned by those > functions can be compared directly. > > As for how to get from a string representation to a date object, > you're now talking about parsing strings to extract date/time > information. This isn't provided in the standard library As soon as I sent this, I remembered that the standard library *does* provide datetime parsing: So your task now consists of: - get a date object of today's date using datetime.date.today() - define a format for parsing a string date - get a struct_time object from time.strptime() feeding it the string and the format - make any assumptions about missing pieces of the date (e.g. the year) - get a date object by feeding values to datetime.date() - compare the two date objects -- \ "Hey Homer! You're late for English!" "Pff! English, who needs | `\ that? I'm never going to England!" -- Barney & Homer, _The | _o__) Simpsons_ | Ben Finney From python at hope.cz Tue Jun 6 08:50:44 2006 From: python at hope.cz (Lad) Date: 6 Jun 2006 05:50:44 -0700 Subject: How to add few pictures into one In-Reply-To: References: <1149511692.796038.155930@c74g2000cwc.googlegroups.com> <1149517433.880564.128350@h76g2000cwa.googlegroups.com> <1149529269.228019.120480@u72g2000cwu.googlegroups.com> <1149573892.526072.6770@i39g2000cwa.googlegroups.com> <1149580572.739202.110940@y43g2000cwc.googlegroups.com> <1149587802.895959.37210@f6g2000cwb.googlegroups.com> <1149591704.231602.158740@c74g2000cwc.googlegroups.com> Message-ID: <1149598244.477257.58950@c74g2000cwc.googlegroups.com> Fredrik Lundh wrote: > Lad wrote: > > > I really would like to have ALL pictures in one file. > > So, what would be the easiest/best way how to do that? > > do you want to look at the images as a slideshow or as a collage? > > As a collage only From duncan.booth at invalid.invalid Mon Jun 5 10:27:04 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 5 Jun 2006 14:27:04 GMT Subject: strategy pattern and non-public virtual functions References: <1149516464.874257.194030@j55g2000cwa.googlegroups.com> Message-ID: wrote: > The users of the derived classes are unable to bypass this base class > function. Just to be clear, the users of the derived C++ classes *are* able to bypass the base class function and call f_() directly, they just have to be prepared to twist the rules somewhat. I know: I've been in the situation where there was absolutely no other way to get the job done other than to call a private method in a class supplied in a library which I couldn't change. To do the same in Python you simply make a rule 'dont call f_ directly' and you get effectively the same thing: users can call f_ if they really want, but they are breaking the rules if they do. The difference in Python is that you don't have to go to such extremes to break the rules. The Pythonic way to do it: class B(object): def f(self): self._f() class D(B): def _f(self): pass d = D() d.f() Calling a method with a single leading underscore from outside the implementation of the class is generally accepted in Python to be 'breaking the rules' and therefore something only to be done by consenting adults in the full knowledge of the consquences of their actions. From uval at rz.uni-karlsruhe.de Fri Jun 23 12:22:57 2006 From: uval at rz.uni-karlsruhe.de (Daniel Schüle) Date: Fri, 23 Jun 2006 18:22:57 +0200 Subject: re question References: Message-ID: "Paul McGuire" schrieb im Newsbeitrag news:QeUmg.28197$vU.25824 at tornado.texas.rr.com... > Shouldn't > > End Package Test; > > read: > > End Package Test123; > > > -- Paul yes it must :) my mistake thx From shejo284 at gmail.com Sun Jun 25 12:06:18 2006 From: shejo284 at gmail.com (Sheldon) Date: 25 Jun 2006 09:06:18 -0700 Subject: array manipulation without for loops Message-ID: <1151251578.463273.24370@m73g2000cwd.googlegroups.com> Hi, I have two arrays that are of the same dimension but having 3 different values: 255, 1 or 2. I would like to set all the positions in both arrays having 255 to be equal, i.e., where one array has 255, I set the same elements in the other array to 255 and visa versa. Does anyone know how to do this without using for loops? Sincerely, Sheldon From samaloth at gmail.com Mon Jun 19 17:02:19 2006 From: samaloth at gmail.com (Saint Malo) Date: 19 Jun 2006 14:02:19 -0700 Subject: Newbie Question Message-ID: <1150750938.973049.114780@y41g2000cwy.googlegroups.com> I am new to programming, and I've chosen python to start with. I wrote a simple program that asks several questions and assings each one of them a variable via raw_input command. I then combined all the variables into one like this a = b + c + d. After this I wrote these values to a file. What I want to do now is be able to search through the file for any data in there. Is this possible? From mikeisgreat at gmail.com Sat Jun 3 14:05:23 2006 From: mikeisgreat at gmail.com (mikeisgreat at gmail.com) Date: 3 Jun 2006 11:05:23 -0700 Subject: restarting multiple instances of apache - newbie Q Message-ID: <1149357923.926548.96230@y43g2000cwc.googlegroups.com> hi all, i am new to python programming, so thanks for your patience in advance. I have a small script that I am working on that i want to restart multiple instances of apaches on our developers servers. We have about 25 developers each with their own apache. import sys, os try: file = open("users.dat", "r") except IOError, message: print >> sys.stderr, "File could not be opened:", message sys.exit( 1 ) fdata = file.xreadlines() for data in fdata: fields = data.split("_") # print "USER: " + fields[0] + " ADDRESS: " + fields[1].strip("\n") print '/etc/init.d/httpd_' + fields[0] + ' restart each users apache is named 'httpd_{user}' I am not sure how to do this cleanly other than in a shell script. I want to restart the apache and wait until complete to restart the next users apache. Any advice is appreciated .. again, thanks for your time. -mike From kkylheku at gmail.com Sun Jun 4 03:26:38 2006 From: kkylheku at gmail.com (Kaz Kylheku) Date: 4 Jun 2006 00:26:38 -0700 Subject: Python less error-prone than Java In-Reply-To: References: Message-ID: <1149405998.784652.68510@y43g2000cwc.googlegroups.com> Christoph Zwerschke wrote: > You will often hear that for reasons of fault minimization, you should > use a programming language with strict typing: > http://turing.une.edu.au/~comp284/Lectures/Lecture_18/lecture/node1.html Quoting from that web page: "A programming language with strict typing and run-time checking should be used." This doesn't prescribe latent or manifest typing, only that there be type checking. There is no question that for reliability, it is necessary to have type checking, whether at run time or earlier. You can have statically typed languages with inadequate type safety, and you can have dynamically typed languages with inadequate type safety. > Now the same thing, directly converted to Python: > > def binarySearch(a, key): > low = 0 > high = len(a) - 1 > while low <= high: > mid = (low + high) / 2 > midVal = a[mid] > if midVal < key: > low = mid + 1 > elif midVal > key: > high = mid - 1; > else: > return mid # key found > return -(low + 1) # key not found. > > What's better about the Python version? First, it will operate on *any* > sorted array, no matter which type the values have. Uh huh! With hard-coded < and = operators, how stupid. What if you want to use it on strings? Would that be a case-insensitive lexicographic comparison, or case-insensitive? How do you specify what kind of less-than and equal you want to do? -1 to indicate not found? Why copy Java braindamage induced by an antiquated form of static typing? The Java version has to do that because the return value is necessarily declared to be of type integer. ;; Common Lisp ;; Binary search any sorted sequence SEQ for ITEM, returning ;; the position (starting from zero) if the item is found, ;; otherwise returns NIL. ;; ;; :REF specifies positional accessing function, default is ELT ;; :LEN specifies function for retrieving sequence length ;; :LESS specifies function for less-than item comparison ;; :SAME specifies function for equality comparison (defun binary-search (seq item &key (ref #'elt) (len #'length) (less #'<) (same #'=)) (loop with low = 0 and high = (funcall len seq) while (<= low high) do (let* ((mid (truncate (+ low high) 2)) (mid-val (funcall ref seq mid))) (cond ((funcall less mid-val item) (setf low (1+ mid))) ((funcall same mid-val item) (return mid)) (t (setf high (1- mid))))))) Common Lisp integers are "mathematical", so the overflow problem described in your referenced article doesn't exist here. From http Tue Jun 27 22:53:17 2006 From: http (Paul Rubin) Date: Wed, 28 Jun 2006 02:53:17 GMT Subject: What is Expressiveness in a Computer Language References: <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <1151384511.223582.305760@m73g2000cwd.googlegroups.com> <1151425350.679754.278820@i40g2000cwc.googlegroups.com> <1151450513.458623.139460@b68g2000cwa.googlegroups.com> Message-ID: <7xwtb2j8ir.fsf@ruckus.brouhaha.com> David Hopwood writes: > Note that I'm not claiming that you can check any desirable property of > a program (that would contradict Rice's Theorem), only that you can > express any dynamically typed program in a statically typed language -- > with static checks where possible and dynamic checks where necessary. It starts to look like sufficiently powerful static type systems are confusing enough, that programming with them is at least as bug-prone as imperative programming in dynamically typed languages. The static type checker can spot type mismatches at compile time, but the types themselves are easier and easier to get wrong. From grante at visi.com Wed Jun 14 13:29:52 2006 From: grante at visi.com (Grant Edwards) Date: Wed, 14 Jun 2006 17:29:52 -0000 Subject: Numerics, NaNs, IEEE 754 and C99 References: <12904mjhl493t49@corp.supernews.com> <1290aik50hmk94a@corp.supernews.com> <4490329e$0$12356$636a55ce@news.free.fr> <1290dlgfqnf79ca@corp.supernews.com> <449038f8$0$29657$636a55ce@news.free.fr> Message-ID: <1290hsgplgl794d@corp.supernews.com> On 2006-06-14, Christophe wrote: >>>>The division by zero trap is really annoying. In my world the >>>>right thing to do is to return Inf. >>> >>>Your world is flawed then, this is a big mistake. NaN is the >>>only aceptable return value for a division by zero. >> >> You're probably right if you're talking about math, but I'm not >> doing math. I'm doing engineering. In all of the situations >> I've ever encountered, Inf was a much better choice. > > You should have been more precise then : "In my ideal world, when > dividing a non zero value by a zero value, the result should be +Inf or > -Inf according the the sign rules" True. I've been dealing with IEEE 754 so long that I assume things like that go without saying. > On that point, you should also note that +0 and -0 are sometimes > considered two different floating point numbers in Python :) Different but equal. [Don't tell the Supreme Court.] -- Grant Edwards grante Yow! I just had a NOSE at JOB!! visi.com From gandalf at designaproduct.biz Tue Jun 13 05:53:45 2006 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Tue, 13 Jun 2006 11:53:45 +0200 Subject: Decimals In-Reply-To: <1150191995.559582.140270@p79g2000cwp.googlegroups.com> References: <1150188516.739925.102810@h76g2000cwa.googlegroups.com> <1150190908.231517.314040@h76g2000cwa.googlegroups.com> <1150191995.559582.140270@p79g2000cwp.googlegroups.com> Message-ID: <448E8B29.9030805@designaproduct.biz> >> Try string formatting: >> >> print '%.2f' % product.price >> > > That works. I expected Python to display the data exactly as it is in > the database, like most languages. It depends on what you get back from MySQLdb. Try this: import decimal d = decimal.Decimal("3.0000") print d Now try this: d = float("3.0000") print d The problem is -- probably -- with your db module. It may return a float instead of a Decimal. I cannot help more with MySQL, because I do not use it. Sorry. Laszlo From olsongt at verizon.net Thu Jun 15 15:42:54 2006 From: olsongt at verizon.net (olsongt at verizon.net) Date: 15 Jun 2006 12:42:54 -0700 Subject: a good programming text editor (not IDE) In-Reply-To: References: <_xgkg.2317$No6.48542@news.tufts.edu> <1150393919.514359.55580@h76g2000cwa.googlegroups.com> Message-ID: <1150400573.981904.83160@f6g2000cwb.googlegroups.com> John Salerno wrote: > Ant wrote: > > > jEdit is for me still the best text editor available. Very extensible > > with macros (which can be written in Jython with the appropriate plugin > > installed). > > I like the idea of being extensible, but of course I can only write in > Python. Are there any editors that support that? I can think of one editor that supports that ;-) http://www.vim.org/htmldoc/if_pyth.html#Python Seriously though, yes vim is wierd. Wierd enough that you might think maybe people just use it because they're trying to proove they're l337 or hardcore, instead of using it for real practical reasons. But it really is an amazing text editor once you accept the wierdness. If you use it for a little bit, one day you'll be editing a document in Word, or notepad, or SciTE, or Eclipse; you'll instinctively type '[ESC]:wq', and be suprised that the app is still open. That's when you realize there's no turning back. -Grant [ESC]:wq From doIlookDAFTenoughTOpost at validEMAILaddressTOa.NEWS.group Wed Jun 14 16:36:45 2006 From: doIlookDAFTenoughTOpost at validEMAILaddressTOa.NEWS.group (Aidan Karley) Date: Wed, 14 Jun 2006 21:36:45 +0100 Subject: Earthquake and Tornado Forecasting Programs June 13, 2006 References: <448eef76$0$30713$ec3e2dad@news.usenetmonster.com> <448EFE0D.3B2D968B@yahoo.com> Message-ID: In article <448EFE0D.3B2D968B at yahoo.com>, CBFalconer wrote: > Oh for a newsreader that can eliminate all such ugly excessively > cross-posted articles lacking follow-ups. PLONK thread is the only > remaining answer. > See my reply posted to alt.disasters.misc and sci.geo.earthquakes for an alternative strategy. But yes, cross-posting like that is highly irritating, which makes the actual purpose of the original posting highly suspect. I don't know which of the comp.lang groups you're coming from, but since any of them could probably be used to write cross-post filtering code ... I'll leave the lot in. -- Aidan Karley, FGS Aberdeen, Scotland Written at Wed, 14 Jun 2006 08:14 +0100, but posted later. From jmbc at nospam.fr Mon Jun 12 02:36:33 2006 From: jmbc at nospam.fr (jean-michel bain-cornu) Date: Mon, 12 Jun 2006 08:36:33 +0200 Subject: wxPython: Keyboard events and TreeCtrl In-Reply-To: <1150055217.354043.135340@h76g2000cwa.googlegroups.com> References: <1150055217.354043.135340@h76g2000cwa.googlegroups.com> Message-ID: <448d0bb2$0$7761$7a628cd7@news.club-internet.fr> > Am I supposed to connect the method to the Frame somehow? Or does it > automatically get called when the user hits Ctrl-I, regardless of the > fact that no other methods call OnKeyDown? I think it must be connected to the treectrl. One line or a combination of : self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown) self.Bind(wx.EVT_KEY_UP, self.OnKeyUp) self.Bind(wx.EVT_CHAR, self.OnChar) That's coming from the demo (process and events->key events). If it does not work, it'd be helpful if you join your program to a next post, something that we can test without having to write a demo specifically. Regards, jm From john at castleamber.com Thu Jun 1 13:41:33 2006 From: john at castleamber.com (John Bokma) Date: 1 Jun 2006 17:41:33 GMT Subject: how to print newline in xml? References: <1149023930.292203.152540@u72g2000cwu.googlegroups.com> <1149145466.190011.146250@i39g2000cwa.googlegroups.com> Message-ID: "anatoli.barski at googlemail.com" wrote: > Thank you for a possible solution, but it's not what I'm looking for, > cause something like would look quite similar... for > big elements like robot it would be ok to use comment as a child of > element - but imagine I'd like to comment transformation: > > I wouldn't like to make this > element parent of a description - it is not nice - I have lots of such > elements. Then add the comment to the parent of transformation, or an other option might be: > It is important that a user after having a glance at the document is > able to quickly find and change some values. I don't want to bother > him with reading documentation nodes - but if he needs - they should > be there... the only possible solution I can think of would be: > > > Several of your comments are stating the obvious, it's like: x++ increments the value x contains with one > > """ % (char_codes(email_address), char_codes(text)) > > The newlines within the triple quoted string are important; use that > function something like this: > > print "" > print "Title > print " > print "

%s

" % spam_averse_email_address( 'email at mydomain.com', > 'click here to email me' ) > print "" > print "" > > You mentioned accessibility; make sure that your HTML does something > sensible if the user's browser doesn't do javascript. > > HTH, > Dan > Bruno Desthuilliers has a nice one-liner: python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" I came up with this: python < Message-ID: <1151033409_11077@sp6iad.superfeed.net> "Jim" wrote in message news:1150887820.604214.276880 at i40g2000cwc.googlegroups.com... >I have a C++ app which fires up a Python script using C API calls. > That script operates the app via Automation calls, like this: > > from win32com.client import * > from mywrapper import * > > myapp = Application() > myapp.Visible = True > mydoc = myapp.Documents.Open(...) > > My problem is to make sure the instance of myapp is the same one I am > calling from. The above code starts up a new instance of the app, > which is not what I want. In other words I need something like a > GetObject instead of a CreateObject, and I need some way to identify > the calling app so I can tell GetObject about it. > > Before I go and do something hack, I thought I'd see if anyone else is > in this situation and knows a good way to do the job. > > -- Jim Pythoncom.GetActiveObject will retrieve the running instance of the app. (assuming that it registers itself in the Running Object Table) Roger ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= East/West-Coast Server Farms - Total Privacy via Encryption =--- From maric at aristote.info Fri Jun 23 11:15:12 2006 From: maric at aristote.info (Maric Michaud) Date: Fri, 23 Jun 2006 17:15:12 +0200 Subject: Using metaclassed to dynamically generate a class based on a parameter to the objects init function. In-Reply-To: <200606231709.10456.maric@aristote.info> References: <1151018669.849641.265990@g10g2000cwb.googlegroups.com> <1151071434.945199.39490@i40g2000cwc.googlegroups.com> <200606231709.10456.maric@aristote.info> Message-ID: <200606231715.13175.maric@aristote.info> Le Vendredi 23 Juin 2006 17:09, Maric Michaud a ?crit?: > Hmmm, rigourously speaking, metaclasses in OOP are classes whose instances > are class. Ooops, sorry i didn't notice you were calling type's __new__ (and not object'sone). -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From jzgoda at o2.usun.pl Thu Jun 15 14:42:09 2006 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Thu, 15 Jun 2006 20:42:09 +0200 Subject: a good programming text editor (not IDE) In-Reply-To: References: <_xgkg.2317$No6.48542@news.tufts.edu> Message-ID: John Salerno napisa?(a): >> Vim is definitely the best. If you're a GUI man, you can use GVim. > > Ok, you guys are slowly converting me, but I do have one question: which > "version" of VIM should I use, or does it matter? I mean, there seem to > be at least two versions, a text version and the GUI version you > mention. Are the options shared between the two, or is it that you are > more or less "set" in one once you choose it, and if you move to the > other you have to redefine your preferences, etc.? The "version" doesn't matter, but anyway you should get the newest one available. 7.0 has some nice features for text editing in graphic environments (like Windows), but in terminal it's the same beast. You'll love it in short time. ;) -- Jarek Zgoda http://jpa.berlios.de/ From alanalan at newsgroup.nospam Thu Jun 1 16:19:11 2006 From: alanalan at newsgroup.nospam (A.M) Date: Thu, 1 Jun 2006 16:19:11 -0400 Subject: New to Python: Do we have the concept of Hash in Python? References: Message-ID: "Fredrik Lundh" wrote in message news:mailman.6424.1149190330.27775.python-list at python.org... > A.M wrote: > >> This is my 1st day that I am seriously diving into Python and I have to >> finish this application by the end of today. Maybe it wasn't a good idea >> to choose the language that I don't know when I have to deliver my work >> in such short time. > > are your boss aware of this ? > > > > are your boss aware of this ? What is wrong with *this*? Yes, they are aware of *this*. The application is not mission critical system. It is just a simple reporting tool. From claird at lairds.us Fri Jun 23 12:19:00 2006 From: claird at lairds.us (Cameron Laird) Date: Fri, 23 Jun 2006 16:19:00 +0000 Subject: Network Programming in Python References: <1151002934.586359.174540@m73g2000cwd.googlegroups.com> <1151067757.353199.238420@g10g2000cwb.googlegroups.com> <129o2p1l3149579@corp.supernews.com> Message-ID: In article <129o2p1l3149579 at corp.supernews.com>, Grant Edwards wrote: >On 2006-06-23, diffuser78 at gmail.com wrote: > >> How will Pyon help my cause ? > >What's Pyon? . . . A misreading of "Pyro". Pyro , of course, is yet another communications layer, but, as was suggested, one that might particularly suit Mr. Johnson. From chris.uppal at metagnostic.REMOVE-THIS.org Wed Jun 21 05:39:15 2006 From: chris.uppal at metagnostic.REMOVE-THIS.org (Chris Uppal) Date: Wed, 21 Jun 2006 10:39:15 +0100 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <7i3mg.204167$8W1.155367@fe1.news.blueyonder.co.uk> Message-ID: <44992e6c$2$664$bed64819@news.gradwell.net> David Hopwood wrote: > When people talk > about "types" being associated with values in a "latently typed" or > "dynamically typed" language, they really mean *tag*, not type. I don't think that's true. Maybe /some/ people do confuse the two, but I am certainly a counter-example ;-) The tag (if any) is part of the runtime machinery (or, if not, then I don't understand what you mean by the word), and while that is certainly a reasonably approximation to the type of the object/value, it is only an approximation, and -- what's more -- is only an approximation to the type as yielded by one specific (albeit abstract, maybe even hypothetical) type system. If I send #someMessage to a proxy object which has not had its referent set (and assuming the default value, presumably some variant of nil, does not understand #someMessage), then that's just as much a type error as sending #someMessage to a variable holding a nil value. If I then assign the referent of the proxy to some object which does understand #someMessage, then it is not a type error to send #someMessage to the proxy. So the type has changed, but nothing in the tag system of the language implementation has changed. -- chris From maxilys at SPAMCOP_tele2.fr Thu Jun 15 19:57:08 2006 From: maxilys at SPAMCOP_tele2.fr (Remi Villatel) Date: Fri, 16 Jun 2006 01:57:08 +0200 Subject: Python is fun (useless social thread) ;-) In-Reply-To: References: Message-ID: John Salerno wrote: [---CUT---] > So out of curiosity, I'm just wondering how everyone else came to learn > it. [---CUT---] I just needed it. I needed it to recode text files from my old Atari computer for my Linux box. I had already seen Python sources during some googling sessions and found them mostly understandable. I also knew it was already installed so I decided to give it a try. One night was all I needed to write my "recoder" with nothing more to help me than the (cryptic) included docs and the examples. Yes, 8 hours and I had learned arguments passing, files operations, strings manipulations and even module import with no prior knowledge. I fell in love with Python. I still have the source, it's very basic Python and I definitively could have used a dictionary... but it worked. From that moment, Python became my script language. Whenever I need to write more than 2 lines in Bash, I use Python. I learned the classes to play with some (rudimentary) artificial intelligence. I even took part in a contest where I learned 'lambda' and the generators. The only thing I haven't taken much care about is GUI in Python. For that, I learned C++... ;-) Any way, Python even helps me sometimes to write C++ since I use it to test my algorithms when it comes to data manipulation. I can feed my routines on the fly with whatever data I want to see how they react. So I use Python as a debugger before to even start writing things in C++. No need to compile or debug in Python. When something goes wrong: CTRL+C, correct and restart. Python is fun because it's easy to write, to understand and to use. -- ================== Remi Villatel maxilys_ at _tele2.fr ================== From anton at appsolutions.com Mon Jun 26 02:34:15 2006 From: anton at appsolutions.com (Anton van Straaten) Date: Mon, 26 Jun 2006 06:34:15 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150904134.520639.71070@b68g2000cwa.googlegroups.com> <1151056505.908723.162580@u72g2000cwu.googlegroups.com> <1151171007.230666.235430@r2g2000cwb.googlegroups.com> <1151224844.569347.167420@r2g2000cwb.googlegroups.com> Message-ID: John Thingstad wrote: > On Sun, 25 Jun 2006 20:11:22 +0200, Anton van Straaten > wrote: > >> rossberg at ps.uni-sb.de wrote: ... >>> \sarcasm One step further, and somebody starts calling C a "latently >>> memory-safe language", because a real programmer "knows" that his code >>> is in a safe subset... And where he is wrong, dynamic memory page >>> protection checks will guide him. >> >> >> That's a pretty apt comparison, and it probably explains how it is >> that the software we all use, which relies so heavily on C, works as >> well as it does. >> >> But the comparison critiques the practice of operating without static >> guarantees, it's not a critique of the terminology. >> >> Anton > > > Actually I have never developed a C/C++ program > without a bounds checker the last 15 years. > It checks all memory references and on program shutdown > checks for memory leaks. What is it about you guys that make you blind > to these fact's. You misunderstand -- for the purposes of the above comparison, a bounds checker serves essentially the same purpose as "dynamic memory page protection checks". The point is that it happens dynamically, i.e. at runtime, and that there's a lack of static guarantees about memory safety in C or C++. That's why, as I said, the comparison to latent vs. static typing is an apt one. Anton From kay.schluehr at gmx.net Tue Jun 20 05:03:31 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 20 Jun 2006 02:03:31 -0700 Subject: code is data In-Reply-To: References: <1150779608.479611.44120@g10g2000cwb.googlegroups.com> Message-ID: <1150794210.996036.194000@g10g2000cwb.googlegroups.com> Fredrik Lundh wrote: > Kay Schluehr wrote: > > > If it is just a different kind of representation of common data > > structures > > but how do you know ? > > The semantics is specified by the syntax transformer so it is actually compile-time semantics relative to the base language Python . For any custom statement/expression ( expressed by a production rule / node in the parse-tree ) one or more target statements/expressions in standard Python are created. The specification of the with-statement in PEP 343 can be regarded as a good example of this definition practice. The with-statement is expanded to a "protocol" that can be expressed in Python 2.4. In a more general case this expansion might involve additional libraries e.g. ctypes or elementree. From tenax.raccoon at gmail.com Wed Jun 7 18:38:11 2006 From: tenax.raccoon at gmail.com (Jason) Date: 7 Jun 2006 15:38:11 -0700 Subject: what are you using python language for? References: Message-ID: <1149719891.761757.263650@c74g2000cwc.googlegroups.com> I've been working on an RPG character generator for consistent (yet varied) set of role-playing systems. Nothing like a pen-and-pencil RPG to throw in tons of special cases and strange rulesets. Python's turned out to be very useful for this project: 1. Fast prototyping and testing. I'm not starting the GUI until after I get all the quirks of the rule-set down first. Naturally, I've got a python script which sets up a subset of the rules, then a series of unit tests which operate on the partially constructed RPG. 2. Dynamic typing. The cost object for a Character Gift can vary dramatically in behavior. Being able to dynamically re-assign the current cost object to a different cost type is very nice. (The cost types are pretty much similar in data, but their methods act differently.) 3. Joyous object serialization via the pickle protocol. While I'm using the Gnosis XML pickler, there's always the default picklers, too. While not part of Python, the platform-agnostic ruleset should be a bonus. If someone doesn't like my wxPython front-end, then they can go through the trouble of re-implementing it in their favorite system, be it .NET and IronPython or Python/TK. From chris.cavalaria at free.fr Fri Jun 2 05:03:34 2006 From: chris.cavalaria at free.fr (Christophe) Date: Fri, 02 Jun 2006 11:03:34 +0200 Subject: Function mistaken for a method In-Reply-To: References: <447eed61$0$20860$626a54ce@news.free.fr> Message-ID: <447ffed3$0$6176$626a54ce@news.free.fr> Maric Michaud a ?crit : > Le Jeudi 01 Juin 2006 15:36, Christophe a ?crit : > >> self.x = self.__class__.f(0) > > nope, this will result in a TypeError "unbound method must be called with > instance as first argument" Your right :( staticmethod it is then. From fredrik at pythonware.com Fri Jun 2 03:30:56 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 2 Jun 2006 09:30:56 +0200 Subject: New to Python: Do we have the concept of Hash in Python? References: <%aIfg.3027$EF1.232063@news20.bellglobal.com> Message-ID: "A.M" wrote: >> are your boss aware of this ? > > In fact my boss is quite impressed with my progress so far. *your* progress ? From python.list at tim.thechases.com Fri Jun 30 10:23:18 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 30 Jun 2006 09:23:18 -0500 Subject: string replace In-Reply-To: <1aapg.21924$_J1.275201@twister2.libero.it> References: <1aapg.21924$_J1.275201@twister2.libero.it> Message-ID: <44A533D6.5060207@tim.thechases.com> > a lot of times I need to replace more than one char into a > string, so I have to do something like > > value = "test" > chars = "e" > for c in chars: > value = value.replace(c, "") > > A solution could be that "replace" accept a tuple/list of > chars, like that was add into the new 2.5 for startswith. > > I don't know, but can be this feature included into a future > python release? Well, another way of doing it would be >>> values = "this is a test" >>> chars = "aeiou" >>> "".join([c for c in values if c not in chars]) 'ths s tst' If your either your chars is a large set or you're performing this repeatedly with the same set of chars, you might want the speed of membership-testing that one would get from a true set: >>> charset = set(chars) # do this once for the set >>> # do the following as many times as you like in loops, etc. >>> "".join([c for c in values if c not in charset]) 'ths s tst' HTH, -tkc From marshall.spight at gmail.com Fri Jun 23 16:29:34 2006 From: marshall.spight at gmail.com (Marshall) Date: 23 Jun 2006 13:29:34 -0700 Subject: What is a type error? In-Reply-To: <449bde60$0$663$bed64819@news.gradwell.net> References: <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <7i3mg.204167$8W1.155367@fe1.news.blueyonder.co.uk> <44992e6c$2$664$bed64819@news.gradwell.net> <%Igmg.464974$xt.353729@fe3.news.blueyonder.co.uk> <449aaea0$2$656$bed64819@news.gradwell.net> <449bde60$0$663$bed64819@news.gradwell.net> Message-ID: <1151094574.908557.86040@p79g2000cwp.googlegroups.com> Chris Uppal wrote: > /Given/ a set of operations which I want to forbid, > I would like to say that a "dynamic type system" which prevents them executing > is doing very much the same job as a static type system which stops the code > compiling. There are similarities, (classifying values into categories, and checking whether functions are sensibly invoked according these categories) and there are differences (in the difference between existential quantification of success vs. universal quantification of success.) They are certainly not identical. (I'm not sure if by "very much the same" you meant identical or not.) > Of course, we can talk about what kinds of operations we want to forbid, but > that seems (to me) to be orthogonal to this discussion. Indeed, the question > of dynamic/static is largely irrelevant to a discussion of what operations we > want to police, except insofar as certain checks might require information > which isn't available to a (feasible) static theorem prover. Sometimes the things you want to check are emergent properties of a progam rather than local properties. I don't see how runtime checks can do anything with these properties, at least not without a formal framework. An example is deadlock freedom. There exist type systems that can prove code free of deadlock or race conditions. How woud you write a runtime check for that? Marshall From bdesth.quelquechose at free.quelquepart.fr Tue Jun 20 18:30:10 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 21 Jun 2006 00:30:10 +0200 Subject: Iteration over recursion? In-Reply-To: <1150828012.837354.160110@u72g2000cwu.googlegroups.com> References: <1150808045.539887.291180@i40g2000cwc.googlegroups.com> <1150816827.826028.114740@h76g2000cwa.googlegroups.com> <4498211b$0$8390$626a54ce@news.free.fr> <1150828012.837354.160110@u72g2000cwu.googlegroups.com> Message-ID: <449846e0$0$4793$636a55ce@news.free.fr> Sudden Disruption a ?crit : > Bruno, > > >>It doesn't. Technical possible, but BDFL's decision... > > > Sure. But why bother? Because I do like recursion, and would personnally prefer tail-recursion optimisation over nice tracebacks. But I'm not in position to decide anything here. > Anything that can be done with recursion can be done with iteration. > Turng proved that in 1936. Yes. And everything done with Python can be done with assembly language too. > Recursion was just an attempt to "unify" design approach by abstracting > itteration and creating a new context. It allowed the programmer to > isolate himself from the reality that he was actually iterating. Talk > about mind fuck. Recursion is the most convenient way to express some common algorithms. Too bad for you if it does some nasty things to your mind. From onurb at xiludom.gro Mon Jun 19 04:24:49 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Mon, 19 Jun 2006 10:24:49 +0200 Subject: [OT] code is data In-Reply-To: References: Message-ID: <44965f53$0$12743$636a55ce@news.free.fr> Anton Vredegoor wrote: > With the inclusion of ElementTree (an XML-parser) in Python25 and recent > developments concerning JSON (a very Pythonesque but somewhat limited > XML notation scheme, let's call it statically typed XML) JSON stands for JavaScript Object Notation, and has *nothing* to do with XML - except for the fact that it's more and more used instead of XML for AJAX stuff. > Python seems to > have reached a stage where it now seems to be possible to completely > swallow lesser languages code, modify it, and spit out new source code > targeting the original language the code was written in, or even make a > translation to other languages. If you mean "parsing source in a given format and outputting another - modified or not - representation, in the same or another format", Python as always been able to do so. > The idea is that we now have a fast parser (ElementTree) with a > reasonable 'API' and a data type (XML or JSON) that can be used as an > intermediate form to store parsing trees. Especially statically typed > little languages seem to be very swallow-able. Maybe I will be able to > reimplement GFABasic (my first love computer language, although not my > first relationship) someday, just for fun. > > Then there are things like cTypes (calling functions from native DLL's) > and PyPy (implementing Python in Python). > > All this taken together, to me it starts looking like we're now entering > a territory that traditionally was exclusively in the Lisp domain. Sorry, but I just don't get the point. Parsing, working with trees and calling native code are in no way "exclusively in the Lisp domain". > Yes, Python had eval and exec for a long time already, and metatypes and > generators are having some strange unexplored possibilities too, but the > day will come soon (and at last when PyPy is reaching execution speeds > close to cPython) where Python will be able to swallow smaller > languages, and finally it will be able to swallow its own tail, like > Lisp but then more powerful I'm afraid Python is still very far from Lisp - and will never get there (FWIW, this seems not to be the goal anyway). > (because of the widely used standard data > types and the code exchange between languages that that makes possible). I still don't get the point. > Your thoughts please. > > Anton -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From steve at holdenweb.com Fri Jun 9 10:26:38 2006 From: steve at holdenweb.com (Steve Holden) Date: Fri, 09 Jun 2006 15:26:38 +0100 Subject: removing dictionary key-pair In-Reply-To: <128j0r7tla1qi12@corp.supernews.com> References: <128j0r7tla1qi12@corp.supernews.com> Message-ID: JD wrote: > Hello, > > I try to remove a dictionary key-pair (remove an entry), > but I'm unsuccessful. Does anyone know how to achieve this? > > Thanks >>> d = {1: "one", 2: "two", 3: "three"} >>> del d[2] >>> d {1: 'one', 3: 'three'} >>> regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From sudheerb at netapp.com Wed Jun 7 17:35:58 2006 From: sudheerb at netapp.com (Sudheer Gupta) Date: Wed, 07 Jun 2006 17:35:58 -0400 Subject: Using C struct in Python Message-ID: <448746BE.9080504@netapp.com> Hi, I am having trouble using C struct in python. Hope anyone can help me out ... Say, I have my C struct as typedef struct call { struct call *next; // ..... } call_t; I have a global variable, namely call_pool, which is of type call_t * My python program: cp = call_pool # no error doing this, means that call_pool is accessable while cp: print cp print cp.next This is giving me error: " There is no member or method name c_next" Now, If I just do: print cp print cp.next there is no problem. But I am seeing a difference in the way python is looking at the struct: print cp -> (call_t*) 0xb0... print cp.next -> (struct call *) 0xb0... Is python not intelligent enough to diagnose the next pointer ?? Responses appreciated. Thanks Sudheer From raffaelcavallaro at pas-d'espam-s'il-vous-plait-mac.com Thu Jun 15 01:58:24 2006 From: raffaelcavallaro at pas-d'espam-s'il-vous-plait-mac.com (Raffael Cavallaro) Date: Thu, 15 Jun 2006 01:58:24 -0400 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <2006061410510511272-raffaelcavallaro@pasdespamsilvousplaitmaccom> <878xnzv5i3.fsf@thalassa.informatimago.com> Message-ID: <2006061501582450878-raffaelcavallaro@pasdespamsilvousplaitmaccom> On 2006-06-14 16:36:52 -0400, Pascal Bourguignon said: > In lisp, all lists are homogenous: lists of T. CL-USER 123 > (loop for elt in (list #\c 1 2.0d0 (/ 2 3)) collect (type-of elt)) (CHARACTER FIXNUM DOUBLE-FLOAT RATIO) i.e., "heterogenous" in the common lisp sense: having different dynamic types, not in the H-M sense in which all lisp values are of the single union type T. From ajones1 at gmail.com Mon Jun 26 03:30:31 2006 From: ajones1 at gmail.com (Adam Jones) Date: 26 Jun 2006 00:30:31 -0700 Subject: What technologies should I use for my application manager? References: <1151260635.570013.87210@b68g2000cwa.googlegroups.com> Message-ID: <1151307031.166916.232330@m73g2000cwd.googlegroups.com> MrBlueSky wrote: > Hello! I've just finished working on my first Python app (a > Tkinter-based program that displays the content of our application log > files in graphical format). It was a great experience that's had a > very positive response from my colleagues. > > So I'd like to try something different for my second Python > application. It's a simple server that can launch and monitor the > state of our program, to help our software developers. In my mind I > have a vision of: > * a web server > * allows the user to launch our product (choosing from a set of > different launch scripts) > * allow user to stop a launched product > * report state by retrieving data from the RDBMS against which the > product runs (Oracle or SQL Server) > > There seem to be a lot of web server related Python libraries around, > and I've no experience in web servers at all. So I'd really > appreciate some advice on what Python "technologies" you think I should > base my application on. > For speed of development I would suggest looking into a framework that can do some of the heavy lifting for you. Out of those the "really big names" in python are Turbogears ( http://www.turbogears.org/ ), Django ( http://www.djangoproject.org/ ), and Zope ( http://www.zope.org ). (along with others that I have forgotten who shall most likely be mentioned promptly) Of them all I have the most experience with Turbogears, so that is what I will try and sell you on. By default Turbogears provides support for *either* MS SQL or Oracle. One of the differences between Turbogears and most web frameworks is that many of the bigger chunks of code for it are taken from existing projects instead of being written internally. Due to this Turbogears provides support for two database mappers: Sqlobject, which supports MS SQL; and Sqlalchemy, which supports Oracle. Of the two Sqlalchemy is much more flexible, but is also a newer project and may be harder to work with until the api finishes settling. Both projects offer full support for one of the databases you mentioned, and developmental support for the other. If you need to work with both it is possible to bring in the database integration method of your choice. Turbogears has a very flexible widget system that supports a lot of interesting code. Basic things like user input forms can be handled with widgets, but there are also prebuilt widgets for things like find-as-you-type form fields, calendar-based date pickers, tabbed displays, syntax-highlighted text, and a plotting kit (and those are just the fancy things that looked like they would be useful). There is a pretty nice validation system that can handle converting user input into appropriately typed python objects, and can automatically force a correction page if you would like it to do so. Like any other framework Turbogears has a templating system to help handle the html/css/javascript that you will be using. By default it uses Kid, which is XHTML with an additional namespace that provides support for looping, element replacement, and limited function definitions. Overall I have found it to be pretty nice to work with. That said if you want something else you can install plugins for a few different templating languages. (Currently supported are Cheetah, Stan, ZPT, HtmlPy, Clearsilver, Myghty, and Python String Templates) Obviously some of the more important parts you are looking for are integration into the system environment, logging, and possibly user authentication and scheduled tasks. By default Turbogears supports all of the access to the surrounding system that Python does. This is kind of a no-brainer, but for me at least was something of a stumbling block in coming from PHP. The logging system is based on the built-in logging package for Python. It is configured through Turbogears to allow some of the components involved to support it. You have access to pretty much all of the facilities that the Python logger provides. User authentication in Turbogears is generally handled through the Identity system. This allows you to restrict access to directories, pages, and even specific page elements (like links or forms) based on the connecting host, user account, group membership, or permissions granted. The identity system itself is pretty extensible and can probably be made to support anything you can think of as an authentication method. Scheduled tasks can be handled from inside of turbogears with the built in scheduler. This allows you to schedule tasks while working inside turbogears, which saves the headache of handling database access separately. Installing and configuring Turbogears can actually be pretty simple. The system is based around python eggs ( http://peak.telecommunity.com/DevCenter/PythonEggs/ ) which can handle installation requirements and upgrades for you. Overall I have found Turbogears to be a flexible, easy-to-use framework. It generally seems to do well at staying out of the way, and most of the extra features it adds have been well worth the (optional) time spent learning them. From fredrik at pythonware.com Tue Jun 6 06:09:11 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 06 Jun 2006 12:09:11 +0200 Subject: Writing to a certain line? In-Reply-To: <44854184$0$29904$636a55ce@news.free.fr> References: <1149576072.168354.14470@f6g2000cwb.googlegroups.com> <44854184$0$29904$636a55ce@news.free.fr> Message-ID: bruno at modulix wrote: > > This is a FAQ (while I don't know if it's in the FAQ !-), and is in no > way a Python problem. FWIW, this is also CS101... > feel free to repost your response here: http://pyfaq.infogami.com/suggest From rabkinDELETE at mweb.co.za Thu Jun 1 16:35:17 2006 From: rabkinDELETE at mweb.co.za (Max) Date: Thu, 01 Jun 2006 22:35:17 +0200 Subject: if not CGI: Message-ID: I've never done anything on the web. I mean, never developed anything. (I've got accounts on dA and wikipedia and half-a-dozen other things; I know HTML and enough JavaScript to hack away at it when friends need help). Mostly because I've never had anything worth doing: I've written a set of python CGI programs (an eCards site) and set up apache, just because I wanted to learn how. It used raw files; no database. And it sits there, working just about flawlessly, at http://localhost/maxecards/. I've even done a minor security audit, just to learn how (I met a hacker and he impressed me). But now I'm ready to do it in the real world. Nothing complicated, but a real project. And I have to choose my tools. Zope, Plone, Django, what are these? I don't have to stick with Python, although it's my preferred language. I know Python, Java and C++. But I'm ready to learn Ruby if RoR is as good as they say. I could do it in Python cgi (or mod_python). But it seems from all the hype that this is not a good way to write scaleable, extensible web applications. There's a reason I'm asking here: I like Python. But I only learned it because I had incentive (30000 local monetary units in the computer olympiad; I won 10000). Is RoR incentive enough? --Max From sreeram at tachyontech.net Thu Jun 8 01:23:52 2006 From: sreeram at tachyontech.net (K.S.Sreeram) Date: Thu, 08 Jun 2006 10:53:52 +0530 Subject: xml processing speed test In-Reply-To: References: <44870F5C.8010407@tachyontech.net> <44871850.2070404@tachyontech.net> Message-ID: <4487B468.5060707@tachyontech.net> Fredrik Lundh wrote: > by using it to split your document into reasonably-sized chunks (one > record, one expression, one text block, one paragraph, etc), and using > Python code to process the chunks. I've updated cElementTree/iterparse implementation to build one full expression at a time. http://sreeram.cc/files/xmlspeed/py_etree.py Here are the updated timings: Input file size 80mb: C/Expat: 4.25 secs Python/cElementTree: 11.78 secs (down from 15.52 secs) Python/pyexpat: 16.10 secs Input file size 800mb: C/Expat: 105 secs Python+cElementTree: 157 secs (down from 184 secs) Python+pyexpat: 191 secs Regards Sreeram -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 260 bytes Desc: OpenPGP digital signature URL: From digitalorganics at gmail.com Mon Jun 26 09:21:17 2006 From: digitalorganics at gmail.com (digitalorganics at gmail.com) Date: 26 Jun 2006 06:21:17 -0700 Subject: DictProxy? What is this? Message-ID: <1151328077.677523.57820@b68g2000cwa.googlegroups.com> When I tried to update a class's __dict__, I got an error saying that there is no 'update' attribute for dictproxy object. What is a dictproxy object? I thought that __dict__ is always suppose to be a, no kidding, dictionary? Hence there should indeed be an update method. What's this proxy business? Thanks all. From Kiran.Karra at gmail.com Wed Jun 21 08:46:33 2006 From: Kiran.Karra at gmail.com (Kiran) Date: 21 Jun 2006 05:46:33 -0700 Subject: Segmentation fault only on Iinux In-Reply-To: <1150868236.699993.53850@m73g2000cwd.googlegroups.com> References: <1150831329.649174.60410@g10g2000cwb.googlegroups.com> <1150868236.699993.53850@m73g2000cwd.googlegroups.com> Message-ID: <1150893993.376206.182670@u72g2000cwu.googlegroups.com> Unfortunately (i guess), I am not doing any XML. However, I am taking the previous suggestion of putting print lines in every other line of my code and then seeing where it crashes. Hopefully, that will solve the problem. thanks for the suggestions everybody -- Kiran Frank Millman wrote: > Kiran wrote: > > Hello All, > > In my program, I have a main thread which is the GUI (wxPython) and > > then a thread which goes and reads data from a socket. The reason this > > is in a different thread is because the data might take some time to > > come back, and I want to have the GUI to be responsive during this > > wait. > > > > When I run my program in Linux, a segmentation fault occurs. When I > > run it in Windows XP, it works just fine. > > > > Are you doing any xml processing? If so, it may be the same problem as > described in this recent post - > > http://tinyurl.com/l3nr7 > > Frank Millman From pkarjala at mail.student.oulu.fi Wed Jun 21 07:36:35 2006 From: pkarjala at mail.student.oulu.fi (Pekka Karjalainen) Date: Wed, 21 Jun 2006 11:36:35 +0000 (UTC) Subject: help() on stdout.closed References: Message-ID: On 2006-06-21, Fredrik Lundh wrote: > have you tried things like [...] I have now. I'm not sure what the results are supposed to tell me, but I am not going to press the issue. Suppose I had no idea what sys.stdout.closed was and wanted to find out. Where would I look it up? Pekka From nate at natefico.com Sun Jun 18 06:01:53 2006 From: nate at natefico.com (nate) Date: Sun, 18 Jun 2006 03:01:53 -0700 Subject: python texts? In-Reply-To: <44939CBA.4090709@natefico.com> References: <44939CBA.4090709@natefico.com> Message-ID: <44952491.1010907@natefico.com> Everyone that took their time to reply, thank you. I have a better idea of where to go after Learning Python. I still do not have a good idea of where this book will put me in the grand scheme of things, but oh well. I suppose that is something I will find out soon enough. Once again, thank you for your responses --Nate. From jjlee at reportlab.com Mon Jun 5 15:47:03 2006 From: jjlee at reportlab.com (John J. Lee) Date: Mon, 05 Jun 2006 19:47:03 GMT Subject: strategy pattern and non-public virtual functions References: <1149516464.874257.194030@j55g2000cwa.googlegroups.com> Message-ID: <87y7wbcrm0.fsf@reportlab.com> pythoncurious at gmail.com writes: > Hi python experts > > In C++ I can do something like this: > class Base { > public: > void f() { this->f_(); } > private: > virtual void f_() = 0; > }; > > class Derived : public Base { > private: > void f_() { // Do something } > }; > > int main() { > Derived d; > d.f(); > } [...] The others have already answered the Python question and pointed out this isn't really the Strategy Pattern. Still, these slides from Alex Martelli specifically on the Template Method DP in Python are probably very relevant to you: http://www.aleax.it/Python/os03_template_dp.pdf John From jon+usenet at unequivocal.co.uk Wed Jun 21 06:21:48 2006 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: 21 Jun 2006 10:21:48 GMT Subject: help() on stdout.closed References: Message-ID: In article , Pekka Karjalainen wrote: >>>> from sys import stdout >>>> help (stdout.closed) > > If I do this, it gives me help on the bool object. stdout.closed is a bool. What were you expecting it to show you? From robert.kern at gmail.com Sun Jun 4 21:52:12 2006 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 04 Jun 2006 20:52:12 -0500 Subject: Max function question: How do I return the index of the maximum value of a list? In-Reply-To: <38adnTLbg47fFh7ZnZ2dnUVZ_qednZ2d@comcast.com> References: <1149459320.802652.186930@i40g2000cwc.googlegroups.com> <38adnTLbg47fFh7ZnZ2dnUVZ_qednZ2d@comcast.com> Message-ID: Steven Bethard wrote: > Can you do something like:: > > max_val, max_index = max((x, i) for i, x in enumerate(my_list)) > > ? If any two "x" values are equal, this will return the one with the > lower index. Don't know if that matters to you. Wouldn't it return the one with the highest index? -- 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 From nick at craig-wood.com Wed Jun 21 13:30:03 2006 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 21 Jun 2006 12:30:03 -0500 Subject: help() on stdout.closed References: Message-ID: Marc 'BlackJack' Rintsch wrote: > In , Pekka Karjalainen wrote: > > > Suppose I had no idea what sys.stdout.closed was and wanted to find out. > > Where would I look it up? > > `sys.stdout` is a file (like) object: > > http://docs.python.org/lib/bltin-file-objects.html Since the OP is using linux he may prefer to look this up using "info". Info contains all the same stuff as the web pages and it is terminal friendly. To find the below I typed info CTRL-S pytho Cursor down to "Python2.3-lib:" and press ENTER CTRL-S closed CTRL-S, CTRL-S until correct entry found (the 4th one) ... File objects also offer a number of other interesting attributes. These are not required for file-like objects, but should be implemented if they make sense for the particular object. `closed' bool indicating the current state of the file object. This is a read-only attribute; the `close()' method changes the value. It may not be available on all file-like objects. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From alan.franzoni.xyz at gmail.com Wed Jun 28 10:39:43 2006 From: alan.franzoni.xyz at gmail.com (Alan Franzoni) Date: Wed, 28 Jun 2006 16:39:43 +0200 Subject: compiling python (or ironpython) to .exe or .dll for or not for .NET References: <1151501398.664329.142920@d56g2000cwd.googlegroups.com> Message-ID: <1bn130p868zia.1rtctwxd9uy7p$.dlg@40tude.net> Il 28 Jun 2006 06:29:58 -0700, per9000 ha scritto: > Is the newest Ironpython really as old as from 2004 July 28 (as stated > on http://www.ironpython.com/)? Ironpython homepage seems long to have been abandoned. Try this: http://www.gotdotnet.com/Workspaces/Workspace.aspx?id=ad7acff7-ab1e-4bcb-99c0-57ac5a3a9742 -- Alan Franzoni - Togli .xyz dalla mia email per contattarmi. Rremove .xyz from my address in order to contact me. - GPG Key Fingerprint: 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E - Blog: http://laterradeglieroi.verdiperronchi.com From fredrik at pythonware.com Tue Jun 20 10:15:36 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 20 Jun 2006 16:15:36 +0200 Subject: unittest behaving oddly In-Reply-To: References: <1150809306.287758.48870@h76g2000cwa.googlegroups.com> Message-ID: David Vincent wrote: > The code quoted above was from my verbatim copy of the example from the > doc strings of unittest.py, from my computer's Python library. I > wonder how the example code could have been so badly wrong? self-eating viruses on your machine ? $ more unittest.py ... Simple usage: import unittest class IntegerArithmenticTestCase(unittest.TestCase): def testAdd(self): ## test method names begin 'test*' self.assertEquals((1 + 2), 3) self.assertEquals(0 + 1, 1) def testMultiply(self): self.assertEquals((0 * 10), 0) self.assertEquals((5 * 8), 40) ... From johnjsal at NOSPAMgmail.com Fri Jun 2 15:15:15 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 02 Jun 2006 19:15:15 GMT Subject: can you iterate over a FieldStorage object? Message-ID: <770gg.2223$No6.47403@news.tufts.edu> I'm trying to use a for loop with a FieldStorage object and I get the following error. Can you not treat it like a dictionary, or am I writing the for loop incorrectly? for item in form: print item # or print item.value KeyError Python 2.2.1: /usr/bin/python Fri Jun 2 15:12:36 2006 A problem occurred in a Python script. Here is the sequence of function calls leading up to the error, in the order they occurred. /kunden/homepages/7/d159103796/htdocs/labinfo.py 6 print 'content-type: text/html\n' 7 8 form = cgi.FieldStorage(keep_blank_values=True) 9 for item in form: 10 print item item undefined, form = FieldStorage(None, None, [MiniFieldStorage('firs...02116'), MiniFieldStorage('foreignAddress', '')]) /usr/lib/python2.2/cgi.py in __getitem__(self=FieldStorage(None, None, [MiniFieldStorage('firs...02116'), MiniFieldStorage('foreignAddress', '')]), key=0) 548 if item.name == key: found.append(item) 549 if not found: 550 raise KeyError, key 551 if len(found) == 1: 552 return found[0] KeyError undefined, key = 0 KeyError: 0 __doc__ = 'Mapping key not found.' __getitem__ = > __init__ = > __module__ = 'exceptions' __str__ = > args = (0,) From bdesth.quelquechose at free.quelquepart.fr Wed Jun 28 22:07:15 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 29 Jun 2006 04:07:15 +0200 Subject: Module executed twice when imported! In-Reply-To: References: Message-ID: <44a30581$0$4896$626a54ce@news.free.fr> Michael Abbott a ?crit : > It seems to be an invariant of Python (insofar as Python has invariants) > that a module is executed at most once in a Python session. I have a > rather bizzare example that breaks this invariant: can anyone enlighten > me as to what is going on? > > --- test.py --- > import imptest > execfile('subtest.py', dict(__name__ = 'subtest.py')) > --- imptest.py --- > print 'Imptest imported' > --- subtest.py --- > import imptest > --- > > $ python test.py > Imptest imported > Imptest imported > $ > > Hmm. If the value __name__ is omitted from the dictionary, or if its > value doesn't match at least 'subtest.' then the message is printed only > once (for example, passing dict(__name__='subtest') produces one > "imported" message). During module evaluation, __name__ is usually set to the name of the module *object*, not the name of the *file*. I suspect that it has something to do with your observation. From scott.daniels at acm.org Mon Jun 19 12:51:13 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Mon, 19 Jun 2006 09:51:13 -0700 Subject: Which compiler will Python 2.5 / Windows (Intel) be built with? In-Reply-To: <1150732472.933138.81170@y41g2000cwy.googlegroups.com> References: <1150367139.495114.148550@g10g2000cwb.googlegroups.com> <44917535$1@nntp0.pdx.net> <1150391891.130185.4640@f6g2000cwb.googlegroups.com> <4492414C.10505@v.loewis.de> <1150444191.618761.22810@c74g2000cwc.googlegroups.com> <1150732472.933138.81170@y41g2000cwy.googlegroups.com> Message-ID: <4496d11a$1@nntp0.pdx.net> meyer at mesw.de wrote: > .... Also, there are many free software programs that use special > features of GCC and cannot be compiled using another compiler. This is precisely what bothers me about standardizing on GCC -- lock-in is lock-in whether you must pay cash or not. --Scott David Daniels scott.daniels at acm.org From david.nospam.hopwood at blueyonder.co.uk Fri Jun 23 20:56:12 2006 From: david.nospam.hopwood at blueyonder.co.uk (David Hopwood) Date: Sat, 24 Jun 2006 00:56:12 GMT Subject: What is a type error? In-Reply-To: <4fv0v3F1kipa6U1@individual.net> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <7i3mg.204167$8W1.155367@fe1.news.blueyonder.co.uk> <44992e6c$2$664$bed64819@news.gradwell.net> <%Igmg.464974$xt.353729@fe3.news.blueyonder.co.uk> <4fv0v3F1kipa6U1@individual.net> Message-ID: Pascal Costanza wrote: > Chris Smith wrote: > >> While this effort to salvage the term "type error" in dynamic >> languages is interesting, I fear it will fail. Either we'll all have >> to admit that "type" in the dynamic sense is a psychological concept >> with no precise technical definition (as was at least hinted by >> Anton's post earlier, whether intentionally or not) or someone is >> going to have to propose a technical meaning that makes sense, >> independently of what is meant by "type" in a static system. > > What about this: You get a type error when the program attempts to > invoke an operation on values that are not appropriate for this operation. > > Examples: adding numbers to strings; determining the string-length of a > number; applying a function on the wrong number of parameters; applying > a non-function; accessing an array with out-of-bound indexes; etc. This makes essentially all run-time errors (including assertion failures, etc.) "type errors". It is neither consistent with, nor any improvement on, the existing vaguely defined usage. -- David Hopwood From grante at visi.com Thu Jun 15 09:47:40 2006 From: grante at visi.com (Grant Edwards) Date: Thu, 15 Jun 2006 13:47:40 -0000 Subject: Numerics, NaNs, IEEE 754 and C99 References: <12904mjhl493t49@corp.supernews.com> <1290aik50hmk94a@corp.supernews.com> <4490329e$0$12356$636a55ce@news.free.fr> <12917f6jp7u90f8@corp.supernews.com> <44912058$0$29674$636a55ce@news.free.fr> Message-ID: <1292p7s46ef5off@corp.supernews.com> On 2006-06-15, Nick Maclaren wrote: > Hence, the SAFE approach is to make the inverse of all zeros a > NaN. OK. You're right. I'm wrong about what my Python programs should do. In any case, that ship sailed. Maybe you can argue convincingly that theoretically your approach is better than IEEE 754. You're not going to get the standard changed. You're not going to get all of the computers on the planet re-worked. Making Python incompatible with IEEE 754 is a bad idea. I might be able to come up with a convincing arguement that driving on the right-hand side of the road is better than driving on the left, but that doesn't make a good idea to do so when in England, Japan, or Australia. -- Grant Edwards grante Yow! This PIZZA symbolizes at my COMPLETE EMOTIONAL visi.com RECOVERY!! From bearophileHUGS at lycos.com Sun Jun 4 16:47:51 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 4 Jun 2006 13:47:51 -0700 Subject: re beginner In-Reply-To: References: Message-ID: <1149454071.232909.197270@y43g2000cwc.googlegroups.com> SuperHik wrote: > I was wondering is there a better way to do it using re module? > perheps even avoiding this for loop? This is a way to do the same thing without REs: data = 'Yellow hat\t2\tBlue shirt\t1\nWhite socks\t4\tGreen pants\t1\nBlue bag\t4\tNice perfume\t3\nWrist watch\t7\tMobile phone\t4\nWireless cord!\t2\tBuilding tools\t3\nOne for the money\t7\tTwo for the show\t4' data2 = data.replace("\n","\t").split("\t") result1 = dict( zip(data2[::2], map(int, data2[1::2])) ) O if you want to be light: from itertools import imap, izip, islice data2 = data.replace("\n","\t").split("\t") strings = islice(data2, 0, len(data), 2) numbers = islice(data2, 1, len(data), 2) result2 = dict( izip(strings, imap(int, numbers)) ) Bye, bearophile From marc.t.davies at gmail.com Tue Jun 20 05:26:47 2006 From: marc.t.davies at gmail.com (MTD) Date: 20 Jun 2006 02:26:47 -0700 Subject: How to truncate/round-off decimal numbers? In-Reply-To: <1150795481.361532.310790@b68g2000cwa.googlegroups.com> References: <1150795481.361532.310790@b68g2000cwa.googlegroups.com> Message-ID: <1150795607.818914.186950@h76g2000cwa.googlegroups.com> > The system cannot > accurately represent some integers, Er, I meant FLOATS. Doh. Anyway, just to underline the example: >>> x 0.66666666666666663 >>> s = str(round(x,2)) >>> s '0.67' >>> f = float(s) >>> f 0.67000000000000004 >>> f == round(x,2) True From fcorreia at gmail.com Fri Jun 30 12:10:03 2006 From: fcorreia at gmail.com (Filipe) Date: 30 Jun 2006 09:10:03 -0700 Subject: handling unicode data References: <1151506510.391856.207460@y41g2000cwy.googlegroups.com> <44a2af7d$0$7205$9b622d9e@news.freenet.de> <1151515932.365483.311890@m73g2000cwd.googlegroups.com> <1151573265.293086.94430@d56g2000cwd.googlegroups.com> Message-ID: <1151683803.505991.233790@h44g2000cwa.googlegroups.com> Frank Millman wrote: > You did not mention the odbc module from Mark Hammond's win32 > extensions. This is what I use, and it works for me. I believe it is > not 100% DB-API 2.0 compliant, but I have not had any problems. > > I have not tried connecting to the database from a Linux box (or from > another Windows box, for that matter). I don't know if there are any > implications there. According to sourceforge's project page (https://sourceforge.net/projects/pywin32/) it seems to only work on windows. There's also adodbapi (http://adodbapi.sourceforge.net/), that also depends on PyWin32, but it would be very handy if I could run this code on a linux box, and with these libs I wouldn't be able to. Still, options are always good to have around :) From digitalorganics at gmail.com Mon Jun 12 11:28:54 2006 From: digitalorganics at gmail.com (digitalorganics at gmail.com) Date: 12 Jun 2006 08:28:54 -0700 Subject: Bridge: Ruby to Python communication Message-ID: <1150126134.802843.122890@h76g2000cwa.googlegroups.com> Hello all. I want a ruby and a python module to be able to communicate with each other, access classes, instances and the like. Is there a bridge for this? I'm aware of rupy, but the documentation seems rather inadequate for the uninitiated. Are there other libraries/bridges or maybe a rupy tutorial? Thank you. From scott.daniels at acm.org Tue Jun 20 12:03:23 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Tue, 20 Jun 2006 09:03:23 -0700 Subject: How to truncate/round-off decimal numbers? In-Reply-To: References: Message-ID: <4498175c$1@nntp0.pdx.net> Sybren Stuvel wrote: > Girish Sahani enlightened us with: >> I want to truncate every number to 2 digits after the decimal point.... >>>>> a = 2 >>>>> b = 3 >>>>> round(a*1.0 / b,2) >> 0.67000000000000004 > > If you want to format it, use '%.2f' % (float(a)/b) Sybren has this right. If you follow everyone else's advice, you'll eventually discover: >>> print round(11024. / 5000.1, 2) only gives you "2.2", not "2.20" (which is what, I suspect, you want). --Scott David Daniels scott.daniels at acm.org From jussij at zeusedit.com Mon Jun 19 20:06:42 2006 From: jussij at zeusedit.com (jussij at zeusedit.com) Date: 19 Jun 2006 17:06:42 -0700 Subject: a good programming text editor (not IDE) References: <_xgkg.2317$No6.48542@news.tufts.edu> <1150406662.900552.46650@u72g2000cwu.googlegroups.com> <1150533881.540254.270400@i40g2000cwc.googlegroups.com> Message-ID: <1150762002.081548.326810@f6g2000cwb.googlegroups.com> 63q2o4i02 at sneakemail.com wrote: > Anyway, the only thing editplus doesn't do that I wish it > did is code folding. If you need a Python folding editor you could always take a look at Zeus: http://www.zeusedit.com/python.html > All the stuff you guys are talking about: line numbers, > syntax highlighting, custom tools (running the interpreter), > regexp search and replace, keeping your environment the same > between sessions, soft word wrap, tab-vs-spaces, auto-indent, > braces-matching, bla bla... it does it all in an appropriately > gui manner without making you feel Zeus does all this, plus it adds features project/workspace management, ftp editing and class browsing. Jussi Jumppanen Author: Zeus for Windows From fredrik at pythonware.com Thu Jun 29 04:50:25 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 29 Jun 2006 10:50:25 +0200 Subject: Amara: Where's my attribute? References: <1151570478.731909.154790@b68g2000cwa.googlegroups.com> Message-ID: "AdSR" wrote: > I'm having a problem with the Amara toolkit. Try this: > >>>> from amara import binderytools >>>> raw = '' >>>> rwd = binderytools.bind_string(raw) >>>> print rwd.xml() > > > > What happened to the xmlns attribute? Does anyone know a solution to > this? the documents are 100% identical in XML infoset terms, so what's the problem here ? > I see that people have reported similar problems with other XML toolkits, so I guess this is a > general namespace ugliness. lack of namespace understanding, more likely. From me at privacy.net Sun Jun 25 19:22:02 2006 From: me at privacy.net (Dan Sommers) Date: Sun, 25 Jun 2006 19:22:02 -0400 Subject: Looking for Python code to obsfucate mailto links on web site References: Message-ID: On Sun, 25 Jun 2006 21:10:31 +0100, Andrew McLean wrote: > I'm looking at putting some e-mail contact addresses on a web site, > and wanted to make it difficult for spammers to harvest them. [ ... ] > Searching the web it looks like the best solution for me might be to > embed JavaScript in the web page that dynamically generates the e-mail > address in the browser client. [ ... ] > Now I could write suitable code myself, but would be surprised if it > wasn't already available. Any pointers? Pointers? What do you think this is, C? ;-) Try this: def spam_averse_email_address( email_address, text ): """return HTML-embedded javascript to create a spam-averse mailto link""" def char_codes( a_string ): return ",".join(str(ord(a_char)) for a_char in a_string) return """""" % (char_codes(email_address), char_codes(text)) The newlines within the triple quoted string are important; use that function something like this: print "" print "Title print " print "

%s

" % spam_averse_email_address( 'email at mydomain.com', 'click here to email me' ) print "" print "" You mentioned accessibility; make sure that your HTML does something sensible if the user's browser doesn't do javascript. HTH, Dan -- Dan Sommers "I wish people would die in alphabetical order." -- My wife, the genealogist From wegein at gmail.com Fri Jun 23 21:36:18 2006 From: wegein at gmail.com (damacy) Date: 23 Jun 2006 18:36:18 -0700 Subject: python + postgres psql + os.popen In-Reply-To: <1150992464.012824.295810@r2g2000cwb.googlegroups.com> References: <1150946077.931411.170930@u72g2000cwu.googlegroups.com> <1150992464.012824.295810@r2g2000cwb.googlegroups.com> Message-ID: <1151112978.614123.161120@p79g2000cwp.googlegroups.com> hi, there. thanks for the help. now i have a different problem now. i decided to use 'subprocess' and 'Popen' objects instead of 'os.popen()' function, which i believe do not make much difference. my code is like the following... [1] link = subprocess.Popen(command, stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE, shell = True) [2] link.communicate(password) [3] link.wait() [4] err = link.communicate()[1] [5] if err != None: print str(err) i have read several threads about 'subprocess' posted on this group and still i have way too much confusion regarding the above section of code. 1. i'm currently using MS Windows. i remember some have said that communicate() function is not usable on this OS. could anyone confirm this? 2. i'm expecting an error message, as i am trying to create a table which does already exist in the database. but if i try to print out the error message as [5], it is just an EMPTY string. and, if i try the SAME THING using command-line, i get a correct error message this time ('psql:createstudent.sql:12: ERROR: relation "student" already exists'). HOWEVER, if i comment out [2] link.communicate(password), meaning i do not supply a password, it shows an error message, 'psql: fe_sendauth: no password supplied', which is correct as expected. my question is... why does it work (i.e. showing a correct error message) when no password supplied but NOT when creating a table which already exists in the database? it should work for both cases. thank you very much. Simon Forman wrote: > damacy wrote: > > hello, everyone. > ... > > this works well. however, it does not show me any warning nor error > > messages if there is one. for example, i am trying to create a table > > which already exists in the database, it should show me a warning/error > > message saying there already is one present in the database, or > > something like that. > > > > can anyone help me? > > I recently needed to use psql from python on a computer that I couldn't > install psycopg on and I used something similar to this to do it (I > edited the code slightly to make it clearer): > > from subprocess import Popen, PIPE > > # Pass the password through an environment > # variable to prevent psql asking for it. > psql_env = dict(PGPASSWORD='********') > > # Create the subprocess. > proc = Popen(cmd, shell=True, env=psql_env, stdout=PIPE, stderr=PIPE) > > # Try reading it's data. > data = proc.stdout.read() > > # Check for errors. > err = proc.stderr.read() > if err: raise Exception(err) > > > It worked nicely for me, YMMV. > > > Hope that helps, > > ~Simon From sekhon.hari at googlemail.com Tue Jun 27 09:19:15 2006 From: sekhon.hari at googlemail.com (Hari Sekhon) Date: Tue, 27 Jun 2006 14:19:15 +0100 Subject: how to do -vv for very verbose? In-Reply-To: References: <44A12872.9030104@gmail.com> Message-ID: <44A13053.4010208@gmail.com> Fredrik Lundh wrote: > Hari Sekhon wrote: > > >> I'm using optparse.Optionparser to take switches for a script I'm >> writing, but I can't see how to give it -vv for very verbose. >> >> the option for -v is simply set to True by the option parser if present, >> whereas I really want a numeric value, 1 if there is -v and 2 if there >> is -vv. >> > > action="count" ? > > > > > > yeah, I realised this just after I sent it, sort it out. Thanks. -h -------------- next part -------------- An HTML attachment was scrubbed... URL: From hancock at anansispaceworks.com Wed Jun 21 02:31:08 2006 From: hancock at anansispaceworks.com (Terry Hancock) Date: Wed, 21 Jun 2006 06:31:08 +0000 Subject: Simple question regarding module initialization In-Reply-To: References: <28dc07920606201846q30e04f2cx28c021818774b4fb@mail.gmail.com> Message-ID: <4498E7AC.7040603@anansispaceworks.com> > On 6/20/06, Patrick M. Nielsen wrote: > > for module in modules: print "Loading %s..." % module exec 'import > > %s' % module > > > > Although I like the outcome of writing it like this, I don't feel > > good about it. Is this against standard Python conventions or > > morals? Loading modules this way, that is (instead of just > > importing it all "the right way" and making a print statement for > > each one). > > > > Troy Melhase wrote: > __import__(name, globals, locals, fromlist) -> module > > Import a module. ... grumble ... top posting ... grumble ... no text ... grumble ... (Probably) Troy's point here is that you'd be better off to use the built-in __import__ function instead of using exec. This is probably clearer. There is no fundamental reason why it is more secure, though (the usual complaint about exec), because you are in complete control of what exec is being fed. However, I'd still recommend __import__ for clarity. Cheers, Terry -- Terry Hancock (hancock at AnansiSpaceworks.com) Anansi Spaceworks http://www.AnansiSpaceworks.com From find at my.address.elsewhere Sun Jun 25 22:43:23 2006 From: find at my.address.elsewhere (Matthias Blume) Date: Sun, 25 Jun 2006 21:43:23 -0500 Subject: What is Expressiveness in a Computer Language References: <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150908952.804184.218990@r2g2000cwb.googlegroups.com> <1150991074.705803.211570@m73g2000cwd.googlegroups.com> <1151244628.566060.40500@p79g2000cwp.googlegroups.com> <1151252226.104247.62960@b68g2000cwa.googlegroups.com> <1151257480.183097.165640@b68g2000cwa.googlegroups.com> Message-ID: Gabriel Dos Reis writes: > rossberg at ps.uni-sb.de writes: > > | think that it is too relevant for the discussion at hand. Moreover, > | Harper talks about a relative concept of "C-safety". > > Then, I believe you missed the entire point. > > First point: "safety" is a *per-language* property. Each language > comes with its own notion of safety. ML is ML-safe; C is C-safe; > etc. I'm not being facetious; I think this is the core of the > confusion. > > Safety is an internal consistency check on the formal definition of > a language. In a sense it is not interesting that a language is > safe, precisely because if it weren't, we'd change the language to > make sure it is! I regard safety as a tool for the language > designer, rather than a criterion with which we can compare > languages. I agree with Bob Harper about safety being language-specific and all that. But, with all due respect, I think his characterization of C is not accurate. In particular, the semantics of C (as specified by the standard) is *not* just a mapping from memories to memories. Instead, there are lots of situations that are quite clearly marked in C's definition as "undefined" (or whatever the technical term may be). In other words, C's specified transition system (to the extend that we can actually call it "specified") has lots of places where programs can "get stuck", i.e., where there is no transition to take. Most actual implementations of C (including "Unix") are actually quite generous by filling in some of the transitions, so that programs that are officially "legal C" will run anyway. Example: The following program (IIRC) is not legal C, even though I expect it to run without problem on almost any machine/OS, printing 0 to stdout: #include int a[] = { 0, 1, 2 }; int main (void) { int *p, *q; p = a; q = p-1; /** illegal **/ printf("%d\n", q[1]); return 0; } Nevertheless, the line marked with the comment is illegal because it creates a pointer that is not pointing into a memory object. Still, a C compiler is not required to reject this program. It is allowed, though, to make the program behave in unexpected ways. In particular, you can't really blame the compiler if the program does not print 0, or if it even crashes. AFAIC, C is C-unsafe by Bob's reasoning. --- Of course, C can be made safe quite easily: Define a state "undefined" that is considered "safe" and add a transition to "undefined" wherever necessary. Kind regards, Matthias From marshall.spight at gmail.com Fri Jun 23 17:49:44 2006 From: marshall.spight at gmail.com (Marshall) Date: 23 Jun 2006 14:49:44 -0700 Subject: Saying "latently-typed language" is making a category mistake In-Reply-To: <449c1f4c$0$662$bed64819@news.gradwell.net> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <86Qmg.10725$o4.1907@newsread2.news.pas.earthlink.net> <4g251pF1knc6tU1@individual.net> <4g28s6F1k9npnU1@individual.net> <4g2e1bF1kmiteU1@individual.net> <449c1f4c$0$662$bed64819@news.gradwell.net> Message-ID: <1151099384.490397.22510@i40g2000cwc.googlegroups.com> Chris Uppal wrote: > Pascal Costanza wrote: > > > Sorry, obviously I was far from being clear. ACL2 is not > > Turing-complete. All iterations must be expressed in terms of > > well-founded recursion. > > How expressive does that end up being for real problems ? I mean obviously in > some sense it's crippling, but how much of a restiction would that be for > non-accademic programming. Could I write an accountancy package in it, or an > adventure games, or a webserver, with not too much more difficulty than in a > similar language without that one aspect to its type system ? > > Hmm, come to think of it those all hae endless loops at the outer level, with > the body of the loop being an event handler, so maybe only the handler should > be required to guaranteed to terminate. An example of a non-Turing-complete language (at least the core language; the standard is getting huge) with guaranteed termination, that is used everywhere and quite useful, is SQL. I wouldn't want to write an accounting package in it; its abstraction facilities are too weak. But the language is much more powerful than it is usually given credit for. Marshall From paul at boddie.org.uk Wed Jun 7 13:50:21 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 7 Jun 2006 10:50:21 -0700 Subject: 10GB XML Blows out Memory, Suggestions? References: <1149594519.098115.8980@u72g2000cwu.googlegroups.com> <4eleh3F1eguosU1@uni-berlin.de> <1149648187.891942.258300@i40g2000cwc.googlegroups.com> <1149692437.283605.74410@f6g2000cwb.googlegroups.com> Message-ID: <1149702621.467403.70960@y43g2000cwc.googlegroups.com> gregarican wrote: > Am I missing something? I don't read where the poster mentioned the > operation as being CPU intensive. He does mention that the entirety of > a 10 GB file cannot be loaded into memory. If you discount physical > swapfile paging and base this assumption on a "normal" PC that might > have maybe 1 or 2 GB of RAM is his assumption that out of line? Indeed. The complaint is fairly obvious from the title of the thread. Now, if the complaint was specifically about the size of the minidom representation in memory, perhaps a more efficient representation could be chosen by using another library. Even so, the size of the file being processed is still likely to be pretty big, considering various observations and making vague estimates: http://effbot.org/zone/celementtree.htm For many people, an XML file of, say, 600MB would still be quite a load on their "home/small business edition" computer if you had to load the whole file in and then work on it, even just as a text file. Of course, approaches where you can avoid keeping a representation of the whole thing around would be beneficial, and as mentioned previously in a thread on large XML files, there's always the argument that some kind of database system should be employed to make querying more efficient if you can't perform some kind of sequential processing. Paul From find at my.address.elsewhere Thu Jun 22 09:54:44 2006 From: find at my.address.elsewhere (Matthias Blume) Date: Thu, 22 Jun 2006 08:54:44 -0500 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150902275.129780.50260@p79g2000cwp.googlegroups.com> <1150918629.818145.143220@y41g2000cwy.googlegroups.com> <4fv081F1jh4ifU1@individual.net> <1150967543.947096.72840@g10g2000cwb.googlegroups.com> <4fv84rF1kp06kU1@individual.net> <4fvfuiF1kncqtU1@individual.net> <87ejxh9xoq.fsf@thalassa.informatimago.com> Message-ID: Pascal Bourguignon writes: > Moreover, a good proportion of the program and a good number of > algorithms don't even need to know the type of the objects they > manipulate. > > For example, sort doesn't need to know what type the objects it sorts > are. It only needs to be given a function that is able to compare the > objects. Of course, some statically typed languages handle this sort of thing routinely. > Only a few "primitive" functions need specific types. Your sort function from above also has a specific type -- a type which represents the fact that the objects to be sorted must be acceptable input to the comparison function. > So basically, you've got a big black box of applicaition code in the > middle that doesn't care what type of value they get, and you've got a > few input values of a specific type, a few processing functions > needing a specific type and returning a specific type, and a few > output values that are expected to be of a specific type. At anytime, > you may change the type of the input values, and ensure that the > needed processing functions will be able to handle this new input > type, and the output gets mapped to the expected type. ...or you type-check your "black box" and make sure that no matter how you will ever change the type of the inputs (in accordance with the interface type of the box) you get a valid program. From deets at nospam.web.de Sun Jun 18 10:11:37 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 18 Jun 2006 16:11:37 +0200 Subject: Detecting key presses In-Reply-To: <1150607857.186185.183130@g10g2000cwb.googlegroups.com> References: <1150607857.186185.183130@g10g2000cwb.googlegroups.com> Message-ID: <4fl58mF1j704vU1@uni-berlin.de> tylertacky at gmail.com schrieb: > Ok, I'm pretty new to python, so this might be a stupid question. I'm > trying to write a simple text-based pong clone, and I can't figure out > how to read key presses to move the paddles. I just need something that > does the same thing as getch() and kbhit(). I can't use those because > their windows only, and I'm running Linux. > > Someone suggested using curses, but that does crazy things with my > output, and leaves the terminal unusable after the program closes. Maybe using pygame for a graphical version is appealing to you - additionally, the event-sytem of it will do what you ask for. Diez From rogue_pedro at yahoo.com Thu Jun 22 12:47:41 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 22 Jun 2006 09:47:41 -0700 Subject: OverflowError: math range error... In-Reply-To: <1150965908.354492.239230@i40g2000cwc.googlegroups.com> References: <1150965908.354492.239230@i40g2000cwc.googlegroups.com> Message-ID: <1150994861.611691.74220@c74g2000cwc.googlegroups.com> Sheldon wrote: > Hi, > > I have a written a script that will check to see if the divisor is zero > before executing but python will not allow this: > > ?if statistic_array[0:4] > 0.0: > statistic_array[0,0:4] = > int(multiply(divide(statistic_array[0,0:4],statistic_array \ > [0,4]),10000.0))/100.0 > > Does anyone know why Python is complaining: > > "statistic_array[0,0:4] = > int(multiply(divide(statistic_array[0,0:4],statistic_array[0,4]),10000.0))/100.0 > > OverflowError: math range error" > > and how do I get around this problem? This stupid because there is a if > statement preventing this "dividing by zero". > > Sincerely, > Sheldon I don't know what special math modules you're using, but python usually raises ZeroDivisionError for divide-by-zero problems. Try printing the intermediate values of each step in your problem code. d = divide(statistic_array[0,0:4], statistic_array[0,4]) print d m = multiply(d, 10000.0) print m i = int(m) print i statistic_array[0,0:4] = i That might help you track down what's wrong. From nogradi at gmail.com Tue Jun 6 14:03:26 2006 From: nogradi at gmail.com (Daniel Nogradi) Date: Tue, 6 Jun 2006 20:03:26 +0200 Subject: newbie: python application on a web page In-Reply-To: References: <1149615269.695229.88820@j55g2000cwa.googlegroups.com> Message-ID: <5f56302b0606061103g618cae39u58794970a81498b5@mail.gmail.com> > > I made this Python calculator that will take an equation as an input > > and will display the computed curves on a shiny Tkinter interface > > well, it doesn't sound like you're quite as newbie-ish as many other > newbies ;-) > > > Now, I'd like to make this application available on a public web > > page... and all I could come up with was this post > > some potentially useful links: > > http://tkinter.unpythonic.net/wiki/ > http://infogami.com/ > http://pages.google.com > > > I'd also appreciate a link to a beginner forum > > assuming "beginner" implies "really wants to learn", this one's quite nice: > > http://mail.python.org/mailman/listinfo/tutor And perhaps you'll find this also helpful: http://modpython.org/ an apache module that embeds the interpreter into the webserver. From gbsuar at gmail.com Fri Jun 30 10:21:17 2006 From: gbsuar at gmail.com (gbsuar at gmail.com) Date: 30 Jun 2006 07:21:17 -0700 Subject: Icono en wxpython In-Reply-To: References: <91906ddf0606281609l17753eaexf12dd3b22433c514@mail.gmail.com> <44a3c7a2$0$21283$626a54ce@news.free.fr> Message-ID: <1151677277.790164.18160@m73g2000cwd.googlegroups.com> Thank. But I to solve my problem. On other hand I commented that I writed a litle program for to send and to recive data from the Serial Port in byte format, no chars. I wanted publish this GNU program in brief. Do you would like to translate to frances? Thank From rvtol+news at isolution.nl Tue Jun 27 05:46:27 2006 From: rvtol+news at isolution.nl (Dr.Ruud) Date: Tue, 27 Jun 2006 11:46:27 +0200 Subject: What is Expressiveness in a Computer Language References: <7zy7vt1mz2.fsf@app-3.diku.dk> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <1151384511.223582.305760@m73g2000cwd.googlegroups.com> Message-ID: Chris Smith schreef: > So it seems to me that we have this ideal point at which it is > possible to write all correct or interesting programs, and impossible > to write buggy programs. I think that is a misconception. Even at the idealest point it will be possible (and easy) to write buggy programs. G?del! -- Affijn, Ruud "Gewoon is een tijger." From keesvanschaik at gmail.com Fri Jun 9 09:26:51 2006 From: keesvanschaik at gmail.com (KvS) Date: 9 Jun 2006 06:26:51 -0700 Subject: Short questions wrt Python & Unicode In-Reply-To: <448970C1.6020005@lexicon.net> References: <1149854676.717074.309260@f6g2000cwb.googlegroups.com> <448970C1.6020005@lexicon.net> Message-ID: <1149859611.112093.314390@i39g2000cwa.googlegroups.com> John Machin wrote: > On 9/06/2006 10:04 PM, KvS wrote: > > > 2) How do I get a representation of a unic. object in terms of Unicode > > code points? repr() doesn't do that, it sometimes parses or encodes the > > code points right: > > > >|>>> s=u"\u0040\u0166\u00e6" > >|>>> s > > u'@\u0166\xe6' > > |>>> ' '.join('U+%04X % ord(c) for c in s) > 'U+0040 U+0166 U+00E6' > > If you'd prefer it more Pythonic than unicode.orgic, adjust the format > string and separator to suit your taste. > > > (does this latter \xe6 have to do with the internal representation of > > unic. objects, maybe with this UCS-2 encoding?) > > |>>> u'\xe6' == u'\u00e6' == unichr(0xe6) > True > |>>> hex(ord(u'\u00e6')) > '0xe6' > > U+nnnnnn is represented internally as the integer 0xnnnnnn -- except if > it won't fit, but you can pretend that surrogate pairs don't exist, for > the moment :-) > > Cheers, > John Thanks to you and Fredrik! What about q1? I know it's silly since for integers e.g. one doesn't give such an issue any thought at all, it's just that this understanding of en/decodings etc. make things a bit more blurry to me. It should be the case that a package may do internally (en-/decodign etc.) what it wants to represent/manipulate unic. strings but should always communicate to the outside world via the interchangable & uniform Python unicode object right? From sreeram at tachyontech.net Wed Jun 7 14:17:52 2006 From: sreeram at tachyontech.net (K.S.Sreeram) Date: Wed, 07 Jun 2006 23:47:52 +0530 Subject: xml processing speed test In-Reply-To: References: <44870F5C.8010407@tachyontech.net> Message-ID: <44871850.2070404@tachyontech.net> Fredrik Lundh wrote: > your celementtree example isn't exactly optimal, though... are you sure > you understand how iterparse works? From what i understand, the iterparse interface constructs the xml tree, but gives you hooks into the tree construction process itself, so that the programmer can control how much state he wants to retain and how much state he can discard. I wanted the test program to maintain as little state as possible, so i'm discarding all state at the earliest. I also read the note regarding clearing the root node on your website, but if add code to do that, the test program actually became *slower*!! So can you tell me how i can use iterparse more effeciently? Regards Sreeram -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 260 bytes Desc: OpenPGP digital signature URL: From onurb at xiludom.gro Thu Jun 29 08:29:21 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Thu, 29 Jun 2006 14:29:21 +0200 Subject: Icono en wxpython In-Reply-To: References: <91906ddf0606281609l17753eaexf12dd3b22433c514@mail.gmail.com> Message-ID: <44a3c7a2$0$21283$626a54ce@news.free.fr> Gabriel wrote: > Hola: > He echo un programa en wxpython. Se trata de un programa para > desarrollos con microcontroladores como PIC's etc. en cuanto a > transmisi?n RS232 se refiere. > > El programa es GNU y quiero publicarlo pronto pero no se como poner el > ?cono a la ventana y al archivo en si... > > ?Alguien puede darme una mano con esto? > > Otra cosa ?d?nde puedo publicar el programa una vez que este terminado? > > Desde ya muchas gracias Bonjour. Je n'ai pas compris un seul mot de ton post, ? part qu'il concernait une appli wxPython, des microcontrolleurs, et des transmission RS232. Peut-?tre que si tu postais la question in English, ?a aiderait un peu ?-) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From fredrik at pythonware.com Wed Jun 21 11:08:42 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 21 Jun 2006 17:08:42 +0200 Subject: need all python dialog equivalent In-Reply-To: References: Message-ID: Eric S. Johansson wrote: > I'm creating a dialogue style interface for an application on a > dedicated system. All I have is basic Python 2.3. Is there anything > like an all Python dialog equivalent floating around? I'm currently > hacking away in curses but it's taking me a long way down what I fear to > be a wrong path. http://excess.org/urwid/ ? From yaru22 at gmail.com Sun Jun 18 10:46:48 2006 From: yaru22 at gmail.com (yaru22) Date: 18 Jun 2006 07:46:48 -0700 Subject: debugging in eclipse+pydev Message-ID: <1150642008.751778.86360@c74g2000cwc.googlegroups.com> Hi. I'd like to know how to debug in eclipse+pydev. In the menu, "Pydev Debug", there's Start Debug Server option, but I don't know how to use it. Few questions I have about debugging are: 1) how do i set a breakpoints in pydev? 2) how do i execute the code line by line? I mean... step into, step over, and so on... When I searched on http://www.fabioz.com/pydev/, I found that Run/Debug Step Into F5 Debugging Run/Debug Step Over F6 Debugging Run/Debug Step Return F7 Debugging Run/Debug Resume F8 Debugging However, Starting Debug Server and pressing F5, F6, F7 didn't do those functions. Can anyone give me a small tutorial as to how to debug in Eclipse + Pydev please? Thanks in advance. From steve at holdenweb.com Mon Jun 5 14:36:34 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 05 Jun 2006 19:36:34 +0100 Subject: How to add few pictures into one In-Reply-To: <1149529269.228019.120480@u72g2000cwu.googlegroups.com> References: <1149511692.796038.155930@c74g2000cwc.googlegroups.com> <1149517433.880564.128350@h76g2000cwa.googlegroups.com> <1149529269.228019.120480@u72g2000cwu.googlegroups.com> Message-ID: Lad wrote: > Steve Holden wrote: > >>Lad wrote: >> >>>K.S.Sreeram wrote: >>> >>> >>>>Lad wrote: >>>> >>>> >>>>>Hello , >>>>>is it possible to add( with PYTHON language) several image files into >>>>>one? >>>> >>>>Google for 'Python Imaging Library'... >>>> >>>>Regards >>>>Sreeram >>>> >>>> >>>> >>> >>>Thank you for your reply. >>>I was thinking about this: >>>to open each image file in binary mode , read it and write into the >>>result image file? >>>Is that possible? >>>Regards, >>>L >>> >> >>Of course, but what you haven't said yet is how you want the resulting >>image file to behave. Do you want it to contain tiled copies of the >>original images, or be an animation with each frame being one of the >>original images, or something else I haven't thought of. >> >>We aren't mind readers here. >> >>though-some-regulars-get-close-ly y'rs - steve >>-- > > Steve > Thank you for your reply > All that I want is this: > I download ( via Python) some pictures from internet and I want to add > all these pictures into one =one file/ > So far, I managed to download pictures but I do not know how to add i > them nto one file. > How can I do that? > Thank you for reply and help > L. > Zip file? Image file? "Add all these pictures into one file" isn't (fro me) a sufficient specification. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From grahn+nntp at snipabacken.dyndns.org Thu Jun 29 16:30:08 2006 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 29 Jun 2006 20:30:08 GMT Subject: style question References: <1151314163.701348.195370@u72g2000cwu.googlegroups.com> <1151314474.696043.201250@b68g2000cwa.googlegroups.com> Message-ID: On Mon, 26 Jun 2006 11:47:21 +0200, Fredrik Lundh wrote: ... > assuming fixed-pitch fonts isn't very Pythonic, though; to get reliable indentation > no matter what font you're using, you can write [...] Since when? I've always coded, in all languages I've ever used[1], under the assumption that the reader will view it with a fixed-pitch (or whatever the proper term is) font. I assumed everyone else did, too. I still assume that, in fact -- noone has ever come up to me and said "hey, that code you wrote looks ugly in Comic Sans MS". (I like well-typeset code in print though. Bjarne Stroustrup uses an elegant system for C++ code, where identifiers and strings are in Times italic, operators in Courier, and so on.) /Jorgen [1] Too young for punch cards. -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From riteshsarraf at gmail.com Thu Jun 29 03:02:20 2006 From: riteshsarraf at gmail.com (Ritesh Raj Sarraf) Date: 29 Jun 2006 00:02:20 -0700 Subject: zipfile module doesn't allow append Message-ID: <1151564540.032393.182600@m73g2000cwd.googlegroups.com> Hi, I've got a problem here. def compress_the_file(zip_file_name, files_to_compress, sSourceDir): """ Condenses all the files into one single file for easy transfer """ try: import zipfile except ImportError: sys.stderr.write("Aieeee! module not found.\n") try: os.chdir(sSourceDir) except: #TODO: Handle this exception pass filename = zipfile.ZipFile(zip_file_name, "a") # try: # filename = zipfile.ZipFile(zip_file_name, "a") # except: # #TODO Handle the exception # sys.stderr.write("\nAieee! Some error exception in creating zip file %s\n" % (zip_file_name)) # sys.exit(1) filename.write(files_to_compress, files_to_compress, zipfile.ZIP_DEFLATED) filename.close() The line filename = zipfile.ZipFile(zip_file_name, "a") throws an exception if the given filename is not present already. Shouldn't it create a file (in case one is not there) since it is "append" mode ?? Ritesh From ilias at lazaridis.com Thu Jun 8 13:59:31 2006 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Thu, 08 Jun 2006 20:59:31 +0300 Subject: CONSTRUCT - Python's way of Ruby's "alias_method" In-Reply-To: References: Message-ID: Maric Michaud wrote: > Le Jeudi 08 Juin 2006 15:15, Duncan Booth a ?crit : >> but the more usual way is just to call the original method directly in the >> base class. >> >> class SqliteAdapter(BaseClass): >> def create_table(self, *args) >> self.table_evolve(*args) >> result = BaseClass.create_table(self, *args) >> return result >> > > Yeah, this the right way to reuse ancestor's implementation of a method. > >> If that isn't what you are trying to achieve you'll have to explain more. > I'm not a ruby programmer, but I understood it like this : the prupose is to > modify the behavior of an existing third-party class, in all application > (even in existing third party modules), without any code modifications > (traditional patch) in those modules. yes, you've understood right. > Your proposal is not as good here, assuming BaseClass is defined in module > toto, you can still do toto.BaseClass = SqliteAdapter, but you must ensure > that this code is imported before any other where classes inherit from > BaseClass. The one I porpose in my other post is robust, several packages can > even patch the same method with no side effects. Your suggestion is most possibly the relevant construct. I'll post a note after changing the implementation. Thank's a lot! . -- http://lazaridis.com From jzgoda at o2.usun.pl Thu Jun 15 18:11:14 2006 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Fri, 16 Jun 2006 00:11:14 +0200 Subject: a good programming text editor (not IDE) In-Reply-To: References: <_xgkg.2317$No6.48542@news.tufts.edu> <1150402733.116243.9680@y41g2000cwy.googlegroups.com> Message-ID: Fredrik Lundh napisa?(a): >> You died in last century with your editor, we have tabs. > > real python programmers don't use tabs. So I'll tab you the beer I owe you when we meet at EuroPython. -- Jarek Zgoda http://jpa.berlios.de/ From davidh at ilm.com Wed Jun 21 14:34:42 2006 From: davidh at ilm.com (David Hirschfield) Date: Wed, 21 Jun 2006 11:34:42 -0700 Subject: Help with deprecation-wrapper code Message-ID: <44999142.3040205@ilm.com> I have a deprecation-wrapper that allows me to do this: def oldFunc(x,y): ... def newFunc(x,y): ... oldFunc = deprecated(oldFunc, newFunc) It basically wraps the definition of "oldFunc" with a DeprecationWarning and some extra messages for code maintainers, and also prompts them to look at "newFunc" as the replacement. This way, anyone who calls oldFunc() will get the warning and messages automatically. I'd like to expand this concept to classes and values defined in my modules as well. So, I'd like a deprecatedClass that would somehow take: class OldClass: ... class NewClass: ... OldClass = deprecatedClass(OldClass, NewClass) and would similarly give the warning and other messages when someone tried to instantiate an OldClass object. And, for general values, I'd like: OLD_CONSTANT = "old" NEW_CONSTANT = "new" OLD_CONSTANT = deprecatedValue(OLD_CONSTANT, NEW_CONSTANT) so any attempt to use OLD_CONSTANT (or just the first attempt) would also output the warning and associated messages. I think that setting it up for classes would just mean making a wrapper class that generates the warning in its __init__ and then wraps the instantiation of the old class. But how can I do something similar for plain values like those constants? Is there a better way to do this whole thing, in general? Anyone already have a similar system set up? Thanks in advance, -David -- Presenting: mediocre nebula. -- http://mail.python.org/mailman/listinfo/python-list -- Presenting: mediocre nebula. -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan.behnel-n05pAM at web.de Fri Jun 2 06:53:29 2006 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Fri, 02 Jun 2006 12:53:29 +0200 Subject: [ANN] lxml 1.0 released Message-ID: Hallo everyone, I have the honour to announce the availability of lxml 1.0. http://codespeak.net/lxml/ It's downloadable from cheeseshop: http://cheeseshop.python.org/pypi/lxml """ lxml is a Pythonic binding for the libxml2 and libxslt libraries. It provides safe and convenient access to these libraries using the ElementTree API. It extends the ElementTree API significantly to offer support for XPath, RelaxNG, XML Schema, XSLT, C14N and much, much more. Its goals are: * Pythonic API. * Documented. http://codespeak.net/lxml/#documentation * FAST! http://codespeak.net/lxml/performance.html * Use Python unicode strings in API. * Safe (no segfaults). * No manual memory management! (as opposed to the official libxml2 Python bindings) """ While the list of features added since the last beta version (1.0.beta) is rather small, this version contains a large number of bug fixes found by various users and testers. Thank you all for your help! Stefan Features added since 0.9.2: * Element.getiterator() and the findall() methods support finding arbitrary elements from a namespace (pattern {namespace}*) * Another speedup in tree iteration code * General speedup of Python Element object creation and deallocation * Writing C14N no longer serializes in memory (reduced memory footprint) * PyErrorLog for error logging through the Python logging module * element.getroottree() returns an ElementTree for the root node of the document that contains the element. * ElementTree.getpath(element) returns a simple, absolute XPath expression to find the element in the tree structure * Error logs have a last_error attribute for convenience * Comment texts can be changed through the API * Formatted output via pretty_print keyword to serialization functions * XSLT can block access to file system and network via XSLTAccessControl * ElementTree.write() no longer serializes in memory (reduced memory footprint) * Speedup of Element.findall(tag) and Element.getiterator(tag) * Support for writing the XML representation of Elements and ElementTrees to Python unicode strings via etree.tounicode() * Support for writing XSLT results to Python unicode strings via unicode() * Parsing a unicode string no longer copies the string (reduced memory footprint) * Parsing file-like objects now reads chunks rather than the whole file (reduced memory footprint) * Parsing StringIO objects from the start avoids copying the string (reduced memory footprint) * Read-only 'docinfo' attribute in ElementTree class holds DOCTYPE information, original encoding and XML version as seen by the parser * etree module can be compiled without libxslt by commenting out the line include "xslt.pxi" near the end of the etree.pyx source file * Better error messages in parser exceptions * Error reporting now also works in XSLT * Support for custom document loaders (URI resolvers) in parsers and XSLT, resolvers are registered at parser level * Implementation of exslt:regexp for XSLT based on the Python 're' module, enabled by default, can be switched off with 'regexp=False' keyword argument * Support for exslt extensions (libexslt) and libxslt extra functions (node-set, document, write, output) * Substantial speedup in XPath.evaluate() * HTMLParser for parsing (broken) HTML * XMLDTDID function parses XML into tuple (root node, ID dict) based on xml:id implementation of libxml2 (as opposed to ET compatible XMLID) Bugs fixed since 0.9.2: * Memory leak in Element.__setitem__ * Memory leak in Element.attrib.items() and Element.attrib.values() * Memory leak in XPath extension functions * Memory leak in unicode related setup code * Element now raises ValueError on empty tag names * Namespace fixing after moving elements between documents could fail if the source document was freed too early * Setting namespace-less tag names on namespaced elements ('{ns}t' -> 't') didn't reset the namespace * Unknown constants from newer libxml2 versions could raise exceptions in the error handlers * lxml.etree compiles much faster * On libxml2 <= 2.6.22, parsing strings with encoding declaration could fail in certain cases * Document reference in ElementTree objects was not updated when the root element was moved to a different document * Running absolute XPath expressions on an Element now evaluates against the root tree * Evaluating absolute XPath expressions (/*) on an ElementTree could fail * Crashes when calling XSLT, RelaxNG, etc. with uninitialized ElementTree objects * Memory leak when using iconv encoders in tostring/write * Deep copying Elements and ElementTrees maintains the document information * Serialization functions raise LookupError for unknown encodings * Memory deallocation crash resulting from deep copying elements * Some ElementTree methods could crash if the root node was not initialized (neither file nor element passed to the constructor) * Element/SubElement failed to set attribute namespaces from passed attrib dictionary * tostring() now adds an XML declaration for non-ASCII encodings * tostring() failed to serialize encodings that contain 0-bytes * ElementTree.xpath() and XPathDocumentEvaluator were not using the ElementTree root node as reference point * Calling document('') in XSLT failed to return the stylesheet From paddy3118 at netscape.net Thu Jun 1 18:53:08 2006 From: paddy3118 at netscape.net (Paddy) Date: 1 Jun 2006 15:53:08 -0700 Subject: grouping a flat list of number by range References: <1149196642.001466.53990@c74g2000cwc.googlegroups.com> <1149201416.196975.123370@c74g2000cwc.googlegroups.com> Message-ID: <1149202388.135494.148890@u72g2000cwu.googlegroups.com> I did a little re-arranging of the generator version: def interv3(inlist): tmp = inlist[0] valinc = tmp+1 for val in inlist[1:]: if val != valinc: yield [tmp, valinc]; tmp = val valinc = val+1 yield [tmp, valinc] From francois.schnell at gmail.com Tue Jun 6 14:33:19 2006 From: francois.schnell at gmail.com (francois.schnell at gmail.com) Date: 6 Jun 2006 11:33:19 -0700 Subject: capture video from camera In-Reply-To: <1149603488.012417.269760@j55g2000cwa.googlegroups.com> References: <1149598946.182874.121650@c74g2000cwc.googlegroups.com> <1149603488.012417.269760@j55g2000cwa.googlegroups.com> Message-ID: <1149618799.409008.33060@h76g2000cwa.googlegroups.com> aljosa wrote: >and doesn't provide additional options like > motion detection nor any info on possibility of motion detection or > howto implement An example for motion detection and even pythonic eye toys :) http://gumuz.looze.net/wordpress/index.php/archives/2005/06/06/python-webcam-fun-motion-detection/ francois From bdesth.quelquechose at free.quelquepart.fr Wed Jun 28 21:40:31 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 29 Jun 2006 03:40:31 +0200 Subject: curiosity about the nature of identity (in python) In-Reply-To: References: Message-ID: <44a2ff3e$0$5668$636a55ce@news.free.fr> James Stroud a ?crit : > Hello all, > > What /is/ identity in python? A unique identifier associated with each and every object in the process. What exactly is this identifier is left to the implementation - FWIW and IIRC, CPython uses the memory address of the C 'object' datastructure. > For example, we can always count on > > py> None is None > True Yes. None is a singleton. > But I have noticed that this works for strings: > > py> "none" is "none" > True > > and, for example, integers: > > py> 42 is 42 > True This is an implementation detail of CPython - which does some caching, and is by no way specified by the language. You should *never* rely on this. FWIW, try: a = 3900000 b = 3900000 a is b > And I have noticed that this works for equivalent expressions: > > py> 42 is (40 + 2) > True > > So, I'm guessing that the integer 42, or the string "none" is cached > somewhere Bingo !-) > and python looks to see if it is in the cache when evaluating > 'is'. I don't think the evaluation of 'is' as anything to do with this. > My guess is supported with this test: > > py> id(42) > 149679044 > py> id(40+2) > 149679044 > py> id(7*6) > 149679044 Now what about this: >>> id(600) 134745616 >>> id(601) 134745616 id of an object is unique *for the lifetime of this object*. Nothing prevents it from being reused later. > So, I guess my question is to what extent is this equivalency > implementation dependent? cf above > Is this equivalency a requirement for a > legitimate python implementation? cf above > Won't these checks slow down > evaluation of 'is' considerably? I really doubt that comparing memory addresses could be slow... > Does '==' ever fall back and use 'is' > (or 'id') for evaluation? Seems so : >>> class Foo(object): pass ... >>> f1 = Foo() >>> f2 = Foo() >>> f3 = f1 >>> f1 == f2 False >>> f1 == f3 True From michele.simionato at gmail.com Thu Jun 15 04:33:36 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 15 Jun 2006 01:33:36 -0700 Subject: Correctly reading stdout/stderr from subprocess In-Reply-To: References: <20060613222002.GB5153@workaround.org> <200606141314.14587.maric@aristote.info> Message-ID: <1150360416.019559.203780@c74g2000cwc.googlegroups.com> Maric Michaud wrote: I would consider avoiding threads via Twisted utils.getProcessOutput: http://twistedmatrix.com/projects/core/documentation/howto/process.html#auto6 Michele Simionato From mgalves at gmail.com Fri Jun 9 16:09:32 2006 From: mgalves at gmail.com (Miguel Galves) Date: Fri, 9 Jun 2006 17:09:32 -0300 Subject: Python or Ajax? In-Reply-To: References: Message-ID: <52655700606091309j776503b7uf0a5e0b7e14adca9@mail.gmail.com> These are two very different things. Python is a programming language, that can be used to write server side code, and web applications. AJAX is mora way of life than a technology. Its a list of well known technologies that can be used together to build rich user interfaces. AJAX and Python could be used together to build nice web applications. Inf fact..AJAX should be used within any web app. []s Miguel On 6/9/06, Redefined Horizons wrote: > > I've been hearing a ot about AJAX lately. I may have to build a web > application in the near future, and I was curoius: > > How does a web application that uses Python compare with one that uses > AJAX? > > I've done some basic web page design with HTML and CSS, but never any > web applications. I don't want to learn a new language if I can use > Python. Would AJAX offer me any significant advantages? > > Thanks, > > Scott Huey > -- > http://mail.python.org/mailman/listinfo/python-list > -- Miguel Galves - Engenheiro de Computa??o J? leu meus blogs hoje? Para geeks http://log4dev.blogspot.com Pra pessoas normais http://miguelgalves.blogspot.com "N?o sabendo que era imposs?vel, ele foi l? e fez..." -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Tue Jun 20 10:07:18 2006 From: tjreedy at udel.edu (tjreedy) Date: Tue, 20 Jun 2006 10:07:18 -0400 Subject: Tail recursion Re: list of polynomial functions References: <1150390140.459461.169900@i40g2000cwc.googlegroups.com><1150777400.370686.162340@i40g2000cwc.googlegroups.com> Message-ID: "Pekka Karjalainen" wrote in message news:slrne9f84g.227.pkarjala at paju.oulu.fi... > Python doesn't do any kind of tail recursion optimization by default > because Guido has decided it shouldn't (at least so far). I'm sure it has > been discussed in detail in Python development forums & lists, but I > don't know those details. Giving Python's late name resolution, the transformation would be a change in semantics. Something might be proposed for 3.0. Terry Jan Reedy From rune.strand at gmail.com Sat Jun 17 15:52:41 2006 From: rune.strand at gmail.com (Rune Strand) Date: 17 Jun 2006 12:52:41 -0700 Subject: Python is fun (useless social thread) ;-) In-Reply-To: References: Message-ID: <1150573961.441575.270110@r2g2000cwb.googlegroups.com> In 2002, I was in need of a multi-platform language. My choice became Python, in spite of friends fiercly defending Perl and some interesting Slashdot-articles on Ruby. But back on university, I met a very, very pretty C++ girl who said many favourable things about Python. She never became mine, but the sympathy for Python that she implanted in my mind, turned out to make me immune against the Perl propaganda. So Python (for me) could be said to be either a substitute for the prettiest of the (many) pretty girls of Norway or a mindchild of the same. I found a script demonstrating search/replace in files. And even if I hadn't coded in a year, I found Python surprisingly easy to read, understand and change. So there I was. > Did you have to learn it for a job? No, but I use it as often as possible in work contexts. > Or did you just like what you saw and decided to learn it for fun? That's more like it. > Also, how did you go about learning it? I ported som other scripts (Bash, PHP, and DOS bat-files) to Python while searching the net each time I became lost. Porting is a good learning method. > Was there any necessity in the specifics you learned, > or did you just dabble in something > (e.g. wxPython) for fun? Mostly fun and some practical problems. Later I've used Boa Constructor to make GUI's for some customers. > Are there still some things you feel you need to learn or improve? Sure, I struggle with OO when it gets complicated and new features like decorators. And idioms. But generally it's programming skills and algorithmic scent I need. > Additional comments/complains here: :) I'm a bit afraid that the new features and the turning to concepts like iterators and generators are making Python elitistic. Old python code floating around the net is generally easy to read, while newer often is harder to grasp. I don't like it when my own inherent stupidity becomes to obvious to hide. From onurb at xiludom.gro Tue Jun 27 08:13:49 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Tue, 27 Jun 2006 14:13:49 +0200 Subject: pyrex functions to replace a method (Re: replace a method in class: how?) In-Reply-To: References: <44A06A6B.6010200@bryant.edu> Message-ID: <44a120fd$0$12756$636a55ce@news.free.fr> Brian Blais wrote: > Thanks for all who replied to this question about replacing a method. I > feel a little sheepish for not having caught that I have to replace it > in the class, not the instance, But you *can* replace it on a per-instance basis. It's easy, perfectly legal, and can be very convenient. I'm very sorry that some poster here try to forcefit Javaish restricted OO conception into Python. Free your mind, burn your books, and take full advantage of Python's powerfull object model. > but I have found a very similar problem > trying to replace a method using a function defined in pyrex. I post > all of the code below, but there are several files. > > The main code is: > > import module_py # import a function from a python module > import module_pyrex # import a function from a pyrex extension module > > class This(object): > > def update1(self,val): > print val > > def update2(self,val): > print "2",val > > def update3(self,val): > print "3",val > > def local_update(obj,val): > > print "local",val > > > This.update1=local_update # replace the method from a local function > This.update2=module_py.python_update # replace the method from a python > module > This.update3=module_pyrex.pyrex_update # replace the method from a > pyrex module Note that - from a purely technical POV - you don't need to define the updateXXX methods in This. You can add methods directly - in fact, defining a function in a class statement will end up doing the same thing as binding it to the class objet outside the class statement. > t=This() > > t.update1('local') # works fine > t.update2('python') # works fine > t.update3('pyrex') # gives a typeerror function takes exactly 2 > arguments (1 given) (snip) > > any ideas why the pyrex function fails? > I don't have much knowledge wrt/ pyrex, but I guess that pyrex functions don't implement the descriptor protocol as pure Python functions do, so the instance object is not passed to the function at calltime. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From kay.schluehr at gmx.net Mon Jun 19 05:06:43 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 19 Jun 2006 02:06:43 -0700 Subject: Seeking regex optimizer In-Reply-To: References: <1150650439.651839.38180@y41g2000cwy.googlegroups.com> Message-ID: <1150708003.681073.296430@f6g2000cwb.googlegroups.com> Mirco, with "special characters" I mentioned control characters of regular expressions i.e. one of ".^$()?[]{}\|+*" but not non ascii-127 characters. For a workaround you simply have to "mangle" those using an escape control character: REGEXCHAR = ".^$()?[]{}\\|+*" def mangle(s): pattern = [] for c in s: if c in REGEXCHAR: pattern.append("\\") pattern.append(c) return "".join(pattern) Regards, Kay From onurb at xiludom.gro Mon Jun 12 07:18:53 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Mon, 12 Jun 2006 13:18:53 +0200 Subject: Function to remove elements from a list working, but python hangs :(( In-Reply-To: References: <448d346b$0$20350$636a55ce@news.free.fr> Message-ID: <448d4d9e$0$10993$626a54ce@news.free.fr> Girish Sahani wrote: (please don't top-post) > Hey Bruno...you are seeing the wrong post :P...please ignore this and > check out the one with (corrected) appended at the end... You should have posted the correction in the same thread. > Also, i used the list comprehension thingy which u have given, but now the > problem is python just hangs if my list l4 contains around 50 > pairs...considering its not that big a data, this shouldnt happen.... > Should it?? It shouldn't. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From girish at cse.iitb.ac.in Mon Jun 12 04:12:41 2006 From: girish at cse.iitb.ac.in (Girish Sahani) Date: Mon, 12 Jun 2006 13:42:41 +0530 (IST) Subject: Function to remove elements from a list not working Message-ID: <45877.10.209.4.1.1150099961.squirrel@10.105.1.3> Hi, I am trying to convert a list of pairs (l4) to list l5 by removing those pairs from l4 which are not present in a third list called pairList. The following is a simplified part of the routine i have written. However it does not give the correct output. Please help! Its possible i have made a trivial mistke since i am a newbie. def getl5(): l5 = [] pairList = [[1,2],[3,4],[3,5],[3,6],[9,7],[8,9],[8,7],[7,9],[11,10]] l4 = [[4,2],[4,7],[4,10],[4,12],[9,2],[9,7],[9,10],[9,12],[11,2],[11,7]] for pair in l4: if pair not in pairList: element.remove(l4) l5.append(element) print "l5 is",l5 From buchstaebchen at googlemail.com Fri Jun 30 06:41:48 2006 From: buchstaebchen at googlemail.com (mart_jeeha) Date: 30 Jun 2006 03:41:48 -0700 Subject: image output in matplotlib Message-ID: <1151664108.697157.116030@p79g2000cwp.googlegroups.com> Hey folks, I got a problem in printing images from a matplotlib - FigureCanvas Object (child of a wxFrame, library backend_wx) into jpeg-formatted files. (I like to create a sequence of images that I can assemble to an avi) self.mycanvas.print_figure("test.jpg") merely gives an error stating, that there should be "an image handler of type 17", which I didn't come across ever :) No idea about the handles, does anybody has any hint how to proceed ? (or any thread I missed to grab..) thanks a lot and cheers, Martin From andre.roberge at gmail.com Sat Jun 3 12:46:13 2006 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: 3 Jun 2006 09:46:13 -0700 Subject: elementtree and inclusion of special characters Message-ID: <1149353173.530528.116170@f6g2000cwb.googlegroups.com> I'm using elementtree to process some html files, by building a tree, manipulating it, and writing it back. One problem I encounter is that elementtree converts some symbols in an unwanted way. For example, the symbol ">" is converted to ">". This is fine in html code, but not if the page includes some script like the example below The resulting code, with "a > 0" is not understood by the browser... Any suggestions as to how I can circumvent this problem in an easy way? Andr? From invalidemail at aerojockey.com Fri Jun 9 19:38:19 2006 From: invalidemail at aerojockey.com (Carl Banks) Date: 9 Jun 2006 16:38:19 -0700 Subject: Allowing zero-dimensional subscripts In-Reply-To: References: <1149801040.936452.26270@i40g2000cwc.googlegroups.com> Message-ID: <1149896299.760886.52810@f6g2000cwb.googlegroups.com> Fredrik Lundh wrote: > noam's proposal is to make this work: > > >>> x[] > () > > (but should it really result in an empty tuple? wouldn't None be a bit > more Pythonic?) How would you index a 2-D array? With a 2-tuple. How would you index a 1-D array? With a 1-tuple. How would you index a 0-D array? ... Carl Banks From ptmcg at austin.rr._bogus_.com Tue Jun 13 00:02:15 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Tue, 13 Jun 2006 04:02:15 GMT Subject: Combining The Best Of Python, Ruby, & Java?????? References: Message-ID: "Tim Daneliuk" wrote in message news:nf81m3-l7k.ln1 at eskimo.tundraware.com... > So it is claimed: > > http://www.infoq.com/news/Scala--combing-the-best-of-Ruby-;jsessionid=CC7C8366455E67B04EE5864B7319F5EC > > Has anyone taken a look at this that can provide a meaningful contrast > with Python? Ok, here's the Hello World example from the Scala website: object HelloWorld { def main(args: Array[String]) = { Console.println("Hello, world!") } } Opening and closing braces? "def main(args: Array[String])"? Console.println? About the only Pythonic thing I can see here is the "def" keyword. Otherwise, it looks too much like Java - no, thanks! -- Paul From anthra.norell at tiscalinet.ch Thu Jun 1 04:51:57 2006 From: anthra.norell at tiscalinet.ch (Anthra Norell) Date: Thu, 1 Jun 2006 10:51:57 +0200 Subject: losing handles of open files Message-ID: <000c01c68558$a48a9680$0201a8c0@mcuf7> Hi If a piece of code exits with an exception before it closes an open file, that file seems to remain locked, which is real pain in the butt if I develop a file in parallel with a piece of code. Is there a way to close such lost files short of starting a new session? Frederic -------------- next part -------------- An HTML attachment was scrubbed... URL: From markus_wankus at hotmail.com Sun Jun 25 19:33:38 2006 From: markus_wankus at hotmail.com (Markus Wankus) Date: Sun, 25 Jun 2006 23:33:38 GMT Subject: Eclipse IDE question References: <1151241922.620601.218580@r2g2000cwb.googlegroups.com> Message-ID: On Sun, 25 Jun 2006 13:21:32 -0400, seerhut wrote: > kilnhead wrote: >> I am trying to use eclipse for python development. Is it possible to >> run a python script without having to name/setup a configuration? Can >> eclipse be set up so that "run" loads the code into the interpreter and >> goes? I don't want to create a new run config every time I want to run >> a script. >> > try pydev , a plugin for eclipse I'm fairly certain the OP is already doing that... As far as I know (I haven't used pydev in awhile) you need a launch configuration for each script. I do know you can run a script easily and have the launch created for you just by right-clicking the file and saying Run As > Python (I think). Here is what the FAQ says: How do I run a module from within eclipse using PyDev (either Python or Jython)? To do that, the easiest way is going to the Run menu (Run->Run As->Python or Jython). If it is not available in your current eclipse perspective, you can enable it by going to window->customize perspective->commands and checking the "Lauch" item (in this way, you can go only with the keyboard). Another way to run a module is right clicking the module in the navigator and choosing python->run (when a .py file is selected). Markus. From aleax at mac.com Sun Jun 18 01:22:42 2006 From: aleax at mac.com (Alex Martelli) Date: Sat, 17 Jun 2006 22:22:42 -0700 Subject: Easy question on minidom References: Message-ID: <1hh3kle.15914xibwdc53N%aleax@mac.com> Dean Card wrote: > I am using minidom to parse a 20,000 line XML file. I have a few instances > where the number of child nodes of a particular node can be variable in > number. To access them I am doing something like the following... > > xmldoc = minidom.parseString(r) > results = xmldoc.childNodes[0] > > for myNode in results.childNodes[1].childNodes: > do Stuff with myNode... > > problem is I am having a heck of a time trying to access the value of the > node. For instance I get things like this > > > > > > > > But I need the values... any help here? Not sure what you mean by "the values" -- if you mean for example the contents of text data lying under the node, you can access them...: >>> from xml.dom import minidom >>> s='unodos' >>> xmldoc = minidom.parseString(s) >>> xmldoc.childNodes[0] >>> xmldoc.childNodes[0].childNodes [, ] >>> for node in xmldoc.childNodes[0].childNodes: print node ... >>> for node in xmldoc.childNodes[0].childNodes: print node.childNodes[0] ... >>> for node in xmldoc.childNodes[0].childNodes: print node.childNodes[0].data ... uno dos >>> i.e., the text node is the .childNodes[0] (or more elegantly the .firstChild, of course) of the element node containing it, and if you need that text node's text data, that's its .data attribute. If you need something else, I suggest you post a small example (like mine here) with a clear explanation of what exactly it is that you need! Alex From john.hicken at gmail.com Mon Jun 12 06:43:07 2006 From: john.hicken at gmail.com (John Hicken) Date: 12 Jun 2006 03:43:07 -0700 Subject: urllib behaves strangely In-Reply-To: References: Message-ID: <1150108987.349838.53130@f14g2000cwb.googlegroups.com> Gabriel Zachmann wrote: > Here is a very simple Python script utilizing urllib: > > import urllib > url = > "http://commons.wikimedia.org/wiki/Commons:Featured_pictures/chronological" > print url > print > file = urllib.urlopen( url ) > mime = file.info() > print mime > print file.read() > print file.geturl() > > > However, when i ecexute it, i get an html error ("access denied"). > > On the one hand, the funny thing though is that i can view the page fine in my > browser, and i can download it fine using curl. > > On the other hand, it must have something to do with the URL because urllib > works fine with any other URL i have tried ... > > Any ideas? > I would appreciate very much any hints or suggestions. > > Best regards, > Gabriel. > > > -- > /-----------------------------------------------------------------------\ > | If you know exactly what you will do -- | > | why would you want to do it? | > | (Picasso) | > \-----------------------------------------------------------------------/ I think the problem might be with the Wikimedia Commons website itself, rather than urllib. Wikipedia has a policy against unapproved bots: http://en.wikipedia.org/wiki/Wikipedia:Bots It might be that Wikimedia Commons blocks bots that aren't approved, and might consider your program a bot. I've had similar error message from www.wikipedia.org and had no problems with a couple of other websites I've tried. Also, the html the program returns seems to be a standard "ACCESS DENIED" page. I might be worth asking at the Wikimedia Commons website, at least to eliminate this possibility. John Hicken From greg.kujawa at gmail.com Thu Jun 1 15:35:20 2006 From: greg.kujawa at gmail.com (gregarican) Date: 1 Jun 2006 12:35:20 -0700 Subject: New to Python: Do we have the concept of Hash in Python? References: Message-ID: <1149190520.444779.314420@h76g2000cwa.googlegroups.com> We have sort of a .... problem .... here .... uh .... yeah (http://www.luminomagazine.com/2004.03/spotlight/officespace/images/lumbergh/lumbergh1.jpg)... Fredrik Lundh wrote: > A.M wrote: > > > This is my 1st day that I am seriously diving into Python and I have to > > finish this application by the end of today. Maybe it wasn't a good idea to > > choose the language that I don't know when I have to deliver my work in such > > short time. > > are your boss aware of this ? > > From fredrik at pythonware.com Fri Jun 30 06:32:28 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 30 Jun 2006 12:32:28 +0200 Subject: delete first line in a file References: <44a4f854$0$12942$91cee783@newsreader02.highway.telekom.at> Message-ID: Juergen Huber wrote: > i am a dummy user in python and new in this programming language and so > there will be questions, that?s for you no problem! i never have before > programmed in any language! sorry for this! i hope you will help me, that i > also could the basics in this language! and later many more, so i hope ! :) > > the first question for me in this newsgroup will be the follow one: > > - is there a way to delete in a csv-file the first line?! in general, modern file systems can only remove and add stuff at the end of a file, so the only way to do this is to rewrite the entire file. (you can either load the entire file, fix it up, and write it out again, or copy the file to a new file, skipping the first line or row). From emanuele.aina at gmail.com Thu Jun 15 08:14:31 2006 From: emanuele.aina at gmail.com (Emanuele Aina) Date: 15 Jun 2006 05:14:31 -0700 Subject: __lt__ slowing the "in" operator even if not called References: <1150318630.203249.191250@r2g2000cwb.googlegroups.com> Message-ID: <1150373671.227640.50910@f6g2000cwb.googlegroups.com> Maric Michaud spieg?: > Le Mercredi 14 Juin 2006 22:57, Emanuele Aina a ?crit : > > Here you can see that even with only the __lt__ method it goes 10x > > slower, but __lt__ is never called as "Foo" is not printed. > > No, that is not what it shows. The only thing it shows is that in operator is > slow for lists, and as it iterates over the entire list untill it find an > element, it is much slower when it fails a lot. Yes, I now that "in" is slow for lists and that a dict is preferable, but what I'm pointing out is that in one case is much slower without a reason. In my test, the one without __lt__ runs in ~500ms, while the one with the __lt__ method runs in ~5000ms. Just for comparision I've also tested with an overridden __eq__ and it shows timings similar to the ones in the second test, but this time it is expected, as "in" has to call __eq__ for every element in the list. In the first test python uses the native equality (comparing memory pointer) and it is fast because it is implemented in C in the interpreter (no python function call). In the last case python has to call __eq__ for every element, and a python function call is obviuosly more expensive than the native comparision. But the __lt__ case leaves me wondering why it is slow as the __eq__ case, while using the native comparision. What I asked is what is the difference between the first and the second case? > Use dict in operator instead. Yes, I know that a dict is the right datastructure for a fast "in", but I need to keep track of the ordering, so I cannot use a dict. > Here is a program to show this in details : > > import timing > > class State(object): > def __init__(self, value): > self.v = value > > class StateEQ(State): > def __eq__ (self, other): > if isinstance(other, State) : > return self.v == other.v > else : > return self.v == other > > class StateLT(State) : > def __lt__ (self, other): > if isinstance(other, State) : > return self.v < other.v > else : > return self.v < other > > class StateLTEQ(StateEQ, StateLT) : pass > > def test(state_cls): > num_elem = 3*10**4 > print > print state_cls > > l = [state_cls(0)] > for i in xrange(num_elem): l.append(state_cls(i+1)) > print > print "in operator at the beginning of list:", > timing.start() > for i in xrange(300): i in l > timing.finish() > print timing.milli() > print "in operator at the end of list:", > timing.start() > for i in xrange(num_elem-300, num_elem): i in l > timing.finish() > print timing.milli() Sorry, but this works only when you override __eq__. Without it it will alway scan the entire list, so you are comparing the timings of two different things. > print > print "converting to dict :", > timing.start() > d = {}.fromkeys(l) > timing.finish() > print timing.milli() > print "in operator for a dict for %s elements:" % (num_elem*2), > timing.start() > for i in xrange(num_elem, num_elem*2): i in d > timing.finish() > print timing.milli() As I said, that was only a test demo exploiting my observation, in my real program I need to keep track of the order in which I add items in the list, so I can't use a dict. > for which the output is : > > > > in operator at the beginning of list: 1983 > in operator at the end of list: 2011 > > converting to dict : 82 > in operator for a dict for 60000 elements: 12 > > > > in operator at the beginning of list: 3866 > in operator at the end of list: 3871 Here python is using the equality comparator from "int", giving those fast results. I've substituted the ints with instances of state_cls: - for i in xrange(300): i in l + for i in xrange(300): state_cls(i) in l - for i in xrange(num_elem-300, num_elem): i in l + for i in xrange(num_elem-300, num_elem): state_cls(i) in l Running these test, in the case of StateLT, now takes ~10000ms and ~9000ms. [...] > Every classes that define the __eq__ operator will find quickly the elements > if they are at the beginning of the list. > If they are at the end, the in oprerator is slower in these classes because of > the overhead of function calls (in StateLt there is also an overhead due to ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ > internal lookup, IMO). ^^^^^^^^^^^^^^^ Yes, that was my question! :) But I hoped in a more exaustive answer: why python has to do this lookup when the __lt__ method is not involved at all? From nicolasg at gmail.com Thu Jun 1 15:19:30 2006 From: nicolasg at gmail.com (nicolasg at gmail.com) Date: 1 Jun 2006 12:19:30 -0700 Subject: integer to binary... Message-ID: <1149189570.376091.319890@j55g2000cwa.googlegroups.com> does anyone know a module or something to convert numbers like integer to binary format ? for example I want to convert number 7 to 0111 so I can make some bitwise operations... Thanks From luismgz at gmail.com Wed Jun 28 20:53:01 2006 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 28 Jun 2006 17:53:01 -0700 Subject: web Develop question In-Reply-To: <1151542083.518621.93970@x69g2000cwx.googlegroups.com> References: <1151514841.490454.284770@i40g2000cwc.googlegroups.com> <1151515979.877494.316720@m73g2000cwd.googlegroups.com> <1151541085.359563.156990@i40g2000cwc.googlegroups.com> <1151542083.518621.93970@x69g2000cwx.googlegroups.com> Message-ID: <1151542381.050638.145430@j72g2000cwa.googlegroups.com> Just to give you an idea of what it is, you can check this article: http://www.onlamp.com/pub/a/python/2004/02/26/python_server_pages.html... This explains the whole thing much better than I did with my poor english... Luis From bucodi at yahoo.fr.invalid Mon Jun 19 04:13:45 2006 From: bucodi at yahoo.fr.invalid (Rony Steelandt) Date: Mon, 19 Jun 2006 10:13:45 +0200 Subject: wxPython GUI designer References: <1150661348.837969.46870@r2g2000cwb.googlegroups.com> <44965a22$0$7767$7a628cd7@news.club-internet.fr> Message-ID: > >> I am newbie learning wxPython. I tried using GUI designer called >> wxGlade. When it generated code I couldnt get the same level of >> flexibility as writing the code by oneself. >> >> Any view on what you think about using GUI designer tools. >> >> Every help is appreciated. >> > Boa is excellent if you stay at a primary level. It's a visual design tool, > and it can help you to learn how to manage wx classes. It works on windows > and linux as well. > My understanding of wxglade is that you need skills about sizers to be > confident with it. So if you know how to use sizers, you don't really need a > tool. > Regards, > jm I use wxDesigner -- --- Rony Steelandt BuCodi rony dot steelandt (at) bucodi dot com Visit the python blog at http://360.yahoo.com/bucodi From laurent.pointal at limsi.fr Wed Jun 28 04:02:12 2006 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Wed, 28 Jun 2006 10:02:12 +0200 Subject: Problem with sets and Unicode strings In-Reply-To: <44a19d55$2@news.uni-ulm.de> References: <44a17d05$1@news.uni-ulm.de> <44a19d55$2@news.uni-ulm.de> Message-ID: Dennis Benzinger a ?crit : > No, byte strings contain characters which are at least 8-bit wide > . But I don't understand what > Python is trying to decode and why the exception says something about > the ASCII codec, because my file is encoded with UTF-8. [addendum to others replies] The file encoding directive is used by Python to convert u"xxx" strings into unicode objects using right conversion rules when compiling the code. When a string is written simply with "xxx", its a 8 bits string with NO encoding data associated. When these strings must be converted they are considered to be using sys.getdefaultencoding() [generally ascii - forced ascii in python 2.5] So a short reply: the utf8 directive has no effect on 8 bits strings, use unicode strings to manage correctly non-ascii texts. A+ Laurent. From Bulkan at gmail.com Fri Jun 23 10:18:40 2006 From: Bulkan at gmail.com (placid) Date: 23 Jun 2006 07:18:40 -0700 Subject: * in Python In-Reply-To: <449beca5$0$13891$626a54ce@news.free.fr> References: <1151061836.557835.295820@p79g2000cwp.googlegroups.com> <1151065046.668902.23010@g10g2000cwb.googlegroups.com> <449beca5$0$13891$626a54ce@news.free.fr> Message-ID: <1151072320.621378.218520@r2g2000cwb.googlegroups.com> Bruno Desthuilliers wrote: > placid wrote: > > Duncan Booth wrote: > > > >>placid wrote: > >> > >> > >>>Hi all, > >>> > >>>Can someone tell me what * in the following code means/does a Google > >>>search didnt turn up anything as i dont know what the * is called > >>>(related to Python and i dont think Python has pointers) > >>> > >> > >>* is for variable number of positional arguments, ** is for variable > >>keyword arguments. The syntax is symmetrical when defining functions and > >>when calling them. > >> > >>See http://docs.python.org/ref/calls.html > >>and http://docs.python.org/ref/function.html > > > > > > so * basically means that args is a list > > A tuple IIRC > > > containing more arguments that > > can change in size, whereas ** means that args is a dictionary of > > key=value arguments? > > > > Why don't you try by yourself in the Python shell ? One of the nice > things with Python is that it's quite easy to explore and experiment. i did try it in a Python shell after i learnt what it was. Like i said *args will be a list, but when i try **args with the following code it doesnt work def test(**args): keys = args.keys() for key in keys: print key+"="+args(key) > > > -- > bruno desthuilliers > python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for > p in 'onurb at xiludom.gro'.split('@')])" From sdcook55 at sbcglobal.net Wed Jun 14 23:54:56 2006 From: sdcook55 at sbcglobal.net (Stan Cook) Date: Thu, 15 Jun 2006 03:54:56 GMT Subject: Database read and write Message-ID: Ok . I know I'm talking ancient history, but some of us are stuck working with them. Is there anything for python which will ope, read, and write to a Dbase 3 or 4 file? I really need your assistance on this one. Regards, Stan From ketil+news at ii.uib.no Mon Jun 26 06:13:58 2006 From: ketil+news at ii.uib.no (Ketil Malde) Date: Mon, 26 Jun 2006 12:13:58 +0200 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> Message-ID: Chris Smith writes: > Joachim Durchholz wrote: >> Assume a language that >> a) defines that a program is "type-correct" iff HM inference establishes >> that there are no type errors >> b) compiles a type-incorrect program anyway, with an establishes >> rigorous semantics for such programs (e.g. by throwing exceptions as >> appropriate). > So the compiler now attempts to prove theorems about the program, but > once it has done so it uses the results merely to optimize its runtime > behavior and then throws the results away. Hmm... here's my compiler front end (for Haskell or other languages that ..er.. define 'undefined'): while(type error) { replace an incorrectly typed function with 'undefined' } Wouldn't the resulting program still be statically typed? In practice I prefer to (and do) define troublesome functions as 'undefined' manually during development. -k -- If I haven't seen further, it is by standing in the footprints of giants From nick at craig-wood.com Sat Jun 10 04:30:03 2006 From: nick at craig-wood.com (Nick Craig-Wood) Date: Sat, 10 Jun 2006 03:30:03 -0500 Subject: os.link makes a copy, not a link References: Message-ID: Dan M wrote: > I'm a little bit confused. According to the sources I've looked at on the > net, > os.link('file1', 'file2') > should make a hard link from file1 to file2. But what I'm finding is that > it's actually making a copy. Am I forgetting a step or something? > > Python 2.3.4 running on CentOS 4.3 It works here (Py 2.4.3 on Ubuntu Dapper Drake) The way to check whether you are getting a copy or a hardlink is to see whether the inode number is the same. Otherwise it is impossible to tell whether you have a copy or a hardlink. >>> import os >>> file("z", "w").write("test") >>> os.link("z", "z2") >>> os.stat("z").st_ino 1685186L >>> os.stat("z2").st_ino 1685186L >>> print os.popen("ls -li z z2").read() 1685186 -rw-r--r-- 2 ncw ncw 4 2006-06-10 08:31 z 1685186 -rw-r--r-- 2 ncw ncw 4 2006-06-10 08:31 z2 -- Nick Craig-Wood -- http://www.craig-wood.com/nick From felipe.lessa at gmail.com Sun Jun 11 16:44:15 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Sun, 11 Jun 2006 17:44:15 -0300 Subject: how to get the length of a number In-Reply-To: References: Message-ID: <1150058655.31060.1.camel@kenshin.CASA> Em Dom, 2006-06-11 ?s 20:10 +0000, Stan Cook escreveu: > Can anyone tell me how to get the length of a number. I > know len(string) will get the length of a string, but it > doesn't like len(int). I seem to remember something like %s > string. I tried to set a variable = to %s int, but that > doesn't work. Is there a function I've forgotten about to > convert an integer to a string? To convert an integer i to a string: str(i) or "%s" % i To see how many decimal digits it has: import math math.ceil(math.log(i, 10)) -- Felipe. From no-spam at no-spam-no-spam.com Thu Jun 15 16:22:22 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Thu, 15 Jun 2006 22:22:22 +0200 Subject: plotting to gif ? Message-ID: What is a good library for plotting graphs to (compressed) gif / jpg images? Has anybody experience with this? I want to put some simple 2D (and maybe 3D) graph data visualization on a web server. Currently I test-output the data through Gnuplot.py & Gnuplot. I'm quite confused about http://wiki.python.org/moin/NumericAndScientific/Plotting which would leave me trying out almost everything. I'd need/like: * simple usage (not requesting too many other frameworks/libs installed extra) * displaying many curves in parallel / 2 y-achses scaling independently. * compressed gif's/png/jpg as the images are big but mostly white and going robert From scott.daniels at acm.org Tue Jun 20 00:17:48 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Mon, 19 Jun 2006 21:17:48 -0700 Subject: Newbie Question In-Reply-To: <1150767547.252901.163870@r2g2000cwb.googlegroups.com> References: <1150750938.973049.114780@y41g2000cwy.googlegroups.com> <129e55eahc35f00@corp.supernews.com> <1150753085.332654.283270@f6g2000cwb.googlegroups.com> <1150767547.252901.163870@r2g2000cwb.googlegroups.com> Message-ID: <44977200$1@nntp0.pdx.net> placid wrote: > Saint Malo wrote: >> Andrew Robert wrote: >>> Saint Malo wrote: >>> # Open a file for read >>> file=open(r'test.txt','r') >>> >>> # Read each line in file >>> for line in file >>> >>> #Search each line >>> if "A" in line: >>> >>> print "I found A" >>> >>> file.close() > Here's a bit nobody has suggested yet: A) use sets of words for easier checking. ... search_words = set(["red", "brown"]) for line in file: words = set(line.split()) if words & search_words: for word in search_words: if word in words: if word == 'red': print 'weasels rip my flesh' else: print word ... --Scott David Daniels scott.daniels at acm.org From rupole at hotmail.com Tue Jun 27 04:51:05 2006 From: rupole at hotmail.com (Roger Upole) Date: Tue, 27 Jun 2006 04:51:05 -0400 Subject: MSoffice metadata References: <1151209771.276872.299240@b68g2000cwa.googlegroups.com> Message-ID: <1151397901_47427@sp6iad.superfeed.net> wrote in message news:1151209771.276872.299240 at b68g2000cwa.googlegroups.com... > hi > is there a module in Python to extract metadata in MS office documents > thanks > The Pywin32 package (http://sourceforge.net/projects/pywin32/) wraps the interfaces used to read and write document properties. Specifically, you can use pythoncom.StgOpenStorage to retrieve an IPropertySetStorage interface. Roger ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= East/West-Coast Server Farms - Total Privacy via Encryption =--- From fabiofz at gmail.com Sun Jun 25 19:50:46 2006 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Sun, 25 Jun 2006 20:50:46 -0300 Subject: Eclipse IDE question In-Reply-To: References: <1151241922.620601.218580@r2g2000cwb.googlegroups.com> Message-ID: On 6/25/06, Markus Wankus wrote: > > On Sun, 25 Jun 2006 13:21:32 -0400, seerhut wrote: > > > kilnhead wrote: > >> I am trying to use eclipse for python development. Is it possible to > >> run a python script without having to name/setup a configuration? Can > >> eclipse be set up so that "run" loads the code into the interpreter and > >> goes? I don't want to create a new run config every time I want to run > >> a script. > >> > > try pydev , a plugin for eclipse > > > I'm fairly certain the OP is already doing that... > > As far as I know (I haven't used pydev in awhile) you need a launch > configuration for each script. I do know you can run a script easily and > have the launch created for you just by right-clicking the file and saying > Run As > Python (I think). Here is what the FAQ says: > > How do I run a module from within eclipse using PyDev (either Python or > Jython)? > > To do that, the easiest way is going to the Run menu (Run->Run As->Python > or Jython). If it is not available in your current eclipse perspective, > you can enable it by going to window->customize perspective->commands and > checking the "Lauch" item (in this way, you can go only with the > keyboard). > > Another way to run a module is right clicking the module in the navigator > and choosing python->run (when a .py file is selected). > Ok, there is another way of doing it is just pressing F9 if using pydev ( http://fabioz.com/pydev/manual_101_root.html contains a complete step-by-step on how to configure pydev and start using it). Cheers, Fabio -------------- next part -------------- An HTML attachment was scrubbed... URL: From ptmcg at austin.rr._bogus_.com Tue Jun 27 09:32:29 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Tue, 27 Jun 2006 13:32:29 GMT Subject: Re-loading updated modules References: <1151414294.809032.44850@u72g2000cwu.googlegroups.com> Message-ID: "fileexit" wrote in message news:1151414294.809032.44850 at u72g2000cwu.googlegroups.com... > Hi, > Shouldn't python recompile a module if there is a later version of the > code (.py file)? While i am debuging, i always have to exit python and > delete the pyc before every run, then start it again and import the > modules. It seems that this is the only way for it to recompile the > new code. > > What is going on? is this normal behaviour? I noticed that on both > Windows and linux (Fedora Core 4, and 5 and RHEL 4) > If there is a later .py file, and you restart Python, Python will recompile the modules when you import them. -- Paul From walter at livinglogic.de Tue Jun 27 11:20:26 2006 From: walter at livinglogic.de (=?ISO-8859-1?Q?Walter_D=F6rwald?=) Date: Tue, 27 Jun 2006 17:20:26 +0200 Subject: Having problems with strings in HTML In-Reply-To: References: Message-ID: <44A14CBA.5060802@livinglogic.de> Richard Brodie wrote: > "Sion Arrowsmith" wrote in message > news:gLB*BXekr at news.chiark.greenend.org.uk... > >>> By the way, you _do_ realize that your "&" characters should be escaped >>> as "&", don't you? >> No they shouldn't. They part of the url, which is (IIRC) a CDATA >> attribute of the A element, not PCDATA. > > It is CDATA but ampersands still need to be escaped. Exactly. See http://www.w3.org/TR/html4/appendix/notes.html#ampersands-in-uris Bye, Walter D?rwald From maric at aristote.info Tue Jun 20 07:32:08 2006 From: maric at aristote.info (Maric Michaud) Date: Tue, 20 Jun 2006 13:32:08 +0200 Subject: Specifing arguments type for a function In-Reply-To: <200606201328.02784.maric@aristote.info> References: <200606201328.02784.maric@aristote.info> Message-ID: <200606201332.08984.maric@aristote.info> Le Mardi 20 Juin 2006 13:28, Maric Michaud a ?crit?: > if not getattr(arg, '__iter__') and not getattr(arg, '__getitem__') : > ? ? raise ValueError('Function accepts only iterables') # or error handling > code oops, hasattr of course : if not hasattr(arg, '__iter__') and not hasattr(arg, '__getitem__') : raise ValueError('Function accepts only iterables') # or error handling -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From fredrik at pythonware.com Thu Jun 8 10:28:49 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 08 Jun 2006 16:28:49 +0200 Subject: From Python to Shell In-Reply-To: <1149775916.711309.260170@i40g2000cwc.googlegroups.com> References: <1149775916.711309.260170@i40g2000cwc.googlegroups.com> Message-ID: NightHawk wrote: > Im not a total noob but i don't know the command and the module to go > from python to the default shell. I'm not sure what you mean by "go to", but if you want to start an interactive OS shell from inside Python, you can do: >>> import os >>> os.system(os.environ["SHELL"]) on Unix, and >>> import os >>> os.system(os.environ["comspec"]) on Windows. From sreeram at tachyontech.net Mon Jun 5 08:45:21 2006 From: sreeram at tachyontech.net (K.S.Sreeram) Date: Mon, 05 Jun 2006 18:15:21 +0530 Subject: finding file In-Reply-To: <1149510738.569437.242050@f6g2000cwb.googlegroups.com> References: <1149510738.569437.242050@f6g2000cwb.googlegroups.com> Message-ID: <44842761.6060201@tachyontech.net> su wrote: > import os, os.path > import re > def core_finder(arg, dir, files): > for file in files: > path = os.path.join (dir, file) > if re.search("core.*", path): > print "found" > print path > > > os.path.walk('.', core_finder, 0) Here's a simpler solution: import glob filenames = glob.glob( 'core*' ) In case you want the full path... import os filepaths = [os.path.join(os.getcwd(),f) for f in filenames] Regards Sreeram -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 260 bytes Desc: OpenPGP digital signature URL: From khemkaamit at gmail.com Wed Jun 14 02:59:22 2006 From: khemkaamit at gmail.com (Amit Khemka) Date: Wed, 14 Jun 2006 12:29:22 +0530 Subject: Logging to a file and closing it again properly (logging module) In-Reply-To: <20060612215823.GA18595@workaround.org> References: <20060612215823.GA18595@workaround.org> Message-ID: <1360b7230606132359q79497913v24479c2a8af526f6@mail.gmail.com> On 6/13/06, Christoph Haas wrote: > Evening, > > I have an application that is running in an endless loop processing an > incoming queue. Every run is supposed to write a log file about the run > and then close it again. While the 'logging' module is generally working > well (even though the documentation makes me miss some proper examples > how everything works together) I can't seem to close the log file again > to open a new one. > > This is basically what I'm doing: > > log = logging.getLogger("myapplication") > log.addHandler(logging.FileHandler("/tmp/testfile")) > log.setLevel(logging.INFO) > log.info("foo") > > Now I'm missing a way to tell this handler to go away. Through 'ipython' > I found out there is a log.handlers array that contains all the > handlers. Perhaps I could delete all of them but I'm sure there is a > more proper way to close files again. > > Googling found me: > > .>>> logging._handlers.clear() > .>>> logging.root.handlers = [] > .>>> for l in logging.Logger.manager.loggerDict.values(): > .>>> l.handlers = [] You can "close" the logger by just removing the handler from the logging object # first creater a logger and file handler fooLogger = logging.getLogger('FOO') fooLogger.setLevel(logging.INFO) fl = logging.FileHandler('foo.txt) fl.setLevel(logging.INFO) fooLogger.addHandler(fl) # remove the handler once you are done fooLogger.removeHandler(fl) cheers, amit. -- ---- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. From Serge.Orlov at gmail.com Fri Jun 16 01:39:21 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 15 Jun 2006 22:39:21 -0700 Subject: BeautifulSoup error References: Message-ID: <1150436361.480316.25400@g10g2000cwb.googlegroups.com> William Xu wrote: > Hi, all, > > This piece of code used to work well. i guess the error occurs after > some upgrade. > > >>> import urllib > >>> from BeautifulSoup import BeautifulSoup > >>> url = 'http://www.google.com' > >>> port = urllib.urlopen(url).read() > >>> soup = BeautifulSoup() > >>> soup.feed(port) > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/lib/python2.3/sgmllib.py", line 94, in feed > self.rawdata = self.rawdata + data > UnicodeDecodeError: 'ascii' codec can't decode byte 0xb8 in position 565: ordinal not in range(128) > >>> > > Any ideas to solve this? According to the documentation chapter "Beautiful Soup Gives You Unicode, Dammit" Beautiful Soup fully supports unicode so it's probably a bug. > version info: > > Python 2.3.5 (#2, Mar 7 2006, 12:43:17) > [GCC 4.0.3 20060212 (prerelease) (Debian 4.0.2-9)] on linux2 > > python-beautifulsoup: 3.0.1-1 Upgrading python-beautifulsoup is a good idea, since there were two bug fix releases after 3.0.1 From fredrik at pythonware.com Fri Jun 30 02:47:38 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 30 Jun 2006 08:47:38 +0200 Subject: XMLLIB References: <1151605613.912057.130510@x69g2000cwx.googlegroups.com> Message-ID: "Heavy" wrote: > I need to know if the 'xmllib' module have some method able to > transform a data structure in a xml file and viceversa, thanks define "data structure" and "xml file (format)". From bj_666 at gmx.net Fri Jun 23 01:23:33 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Fri, 23 Jun 2006 07:23:33 +0200 Subject: Program slowing down with greater memory use References: Message-ID: In , Dan Stromberg wrote: > What's the deal here? Very hard to tell without more details. Ciao, Marc 'BlackJack' Rintsch From noreply at python.org Fri Jun 2 15:12:12 2006 From: noreply at python.org (Returned mail) Date: Fri, 2 Jun 2006 15:12:12 -0400 Subject: Returned mail: see transcript for details Message-ID: <20060602194401.BEF181E400C@bag.python.org> Your message was not delivered due to the following reason(s): Your message could not be delivered because the destination computer was not reachable within the allowed queue period. The amount of time a message is queued before it is returned depends on local configura- tion parameters. Most likely there is a network problem that prevented delivery, but it is also possible that the computer is turned off, or does not have a mail system running right now. Your message was not delivered within 7 days: Server 136.96.117.189 is not responding. The following recipients could not receive this message: Please reply to postmaster at python.org if you feel this message to be in error. From eliotm at pacbell.net Fri Jun 23 15:40:44 2006 From: eliotm at pacbell.net (Eliot Miranda) Date: Fri, 23 Jun 2006 19:40:44 GMT Subject: What is a type error? In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <7i3mg.204167$8W1.155367@fe1.news.blueyonder.co.uk> <44992e6c$2$664$bed64819@news.gradwell.net> <%Igmg.464974$xt.353729@fe3.news.blueyonder.co.uk> <449aaea0$2$656$bed64819@news.gradwell.net> Message-ID: <0tXmg.28329$VE1.19407@newssvr14.news.prodigy.com> Darren New wrote: > Eliot Miranda wrote: > >> can only actually carry-out operations on objects that implement them. > > > Execpt that every operation is implemented by every object in Smalltalk. No they are not. Objects implement the methods defined by their class and (inherit) those implemented by the class's superclasses. Note that classes do _not_ have to inherit from Object, and so one can create classes that implement no methods at all. It is a common idiom to create a class that implements two methods, an initialization method and a doesNotUnderstand: method, so create a transparent proxy that intercepts any and all messages sent to it other than the initialization method (*). [(*) With suitable hackery (since Smalltalk gives access to the execution stack through thisContext) one can also invoke doesNotUnderstand: if the initialization message is sent from any object other than the class.] > Unless you specify otherwise, the implementation of every method is to > call the receiver with doesNotUnderstand. (I don't recall whether the > class of nil has a special rule for this or whether it implements > doesNotUnderstand and invokes the appropriate "don't send messages to > nil" method.) No. The run-time error of trying to invoke an operation that isn't implemented by an object is to send the doesNotUnderstand: message. This is another attempt to invoke an operation, i.e. whatever the object's doesNotUnderstand: method is, if any. If the object doesn't implement doesNotUnderstand:, which is quite possible, then the system, will likely crash (either with an out of memory error as it goes into infinite recursion) or hang (looping attempting to find an implementation of doesNotUnderstand:). > There are a number of Smalltalk extensions, such as > multiple-inheritance, that rely on implementing doesNotUnderstand. Which has nothing to do with the separation between message send and method invocation, or the fact that doesNotUnderstand: is a message send, not a hard call of a given doesNotUnderstand: method. -- _______________,,,^..^,,,____________________________ Eliot Miranda Smalltalk - Scene not herd From max at alcyone.com Thu Jun 1 06:25:23 2006 From: max at alcyone.com (Erik Max Francis) Date: Thu, 01 Jun 2006 03:25:23 -0700 Subject: shuffling elements of a list In-Reply-To: <69ft72516amvri3up8fop5rf543s6en1lg@4ax.com> References: <1149045499.212967.13120@f6g2000cwb.googlegroups.com> <1149051212.139046.155340@c74g2000cwc.googlegroups.com> <1149105576.321676.131600@j55g2000cwa.googlegroups.com> <69ft72516amvri3up8fop5rf543s6en1lg@4ax.com> Message-ID: David C. Ullrich wrote: > Good example, because we know that EMF is not dumb. I've seen > the same algorithm many times - the best example is ... Man, an error made _six years ago_ and people are still bringing it up ... -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis The purpose of man's life is not happiness but worthiness. -- Felix Adler From python.list at tim.thechases.com Wed Jun 14 11:26:42 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 14 Jun 2006 10:26:42 -0500 Subject: convert floats to their 4 byte representation In-Reply-To: <1150297093.191223.152330@c74g2000cwc.googlegroups.com> References: <1150297093.191223.152330@c74g2000cwc.googlegroups.com> Message-ID: <44902AB2.1040909@tim.thechases.com> > s = "%"+str(size) + "X" > return (s % number).replace(' ', '0') While I don't have a fast and easy way to represent floats, you may want to tweak this to be return ("%0*X" % (size,number)) which will zero-pad the number in hex to "size" number of places in a single step. It also helps prevent problems where there might > but I haven't been able to find anything for floats. Any help > would be great. My first stab at such an attempt: >>> from struct import pack, unpack >>> s = pack("d", 3.14) >>> i = unpack("q", s) >>> "%X"%i '40091EB851EB851F' >>> def floatAsHex(f, size): ... return "%0*X" % (size, unpack("q", pack("d", f))[0]) ... >>> floatAsHex(3.14, 20) '000040091EB851EB851F' It's ugly, it's hackish, it's likely architecture-dependant, but it seems to do what you're describing. -tkc From paustin at eos.ubc.ca Fri Jun 16 14:07:41 2006 From: paustin at eos.ubc.ca (Philip Austin) Date: Fri, 16 Jun 2006 11:07:41 -0700 Subject: Which compiler will Python 2.5 / Windows (Intel) be built with? References: <1150367139.495114.148550@g10g2000cwb.googlegroups.com> <44917535$1@nntp0.pdx.net> <1150391891.130185.4640@f6g2000cwb.googlegroups.com> <4491b9e1$1@nntp0.pdx.net> <1150406005.948538.188950@h76g2000cwa.googlegroups.com> <4491d3c0$1@nntp0.pdx.net> <1150410921.201231.277880@c74g2000cwc.googlegroups.com> <1150414509.020482.249110@g10g2000cwb.googlegroups.com> Message-ID: meyer at mesw.de writes: >> This is the .NET 11 SDK, I belive it includes the 2003 compiler (*): > > Last time I checked the .NET SDK they had the C# compiler in there, but > not the C++ optimizing 2003 compiler. Might be wrong though.... I just downloaded and installed this, and see a directory called c:\program files\microsoft visual studio .net 2003\vc7 with bin\cl.exe and lib and include directories. So presumably I'm good to go? I'm following this thread because I'll need to compile and install some extensions I've written for linux/gcc/python2.4 in our Windows computer lab. Presuming I succeed in setting up vc7 correctly, is it as simple as 'python setup.py install' from here? Thanks, Phil From maric at aristote.info Wed Jun 21 07:45:51 2006 From: maric at aristote.info (Maric Michaud) Date: Wed, 21 Jun 2006 13:45:51 +0200 Subject: Search substring in a string and get index of all occurances In-Reply-To: <4499034A.9040306@gmail.com> References: <4499034A.9040306@gmail.com> Message-ID: <200606211345.52243.maric@aristote.info> Another variant, I feel this one more natural as it doesn't contain a C-looking infinite loop (also I made it a generator but this is not the topic). In [160]: def indices(s, subs) : .....: last = 0 .....: for ind, part in in enumerate(s.split(subs)[:-1]) : .....: yield len(part) + last .....: last = len(part) + last + len(subs) .....: .....: In [161]: list(indices('John has a really nice powerbook.', ' ')) Out[161]: [4, 8, 10, 17, 22] In [162]: list(indices('John has a really nice powerbook. John is my friend', 'John')) Out[162]: [0, 34] In [163]: mystring, substr Out[163]: ('John has a really nice powerbook. John is my friend', 'John') In [164]: for i in list(indices(mystring, substr)) : print mystring[i:i+len(substr)] .....: John John Actually it's even more efficient than Lundh's one for smaller strings (less than 1000 characters on my box) and slow down as strings go wider (slowly, seems to be a logarithmic progression) due to the split call resulting in creation of a new list. I'd love str implement a xsplit(sub, start, end) method, so I could have wrote : enumerate(s.xsplit(subs, 0, -1)). Le Mercredi 21 Juin 2006 10:28, Nico Grubert a ?crit?: > Hi there, > > I would like to search for a substring in a string and get the index of > all occurances. > > mystring = 'John has a really nice powerbook.' > substr = ' ' # space > > I would like to get this list: > [4, 8, 10, 17, 22] > > How can I do that without using "for i in mystring" which might be > expensive for large strings? > > Thanks in advance, > Nico -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From jstroud at ucla.edu Thu Jun 8 17:38:02 2006 From: jstroud at ucla.edu (James Stroud) Date: Thu, 08 Jun 2006 14:38:02 -0700 Subject: what is often before a pattern ? In-Reply-To: <1149801756.593936.95110@y43g2000cwc.googlegroups.com> References: <1149801756.593936.95110@y43g2000cwc.googlegroups.com> Message-ID: joh12005 at yahoo.fr wrote: > Hello, > > i'm looking for a way to detect sequence objects which are often before > a pattern. > > say for example some list like: > > a = "a0 a1 a2 a3 a4 myPatternMatchHere".split() > b = "a5 a2 a4 myPatternMatchHere".split() > c = "a6 a7 a2 a3 a8 a4 myPatternMatchHere".split() > d = "a9 a10 a2 myPatternMatchHere".split() > > a2 a3 a4 is the most interesting because it appears 2 times upon 4, and > overlap a2 a4, and we have some clues that a2 is also important as it > appears 4/4. > > maybe have you some suggestions or idioms where i should look after > > best. > Look into suffix trees. http://www.csse.monash.edu.au/~lloyd/tildeAlgDS/Tree/Suffix/ -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From aleax at mac.com Sun Jun 18 01:24:52 2006 From: aleax at mac.com (Alex Martelli) Date: Sat, 17 Jun 2006 22:24:52 -0700 Subject: how can get the module global symbol table from a function or method which it is called? References: <1150597845.758056.135740@p79g2000cwp.googlegroups.com> Message-ID: <1hh3kuc.1pwzs63461etwN%aleax@mac.com> ygao wrote: > when a function or method is called,how can get the module global > symbol table from which > it is called,not the module where it is defined(this is easy). > thanks! You can play with module inspect, or sys._getframe, but they're meant essentially for *debugging* purposes -- if what you have in mind is not related to debugging, but rather some hack to design a highly unPythonic API, I earnestly urge you to reconsider your design intent. Alex From claird at lairds.us Sun Jun 25 07:08:40 2006 From: claird at lairds.us (Cameron Laird) Date: Sun, 25 Jun 2006 11:08:40 +0000 Subject: Python taught in schools? References: <1151220913.406987.162420@u72g2000cwu.googlegroups.com> Message-ID: In article <1151220913.406987.162420 at u72g2000cwu.googlegroups.com>, MilkmanDan wrote: >I'll be a college freshman this fall, attending Florida Institute of >Tech studying electrical engineering. > >I was considering taking some classes in programming and computer >science, and I happened to notice that everything taught is using C++. >After further research, it seems to me that C++ seems to be the >dominating language in universities. > >By comparison, our local community college teaches a few classes in VB, >Java, Javascript, C++, and for some reason, PASCAL. > >I'm certianly not against any of this, but out of curiousity does >anyone know of a school that teaches Python? > There are many. Wartburg College is an example. likely will interest you. I'll gratuitously add that, even though I'm personally fond of C++, I think teaching it as is done in colleges and high schools (!) amounts to child abuse. It's wildly inappropriate. From BjornSteinarFjeldPettersen at gmail.com Wed Jun 7 02:28:24 2006 From: BjornSteinarFjeldPettersen at gmail.com (-- bj0rn) Date: 6 Jun 2006 23:28:24 -0700 Subject: assign operator as variable ? In-Reply-To: <1149661137.454954.234390@u72g2000cwu.googlegroups.com> References: <1149661137.454954.234390@u72g2000cwu.googlegroups.com> Message-ID: <1149661704.801144.294050@h76g2000cwa.googlegroups.com> s99999999s2003 at yahoo.com wrote: > hi > in python is there any way to do this > > op = "<" > a = 10 > b = 20 > if a op b : > print "a is less than b" s99999999s2... at yahoo.com wrote: > hi > in python is there any way to do this > > op = "<" > a = 10 > b = 20 > if a op b : > print "a is less than b" Will this work for you?: import operator op = operator.lt a = 10 b = 20 if op(a, b): print "a is less than b" -- bj0rn From grahamd at dscpl.com.au Tue Jun 13 00:35:51 2006 From: grahamd at dscpl.com.au (grahamd at dscpl.com.au) Date: 12 Jun 2006 21:35:51 -0700 Subject: [newbie]apache authentication questions References: <1150132535.766644.99870@g10g2000cwb.googlegroups.com> Message-ID: <1150173351.116073.316640@u72g2000cwu.googlegroups.com> Steve Holden wrote: > nuffnough at gmail.com wrote: > Since HTTP authentication is managed by the browser it's difficult to > integrate it with web application authentication: basically you have to > choose between the two. There's no way for the server to tell the > browser to start presenting the required authentication credentials > except by raising a 401 (not authorised) error response, which is what > makes the browser bring up its little popup. It is not impossible though and in cases where you don't have a choice but to use a HTTP authentication scheme, use of AJAX may be the answer to still allowing use of a form based login scheme. See: http://www.peej.co.uk/articles/http-auth-with-html-forms.html Graham From alikakakhel at yahoo.com Fri Jun 2 23:40:00 2006 From: alikakakhel at yahoo.com (greenflame) Date: 2 Jun 2006 20:40:00 -0700 Subject: how to erase a variable Message-ID: <1149306000.615590.30020@c74g2000cwc.googlegroups.com> Is there a way to get rid of a variable as though it never existed? I know this sounds very basic but I have not come across any such methods. Also is the fact that I will have a bunch of extra variables just haning around because my use for them is over a bad thing? I will likely have on the order of 10 to 50 or so of these for the particular program I an working on at the moment. From Serge.Orlov at gmail.com Thu Jun 15 18:33:52 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 15 Jun 2006 15:33:52 -0700 Subject: [OT] Re: Python open proxy honeypot References: <1150236597.152868.250740@y43g2000cwc.googlegroups.com> Message-ID: <1150410832.509361.8200@r2g2000cwb.googlegroups.com> imcs ee wrote: > On 13 Jun 2006 15:09:57 -0700, Serge Orlov wrote: > > Alex Reinhart wrote: > > My spam folder at gmail is not growing anymore for many months (it is > > about 600-700 spams a month). Have spammers given up spamming gmail.com > > only or is it global trend? > Gmail said "messages that have been in Spam more than 30 days will be > automatically deleted" > so may be the speed of spam comes in counterbalanced to the speed spam goes out? Yes, it is. My point was "monthly amount" is not increasing for me. But I guess if you publish your email everywhere it is increasing: 20,000 a month. Wow. From python.list at tim.thechases.com Thu Jun 15 21:29:09 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 15 Jun 2006 20:29:09 -0500 Subject: Need Help comparing dates In-Reply-To: <1150419503.224684.320550@c74g2000cwc.googlegroups.com> References: <1150419503.224684.320550@c74g2000cwc.googlegroups.com> Message-ID: <44920965.3060204@tim.thechases.com> > I am new to Python and am working on my first program. I am trying to > compare a date I found on a website to todays date. The problem I have > is the website only shows 3 letter month name and the date. > Example: Jun 15 No year, right? Are you making the assumption that the year is the current year? > How would I go about comparing that to a different date? Once you've got them as dates, >>> from datetime import date you can just compare them as you would any other comparable items. If you need to map the month-strings back into actual dates, you can use this dictionary: >>> month_numbers = dict([(date(2006, m, 1).strftime("%b"), m) for m in range(1,13)]) It happens to be locale specific, so you might have to tinker a bit if you're mapping comes out differently from what the website uses. I also made the assumption the case was the same (rather than trying to normalize to upper/lower case) Then, you can use >>> webpageDateString = "Mar 21" >>> webMonth, webDay = webpageDateString.split() >>> month = m[webMonth] >>> day = int(webDay) >>> webpageDate = date(date.today().year, month, day) >>> compareDate = date.today() >>> compareDate < webpageDate False >>> compareDate > webpageDate True You can wrap the load in a function, something like >>> def isNewer(dateString, year = date.today().year): ... monthString, dayString = dateString.split() ... month = month_numbers[monthString] ... day = int(dayString) ... return date.today() < date(year, month, day) which will allow you to do >>> isNewer("Jul 1") True >>> isNewer("Apr 1") False and the like. There's plenty of good stuff in the datetime module. -tkc From fredrik at pythonware.com Sat Jun 10 05:12:09 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 10 Jun 2006 11:12:09 +0200 Subject: Most elegant way to generate 3-char sequence In-Reply-To: <1149930084.768576.315300@f6g2000cwb.googlegroups.com> References: <1149889784.391965.271570@h76g2000cwa.googlegroups.com> <4489F72C.7010101@lexicon.net> <1149930084.768576.315300@f6g2000cwb.googlegroups.com> Message-ID: Rob Cowie wrote: >> Why type all that punctuation? > > What punctuation? ['','','','']['','','','']['','','',''] (also see david isaac's post) From deets at nospam.web.de Fri Jun 16 08:15:14 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 16 Jun 2006 14:15:14 +0200 Subject: Video capture from webcam on Mac? In-Reply-To: References: Message-ID: <4fflmgF1hr54aU1@uni-berlin.de> Joseph Chase schrieb: > Is there a cross-platform solution for video capture from a webcam? > > I am aware of the Win32 videocapture library, but am unaware of how to > accomplish the same functionality on the Mac side. You could try and make OpenCV work - it has a part called anygui that allows that, and has python-bindings. Alternatively, you could utilize the ToxicFramework from pyobjc, when running on a mac. Diez From sjmachin at lexicon.net Tue Jun 13 17:58:50 2006 From: sjmachin at lexicon.net (John Machin) Date: Wed, 14 Jun 2006 07:58:50 +1000 Subject: "groupby" is brilliant! In-Reply-To: References: <1150180151.643245.148210@y43g2000cwc.googlegroups.com> Message-ID: <448F351A.7000201@lexicon.net> On 13/06/2006 6:28 PM, Paul McGuire wrote: > (Oh, and I like groupby too! Combine it with sort to quickly create > histograms.) > > # tally a histogram of a list of values from 1-10 > dataValueRange = range(1,11) > data = [random.choice(dataValueRange) for i in xrange(10000)] > > hist = [ (k,len(list(g))) for k,g in itertools.groupby(sorted(data)) ] That len(list(g)) looks like it uses O(N) memory just to find out what N is :-( The best I could come up with is sum(itertools.imap(lambda x: 1, g)) -- but that does look a bit ugly ... From venkatbo at yahoo.com Thu Jun 29 12:27:05 2006 From: venkatbo at yahoo.com (venkatbo at yahoo.com) Date: 29 Jun 2006 09:27:05 -0700 Subject: How to disable tk inclusion in py build In-Reply-To: <1151422992.208936.54600@j72g2000cwa.googlegroups.com> References: <1151422992.208936.54600@j72g2000cwa.googlegroups.com> Message-ID: <1151598425.544822.77340@m73g2000cwd.googlegroups.com> > I'd like to disable the inclusion of tk graphics lib in my py build. > Looked around but couldn't find a clear answer. Which one of > the following would I need to use in the configure step: > --disable-tkbuild > --without-tk In case anyone is intereted, as it turns out, one way of achieving this is to disable the following statement in python's setup.py: self.detect_tkinter(inc_dirs, lib_dirs) of def detect_modules(self): This will ignore the compilation of _tkinter.c and tkappinit.c of the python distribution. This will totally skip the detection and inclusion of tk/tcl into the "built-in" pkg, irrespective of its presence on the buildbox. This will also work in the case of cross-compile builds of python. In the cross-compile case, there is a likelihood of the build process attempting to pick tk/tcl lib files from the buildbox (platform) and using it wrongly for the different target platform. In addition, one would also have to skip the inclusion of the python2.x/Lib/lib-tk/*.py files in the final dist. Just this exclusion is not enuff, the earlier detection step change is also needed to prevent all the buildtime errors. Thanks, /venkat From icebear at northpole.gov Thu Jun 22 08:28:52 2006 From: icebear at northpole.gov (icebear) Date: Thu, 22 Jun 2006 12:28:52 GMT Subject: Entity GUI tool? References: Message-ID: <82wmg.5528$Td6.1642@trnddc08> The ubuntu synaptic package manager claims: XML-based GUI builder for GTK+ Entity is an XML-based GUI builder and application scripting framework. It combines the ease of use of XML for GUI layout and the power of Perl, Python, TCL, JavaScript, and C for the application logic. An Entity GUI is usually much shorter than the same program written in any other language. This package contains the core portions of Entity along with Perl From bearophileHUGS at lycos.com Sat Jun 24 20:02:47 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 24 Jun 2006 17:02:47 -0700 Subject: Mix-In Class Methods At Run-Time References: <1151191406.755252.210300@i40g2000cwc.googlegroups.com> Message-ID: <1151193767.589325.158820@m73g2000cwd.googlegroups.com> I think it's possible, most of such kind of things are possible with Python. I'm not an expert yet in such kind of things, so this can be a starting point for you (note the shadowing of m2, the class docstrings, etc). Other people can give you something better or more correct. class A: def m1(self): return "m1" def m2(self): return "m2" class B: def m3(self): return "m3" class P: def m2(self): return "m2b" def m4(self): return"m4" def mixin(object, *classes): class NewClass(object.__class__): pass for C in classes: NewClass.__dict__.update(C.__dict__) object.__class__ = NewClass foo = P() print "Before:" print "foo.__class__.__dict__.keys():", foo.__class__.__dict__.keys() print "P.__dict__.keys():", P.__dict__.keys() print "foo.m2():", foo.m2() print "foo.m4():", foo.m4(), "\n" mixin(foo, A, B) print "After:" print "foo.__class__.__dict__.keys():", foo.__class__.__dict__.keys() print "P.__dict__.keys():", P.__dict__.keys() print "foo.m1():", foo.m1() print "foo.m2():", foo.m2() print "foo.m3():", foo.m3() print "foo.m4():", foo.m4() Bye, bearophile From pats at acm.org Fri Jun 23 10:08:40 2006 From: pats at acm.org (Patricia Shanahan) Date: Fri, 23 Jun 2006 14:08:40 GMT Subject: Saying "latently-typed language" is making a category mistake In-Reply-To: <4g28s6F1k9npnU1@individual.net> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <86Qmg.10725$o4.1907@newsread2.news.pas.earthlink.net> <4g251pF1knc6tU1@individual.net> <4g28s6F1k9npnU1@individual.net> Message-ID: Pascal Costanza wrote: > Matthias Blume wrote: >> Pascal Costanza writes: >> >>> Patricia Shanahan wrote: >>>> Vesa Karvonen wrote: >>>> ... >>>>> An example of a form of informal reasoning that (practically) every >>>>> programmer does daily is termination analysis. There are type systems >>>>> that guarantee termination, but I think that is fair to say that it >>>>> is not >>>>> yet understood how to make a practical general purpose language, whose >>>>> type system would guarantee termination (or at least I'm not aware >>>>> of such >>>>> a language). It should also be clear that termination analysis >>>>> need not >>>>> be done informally. Given a program, it may be possible to >>>>> formally prove >>>>> that it terminates. >>>> To make the halting problem decidable one would have to do one of >>>> two >>>> things: Depend on memory size limits, or have a language that really is >>>> less expressive, at a very deep level, than any of the languages >>>> mentioned in the newsgroups header for this message. >>> Not quite. See http://en.wikipedia.org/wiki/ACL2 >> >> What do you mean "not quite"? Of course, Patricia is absolutely >> right. Termination-guaranteeing languages are fundamentally less >> expressive than Turing-complete languages. ACL2 was not mentioned in >> the newsgroup header. > > ACL2 is a subset of Common Lisp, and programs written in ACL2 are > executable in Common Lisp. comp.lang.lisp is not only about Common Lisp, > but even if it were, ACL2 would fit. To prove Turing-completeness of ACL2 from Turing-completeness of Common Lisp you would need to run the reduction the other way round, showing that any Common Lisp program can be converted to, or emulated by, an ACL2 program. Patricia From steven.bethard at gmail.com Fri Jun 2 14:21:08 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 02 Jun 2006 12:21:08 -0600 Subject: Conditional Expressions in Python 2.4 In-Reply-To: <4480042b$0$29879$636a55ce@news.free.fr> References: <4480042b$0$29879$636a55ce@news.free.fr> Message-ID: <7OidneazQ9UJHB3ZnZ2dnUVZ_sGdnZ2d@comcast.com> A.M wrote: > Do we have the conditional expressions in Python 2.4? bruno at modulix wrote: > No, AFAIK they'll be in for 2.5 Yep: Python 2.5a2 (trunk:46491M, May 27 2006, 14:43:55) [MSC v.1310 32 bit (Intel)] on win32 >>> "Yes" if 1 == 1 else "No" 'Yes' > In the meanwhile, there are (sometime tricky? ways to get the same result: > > a = 1 == 1 and "Yes" or "No" > a = ("No", "Yes")[1 == 1] And just to give some examples where the conditional expression will show a difference:: >>> True and 0 or [] [] >>> 0 if True else [] 0 >>> def f(): ... print "don't evaluate me" ... return 'f' ... >>> def g(): ... return 'g' ... >>> (f(), g())[True] don't evaluate me 'g' >>> g() if True else f() 'g' STeVe From antroy at gmail.com Fri Jun 16 03:51:58 2006 From: antroy at gmail.com (Ant) Date: 16 Jun 2006 00:51:58 -0700 Subject: urllib2 problem with ports. In-Reply-To: References: <1150394282.406329.177960@c74g2000cwc.googlegroups.com> Message-ID: <1150444318.869194.65880@i40g2000cwc.googlegroups.com> Fredrik Lundh wrote: > check your proxy configuration. most likely, your new machine is set up > to route all requests via a remote proxy. Here's me looking like a fool :-) The parts of the machine (eg Firefox, GAIM etc) that I'd set up use a direct connection - it looks like the guy who'd had the machine before me used a proxy with IE... > (on windows, you'll find the proxy configuration under "Internet > Options" - "Connections" - "LAN Settings". before you do anything else, > make sure "Bypass proxy server for local addresses" is checked) Interestingly the "Bypass proxy server for local addresses" was checked. Anyway, I've changed it to a direct connection, and all seems well. Thanks. From levub137 at wi.rr.com Sun Jun 11 17:34:55 2006 From: levub137 at wi.rr.com (Raymond L. Buvel) Date: Sun, 11 Jun 2006 21:34:55 GMT Subject: math.pow(x,y) In-Reply-To: References: <1150049976.916474.186580@j55g2000cwa.googlegroups.com> Message-ID: <300jg.23297$8T4.802@tornado.rdc-kc.rr.com> K.S.Sreeram wrote: > Raymond L. Buvel wrote: >> I just tried this and it is taking an extremely long time even on a fast >> machine with 4 Gb of RAM. Killed it after a couple of minutes. > > Thats odd. > 34564323**456356 completed on my laptop in 28 seconds. > [Python 2.4.3, Celeron-M 1.3GHz, WinXP], and max memory consumption > during the whole process was about 11megs. > > What python version are you using? > > Regards > Sreeram > Sorry, I tripped over the display problem that Tim Peters has repeatedly explained on this news group (decimal algorithm is quadratic in the number of digits) :-( On a 64-bit 2.2 GHz Opteron running Debian stable, Python 2.3 took 26 seconds and Python 2.4 took 11 seconds. From saketh.bhamidipati at gmail.com Sun Jun 11 16:17:54 2006 From: saketh.bhamidipati at gmail.com (Saketh) Date: 11 Jun 2006 13:17:54 -0700 Subject: how to get the length of a number In-Reply-To: References: Message-ID: <1150057074.389755.157060@m38g2000cwc.googlegroups.com> Stan Cook wrote: > Can anyone tell me how to get the length of a number. I > know len(string) will get the length of a string, but it > doesn't like len(int). I seem to remember something like %s > string. I tried to set a variable = to %s int, but that > doesn't work. Is there a function I've forgotten about to > convert an integer to a string? > > Regards > > Stan Use str(int). Then use len(). For example, len(str(12345)) will give you 5. From kylotan at gmail.com Tue Jun 13 10:33:05 2006 From: kylotan at gmail.com (Ben Sizer) Date: 13 Jun 2006 07:33:05 -0700 Subject: numeric/numpy/numarray In-Reply-To: References: <1150188484.888977.189510@y43g2000cwc.googlegroups.com> Message-ID: <1150209185.022926.307780@g10g2000cwb.googlegroups.com> Bryan wrote: > at the end of that page, it says: > > "Numarray is another implementation of an arrayobject for Python written after > Numeric and before NumPy. Sponsors of numarray have indicated they will be > moving to NumPy as soon as is feasible for them so that eventually numarray will > be phased out." > > > on the python wiki > "NumArray is the current reimplementation of NumPy." > http://wiki.python.org/moin/NumArray > > so, was Numarray written *before* NumPY, or was it a reimplementation of NumPy > which implies it came *after* NumPy? it seems clear that Numeric is the old one > and i read is not being worked on anymore. so that leaves Numarray and numpy. > which of these two should i use? Bryan, NumPy is the name of both an old package and a new package. I believe that NumArray came after the first incarnation, but that the new incarnation of NumPy is the most recent, and is probably the one you want. -- Ben Sizer From alanalan at newsgroup.nospam Fri Jun 9 13:00:16 2006 From: alanalan at newsgroup.nospam (A.M) Date: Fri, 9 Jun 2006 13:00:16 -0400 Subject: Win XP: Problem with shell scripting in Python References: Message-ID: Here is what I came up with after John and Fredrik's help. import os import sys def Execute(shell_command,logStream = sys.stdout): print >>logStream, shell_command child_stdin, child_stdout_and_stderr = os.popen4(shell_command) commad_output = child_stdout_and_stderr.read() print >>logStream, commad_output return_code = child_stdout_and_stderr.close() return_code = return_code or child_stdin.close() print >>logStream, "Return Code: " , return_code Execute ("DIR") Execute ("MD :") I tested it and so far it behaves the way that I want. The tricky part is that when you use popen4, you have to close both returned streams to be able to get the return code. I wasn't able to find that in the documentation. Alan From bdesth.quelquechose at free.quelquepart.fr Mon Jun 5 22:18:52 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 06 Jun 2006 04:18:52 +0200 Subject: strategy pattern and non-public virtual functions In-Reply-To: <1149516464.874257.194030@j55g2000cwa.googlegroups.com> References: <1149516464.874257.194030@j55g2000cwa.googlegroups.com> Message-ID: <4484b669$0$883$626a54ce@news.free.fr> pythoncurious at gmail.com a ?crit : > Hi python experts > > In C++ I can do something like this: > class Base { > public: > void f() { this->f_(); } > private: > virtual void f_() = 0; > }; > > class Derived : public Base { > private: > void f_() { // Do something } > }; > > int main() { > Derived d; > d.f(); > } This is eventually the template method pattern, but certainly not the strategy pattern. > The point of this is that the a number of classes will inherit from > Base and only implement a private member function that only will be > accessed from the base class public 'f' function. > The Base::f() can then perform validation of input/return values, add > logging and things like that. This is usually done in Python with function decorators. But the implementer of the derived class (snip - cf other posts in this thread) > So my questions are: > 1. Is there a "pythonic" way to do what I'm trying to do? > > 2. Should I be doing this at all? Any thoughts? Doing what ? adding logging, validation etc, or using the template method pattern ?-) From gene.tani at gmail.com Sun Jun 4 08:59:02 2006 From: gene.tani at gmail.com (gene tani) Date: 4 Jun 2006 05:59:02 -0700 Subject: ANN: PQRC - Python Quick Reference Card - v 0.55 In-Reply-To: <4481b8ff$0$19687$ba4acef3@news.orange.fr> References: <4481b8ff$0$19687$ba4acef3@news.orange.fr> Message-ID: <1149425942.073680.234250@u72g2000cwu.googlegroups.com> Laurent Pointal wrote: > [for those who dont read clp.announce] > > The Python Quick Reference Card (PQRC) aims to provide a printable quick > reference documentation for the Python language and some of its main > standard libraries (currently for Python 2.4). > > PQRC tries to group informations about same/similar subject to avoid > searching in multiple places. > very nice. There's a few others I've collected over the years. I havent found an OS X dashboard widget yet tho: http://rgruet.free.fr/#QuickRef http://infohost.nmt.edu/tcc/help/pubs/python22.pdf http://www.onlamp.com/python/excerpt/PythonPocketRef/examples/python.pdf http://diveintopython.org/appendix/abstracts.html http://www.yukoncollege.yk.ca/~ttopper/COMP118/rCheatSheet.html http://www.schacherer.de/frank/tech/tools/python.html http://www.experimentierkasten.de/python_php.pdf http://ferg.org/pyref/index.html http://projects.edgewall.com/python-sidebar/ http://jotsite.com/blogArchives/2006_03.php#000383 http://www.drweb.de/weblog/weblog/?p=571 http://www.petefreitag.com/item/455.cfm From slawomir.nowaczyk.847 at student.lu.se Thu Jun 15 19:16:42 2006 From: slawomir.nowaczyk.847 at student.lu.se (Slawomir Nowaczyk) Date: Fri, 16 Jun 2006 01:16:42 +0200 Subject: a good programming text editor (not IDE) In-Reply-To: <1150411969.535331.43840@g10g2000cwb.googlegroups.com> References: <1150411969.535331.43840@g10g2000cwb.googlegroups.com> Message-ID: <20060616010904.CCC8.SLAWOMIR.NOWACZYK.847@student.lu.se> On Thu, 15 Jun 2006 15:52:49 -0700 BartlebyScrivener wrote: #> >> Most IDEs are rather weak as text editors compared to emacsen. #> #> That's true, but even emacs and xemacs don't offer simple automatic #> word wrap (i.e. wrap a line without splitting words or putting an eol #> or hard carriage return at the end of every line). Of course it does... there is longlines.el and longlines-mode in my copy of GNU Emacs: ,-------------------------------------------------- | Toggle Long Lines mode. | In Long Lines mode, long lines are wrapped if they extend beyond | `fill-column'. The soft newlines used for line wrapping will not | show up when the text is yanked or saved to disk. `------------------------------------------------- I do not use it, personally, but it does exist. -- Best wishes, Slawomir Nowaczyk ( Slawomir.Nowaczyk at cs.lth.se ) COMMAND: A suggestion made to a computer. From uval at rz.uni-karlsruhe.de Wed Jun 28 18:26:40 2006 From: uval at rz.uni-karlsruhe.de (=?ISO-8859-1?Q?Sch=FCle_Daniel?=) Date: Thu, 29 Jun 2006 00:26:40 +0200 Subject: for and while loops In-Reply-To: <1151531527.496772.65130@i40g2000cwc.googlegroups.com> References: <1151531527.496772.65130@i40g2000cwc.googlegroups.com> Message-ID: kydavis77 at gmail.com schrieb: > i was wondering if anyone could point me to some good reading about the > for and while loops > > i am trying to write some programs > "Exercise 1 > > Write a program that continually reads in numbers from the user and > adds them together until the sum reaches 100. Write another program the hidden hint here is ... "read until" you can't know ahead how many numbers it will be, the pattern in this case is to use "while sum smaller then 100" sum = 0 while sum < 100: sum = sum + input("more numbers please: ") > that reads 100 numbers from the user and prints out the sum. " here you know that you are going to read exactly 100 numbers sum = 0 for i in range(100): sum = sum + input("please number #%i: " % (i+1)) the only unclear point here is range(100) it generates a list with number [0,1,2 ... 99] and iterates through it one could write it like for i in [0,1,2,3,4]: do_something_with(i) but it gets tedious to write such a long list > > but im not quite grasping those functions.. > > please bear im mind i am an extreme newbie at this...thanks in advance > hth, Daniel From steve at holdenweb.com Wed Jun 28 04:23:07 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 28 Jun 2006 09:23:07 +0100 Subject: global name is not defined - error - but for array In-Reply-To: <1151471317.328398.132670@x69g2000cwx.googlegroups.com> References: <1151471317.328398.132670@x69g2000cwx.googlegroups.com> Message-ID: a wrote: > def fn(): > for i in range(l) > global count > count[i]= .... > > how do i declare count to be global if it is an array > > subsequently i should access or define count as an array > > error: > global name 'count' is not defined > The questions you are asking make it likely you would get better help on the Python-tutor list (python-tutor at python.org, if memory serves me right). It would seem you are new not just to Python but also to programming, and that list is specifically for those who might find a little coaching helpful. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From aleax at mac.com Fri Jun 2 22:25:44 2006 From: aleax at mac.com (Alex Martelli) Date: Fri, 2 Jun 2006 19:25:44 -0700 Subject: An oddity in list comparison and element assignment References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> <1hg9nl6.xivwcd7n0j5N%aleax@mac.com> <1149277242.199765.213600@g10g2000cwb.googlegroups.com> Message-ID: <1hgbjx1.1gn7haipx7x5N%aleax@mac.com> Terry Reedy wrote: > wrote in message > news:1149277242.199765.213600 at g10g2000cwb.googlegroups.com... > > (As an aside, may I point out that Python In A Nutshell states on page > > 46 "The result of S*n or n*S is the concatenation of n copies of S". > > It would be more exact to say that S*n is [] extended with S n times, > which makes it clear that 0*S == S*0 == [] and which avoids the apparently > misleading word 'copy'. I presume the C implementation is the equivalent Considering that the very next (and final) sentence in that same paragraph is "If n is zero or less than zero, the result is an empty sequence of the same type as S", I don't think there's anything misleading in the quoted sentence. Moreover, since the paragraph is about sequences, not just lists, it *WOULD* be horribly wrong to use the phrasing you suggest: "bah!"*3 is NOT a list, it's EXACTLY the concatenation of three copies of that string -- no more, no less. > Or one could say that the result *is the same as* (not *is*) the I find this distinction, in this context, to be empty padding, with zero added value on ANY plane -- including the plane of "pedantry";-). > concatenation of n *shallow* copies of S. 'Shallow' means that each copy I do not think it would be good to introduce the concept of "shallow" at a point in the text which is talking about ALL sequences -- including ones, such as strings, for which it just does not apply. But, thanks for the suggestions, anyway! Alex From max at alcyone.com Wed Jun 28 02:22:41 2006 From: max at alcyone.com (Erik Max Francis) Date: Tue, 27 Jun 2006 23:22:41 -0700 Subject: a class variable question In-Reply-To: <1151475322.648696.21880@b68g2000cwa.googlegroups.com> References: <1151474768.546012.254380@p79g2000cwp.googlegroups.com> <1151475322.648696.21880@b68g2000cwa.googlegroups.com> Message-ID: Pierre Quentel wrote: > In func1, _var1 = 1 creates a local variable _var1 (local to the > method), not an attribute of the instance. If you want an instance > attribute you must specify the reference to the instance by > self._var1 = 1 ; self must be passed as an attribute to func1 > > def func1(self): > self._var1 = 1 Note this only changes the attribute in the instance. If he wants it to be changed for all other instances, he needs to change it in the class with:: A._var1 = 1 -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Every path has its puddle. -- (an English proverb) From rzantow at gmail.com Mon Jun 19 15:18:25 2006 From: rzantow at gmail.com (Rick Zantow) Date: Mon, 19 Jun 2006 15:18:25 -0400 Subject: Amara installation References: <1150719788.482305.9560@r2g2000cwb.googlegroups.com> Message-ID: "tjreedy" wrote in news:mailman.7202.1150730143.27775.python-list at python.org: > > wrote in message > news:1150719788.482305.9560 at r2g2000cwb.googlegroups.com... >> O/S WinXP Home >> Vsn of Python: 2.4 >> >> Wish to install Amara. Using amara-allinone-1.0.win32-py2.4.exe >> (2965KB) >> >> Forder structure before installation: >> >> c: >> python24 >> DLLs >> Doc >> Include >> Lib >> site-packages >> [previously installed stuff] >> libs >> scripts >> tcl >> tools >> >> When I run install, the install program indicates: >> >> Python directory: c:\python24\ >> Installation directory: c:\python24\lib\site-packages\ >> >> After install, folder structrue is: >> >> Vsn of Python: 2.4 >> >> Wish to install Amara. Using amara-allinone-1.0.win32-py2.4.exe >> (2965KB) >> >> Forder structure after installation: >> >> c: >> python24 >> DLLs >> Doc >> Include >> Lib >> site-packages >> [previously installed stuff] >> libs >> python24 <<<-- >> lib <<<-- >> site-packages <<<-- new amara files/folders appear >> amara <<<-- to be installed here >> ft <<<-- >> scripts <<<-- >> share <<<-- >> scripts >> tcl >> tools >> >> I was expecting the new amara files/folders to be installed within >> the existing c:\python24\ folder structure...wasn't expecting it to >> create a new ...\python24\ folder within the parent ...\python24\ >> folder. > > That is probably because you told it to, without knowing what exactly > was being asked. It looks like this installer was intended for > someone who does not already have Python installed. You might inquire > as to whether there is one for people who do. > >> My questions: >> 1) has anyone else observed this when installing? >> 2) should I move the newly installed files/folders into the >> previously-existing folder structure? as long as I don't remove >> files/folders, is there any risk of causing a previously installed >> site package that worked to no longer work? > > I don't think so. > As long as the installer did not register file locations, this should > work. If there are any shortcuts or start menu entries, you will have > to edit. > Actually, the installer is broken; I had the same experience (in a prior version as well as the current version). The installer screen displays the install directory path as (in my case) C:\Python24\Lib\site-packages\ but it actually creates C:\Python24\Python24\Lib\site-packages\ and dependents, and populates that subtree. I just moved the files to the appropriate locations and it seems to work, but that first impression doesn't sit well. I reported this to Uche and even got a response, but the installer has not been fixed. -- rzed From pc at p-cos.net Sun Jun 25 10:14:14 2006 From: pc at p-cos.net (Pascal Costanza) Date: Sun, 25 Jun 2006 16:14:14 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150908952.804184.218990@r2g2000cwb.googlegroups.com> <1150991074.705803.211570@m73g2000cwd.googlegroups.com> Message-ID: <4g7k1mF1ma4ghU1@individual.net> Joachim Durchholz wrote: > Andreas Rossberg schrieb: >> >> Luca Cardelli has given the most convincing one in his seminal >> tutorial "Type Systems", where he identifies "typed" and "safe" as two >> orthogonal dimensions and gives the following matrix: >> >> | typed | untyped >> -------+-------+---------- >> safe | ML | Lisp >> unsafe | C | Assembler >> >> Now, jargon "dynamically typed" is simply untyped safe, while "weakly >> typed" is typed unsafe. > > Here's a matrix how most people that I know would fill in with terminology: > > | Statically | Not | > | typed | statically | > | | typed | > ---------+--------------+-------------+ > typesafe | "strongly | Dynamically | > | typed" | typed | > | (ML, Pascal) | (Lisp) | > ---------+--------------+-------------+ > not | (no common | "untyped" | > typesafe | terminology) | | > | (C) | (Assembly) | > ---------+--------------+-------------+ > > (Terms in quotes are challenged on a regular basis, or rarely if ever > applied.) > > With the above terminology, it becomes clear that the opposite if > "(statically) typed" isn't "statically untyped", but "not statically > typed". "Statically typed" and "dynamically typed" aren't even > opposites, they just don't overlap. > > Another observation: type safeness is more of a spectrum than a clearcut > distinction. Even ML and Pascal have ways to circumvent the type system, > and even C is typesafe unless you use unsafe constructs. > IOW from a type-theoretic point of view, there is no real difference > between their typesafe and not typesafe languages in the "statically > typed" column; the difference is in the amount of unsafe construct usage > in practial programs. It's also relevant how straightforward it is to distinguish between safe and unsafe code, how explicit you have to be when you use unsafe code, how likely it is that you accidentally use unsafe code without being aware of it, what the generally accepted conventions in a language community are, etc. pp. Pascal -- 3rd European Lisp Workshop July 3 - Nantes, France - co-located with ECOOP 2006 http://lisp-ecoop06.bknr.net/ From beni.cherniavsky at gmail.com Fri Jun 9 09:34:38 2006 From: beni.cherniavsky at gmail.com (cben@users.sf.net) Date: 9 Jun 2006 06:34:38 -0700 Subject: Where is the ucs-32 codec? In-Reply-To: <4483FD63.2080502@v.loewis.de> References: <1149459785.331497.203920@c74g2000cwc.googlegroups.com> <4483EB71.9090509@v.loewis.de> <4483FD63.2080502@v.loewis.de> Message-ID: <1149860078.334793.308420@y43g2000cwc.googlegroups.com> Martin v. L?wis wrote: > Erik Max Francis wrote: > >> The only reason is that nobody has needed one so far, and because > >> it is quite some work to do if done correctly. Why do you need it? > > Somebody asked me about generating UTF-32 (he didn't have choice of the output format). I was about to propose the obvious ``u.encode('utf-32')`` but discovered it's missing. Someone proposed 'unicode-internal' but it depends on the build and is an ugly answer. Next time, I want Guido's Time Machine to just work, so I have to fix this ;-). > > Why would it be "quite some work"? Converting from UTF-16 to UTF-32 is > > pretty straightforward, and UTF-16 is already supported. > > I would like to see it correct, unlike the current UTF-16 codec. Perhaps > whoever contributes an UTF-32 codec could also deal with the defects of > the UTF-16 codec. > Now this is interesting, as I hoped to base my code on UTF-16 (and perhaps UTF-8 for combining surrogates)... Can you elaborate? I could attempt to fix UTF-16 as well but I don't have the expertise to choose the right behaviour, so you'll have to specify precisely what it should do (that it doesn't do now). From fredrik at pythonware.com Thu Jun 8 02:21:26 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 08 Jun 2006 08:21:26 +0200 Subject: language-x-isms In-Reply-To: References: Message-ID: Bryan wrote: > for example, i've noticed several java developers i know write python code like > this: > > foo_list = [...] > for i in range(len(foo_list)): > print '%d %s' % (i, foo_list[i]) which is a perfectly valid way of doing things if you're targeting older Python platforms as well (including Jython). From pc at p-cos.net Fri Jun 23 09:32:54 2006 From: pc at p-cos.net (Pascal Costanza) Date: Fri, 23 Jun 2006 15:32:54 +0200 Subject: Saying "latently-typed language" is making a category mistake In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <86Qmg.10725$o4.1907@newsread2.news.pas.earthlink.net> <4g251pF1knc6tU1@individual.net> Message-ID: <4g28s6F1k9npnU1@individual.net> Matthias Blume wrote: > Pascal Costanza writes: > >> Patricia Shanahan wrote: >>> Vesa Karvonen wrote: >>> ... >>>> An example of a form of informal reasoning that (practically) every >>>> programmer does daily is termination analysis. There are type systems >>>> that guarantee termination, but I think that is fair to say that it >>>> is not >>>> yet understood how to make a practical general purpose language, whose >>>> type system would guarantee termination (or at least I'm not aware >>>> of such >>>> a language). It should also be clear that termination analysis need not >>>> be done informally. Given a program, it may be possible to >>>> formally prove >>>> that it terminates. >>> To make the halting problem decidable one would have to do one of >>> two >>> things: Depend on memory size limits, or have a language that really is >>> less expressive, at a very deep level, than any of the languages >>> mentioned in the newsgroups header for this message. >> Not quite. See http://en.wikipedia.org/wiki/ACL2 > > What do you mean "not quite"? Of course, Patricia is absolutely > right. Termination-guaranteeing languages are fundamentally less > expressive than Turing-complete languages. ACL2 was not mentioned in > the newsgroup header. ACL2 is a subset of Common Lisp, and programs written in ACL2 are executable in Common Lisp. comp.lang.lisp is not only about Common Lisp, but even if it were, ACL2 would fit. Pascal -- 3rd European Lisp Workshop July 3 - Nantes, France - co-located with ECOOP 2006 http://lisp-ecoop06.bknr.net/ From fredrik at pythonware.com Wed Jun 7 02:33:34 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 07 Jun 2006 08:33:34 +0200 Subject: assign operator as variable ? In-Reply-To: <1149661137.454954.234390@u72g2000cwu.googlegroups.com> References: <1149661137.454954.234390@u72g2000cwu.googlegroups.com> Message-ID: s99999999s2003 at yahoo.com wrote: > in python is there any way to do this > > op = "<" > a = 10 > b = 20 > if a op b : > print "a is less than b" > > ?? the "operator" module contains functions corresponding to all builtin operators: import operator ops = { "==": operator.eq, "!=": operator.ne, "<>": operator.ne, "<": operator.lt, "<=": operator.le, ">": operator.gt, ">": operator.ge } op = "<" a = 10 b = 20 if ops[op](a, b): print "a is less than b" From gandalf at designaproduct.biz Tue Jun 6 05:26:23 2006 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Tue, 06 Jun 2006 11:26:23 +0200 Subject: Checking var is a number? In-Reply-To: <1149583700.145737.170720@j55g2000cwa.googlegroups.com> References: <1149583700.145737.170720@j55g2000cwa.googlegroups.com> Message-ID: <44854A3F.7090302@designaproduct.biz> dav.phillips at ntlworld.com ?rta: > Hi, > I am very new to all this and need to know how to check > a variable to see if it is a number or not. Also can anyone > recommend a reference book apart from dive into python > preferably a reference with good examples of how to impliment > code. > There are different types of number in Python. Integers and Long integers (type: 'int', 'long') Decimal numbers (class 'decimal.Decimal') Floating point numbers (type 'float') You can check this way: import decimal def print_type(var): if isinstance(var,int): print "this is an integer" elif isinstance(var,long): print "this is a long integer" elif isinstance(var,decimal.Decimal): print "this is a decimal" elif isinstance(var,float): print "this is a float" else: print "this is something else..." Test this: ... >>> print_type(12) this is an integer >>> print_type(12L) this is a long integer >>> print_type(3.5) this is a float >>> print_type('hello world') this is something else... >>> print_type('44') this is something else... >>> d = Decimal('123') >>> print_type(d) this is a decimal >>> > The project i have been given to work in is all CGI written > in Python. > Probaby you wanted to convert a string into a number? For example: >>> int(s) 1234 >>> s = 'Foo' >>> int(s) Traceback (most recent call last): File "", line 1, in ? ValueError: invalid literal for int(): Foo >>> Or you can catch the exception: >>> s = 'Foo2' >>> try: ... intval = int(s) ... except ValueError: ... print "This cannot be converted to an int." ... This cannot be converted to an int. >>> Good luck! Laszlo From martin at v.loewis.de Sun Jun 18 04:34:01 2006 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Sun, 18 Jun 2006 10:34:01 +0200 Subject: Which compiler will Python 2.5 / Windows (Intel) be built with? In-Reply-To: <4494953f$1@nntp0.pdx.net> References: <1150367139.495114.148550@g10g2000cwb.googlegroups.com> <44917535$1@nntp0.pdx.net> <1150391891.130185.4640@f6g2000cwb.googlegroups.com> <4492414C.10505@v.loewis.de> <1150444191.618761.22810@c74g2000cwc.googlegroups.com> <4494424f$1@nntp0.pdx.net> <4494953f$1@nntp0.pdx.net> Message-ID: <44950FF9.7070900@v.loewis.de> Scott David Daniels wrote: > I musunderstood you. I thought you were advocating that Python itself > be built on gcc, obviating many compiler access issues. That wouldn't > work because gcc cannot, by itself (as I understand it) get to all the > nooks and crannies a windows developer may need to traverse. I know I > just repeated my argument here against a strawman, but that was really > for other readers, not for you. Even that is incorrect. Python 2.x can be built fully with gcc. It's PythonWin that includes a lot of C++ and MFC code that won't compile with gcc. That doesn't preclude to use gcc for Python 2.x compilation, as long as a msvcrt is selected that can work together with some version of MFC and the MS C++ RTL. Regards, Martin From skip at pobox.com Sun Jun 4 07:22:19 2006 From: skip at pobox.com (skip at pobox.com) Date: Sun, 4 Jun 2006 06:22:19 -0500 Subject: Pyrex list/array In-Reply-To: <1149418950.943306.262510@h76g2000cwa.googlegroups.com> References: <1149360983.373137.200740@i39g2000cwa.googlegroups.com> <448239EB.6010706@lexicon.net> <1149415140.458073.65310@c74g2000cwc.googlegroups.com> <1149418950.943306.262510@h76g2000cwa.googlegroups.com> Message-ID: <17538.49771.991613.732043@montanaro.dyndns.org> >> Is it substantially faster with psyco than without? If psyco is >> performing its magic on the critical section of code already, you are >> going to lose that when switching to Pyrex. Jim> Yes but from what I read Pyrex can be a lot faster than psyco under Jim> the right circumstances. I'm sure that's true. That also means under the wrong circumstances it might not. ;-) Can you post the code that's running too slowly? Also, note that psyco learned some new tricks at the recent NeedForSpeed sprint. You might want to check out the latest version from Subversion and give it a whirl. Skip From tiarno at sas.com Wed Jun 7 09:26:46 2006 From: tiarno at sas.com (Tim Arnold) Date: Wed, 7 Jun 2006 09:26:46 -0400 Subject: wddx problem with entities Message-ID: I'm confused about why I get this error: UnicodeError: ASCII encoding error: ordinal not in range(128) when I try to load a wddx file containing this string: The image file, gif/aperçu.png, does not exist. When I loop through the file as if it's text and check the ord() value of each character, of course it's clean. Do I have to replace numbered entities in the wddx file before I can wddx.load() it? thanks! --tim example program: ------------------- from xml.marshal import wddx datastring = '''
The image file, gif/aperçu.png,does not exist. ''' data = wddx.loads(datastring) From robert.thorpe at antenova.com Wed Jun 21 12:55:52 2006 From: robert.thorpe at antenova.com (Rob Thorpe) Date: 21 Jun 2006 09:55:52 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> Message-ID: <1150908952.804184.218990@r2g2000cwb.googlegroups.com> Vesa Karvonen wrote: > In comp.lang.functional Anton van Straaten wrote: > > Let me add another complex subtlety, then: the above description misses > > an important point, which is that *automated* type checking is not the > > whole story. I.e. that compile time/runtime distinction is a kind of > > red herring. > > I agree. I think that instead of "statically typed" we should say > "typed" and instead of "(dynamically|latently) typed" we should say > "untyped". > > > In a statically-checked language, people tend to confuse automated > > static checking with the existence of types, because they're thinking in > > a strictly formal sense: they're restricting their world view to what > > they see "within" the language. > > That is not unreasonable. You see, you can't have types unless you > have a type system. Types without a type system are like answers > without questions - it just doesn't make any sense. > > > Then they look at programs in a dynamically-checked language, and see > > checks happening at runtime, and they assume that this means that the > > program is "untyped". > > Not in my experience. Either a *language* specifies a type system or > not. There is little room for confusion. Well, at least unless you > equate "typing" with being "well-defined" or "safe" and go to great > lengths to convince yourself that your program has "latent types" even > without specifying a type system. The question is: What do you mean by "type system"? Scheme and Lisp both define how types work in their specifications clearly, others may do too, I don't know. Of-course you may not consider that as a type system if you mean "type system" to mean a static type system. > > It's certainly close enough to say that the *language* is untyped. > > Indeed. Either a language has a type system and is typed or has no > type system and is untyped. I see very little room for confusion > here. In my experience, the people who confuse these things are > people from the dynamic/latent camp who wish to see types everywhere > because they confuse typing with safety or having well-defined > semantics. No. It's because the things that we call latent types we use for the same purpose that programmers of static typed languages use static types for. Statically typed programmers ensure that the value of some expression is of some type by having the compiler check it. Programmers of latently typed languages check, if they think it's important, by asking what the type of the result is. The objection here is that advocates of statically typed language seem to be claiming the "type" as their own word, and asking that others use their definitions of typing, which are really specific to their subjects of interest. This doesn't help advocates of static languages/ latently typed languages, or anyone else. It doesn't help because no-one else is likely to change their use of terms, there's no reason why they would. All that may happen is that users of statically typed languages change the words they use. This would confuse me, for one. I would much rather understand what ML programmers, for example, are saying and that's hard enough as it is. There's also my other objection, if you consider latently typed languages untyped, then what is assembly? From dnew at san.rr.com Thu Jun 22 17:17:28 2006 From: dnew at san.rr.com (Darren New) Date: Thu, 22 Jun 2006 21:17:28 GMT Subject: What is a type error? In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <7i3mg.204167$8W1.155367@fe1.news.blueyonder.co.uk> <44992e6c$2$664$bed64819@news.gradwell.net> <%Igmg.464974$xt.353729@fe3.news.blueyonder.co.uk> <449aaea0$2$656$bed64819@news.gradwell.net> Message-ID: Eliot Miranda wrote: > can only actually carry-out operations on objects that implement them. Execpt that every operation is implemented by every object in Smalltalk. Unless you specify otherwise, the implementation of every method is to call the receiver with doesNotUnderstand. (I don't recall whether the class of nil has a special rule for this or whether it implements doesNotUnderstand and invokes the appropriate "don't send messages to nil" method.) There are a number of Smalltalk extensions, such as multiple-inheritance, that rely on implementing doesNotUnderstand. -- Darren New / San Diego, CA, USA (PST) Native Americans used every part of the buffalo, including the wings. From slomojo83 at gmail.com Thu Jun 15 17:26:26 2006 From: slomojo83 at gmail.com (Josiah Manson) Date: 15 Jun 2006 14:26:26 -0700 Subject: list of polynomial functions In-Reply-To: References: <1150390140.459461.169900@i40g2000cwc.googlegroups.com> Message-ID: <1150406786.353725.5800@r2g2000cwb.googlegroups.com> > The `i` is the problem. It's not evaluated when the lambda *definition* > is executed but when the lambda function is called. And then `i` is > always == `n`. You have to explicitly bind it as default value in the > lambda definition: > > polys.append(lambda x, i=i: polys[i](x)*x) Thank you for your help. From rogue_pedro at yahoo.com Thu Jun 22 12:23:22 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 22 Jun 2006 09:23:22 -0700 Subject: Feed wxComboBox with dictionary/hash References: <1150983925.131182.88670@i40g2000cwc.googlegroups.com> Message-ID: <1150993402.203971.57320@r2g2000cwb.googlegroups.com> Roland Rickborn wrote: > Hi folks, ... > As the subject says, I'd like to feed a wx.ComboBox with a > dictionary/hash. According to the posting of Stano Paska ("wxComboBox > <> combobox", 20 Jul. 2004), there seems to be a way to do this: > > > You must use something like > > combo.Append('aaa', 'a') > > combo.Append('bbb', 'b') > > ... > > My problem is: > my data has thousands of entries. Therefore, I'd like to feed the > combobox with a dictionary (which itself is fed by a database query). > > My first question: > how can a wx.ComboBox be fed by a dictionary? > ... > TIA, > Roland R. I don't know if this is the best way to do this, but you could just feed the wx.ComboBox from the dict in a loop like this: for k, v in data_dict.iteritems(): combo.Append(k, v) >From the manual link that Iain King posted (http://wxwidgets.org/manuals/2.6.3/wx_wxcontrolwithitems.html#wxcontrolwithitems) it appears that you might be able to pass a list of strings to the Append() method. However, it also appears that you wouldn't be able to associate any "clientData" with the strings. Peace, ~Simon From dave.opstad at monotypeimaging.com Thu Jun 15 10:20:04 2006 From: dave.opstad at monotypeimaging.com (Dave Opstad) Date: Thu, 15 Jun 2006 07:20:04 -0700 Subject: Python is fun (useless social thread) ;-) References: Message-ID: In article , John Salerno wrote: I had retired from Apple in 2001 after 33 years in the business, feeling completely burned out. Didn't want to even look at another line of code. After resting and recuperating for a couple years, though, I picked up a book on Python (Alex Martelli's wonderful "Python in a Nutshell") and started tinkering with it. I was utterly amazed at how well Python's metaphors fit my way of thinking. It was actually fun to program again! So now I'm back at work full-time, at a company that lets me do 95%+ of my work in Python, and I'm having the time of my life. My copy of the Martelli book is seriously dog-eared at this point; I'm glad a new edition is being released in a few months. In short: Python rocks. Dave Opstad From claudio.grondi at freenet.de Mon Jun 26 13:55:43 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Mon, 26 Jun 2006 19:55:43 +0200 Subject: style question In-Reply-To: <44a01364@nntp0.pdx.net> References: <44a01364@nntp0.pdx.net> Message-ID: Scott David Daniels wrote: > Claudio Grondi wrote: > <<>> > >> When necessary to skip first line _and_ indentation: >> message = """ >> This is line 1 >> This is line 2 >> This is line 3 >> """.replace('\n ', '\n')[1:] # adjust here '\n ' to indentation > > > Riffing on this idea: > message = """ > This is line 1 > This is line 2 > This is line 3 > """.replace(""" > """, '\n')[1:] This was intended as an excercise for the OP in case he likes that kind of solution ... Claudio > > --Scott David Daniels > scott.daniels at acm.org From claudio.grondi at freenet.de Sat Jun 17 18:08:07 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Sun, 18 Jun 2006 00:08:07 +0200 Subject: Standard Yes / No Windows Dialog box creation In-Reply-To: <1150581640.385143.83410@y41g2000cwy.googlegroups.com> References: <1150581640.385143.83410@y41g2000cwy.googlegroups.com> Message-ID: flaus.a at wanadoo.fr wrote: > I found a way to create "Open File" or "Open Folder" windows dialog > boxes, but not to create an easier Yes / No dialog box... > Maybe someone has a solution for this? > Do it just the same way as you did it with the "Open File" or "Open Folder" windows dialog. What is your problem with it? Claudio From afa at neuf.fr Mon Jun 26 17:35:29 2006 From: afa at neuf.fr (Amaury Forgeot d'Arc) Date: Mon, 26 Jun 2006 23:35:29 +0200 Subject: psyco+webpy In-Reply-To: <1151356858.647976.161520@b68g2000cwa.googlegroups.com> References: <1151348303.344822.18720@u72g2000cwu.googlegroups.com> <1151356858.647976.161520@b68g2000cwa.googlegroups.com> Message-ID: a a ?crit : >> psyco.cannotcompile(??.GET) this gives an error message > invalid syntax Oh, I assumed that you would replace the ?? by the correct expression. You need to specify the GET function of the class you've written in the file "codepsyco.py" (I don't know the class name. It does not appear in the error traceback) Depending on your architecture, this may be written this way: import codepsyco psyco.cannotcompile(codepsyco.YourClassHere.GET) -- Amaury From python.list at tim.thechases.com Thu Jun 15 19:04:04 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 15 Jun 2006 18:04:04 -0500 Subject: list of polynomial functions In-Reply-To: <4491c005$1@nntp0.pdx.net> References: <1150390140.459461.169900@i40g2000cwc.googlegroups.com> <4491AA55.7030200@tim.thechases.com> <4491c005$1@nntp0.pdx.net> Message-ID: <4491E764.7080108@tim.thechases.com> > Just to be a bit more explicit: > In code like: > def make_polys(n): > """Make a list of polynomial functions up to order n.""" > p = lambda x: 1 > polys = [p] > for i in range(n): > polys.append(lambda x: polys[i](x)*x) > i=3 > > The lambda-defined functions will be called after the for loop is done, ::boggle:: My understanding is that the lambda-defined functions are not called until the actual application thereof, with the mypolys = make_polys(8) mypolys[5](2) #the lambda call happens here, no? 's original statement read like a koan...there was more in it than I was getting out of it. There seem to be several concepts I've not yet wrapped my head around. My understanding (likely wrong) was that "lambda" was sort of like defining a function inline, along the lines of def f(x): return x+5 being somewhat equiv to k = lambda x: x+5 you could then do >>> f(20) 25 >>> j = f >>> j(20) 25 >>> k(20) 25 >>> j = k >>> j(20) 25 There does seem to be some subtle difference, as >>> f >>> k at 0xb7d8c0d4> "k" clearly knows it's a just as "f" knows its an "f" (whether asked for by the aliased name or not). So at some point, the Python interpreter is compiling this function/lambda, and expanding matters with or without some sort of scope. The OP's example seems to pull both "polys" and "i" from the local scope. However, Python must only be tokenizing and making references to future-ly available stuff, as, without "spam", "blah", "tapioca", or "spatula" defined in my environment, I can do arbitrary things like q = lambda x: spam[spatula](x) + blah / tapioca and Python swallows the whole lot as syntactically kosher, even though none of these items exist. It seems to only evaluate them at the point that "q" is called. [lightbulb begins to go on...sorta] However, in the OP's example, slightly modified, it seems that polys, even when it doesn't exist in the calling scope, it doesn't matter. >>> def mp(n): ... p = lambda x: 1 ... polys = [p] ... for i in range(n): ... polys.append(lambda x: polys[i](x)*x) ... return polys ... >>> f = mp(5) >>> polys Traceback (most recent call last): File "", line 1, in ? NameError: name 'polys' is not defined >>> for p in f: print p(3) ... 1 Traceback (most recent call last): File "", line 1, in ? File "", line 5, in : : : I'm curious why the very first attempt to call p(3) doesn't bomb out with the NameError that "polys" wasn't defined before it even got to the point of attempting to call it. > Hope this makes it a bit clearer. like chocolate. :-/ Thanks for trying though... -tkc (who is certainly *not* a LISP programmer, as evidenced here...) From robert.thorpe at antenova.com Fri Jun 23 13:00:23 2006 From: robert.thorpe at antenova.com (Rob Thorpe) Date: 23 Jun 2006 10:00:23 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150892256.591282.43880@u72g2000cwu.googlegroups.com> Message-ID: <1151082023.504275.257570@i40g2000cwc.googlegroups.com> Dr.Ruud wrote: > Rob Thorpe schreef: > > > I would suggest that at least assembly should be referred to as > > "untyped". > > There are many different languages under the umbrella of "assembly", so > your suggestion is bound to be false. Well yes, it is false, I know of several typed assemblers. But I mentioned that point elsewhere so I didn't repeat it. This thread is huge and I expect no-one will have read it all, so I will be more clear in future. From ptaku2_wywal_to_ at tlen.pl Tue Jun 27 13:06:30 2006 From: ptaku2_wywal_to_ at tlen.pl (w.p.) Date: Tue, 27 Jun 2006 19:06:30 +0200 Subject: [W2k, wxPython 2.6.1.0] - MDISashDemo bug? In-Reply-To: References: Message-ID: Steve Holden wrote: >> > Well done! Do you know how to feed this information on to the developers > (probably Robin Dunn)? All such changes are valuable. > Hmm... i dont know. wxpython.org -> "submit a patch" or "Report a bug" ? w.p. From zhaodapu at gmail.com Fri Jun 30 16:04:26 2006 From: zhaodapu at gmail.com (zdp) Date: 30 Jun 2006 13:04:26 -0700 Subject: Py2exe make wxPython window looks bad In-Reply-To: <1151654367.250645.189020@d56g2000cwd.googlegroups.com> References: <1151653241.416599.6450@i40g2000cwc.googlegroups.com> <1151654367.250645.189020@d56g2000cwd.googlegroups.com> Message-ID: <1151697866.423613.179670@y41g2000cwy.googlegroups.com> Great, thanks all ray223 at gmail.com ??? > zdp wrote: > > Dear all: > > > > I made a window program by wxPython. Split windows, treectrl, listctrl > > and textctrl are used. When I program in python, the look & feel of the > > window controls are like the windos XP look & feel, with thin and flat > > border (My os is window XP). It's natural because, as I know, wxPython > > use native look and feel. > [snip] > > http://wiki.wxpython.org/index.cgi/FAQ#head-4cc058aed6216dd200d55a6e4c077ccbe82bd142 > > Regards, > > Ray Smith > http://RaymondSmith.com From aleax at mac.com Sun Jun 25 13:30:39 2006 From: aleax at mac.com (Alex Martelli) Date: Sun, 25 Jun 2006 10:30:39 -0700 Subject: array manipulation without for loops References: <1151251578.463273.24370@m73g2000cwd.googlegroups.com> Message-ID: <1hhhh21.z2zqg7lxdf98N%aleax@mac.com> Tim Chase wrote: ... > >>> all = [(x==255 or y==255) and (255, 255) or (x,y) for (x,y) > in itertools.izip(a1,a2)] > >>> b1 = [x[0] for x in all] > >>> b2 = [x[1] for x in all] > >>> a1, a2 = b1, b2 # if you want them to replace the originals > > Seems to do what I understand that you're describing using "no" > loops (other than those implied by list comprehension). Yep, but the performance cost of the for-loops in the comprehension is essentially the same as for such loops written "normally". > There may be some nice pythonic way to "unzip" a list of tuples > created by zip() but I couldn't scare up such a method, and Perhaps what you have in mind is: >>> a=zip('feep','grol') >>> a [('f', 'g'), ('e', 'r'), ('e', 'o'), ('p', 'l')] >>> zip(*a) [('f', 'e', 'e', 'p'), ('g', 'r', 'o', 'l')] But this wouldn't help the OP all that much with his performance problems with large 2-D arrays (though it required some guessing to gauge that it _was_ Numeric arrays that he was dealing with;-), Alex From luca.tavoletti at gmail.com Mon Jun 12 11:25:09 2006 From: luca.tavoletti at gmail.com (lux) Date: 12 Jun 2006 08:25:09 -0700 Subject: VC++ types to ctypes Message-ID: <1150125909.402633.63250@i40g2000cwc.googlegroups.com> Hi to all, i need to traslate this struct in python using ctypes struct Soptions { char chVolumeLabel[128]; __int32 nSessionToImport; BS_BOOL bJolietFileSystem; BS_BOOL bBootable; TCHAR chBootImage[_MAX_PATH]; BS_BOOL bFinalize; BS_BOOL bTestBurn; BS_BOOL bPerformOPC; BS_BOOL bVerifyAfterBurn; __int32 nCacheSize; BS_BOOL bUnderrunProtection; BS_BOOL bEjectAfterBurn; __int32 nCopies; } I try to convert: char xxx[128] -> c_char*128 __int32 -> c_int BS_BOOL -> c_byte TCHAR chBootImage[_MAX_PATH]; -> ??? But not work... how to solve it? Thank's, Luca From python.list at tim.thechases.com Fri Jun 16 10:41:11 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 16 Jun 2006 09:41:11 -0500 Subject: a good programming text editor (not IDE) In-Reply-To: <4492ae6c$0$19179$626a54ce@news.free.fr> References: <_xgkg.2317$No6.48542@news.tufts.edu> <1150402733.116243.9680@y41g2000cwy.googlegroups.com> <4492ae6c$0$19179$626a54ce@news.free.fr> Message-ID: <4492C307.704@tim.thechases.com> > No need to argue. I started with vim, and finally switched to > emacs less than one year later. Both are very-much-so good editors. I made the opposite switch from emacs to vim in less than a year. Both are good^Wgreat editors, so one's decision to use one over the other is more a matter of working style. I don't grok LISP, and just never felt at home in emacs, despite all the power I could see that was there. I grok vim (and its similar power/extensibility), so I migrated to it. I have to laugh at the whole holy-war thing, as it's somewhat like arguing about a favorite color. "But blue is so better than green! The sky is blue!" "Nuh, uh! Green is far better than blue! Grass is green!" (okay, here in Texas, that doesn't always hold as true...maybe personality #2 should be arguing for brown instead). My best friend is an emacs user, and I'm a vimmer...it doesn't come between us. :) -tkc From diesch at spamfence.net Sat Jun 3 20:09:15 2006 From: diesch at spamfence.net (Florian Diesch) Date: Sun, 04 Jun 2006 02:09:15 +0200 Subject: ideas for programs? References: Message-ID: <20060604000919.7E06.0.NOFFLE@dieschf.news.arcor.de> Brandon McGinty wrote: > I've been learning python for the past couple of months and writing > misc scripts here and there, along with some web apps. > I'm wondering if anyone has ideas of programs I might try my hand at making? Something I wanted a few days ago: I have a graph described in the .dot language (used by GraphViz ) and want you get things like "shortest path between two nodes", "all paths between two nodes", "all cycles" and whatever graph theory knows as interesting. Florian -- From richard at pyweek.org Sat Jun 24 23:43:40 2006 From: richard at pyweek.org (richard at pyweek.org) Date: Sun, 25 Jun 2006 13:43:40 +1000 Subject: pygame.draw deadline extended to Sunday midnight UTC Message-ID: <200606251343.40203.richard@pyweek.org> I'm not going to be awake at midnight, so that means that entrants in the pygame.draw challenge have a few extra hours to get their entries in. http://media.pyweek.org/static/pygame.draw-0606.html Get entries to me by email before UTC (GMT) 23:59 Sunday 25th June. Richard -- Visit the PyWeek website: http://www.pyweek.org/ From ms at cerenity.org Wed Jun 21 18:38:50 2006 From: ms at cerenity.org (Michael) Date: Wed, 21 Jun 2006 23:38:50 +0100 Subject: ANN: Axon 1.5.0 RELEASED! Message-ID: <4499ca1e$0$69378$ed2619ec@ptn-nntp-reader01.plus.net> Hi! I'm extremely pleased to say - Axon 1.5.0 has been released! Axon is Kamaelia's core concurrency system, largely based around python generators to enable components to be built following a slightly updated paraphrasing of Unix Philosophy: """Write components that do one thing and do it well. Write components to work together. Write components to handle python object streams, because that is a universal interface.""" (With apologies to Doug McIlroy...) Axon essentially provides a way for active objects (generators, threads) to be composed into pipelines of arbitrary shape (graphlines etc) as a means of system simplification. What's Changed? =============== Axon 1.5 is a major performance related release for Kamaelia's core component system. There have been a number of core changes, some highlights: * Zero copy delivery of data from producers to consumers * The system scheduler is now reactive to threaded components, meaning the system can truly sleep when there is nothing to do. * This means self.pause() REALLY pauses the microprocess, and may result in the component not receiving data. (If you call self.pause, you should really mean it). Generally this is only used at an optimisation stage. * Threaded components are now fully supported with the following caveats: * They should not use the shared environment provided the co-ordinating assistant tracker (they're not expected to need to do so, but this is useful to make explicit) * They should not expect to be able to interact with synchronous boxes (boxes with a maximum size) Aside from these caveats, creating and using a threaded component is the same as a normal generator based one, except you simply don't have yield statements. You obviously use a different base class. The use of the "ipc" message Axon.Ipc.newComponent for child component startup has been deprecated in favour of the simpler API: X = SomeComponent() X.activate() Despite all these changes, components written for earlier versions of Axon will continue to work as before. Documentation has also generally improved,and is included in the the code files for access via pydoc/help. Message Passing and Delivery Optimisation Changes * Boxes are now discrete objects. This change has occured to enable the use of direct (effectively "zero copy" delivery). * This has meant the postman has been deleted - components no longer have a postman associated with them. This also dramatically frees up CPU cycles for components rather than the communications system. * To replace the structural tracking, a "postoffice" class has been created instead. This, however, is passive rather than active. * Because the death of a component no longer also means the death of a postman, microprocess has been simplified to remove the concept of activity creator. This removes the knock on complexity in both the scheduler and inside Component. * Despite these changes components running on top of Axon (ie existing Kamaelia components) operate largely unchanged. (A few that assumed the existance of a postman etc have changed) Flow Control Inversion * The Scheduler therefore now dynamically builds its runqueue to only include unpaused (active) microprocesses. * If there are no active microprocesses, the scheduler can now sleep. Reducing CPU usage to zero, until some kind of event causes something to wake up. Flow of control is therefore effectively inverted as Axon systems can now be reactive. * Pausing state is now managed by the scheduler on behalf of microprocesses (they used to manage it themselves). Requests to wake and pause microprocesses get routed to the Scheduler. * The APIs for Component and Microprocess are, for the most part, unchanged. Existing components will continue to work as before. If they self pause they will benefit from reduced CPU usage. If all components in a system behave in this way, then Axon will cease to busy-wait when idle. Threading Support * The threaded component has had its API fixed to match the rest of Axon (with the obvious exception of removing the yields). * Threaded 'adaptive' component is new. Detailed release notes & changelog: http://kamaelia.sourceforge.net/Axon-1.5.0-ReleaseNotes.html Platforms ========= Axon has been used successfully under both Linux, Windows and Mac OS X (panther). This version of Axon has not yet been tested on series 60 mobiles. Where can I get it? =================== Sourceforge Download: http://sourceforge.net/project/showfiles.php?group_id=122494&package_id=139298 Web pages are here: http://kamaelia.sourceforge.net/ Tutorial for the core component/concurrency system: * http://kamaelia.sourceforge.net/MiniAxon/ Axon Motivations: * http://kamaelia.sourceforge.net/Challenges/?tab=8 Licensing ========= Axon is a part of the Kamaelia project and as a result is released under the Mozilla tri-license scheme (MPL1.1/GPL2.0/LGPL2.1). See http://kamaelia.sourceforge.net/Licensing.html Best Regards, Michael. -- Michael Sparks, Senior Research Engineer, BBC Research, Technology Group michael.sparks at rd.bbc.co.uk, Kamaelia Project Lead, http://kamaelia.sf.net/ This message (and any attachments) may contain personal views which are not the views of the BBC unless specifically stated. From grflanagan at yahoo.co.uk Wed Jun 7 15:24:07 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 7 Jun 2006 12:24:07 -0700 Subject: Use of Python in .NET In-Reply-To: <1149677283.294472.115050@f6g2000cwb.googlegroups.com> References: <1149677283.294472.115050@f6g2000cwb.googlegroups.com> Message-ID: <1149708247.148673.280640@c74g2000cwc.googlegroups.com> sushant.sirsikar at gmail.com wrote: > Hi, > I am developing a code which has MVC (Model - View - Controler) > architecture.My view is in .NET. And my controller is in Python.So can > i call Python script from .NET? If yes, > Can anybody tell me method or related documentation? > Thanks in Advamce.... http://groups.google.com/group/comp.lang.python/browse_frm/thread/da2a675da29b0bd/197b6a89095ef930?lnk=st&q=&rnum=14#197b6a89095ef930 From faik at pardus.org.tr Fri Jun 16 06:59:28 2006 From: faik at pardus.org.tr (Faik Uygur) Date: Fri, 16 Jun 2006 13:59:28 +0300 Subject: getting umask without changing it In-Reply-To: References: <200606161207.56008.faik@pardus.org.tr> <200606161324.57359.faik@pardus.org.tr> Message-ID: <200606161359.28900.faik@pardus.org.tr> Cuma 16 Haziran 2006 13:41 tarihinde, Fredrik Lundh ?unlar? yazm??t?: > afaik, there's no atomic API for this. ?just a unified get/set function: > > ? ? http://www.opengroup.org/pubs/online/7908799/xsh/umask.html Oops. :( Thanks for the help. Regards, - Faik From mike.klaas at gmail.com Mon Jun 12 19:44:24 2006 From: mike.klaas at gmail.com (Klaas) Date: 12 Jun 2006 16:44:24 -0700 Subject: Large Dictionaries In-Reply-To: References: <1147699064.107490@teuthos> <1147772420.405097@teuthos> <1147818548.532882.94180@i39g2000cwa.googlegroups.com> <1147874585.728471@teuthos> <1148514158.790760.205630@i40g2000cwc.googlegroups.com> Message-ID: <1150155864.813698.206600@y43g2000cwc.googlegroups.com> Thomas Ganss wrote: > Klaas schrieb: > > > 4. Insert your keys in sorted order. > This advice is questionable - > it depends on the at least on the db vendor and probably > sometimes on the sort method, if inserting pre-sorted > values is better. The article I wrote that you quoted named a specific vendor (berkeley db) for which my advice is unquestionable and well-known. -Mike From onurb at xiludom.gro Fri Jun 23 10:44:10 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Fri, 23 Jun 2006 16:44:10 +0200 Subject: * in Python In-Reply-To: References: <1151061836.557835.295820@p79g2000cwp.googlegroups.com> <1151065046.668902.23010@g10g2000cwb.googlegroups.com> <449beca5$0$13891$626a54ce@news.free.fr> Message-ID: <449bfe3a$0$13066$626a54ce@news.free.fr> Duncan Booth wrote: > Bruno Desthuilliers wrote: > > >>>so * basically means that args is a list >> >>A tuple IIRC > > > In a function definition * means that any remaining position arguments will > be passed in as a tuple. In a function call the * means that any sequence > will be unpacked as positional arguments: it doesn't have to be a list or > a tuple. yes, of course - I only saw it from the function's POV. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From antroy at gmail.com Tue Jun 13 08:29:06 2006 From: antroy at gmail.com (Ant) Date: 13 Jun 2006 05:29:06 -0700 Subject: Python Video processing. Message-ID: <1150201746.657059.228570@i40g2000cwc.googlegroups.com> Hi all, I have a specific task I want to automate - rotating a video file through 90 degrees. I've used the PIL library quite a bit to perform batch processing on images, and would like to do similar on video. Can anyone see a problem with the following: 1) Use pymedia to convert the video into a sequence of stills (e.g. http://pymedia.org/tut/src/dump_video.py.html) 2) Use PIL to process each still 3) Use pymedia to re-pack the still into video format. In particular, does anyone know whether the data obtained from decoding the video frame as in the following snippet from http://pymedia.org/tut/src/dump_video.py.html: dd= d.convert( fmt ) img= pygame.image.fromstring( dd.data, dd.size, "RGB" ) can be directly loaded into a PIL Image object (and back again?)? From fredrik at pythonware.com Fri Jun 9 15:28:25 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 09 Jun 2006 21:28:25 +0200 Subject: Error in Chain of Function calls (Code Attached) In-Reply-To: <38733.10.209.4.2.1149843082.squirrel@10.105.1.3> References: <448930f1$0$10302$636a55ce@news.free.fr> <38733.10.209.4.2.1149843082.squirrel@10.105.1.3> Message-ID: Girish Sahani wrote: > Ohh...I was thinking that posting the whole code would not be a good idea. > The error i get above is: > line 266, in colocationMiner > prunedNew = genColocations(prunedK) that's a line of code, not an error. please include the entire traceback, or at least the actual error message. also see: http://pyfaq.infogami.com/tutor-i-need-help-im-getting-an-error-in-my-program-what-should-i-do From filipwasilewski at gmail.com Fri Jun 23 05:17:39 2006 From: filipwasilewski at gmail.com (Filip Wasilewski) Date: 23 Jun 2006 02:17:39 -0700 Subject: String negative indices? References: Message-ID: <1151054259.765401.252230@b68g2000cwa.googlegroups.com> drtimhill at comcast.net wrote: > Logically, I should be able to enter x[-2:-0] to get the last and next to last characters. However, since Python doesn't distinguish between positive and negative zero, this doesn't work. Instead, I have to enter x[-2:]. Hooray! Logically there is no such thing as positive or negative zero, or did I miss something in the primary? PS. x[len(x)-2 : len(x)-0] cheers, fw From arv.nntp at gmail.com Thu Jun 1 15:36:33 2006 From: arv.nntp at gmail.com (Alexis Roda) Date: Thu, 01 Jun 2006 21:36:33 +0200 Subject: integer to binary... In-Reply-To: <1149189570.376091.319890@j55g2000cwa.googlegroups.com> References: <1149189570.376091.319890@j55g2000cwa.googlegroups.com> Message-ID: En/na nicolasg at gmail.com ha escrit: > does anyone know a module or something to convert numbers like integer > to binary format ? http://www.google.es/search?q=python+integer+to+binary http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/219300 > for example I want to convert number 7 to 0111 so I can make some > bitwise operations... python already provides some bitwise operators: http://docs.python.org/ref/summary.html HTH From david.nospam.hopwood at blueyonder.co.uk Sat Jun 24 11:04:02 2006 From: david.nospam.hopwood at blueyonder.co.uk (David Hopwood) Date: Sat, 24 Jun 2006 15:04:02 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150904134.520639.71070@b68g2000cwa.googlegroups.com> <1151056505.908723.162580@u72g2000cwu.googlegroups.com> Message-ID: Anton van Straaten wrote: > rossberg at ps.uni-sb.de wrote: > >> I very much agree with the observation that every programmer performs >> "latent typing" in his head [...] >> But I also think that "latently typed language" is not a meaningful >> characterisation. And for the very same reason! Since any programming >> activity involves latent typing - naturally, even in assembler! - it >> cannot be attributed to any language in particular, and is hence >> useless to distinguish between them. (Even untyped lambda calculus >> would not be a counter-example. If you really were to program in it, >> you certainly would think along lines like "this function takes two >> chuch numerals and produces a third one".) > > Vesa raised a similar objection in his post 'Saying "latently typed > language" is making a category mistake'. I've made some relevant > responses to that post. > > I agree that there's a valid point in the sense that latent types are > not a property of the semantics of the languages they're associated with. > > But to take your example, I've had the pleasure of programming a little > in untyped lambda calculus. I can tell you that not having tags is > quite problematic. You certainly do perform latent typing in your head, > but without tags, the language doesn't provide any built-in support for > it. You're on your own. I can accept that dynamic tagging provides some support for latent typing performed "in the programmer's head". But that still does not mean that dynamic tagging is the same thing as latent typing, or that languages that use dynamic tagging are "latently typed". This simply is not a property of the language (as you've already conceded). -- David Hopwood From michele.petrazzo at TOGLIunipex.it Sat Jun 17 03:32:34 2006 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Sat, 17 Jun 2006 07:32:34 GMT Subject: Problem on win xp and run time error In-Reply-To: References: Message-ID: Chris Lambacher wrote: > On Fri, Jun 16, 2006 at 06:11:53PM +0000, Michele Petrazzo wrote: >> Hi list, just found in this moment that my applications stop to >> work with win xp and receive this error: >> >> """ This application has requested the Runtime to terminate it in >> an unusual way. Please contact the application's support team for >> more information. """ >> >> (Note that the same application [python source code + py2exe] with >> python 2.3.x work well!) > Don't use the single file executatble option with py2exe and the > problem will go away. > I'm not using that option! (that has also problems on win9x with python+wx) I'm not using any of the "bundle_files" options, but only: zipfile = "lib/libraries.zip" > -Chris Thanks, Michele From bdesth.quelquechose at free.quelquepart.fr Tue Jun 27 00:14:58 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 27 Jun 2006 06:14:58 +0200 Subject: Replace Whole Object Through Object Method In-Reply-To: <1151354259.082966.25820@p79g2000cwp.googlegroups.com> References: <1151337453.804750.293180@b68g2000cwa.googlegroups.com> <44a0132d$0$21282$626a54ce@news.free.fr> <1151342941.256085.243000@p79g2000cwp.googlegroups.com> <44a041a6$0$17612$636a55ce@news.free.fr> <1151354259.082966.25820@p79g2000cwp.googlegroups.com> Message-ID: <44a0807f$0$5277$636a55ce@news.free.fr> digitalorganics at gmail.com a ?crit : > Bruno Desthuilliers wrote: > >>digitalorganics at gmail.com a ?crit : >> >>>Bruno Desthuilliers wrote: >> >>(snip) >> >>>>Instead of exposing problems with your solution, you may want to expose >>>>the real use case ? >>> >>> >>>I'm working with a team that's doing social modeling, and for example, >>>I need to model workers that at some point in the program may or may >>>not also become employers. >> >>If I understand correctly, only some of the existing workers will become >>employers ? >> >> >>>Now, I want the workers to take on all >>>behaviors and attributes of an employer in addition to their >>>pre-existing "worker" behaviors and attributes. >> >>wrt/ behaviors, it's easy as pie. Attributes (I mean instance >>attributes) are another problem, but I don't have enough informations to >>deal with this problem here. >> >> >>>Also, as I'm sure you >>>guessed, the workers' attributes need to retain their values at that >>>point in the program, so a brand new worker-employer object wouldn't in >>>itself do the trick. >> >>Here's a simple stupid possible solution: >> (snip) > Won't work because there will be employers that aren't workers. Then don't subclass Employer from Worker !-) (don't mind, just kidding) > And yes, only some workers will become employers, > > but also only some > employers will also be workers (at some point in program). Let me be > more clear: > > workers > --> subset of workers --become--> employers > employers > --> subset of employers --become--> workers > > It is very important that both should maintain attribute values, > regardless of whether they take on new "roles". Seems obvious. But just a question, BTW: do workers and employers share the same attributes ? And if not, how do you intend to initialize the employers attributes on workers (and the other way round) ? > Furthermore, this is a > very simple case and ultimately in my program an object *Any* object ?-) > should be able > to dynamically take on a multitude of roles (classes of behavior) > without mucking at all with their pre-existing states. Multiple roles at the same time, or sequentially ? And in the first case (which I assume), do you have the case of overriding behaviors ? And if yes, how should the resolution order be defined ? And what about attributes ? (I mean, do your 'roles' have specific attributes ?) FWIW, just another simple (and very Q&D) snippet: class ObjectWithRoles(object): def _change(self, *bases): self.__class__ = type(self.__class__.__name__, bases, {}) def has_role(self, role): return role in self.__class__.__bases__ def add_role(self, role): if not self.has_role(role): self._change(self.__class__, role) def remove_role(self, role): if self.has_role(role): self._change(*(cls for cls in self.__class__.__bases__ \ if cls is not role)) NB : Not tested (and not sure what it'll do) with roles subclassing other roles, or ObjectWithRoles as roles... wrt/ per-role attributes, you'd of course need to pass them to add_role(). A convenient way of maintaining some sanity here would be to use descriptors for all of these attributes, and store their values in a per-role dict, with the role name as attribute name. From george.sakkis at gmail.com Sat Jun 24 08:16:01 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 24 Jun 2006 05:16:01 -0700 Subject: search engine References: Message-ID: <1151151361.359777.269130@y41g2000cwy.googlegroups.com> vinodh kumar wrote: > hai all, > i am student of computer science dept. i have planned to > design a search engine in python. i am seeking info about how to > proceed further. > i need to know what r the modules that can be used. There is not a "search engine module" around AFAIK. You should do your homework first and learn about search engines in a language-independent way from some good textbook such as "Mining the Web" (http://http.cs.berkeley.edu/~soumen/mining-the-web/), break the problem into subparts and decide which ones you will implement. By then you should have a much better idea of what modules to look for. George From nomail at nixmail.com Sun Jun 11 08:43:30 2006 From: nomail at nixmail.com (DarkBlue) Date: Sun, 11 Jun 2006 20:43:30 +0800 Subject: Import elfclass32 issue References: <448bc040@127.0.0.1> <448bfa54@127.0.0.1> Message-ID: <448c0ff0@127.0.0.1> Fredrik Lundh wrote: > if you do, it's a SuSE problem (this wouldn't be the first time SuSE > ships broken Python software) Thanks for the input . Following your message I reinstalled python2.4 and the modules I want to use and now everything is fine. From amorgan at xenon.Stanford.EDU Sat Jun 3 22:52:13 2006 From: amorgan at xenon.Stanford.EDU (Alan Morgan) Date: Sat, 3 Jun 2006 19:52:13 -0700 (PDT) Subject: Python less error-prone than Java References: <1149378739.429512.26310@f6g2000cwb.googlegroups.com> Message-ID: In article , Christoph Zwerschke wrote: >Simon Percivall wrote: > > First: It's perfectly simple in Java to create a binary sort that > > sorts all arrays that contain objects; so wrong there. > >My point was that the *same* Java source example, directly converted to >Python would *automatically* accept all kinds of arrays. And the same code converted to SML would automatically work on all kinds of arrays and SML is statically typed. It's a language issue, not a typing issue. >No need to make any extra efforts. >By the way, how would you do it in Java? With >function overloading? I would not call that perfectly simple. Since Java doesn't allow function overloading that clearly can't be the way. J2SE 5.0 allows generic classes and functions that operate on generic containers. There are some gotchas, but it's not drastically more complex than the original int-only java code. Alan -- Defendit numerus From mr.roboto.ny at gmail.com Thu Jun 15 13:18:58 2006 From: mr.roboto.ny at gmail.com (Mr Roboto) Date: 15 Jun 2006 10:18:58 -0700 Subject: Which compiler will Python 2.5 / Windows (Intel) be built with? References: <1150367139.495114.148550@g10g2000cwb.googlegroups.com> <1150388468.149672.30810@i40g2000cwc.googlegroups.com> Message-ID: <1150391938.601412.311530@c74g2000cwc.googlegroups.com> Jarek Zgoda wrote: > nikie napisa?(a): > > > If you want to *buy* VS 2003, you could still purchase a 1-year MSDN > > Pro Subscription. The price difference isn't *that* big compared to a > > single-user license of VS, and it automatically includes past VS > > versions (everything from VC++ 6.0 and upwards, IIRC). > > This doesn't make building Python exension libraries any easier. > > In some cases, you can still build Python extension with MinGW. I didn't > try this with anything more complicated than linking to libxml2, but > still, it's some workaround. Not sure about the performace of such > build, though. > > -- > Jarek Zgoda > http://jpa.berlios.de/ I haven't personally tried a Python compile w/ this, but I'll share it in hopes that it'll help: one can download a free copy of Visual C++ 2K5 *Express* from microsoft itself. If you're interested, try: http://msdn.microsoft.com/vstudio/express/visualc/default.aspx It's legal, free (no registration, no BS.) HTH....MR From a at tempinbox.com Wed Jun 28 02:02:37 2006 From: a at tempinbox.com (a) Date: 27 Jun 2006 23:02:37 -0700 Subject: global name is not defined - error - but for array Message-ID: <1151471317.328398.132670@x69g2000cwx.googlegroups.com> def fn(): for i in range(l) global count count[i]= .... how do i declare count to be global if it is an array subsequently i should access or define count as an array error: global name 'count' is not defined thanks -a From andrewdalke at gmail.com Mon Jun 19 20:40:37 2006 From: andrewdalke at gmail.com (andrewdalke at gmail.com) Date: 19 Jun 2006 17:40:37 -0700 Subject: europython room share Message-ID: <1150764037.791056.168810@f6g2000cwb.googlegroups.com> Is anyone here going to Europython and would like a roommate to help split the cost? I'll be there for all three days of the conference plus a few extra days for sprints. I figure I can move elsewhere if need be for the sprints. It looks like the best choices are St. Genis (because it is about 20 minutes walk away) or Geneva (30 minutes by frequent bus, with more to do and places to eat). I did some research looking for places to stay. My biggest problem was my inability to read French, though most of the hotels on the CERN page at http://housing-service.web.cern.ch/housing-service/listhotel.html also have alternate pages in English. My second biggest is not knowing the geography. The Europython "Places to stay" page at http://www.europython.org/sections/accommodation says Nearby places (useful when consulting the hotels with special rates) include Meyrin, Satigny (in Switzerland) and St. Genis-Pouilly (in France). Figuring a lot of students have worked at CERN and written up their experiences, I found one with this comment in http://www.sccs.swarthmore.edu/org/swap/reureviews/cern.html CERN is about 30 minutes by bus from Geneva and a 20 minute walk or bike ride from entertainment in St. Genis, France. Summer students hung out most Tuesdays at a pub in St. Genis. The Europython wiki says the bus to Geneva "leaves four times an hour during most of a weekday." I don't know if most people will meet up for dinner and drinks somewhere close by CERN or in Geneva, making it harder to figure out where to stay. I'm thinking nearby.. at least those staying in the CERN hostel. Andrew dalke at dalkescientific.com From sushant.sirsikar at gmail.com Wed Jun 7 06:48:03 2006 From: sushant.sirsikar at gmail.com (sushant.sirsikar at gmail.com) Date: 7 Jun 2006 03:48:03 -0700 Subject: Use of Python in .NET Message-ID: <1149677283.294472.115050@f6g2000cwb.googlegroups.com> Hi, I am developing a code which has MVC (Model - View - Controler) architecture.My view is in .NET. And my controller is in Python.So can i call Python script from .NET? If yes, Can anybody tell me method or related documentation? Thanks in Advamce.... From sjmachin at lexicon.net Tue Jun 27 22:30:03 2006 From: sjmachin at lexicon.net (John Machin) Date: Wed, 28 Jun 2006 12:30:03 +1000 Subject: Function to prune dictionary keys not working In-Reply-To: References: Message-ID: <44A1E9AB.6060206@lexicon.net> On 28/06/2006 12:15 PM, Girish Sahani wrote: > hi ppl, > Here is a simple function to remove those keys of a dictionary whose > values are less than some specified value. But it isnt working. Please > help. > > def prune(d,cp): > l = [] > for rule,value in d.iteritems(): > #print value > if value >= cp: > l.append(rule) > return l > > >>>> d = {'be=>c': '1.00', 'c=>da': '0.50', 'ea=>b': '0.33', 'be=>d': > '0.50', 'c=>ba': '0.33', 'bd=>a': '1.00', 'a=>cb': '0.33', 'ea=>c': > '0.67', 'a=>cd': '0.50', 'e=>ac': '0.40', 'e=>ab': '0.20', 'c=>bd': > '0.33', 'e=>cb': '0.40', 'ed=>b': '0.25', 'ed=>c': '0.50'} >>>> cp = 0.5 >>>> if prune(d,cp) == d.keys(): > print "code not working :((" > > code not working :(( > |>> '1.00' >= 0.5 True |>> '0.33' >= 0.5 True Python (correctly) does very little (guesswork-based) implicit type conversion. It looks like the values in your dictionary should stored as floats, not as strings. HTH, John From fredrik at pythonware.com Sun Jun 18 13:42:50 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 18 Jun 2006 19:42:50 +0200 Subject: code is data In-Reply-To: <1150650852.275956.249340@p79g2000cwp.googlegroups.com> References: <1150574111.415068.255900@p79g2000cwp.googlegroups.com> <1150606118.456390.262620@y41g2000cwy.googlegroups.com> <1150626424.563673.175060@c74g2000cwc.googlegroups.com> <1150650852.275956.249340@p79g2000cwp.googlegroups.com> Message-ID: Ravi Teja wrote: > Web frameworks, which seem to be the rage now in Python community could > have benefited tremendously from Macro capabilities since they have a > lot of boiler plate. they do? methinks you haven't done much web programming lately... From steven.klass at gmail.com Thu Jun 22 19:07:47 2006 From: steven.klass at gmail.com (rh0dium) Date: 22 Jun 2006 16:07:47 -0700 Subject: Python at compile - possible to add to PYTHONPATH In-Reply-To: <4499d697$0$11922$626a54ce@news.free.fr> References: <1150930496.559207.73320@m73g2000cwd.googlegroups.com> <4499d697$0$11922$626a54ce@news.free.fr> Message-ID: <1151017667.814612.120980@r2g2000cwb.googlegroups.com> Hi all, Thanks for the response. Yeah that's what I'm currently doing but I thought that it would be cleaner for me to append my own location at compile time. I'm surprised that this doesn't exist.. Thanks. Avell Diroll wrote: > rh0dium wrote: > (snip) > > I want to add /foo/bar to the PYTHONPATH build so I don't have to add > > it later on. Is there a way to do this? > (snip) > > If i understand correctly, you want to add a directory to your > PYTHONPATH for a specific script without modifying the system PYTHONPATH > global variable ... > > To import the Gazonk() class defined in /foo/bar/baz.py without adding > /foo/bar to PYTHONPATH you can try this: > > ### > > import sys > sys.path.append('/foo/bar') > > import baz > quux = baz.Gazonk() > > ### > > hope it helped ... From johnjsal at NOSPAMgmail.com Thu Jun 29 09:59:15 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 29 Jun 2006 13:59:15 GMT Subject: Python in a nutshell - new edition ? In-Reply-To: <1hhnvof.1apknoe1v7zz8aN%aleax@mac.com> References: <44A2C52A.6040807@skynet.be> <1hhnpen.1bkiv8l1d0r6puN%aleax@mac.com> <1151551938.499099.162520@75g2000cwc.googlegroups.com> <1hhnvof.1apknoe1v7zz8aN%aleax@mac.com> Message-ID: Alex Martelli wrote: > BartlebyScrivener wrote: > >>>> Yep, we're still aiming for OSCON '06 (Portland, end of July). >> Amazon says July 1st. > > Let me assure you that it _won't_ be on paper this coming Saturday (two > days from now). > > > Alex Doh! I had just noticed this yesterday on Amazon and was all set to head to the bookstore and get it this weekend! :) From fredrik at pythonware.com Wed Jun 7 02:24:23 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 07 Jun 2006 08:24:23 +0200 Subject: 10GB XML Blows out Memory, Suggestions? In-Reply-To: <1149648187.891942.258300@i40g2000cwc.googlegroups.com> References: <1149594519.098115.8980@u72g2000cwu.googlegroups.com> <4eleh3F1eguosU1@uni-berlin.de> <1149648187.891942.258300@i40g2000cwc.googlegroups.com> Message-ID: fuzzylollipop wrote: > you got no idea what you are talking about, anyone knows that something > like this is IO bound. which of course explains why some XML parsers for Python are a 100 times faster than other XML parsers for Python... From sjmachin at lexicon.net Thu Jun 1 19:35:37 2006 From: sjmachin at lexicon.net (John Machin) Date: Fri, 02 Jun 2006 09:35:37 +1000 Subject: grouping a flat list of number by range In-Reply-To: <1149201416.196975.123370@c74g2000cwc.googlegroups.com> References: <1149196642.001466.53990@c74g2000cwc.googlegroups.com> <1149201416.196975.123370@c74g2000cwc.googlegroups.com> Message-ID: <447F79C9.6080407@lexicon.net> On 2/06/2006 8:36 AM, Paddy wrote: > joh12005 at yahoo.fr wrote: >> hello, >> >> i'm looking for a way to have a list of number grouped by consecutive >> interval, after a search, for example : >> >> [3, 6, 7, 8, 12, 13, 15] >> >> => >> >> [[3, 4], [6,9], [12, 14], [15, 16]] >> >> (6, not following 3, so 3 => [3:4] ; 7, 8 following 6 so 6, 7, 8 => >> [6:9], and so on) >> >> i was able to to it without generators/yield but i think it could be >> better with them, may be do you an idea? >> >> best regards, >> >> J. > > I did a proceedural version, then re-read your post and did a generator > based version ;-) > > === interv1 === >>>> inlist = [3, 6, 7, 8, 12, 13, 15] >>>> tmp = [] >>>> for i,val in enumerate(inlist): > ... if i==0: > ... tmp.append(val) > ... elif val != valinc: > ... tmp += [valinc, val] > ... valinc = val+1 > ... >>>> tmp.append(valinc) >>>> tmp > [3, 4, 6, 9, 12, 14, 15, 16] >>>> tmp[0::2] > [3, 6, 12, 15] >>>> tmp[1::2] > [4, 9, 14, 16] >>>> zip(tmp[0::2], tmp[1::2]) > [(3, 4), (6, 9), (12, 14), (15, 16)] > > === END interv1 === > > === interv2 === >>>> def interv2(inlist): > ... for i,val in enumerate(inlist): > ... if i==0: > ... tmp = val > ... elif val != valinc: > ... yield [tmp, valinc] > ... tmp = val > ... valinc = val+1 > ... yield [tmp, valinc] > ... >>>> list(interv2(inlist)) > [[3, 4], [6, 9], [12, 14], [15, 16]] > > === END interv2 === > > - Paddy. > Oh the siren call of every new feature in the language! enumerate() just to get a first-time test, and then botch it?? Read the following; the replacement version uses a simple old-fashioned inelegant flag, works with an empty sequence, and doesn't depend on the input being sliceable or indexable. HTH, John C:\junk>type interval.py def interv2(inlist): for i,val in enumerate(inlist): if i==0: tmp = val elif val != valinc: yield [tmp, valinc] tmp = val valinc = val+1 yield [tmp, valinc] def interv3(inseq): first = True for val in inseq: if first: tmp = val first = False elif val != valinc: yield [tmp, valinc] tmp = val valinc = val + 1 if not first: yield [tmp, valinc] tests = [ [3, 4, 6, 9, 12, 14, 15, 16], [3, 3, 3], [], ] for func in (interv3, interv2): for test in tests: print "%s(%s) ->" % (func.__name__, test) result = list(func(test)) print "\t%r" % result C:\junk>interval.py interv3([3, 4, 6, 9, 12, 14, 15, 16]) -> [[3, 5], [6, 7], [9, 10], [12, 13], [14, 17]] interv3([3, 3, 3]) -> [[3, 4], [3, 4], [3, 4]] interv3([]) -> [] interv2([3, 4, 6, 9, 12, 14, 15, 16]) -> [[3, 5], [6, 7], [9, 10], [12, 13], [14, 17]] interv2([3, 3, 3]) -> [[3, 4], [3, 4], [3, 4]] interv2([]) -> Traceback (most recent call last): File "C:\junk\interval.py", line 33, in ? result = list(func(test)) File "C:\junk\interval.py", line 9, in interv2 yield [tmp, valinc] UnboundLocalError: local variable 'tmp' referenced before assignment C:\junk> From kentilton at gmail.com Fri Jun 9 17:27:35 2006 From: kentilton at gmail.com (Ken Tilton) Date: Fri, 09 Jun 2006 17:27:35 -0400 Subject: What is Expressiveness in a Computer Language In-Reply-To: <1149863687.298352.45980@h76g2000cwa.googlegroups.com> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> Message-ID: Joe Marshall wrote: > Xah Lee wrote: > >>in March, i posted a essay "What is Expressiveness in a Computer >>Language", archived at: >>http://xahlee.org/perl-python/what_is_expresiveness.html >> >>I was informed then that there is a academic paper written on this >>subject. >> >>On the Expressive Power of Programming Languages, by Matthias >>Felleisen, 1990. >>http://www.ccs.neu.edu/home/cobbe/pl-seminar-jr/notes/2003-sep-26/expressive-slides.pdf >> >>Has anyone read this paper? And, would anyone be interested in giving a >>summary? > > > The gist of the paper is this: Some computer languages seem to be > `more expressive' than > others. But anything that can be computed in one Turing complete > language can be computed in any other Turing complete language. > Clearly the notion of > expressiveness isn't concerned with ultimately computing the answer. > > Felleisen's paper puts forth a formal definition of expressiveness in > terms of semantic > equivilances of small, local constructs. In his definition, wholescale > program transformation is > disallowed so you cannot appeal to Turing completeness to claim program > equivalence. > > Expressiveness isn't necessarily a good thing. For instance, in C, you > can express the > addresses of variables by using pointers. You cannot express the same > thing in Java, and > most people consider this to be a good idea. > Thanks for the summary. Me, I would like to see a definition of expressiveness that would exclude a programming mechanism from "things to be expressed". If the subject is programmer productivity, well, I write programs to get some behavior out of them, such as operating an ATM cash dispenser. If I need to keep a list of transactions, I need to express the abstraction "list" in some data structure or other, but below that level of abstraction I am just hacking code, not expressing myself -- well, that is the distinction for which I am arguing. heck, in this case I will even give you as "thing to express" getting back multiple values from a function. That comes up all the time, and it can be an aggravation or a breeze. But then I would score C down because it does not really return multiple values. One still has some heavy lifting to do to fake the expressed thing. But I would still give it an edge over java because Java's fakery would have to be a composite object -- one could not have a primary return value as the function result and ancillary values "somewhere else". kt -- Cells: http://common-lisp.net/project/cells/ "I'll say I'm losing my grip, and it feels terrific." -- Smiling husband to scowling wife, New Yorker cartoon From sekhon.hari at googlemail.com Wed Jun 21 06:44:32 2006 From: sekhon.hari at googlemail.com (Hari Sekhon) Date: Wed, 21 Jun 2006 11:44:32 +0100 Subject: WinPops In-Reply-To: <447f5781$0$15793$14726298@news.sunsite.dk> References: <1149132789_5889@sp6iad.superfeed.net> <447f5781$0$15793$14726298@news.sunsite.dk> Message-ID: If you were going to do this you may as well just do something like if sys.platform='win32': os.system('net send ') elif sys.platform[:5]='linux' os.system('smblcient -M etc...') This would be more portable and simpler than the alternatives I've seen. It would be better if there was just a cross platform library for this protocol so you could just import winpop winpop.send (host,message) Too much to ask? Hari On 01/06/06, Peter Gsellmann wrote: > > Roger Upole wrote: > > > > > "Hari Sekhon" wrote in message > > news:mailman.6230.1148640634.27775.python-list at python.org... > >> Hi, > >> Is there a way of sending winpops (Windows Pop-Up / Net Send > messages) > >> in python? > >> > >> Perhaps some library or something that I can use under both Windows and > >> Linux? > >> > >> Hari > > > > On Windows, you can use win32net.NetMessageBufferSend. > > > > Roger > > > On Linux, i use the smbclient binary: > from subprocess import * > q=Popen(['smbclient','-M','maggy'],stdin=PIPE) > q.stdin.write('hello!') > q.stdin.close() > q.wait() > > Peter > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gdr at integrable-solutions.net Sun Jun 25 12:54:03 2006 From: gdr at integrable-solutions.net (Gabriel Dos Reis) Date: 25 Jun 2006 18:54:03 +0200 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150908952.804184.218990@r2g2000cwb.googlegroups.com> <1150991074.705803.211570@m73g2000cwd.googlegroups.com> <1151244628.566060.40500@p79g2000cwp.googlegroups.com> Message-ID: rossberg at ps.uni-sb.de writes: [...] | > and even C is typesafe unless you use unsafe constructs. | | Tautology. Every language is "safe unless you use unsafe constructs". | (Unfortunately, you can hardly write interesting programs in any safe | subset of C.) Fortunately, some people do, as living job. I must confess I'm sympathetic to Bob Harper's view expressed in http://www.seas.upenn.edu/~sweirich/types/archive/1999-2003/msg00298.html -- Gaby From vesa.karvonen at cs.helsinki.fi Fri Jun 23 05:47:59 2006 From: vesa.karvonen at cs.helsinki.fi (Vesa Karvonen) Date: 23 Jun 2006 09:47:59 GMT Subject: Saying "latently-typed language" is making a category mistake References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> Message-ID: In comp.lang.functional Anton van Straaten wrote: [...] > I reject this comparison. There's much more to it than that. The point > is that the reasoning which programmers perform when working with an > program in a latently-typed language bears many close similiarities to > the purpose and behavior of type systems. > This isn't an attempt to jump on any bandwagons, it's an attempt to > characterize what is actually happening in real programs and with real > programmers. I'm relating that activity to type systems because that is > what it most closely relates to. [...] I think that we're finally getting to the bottom of things. While reading your reponses something became very clear to me: latent-typing and latent- types are not a property of languages. Latent-typing, also known as informal reasoning, is something that all programmers do as a normal part of programming. To say that a language is latently-typed is to make a category mistake, because latent-typing is not a property of languages. A programmer, working in any language, whether typed or not, performs informal reasoning. I think that is fair to say that there is a correspondence between type theory and such informal reasoning. The correspondence is like the correspondence between informal and formal math. *But* , informal reasoning (latent-typing) is not a property of languages. An example of a form of informal reasoning that (practically) every programmer does daily is termination analysis. There are type systems that guarantee termination, but I think that is fair to say that it is not yet understood how to make a practical general purpose language, whose type system would guarantee termination (or at least I'm not aware of such a language). It should also be clear that termination analysis need not be done informally. Given a program, it may be possible to formally prove that it terminates. I'm now more convinced than ever that "(latently|dynamically)-typed language" is an oxymoron. The terminology really needs to be fixed. -Vesa Karvonen From maric at aristote.info Wed Jun 14 07:14:14 2006 From: maric at aristote.info (Maric Michaud) Date: Wed, 14 Jun 2006 13:14:14 +0200 Subject: Correctly reading stdout/stderr from subprocess In-Reply-To: <20060613222002.GB5153@workaround.org> References: <20060613222002.GB5153@workaround.org> Message-ID: <200606141314.14587.maric@aristote.info> Le Mercredi 14 Juin 2006 00:20, Christoph Haas a ?crit?: > Evening, > > I'm having trouble with running a process through Python 2.4's > subprocess module. Example code: > > ======================================================== > def run(command): > run = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, > stderr=subprocess.PIPE) > > # Wait for the process to return > returncode = run.wait() > stdout = run.stdout.readlines() > stderr = run.stderr.readlines() > > # Strip newlines at the end of each line > stdout = [line.rstrip('\n') for line in stdout] > stderr = [line.rstrip('\n') for line in stderr] > > return returncode,stdout,stderr > ======================================================== > > Unfortunately this def fails when it runs programs that do a lot of > output. I believe this problem has also been described in Bug #1162428. > It says: "You must read away the data before wait() on the process." > Easier said than done. If I put the readlines() call before the > run.wait() then the process hangs, too, waiting for further lines. > This because you can't predict which of the two output will block, either merge the outpus with a popen4 or use communicate like below or use a threaded version (much more complicated). > Then I read about the communicate() call which handles both > stdout/stderr reading and also waiting for the process to end. > Unfortunately it returned the output char-wise instead of line-wise. I > could certainly re-join the lines. But somehow I feel I'm missing > something simple. > > Any ideas? > def run2(command): import subprocess run = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # Wait for the process to return out, err = [ e.splitlines() for e in run.communicate() ] return run.returncode, out, err -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From jkn_gg at nicorp.f9.co.uk Wed Jun 14 08:48:33 2006 From: jkn_gg at nicorp.f9.co.uk (jkn) Date: 14 Jun 2006 05:48:33 -0700 Subject: Tiddlywiki type project in Python? Message-ID: <1150289313.533749.52330@i40g2000cwc.googlegroups.com> Hi all I'm trying out, and in general finding really useful, the various TiddlyWiki variants that I guess many people here know about, for organising my activities in a GTD way. One mild annoyance is in the speed of the Javascript applications. I fancy having a go at writing something like this for myself, where update speed would be a higher priority. I don't know Javascript (although it looks moderately simple from a brief peruse, and I know enough languages to know I'll be able to pick it up); however I do know and use Python, although not nuch in a web-oriented way. Since unlike JS, python is at least pre-compiled, I have hopes that this would make things quicker. I do appreciate that JS is built into the browser, which might make my Python approach slower. I'm not sure of the 'architectural' approach to this; any suggestions, and maybe pointers to previous work? Thanks in advance Jon N From onurb at xiludom.gro Tue Jun 27 05:05:28 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Tue, 27 Jun 2006 11:05:28 +0200 Subject: Replace Whole Object Through Object Method In-Reply-To: References: <1151337453.804750.293180@b68g2000cwa.googlegroups.com> <44a041a6$0$17612$636a55ce@news.free.fr> <1151354259.082966.25820@p79g2000cwp.googlegroups.com> <1151376052.727979.71470@c74g2000cwc.googlegroups.com> Message-ID: <44a0f4d9$0$9022$626a54ce@news.free.fr> I V wrote: > On Mon, 26 Jun 2006 19:40:52 -0700, digitalorganics wrote: > >>A misuse of inheritance eh? Inheritance, like other language features, >>is merely a tool. I happen to be using this tool to have my virtual >>persons change roles at different points in their lifetime, as many >>real people tend to do. Thus, at these points, B is indeed an A. What a >>person is, whether in real life or in my program, is not static and >>comes into definition uniquely for each moment (micro-moment, etc.) of >>existence. Now, please, I have no intention of carrying the >>conversation in such a silly direction, I wasn't inviting a discussion >>on philosophy or some such. I seek to work the tools to my needs, not >>the other way around. > > > But thinking about the problem in the vocabulary provided by the > programming language can be helpful in coming up with a solution. If > inheritance tells you what an object _is_, It's not so clear in Python, cf my answer to Maric on this point. > and membership tells you what a > role _has_, and a role is something that a person has, As a matter of fact, in Python, the class is an attribute of an object. So it is really something that an object "have". And this relationship is not carved in stone - it's perfectly legal to modify it at runtime. > that suggests > that an implementation where roles are members of a person might be > simpler than trying to use inheritance. Like, for instance: > > class Role(object): > def __init__(self, person): > self.person = person > (snip) > > class Person(object): > > def __init__(self, name): > self.roles = [] > self.name = name > > > def add_role(self, role_class): > self.roles.append(role_class(self)) > And here you create a circular reference between object and roles... > def forward_to_role(self, attr): > for role in self.roles: > try: > return getattr(role, attr) > except AttributeError: > pass > raise AttributeError(attr) This could as well be directly in __getattr__, and would avoid a useless method call. > > def __getattr__(self, attr): > self.forward_to_role(attr) > -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From diffuser78 at gmail.com Wed Jun 21 10:13:13 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 21 Jun 2006 07:13:13 -0700 Subject: OS specific command in Python References: <1150781429.090359.148560@c74g2000cwc.googlegroups.com> <44979b35$0$8390$626a54ce@news.free.fr> <1150823140.295590.307390@i40g2000cwc.googlegroups.com> <4498d973$0$25496$626a54ce@news.free.fr> Message-ID: <1150899193.321218.235760@i40g2000cwc.googlegroups.com> Hi Avell, I want to communicate using subprocess module but my task is a little different. May be you can guide me. I have a linux box, from where I remotely execute all the commands. The remote machine is windows machine. I installed an OpenSSH server for windows to send the shutdown command. I setup the public keys in such a way that I could login to SSH server without using password. I used import os os.system('ssh Admin at IP_ADDRESS shutdown -s') I was wondering how can I interact with an application . Since you mentioned about subprocess module, I want a ability that my PYthon script can actually interact with the windows box and launch and close application there remotely. Any suggestions on how to do this ? Every help is appreciated. Thanks for your time Avell Diroll wrote: > This is an simple way to proceed if you don't need your python script to > know what happens to the launched process ... > When you need to : > * send some input to the command from the python script after it is launched > * get the output of the command in your python script > * get the pid associated to your command > * wait for your command to finish > * pipe some shell commands > * ... > you should use the subprocess module. > > Here is a quick example from the Python Reference Library : > http://docs.python.org/lib/node242.html > > ##Shell Script : > output=`dmesg | grep hda` > > > ##Python Script : > from subprocess import Popen > p1 = Popen(["dmesg"], stdout=PIPE) > p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) > output = p2.communicate()[0] From jjeffreyclose at yahoo.com Mon Jun 26 19:26:58 2006 From: jjeffreyclose at yahoo.com (J. Jeffrey Close) Date: Mon, 26 Jun 2006 16:26:58 -0700 (PDT) Subject: Arrghh... Problems building Python from source on OS X -- In-Reply-To: Message-ID: <20060626232658.18207.qmail@web52301.mail.yahoo.com> Hi all, I have been trying for some time to build Python 2.4.x from source on OS X 10.4.6. I've found *numerous* postings on various mailing lists and web pages documenting the apparently well-known problems of doing so. Various problems arise either in the ./configure step, with configure arguments that don't work, or in the compile, or in my case in the link step with libtool. The configure options I'm using are the following: --enable-framework --with-pydebug --with-debug=yes --prefix=/usr --with-dyld --program-suffix=.exe --enable-universalsdk I've managed to get past configure and can compile everything, but in the link I get the error "Undefined symbols: ___eprintf" . This appears to have something to do with dynamic library loading not properly pulling in libgcc. I've tried with -lgcc in the LD options, but that produces a configure error "cannot compute sizeof...". If I remove "--enable-framework" the complete build works, but unfortunately that is the one critical element that I need. The web pages I've found referring to this range from 2001 to present -- still apparently everybody is having problems with this. Does *anybody* here have Python built from source on this OS? Jeffrey From colincolehour at gmail.com Mon Jun 19 14:24:40 2006 From: colincolehour at gmail.com (colincolehour at gmail.com) Date: 19 Jun 2006 11:24:40 -0700 Subject: Need Help comparing dates In-Reply-To: References: <1150419503.224684.320550@c74g2000cwc.googlegroups.com> Message-ID: <1150741480.160371.234000@g10g2000cwb.googlegroups.com> I kept getting a Python error for the following line: month = m[webMonth] I changed it to month = month_numbers[webMonth] and that did the trick. Tim Chase wrote: > > I am new to Python and am working on my first program. I am trying to > > compare a date I found on a website to todays date. The problem I have > > is the website only shows 3 letter month name and the date. > > Example: Jun 15 > > No year, right? Are you making the assumption that the year is > the current year? > > > How would I go about comparing that to a different date? > > Once you've got them as dates, > > >>> from datetime import date > > you can just compare them as you would any other comparable items. > > If you need to map the month-strings back into actual dates, you > can use this dictionary: > > >>> month_numbers = dict([(date(2006, m, 1).strftime("%b"), m) > for m in range(1,13)]) > > It happens to be locale specific, so you might have to tinker a > bit if you're mapping comes out differently from what the website > uses. I also made the assumption the case was the same (rather > than trying to normalize to upper/lower case) > > Then, you can use > > >>> webpageDateString = "Mar 21" > >>> webMonth, webDay = webpageDateString.split() > >>> month = m[webMonth] > >>> day = int(webDay) > >>> webpageDate = date(date.today().year, month, day) > >>> compareDate = date.today() > >>> compareDate < webpageDate > False > >>> compareDate > webpageDate > True > > You can wrap the load in a function, something like > > >>> def isNewer(dateString, year = date.today().year): > ... monthString, dayString = dateString.split() > ... month = month_numbers[monthString] > ... day = int(dayString) > ... return date.today() < date(year, month, day) > > which will allow you to do > > >>> isNewer("Jul 1") > True > >>> isNewer("Apr 1") > False > > and the like. > > There's plenty of good stuff in the datetime module. > > -tkc From rpdooling at gmail.com Thu Jun 1 12:42:42 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 1 Jun 2006 09:42:42 -0700 Subject: os.walk trouble References: <1149173920.903876.68370@c74g2000cwc.googlegroups.com> Message-ID: <1149180162.128874.153330@i39g2000cwa.googlegroups.com> Neat. And looks better, at least on my machine, if you had a tab or two and an extra \n after the dirs. rick for filepath, dirs, files in os.walk(root): #you're looking at the "dirs" and "files" in filepath print "Currently in %s" % filepath print "\t[Directories in %s]" % filepath print '\t' + "\n\t".join(dirs) + '\n' print "\t[Files in %s]" % filepath print '\t' + "\n\t".join(files) print "=" * 50 From marshall.spight at gmail.com Wed Jun 28 14:16:03 2006 From: marshall.spight at gmail.com (Marshall) Date: 28 Jun 2006 11:16:03 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1151384511.223582.305760@m73g2000cwd.googlegroups.com> <4gdkmiF1ldalhU3@individual.net> <4gfcclF1mpbg7U1@individual.net> <6gwog.488405$xt.80841@fe3.news.blueyonder.co.uk> <4gfiufF1mg6h9U1@individual.net> Message-ID: <1151518563.638141.313110@b68g2000cwa.googlegroups.com> Matthias Blume wrote: > > How does this "create" such a problem? The problem is there in either > approach. In fact, I believe that the best chance we have of > addressing the problem is by adopting the "replace the code" model > along with a "translate the data where necessary at the time of > replacement". Translating the data, i.e., re-establishing the > invariants expected by the updated/replaced code, seems much harder > (to me) in the case of self-modifying code. Erlang got this one > right. Pardon my ignorance, but what is the Erlang solution to this problem? Marshall From maric at aristote.info Wed Jun 21 11:31:41 2006 From: maric at aristote.info (Maric Michaud) Date: Wed, 21 Jun 2006 17:31:41 +0200 Subject: returning index of minimum in a list of lists In-Reply-To: <1150901648.832039.165590@b68g2000cwa.googlegroups.com> References: <1150901648.832039.165590@b68g2000cwa.googlegroups.com> Message-ID: <200606211731.41813.maric@aristote.info> Le Mercredi 21 Juin 2006 16:54, JJLaRocque at gmail.com a ?crit?: > Hi all, > Is there a simple python function to return the list index of the > minimum entry in a list of lists? > ie, for [[3,3,3,3], [3,3,3,1], [3,3,3,3]] to return 2,4. > Or, same question but just for a list of numbers, not a list of lists. > Thanks, > Josh In [7]: min([3, 3, 1, 3]) Out[7]: 1 In [8]: min(min(e) for e in [ [3, 3], [3, 3, 1, 3], [3, 3, 3] ]) Out[8]: 1 regards, -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From rschroev_nospam_ml at fastmail.fm Thu Jun 15 15:47:50 2006 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Thu, 15 Jun 2006 19:47:50 GMT Subject: a good programming text editor (not IDE) In-Reply-To: References: <_xgkg.2317$No6.48542@news.tufts.edu> Message-ID: John Salerno schreef: > Sybren Stuvel wrote: > >> Vim is definitely the best. If you're a GUI man, you can use GVim. > > Ok, you guys are slowly converting me, but I do have one question: which > "version" of VIM should I use, or does it matter? I mean, there seem to > be at least two versions, a text version and the GUI version you > mention. Are the options shared between the two, or is it that you are > more or less "set" in one once you choose it, and if you move to the > other you have to redefine your preferences, etc.? Some settings are GUI-specific, such as font and window size, but the rest is the same. You can easily copy your preferences file between different systems and use it with both vim and gvim (text mode vim will just ignore the GUI settings). -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From torbenm at app-1.diku.dk Fri Jun 16 05:04:33 2006 From: torbenm at app-1.diku.dk (=?iso-8859-1?q?Torben_=C6gidius_Mogensen?=) Date: 16 Jun 2006 11:04:33 +0200 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <2006061410510511272-raffaelcavallaro@pasdespamsilvousplaitmaccom> <878xnzv5i3.fsf@thalassa.informatimago.com> <2006061501582450878-raffaelcavallaro@pasdespamsilvousplaitmaccom> Message-ID: <7zy7vxqxni.fsf@app-1.diku.dk> Raffael Cavallaro writes: > On 2006-06-14 16:36:52 -0400, Pascal Bourguignon said: > > > In lisp, all lists are homogenous: lists of T. > > CL-USER 123 > (loop for elt in (list #\c 1 2.0d0 (/ 2 3)) collect > (type-of elt)) > (CHARACTER FIXNUM DOUBLE-FLOAT RATIO) > > i.e., "heterogenous" in the common lisp sense: having different > dynamic types, not in the H-M sense in which all lisp values are of > the single union type T. What's the difference? Dynamically types values _are_ all members of a single tagged union type. The main difference is that the tages aren't always visible and that there are only a fixed, predefined number of them. Torben From riteshsarraf at gmail.com Fri Jun 30 04:45:19 2006 From: riteshsarraf at gmail.com (Ritesh Raj Sarraf) Date: 30 Jun 2006 01:45:19 -0700 Subject: optparse multiple arguments Message-ID: <1151657119.837675.213700@p79g2000cwp.googlegroups.com> Hi, I'm having some minor problems with optparse. I'm just worried that someone shouldn't say that multiple argument feature isn't implemented in optpartse. How to tackle multiple arguments to an option ? As far as I dug, I've found that >1 arguments are being ignored. parser.add_option("", "--my-option", dest="my_option", action="store", type="string") Now if someone uses it as: ./foo --my-option a b c I want somehow to store all the three arguments but my_option stores only "a" while ignoring b and c. Any help? Ritesh From d4rkritu4l at gmail.com Sun Jun 18 16:28:09 2006 From: d4rkritu4l at gmail.com (ph0b0s) Date: Sun, 18 Jun 2006 22:28:09 +0200 Subject: Getting output from external programs... Message-ID: <4495B759.4040002@gmail.com> An HTML attachment was scrubbed... URL: From nicolasg at gmail.com Thu Jun 1 15:56:23 2006 From: nicolasg at gmail.com (nicolasg at gmail.com) Date: 1 Jun 2006 12:56:23 -0700 Subject: integer to binary... In-Reply-To: <1149190940.548582.27200@h76g2000cwa.googlegroups.com> References: <1149189570.376091.319890@j55g2000cwa.googlegroups.com> <127ugf9jgu7av18@corp.supernews.com> <1149190940.548582.27200@h76g2000cwa.googlegroups.com> Message-ID: <1149191782.973045.215080@g10g2000cwb.googlegroups.com> nicolasg at gmail.com wrote: > Grant Edwards wrote: > > On 2006-06-01, nicolasg at gmail.com wrote: > > > > > does anyone know a module or something to convert numbers like integer > > > to binary format ? > > > > They _are_ in binary format. > > > > > for example I want to convert number 7 to 0111 so I can make some > > > bitwise operations... > > > > Just do it: > > > > >>> 7 & 3 > > 3 > > >>> 7 | 8 > > 15 > > > > this is exactly what I need -> http://www.daniweb.com/code/snippet285.html thanks. > > -- > I know I can do that but I need to operate in every bit separeted. > > Grant Edwards grante Yow! QUIET!! I'm being > > at CREATIVE!! Is it GREAT > > visi.com yet? It's s'posed to SMOKEY > > THE BEAR... From deets at nospam.web.de Tue Jun 6 08:05:11 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 06 Jun 2006 14:05:11 +0200 Subject: 10GB XML Blows out Memory, Suggestions? In-Reply-To: <1149594519.098115.8980@u72g2000cwu.googlegroups.com> References: <1149594519.098115.8980@u72g2000cwu.googlegroups.com> Message-ID: <4el9blF1fb6mdU1@uni-berlin.de> axwack at gmail.com schrieb: > I wrote a program that takes an XML file into memory using Minidom. I > found out that the XML document is 10gb. > > I clearly need SAX or something else? > > Any suggestions on what that something else is? Is it hard to convert > the code from DOM to SAX? Yes. You could used elementtree iterparse - that should be the easiest solution. http://effbot.org/zone/element-iterparse.htm Diez From aljosa.mohorovic at gmail.com Thu Jun 1 12:53:34 2006 From: aljosa.mohorovic at gmail.com (aljosa) Date: 1 Jun 2006 09:53:34 -0700 Subject: image lib & Qt4 In-Reply-To: <4e8haiF1dp2heU1@uni-berlin.de> References: <1149173540.470829.34940@c74g2000cwc.googlegroups.com> <4e8haiF1dp2heU1@uni-berlin.de> Message-ID: <1149180814.585713.209640@i39g2000cwa.googlegroups.com> does anybody know how to load (in-memory representation of PNG image) from Qt (v.4.1.3) as QImage? Diez B. Roggisch wrote: > aljosa wrote: > > > i'm looking for image lib which supports common image types (maybe > > freeimagepy?) and is relatively easy to display image loaded through > > that lib in PyQt4. > > any ideas? > > Use PIL & StringIO to create a in-memory representation of the image as e.g. > PNG. Load that using Qt. > > Diez From sjmachin at lexicon.net Sat Jun 10 07:37:55 2006 From: sjmachin at lexicon.net (John Machin) Date: Sat, 10 Jun 2006 21:37:55 +1000 Subject: Most elegant way to generate 3-char sequence In-Reply-To: <1149930084.768576.315300@f6g2000cwb.googlegroups.com> References: <1149889784.391965.271570@h76g2000cwa.googlegroups.com> <4489F72C.7010101@lexicon.net> <1149930084.768576.315300@f6g2000cwb.googlegroups.com> Message-ID: <448AAF13.4010306@lexicon.net> On 10/06/2006 7:01 PM, Rob Cowie wrote: > John Machin wrote: >> On 10/06/2006 7:49 AM, Rob Cowie wrote: >>> Hi all, >>> >>> I wish to generate a sequence of the form 'aaa', 'aab', aac'.... 'aba', >>> 'abb', 'abc' etc. all the way to 'zzz'. >>> >>> How would you construct a generator to acheive this? >>> >>> A simple, working but somewhat inelegant solution is... >> You're not wrong. >> >>> alpha = ['a','b','c','d'] #shortened for brevity >> Hope you remember the alphabet correctly. > Not sure I understand your point. Why would I forget the alphabet? ... or mistype it? If you use string.ascii_lowercase, your readers know what is intended without checking that it is in fact that. > >> Why type all that punctuation? > What punctuation? Refer to the effbot's post. > >> Any reason this cruft is global (i.e. not local to the generator)? > No The point being that gizmoids should not be given a wider visibility than is required. A handy side effect is that it is more efficient to reference a local than a global (global names have to be looked up in a dictionary). > >>> alpha2 = ['a','b','c','d'] >>> alpha3 = ['a','b','c','d'] >> Hope you get the redundant copy/paste right. > Again, I don't understand what you mean You need only one alpha, not 3. Otherwise your readers have to compare alpha to alpha2 and alpha2 to alpha3 to ascertain that you haven't typoed. > >>> def generator(): >>> for char in alpha: >> Why stop at two spaces? One-space indentation is syntactically correct :-) > As are 3, 4 and 5 space indentation. Yet again, what is your point? 4-space indentation is more or less standard. 2-space indentation is definitely not an aid to swift comprehension of Python code. > >>> for char2 in alpha2: >>> for char3 in alpha3: >>> yield char + char2 + char3 >>> >>> x = generate() >> Did you meant "generator"? > Yes, made a mistake >>> x.next() # etc, etc, etc, >>> >> |>> def generator(): >> ... import string >> ... alpha = string.ascii_lowercase >> ... for char in alpha: >> ... for char2 in alpha: >> ... for char3 in alpha: >> ... yield char + char2 + char3 >> ... >> |>> x = generator() >> |>> the_lot = list(x) >> |>> len(the_lot) == 26 ** 3 >> True >> |>> [the_lot[i] for i in (0, 1, 25, 26, -27, -26, -1)] >> ['aaa', 'aab', 'aaz', 'aba', 'zyz', 'zza', 'zzz'] >> >> Cheers, >> John > > I'm aware the code I posted is not great - it isn't code I would > consider using. If you wouldn't consider using it, don't drag it out in public. Some n00b might think it the epitome of good style :-) > It was only intended to serve as an illustration of the > task at hand in case my explanation wasn't sufficient. > > I'm grateful to you for using list(generator) in your example. I was > not aware this could be done (I haven't yet fully read the generator > documentation). A generator is an iterable. list(), sum(), max(), min(), enumerate(), zip() etc work on iterables. It's that simple, and that powerful. You might be interested in the itertools standard module as well. Cheers, John From webb.sprague at gmail.com Fri Jun 16 13:55:16 2006 From: webb.sprague at gmail.com (Webb) Date: 16 Jun 2006 10:55:16 -0700 Subject: Opening an editor for interactive use Message-ID: <1150480516.803469.275820@y41g2000cwy.googlegroups.com> Hi all, (I am sure there is a recipe somewhere, but I can't find it.) How does one open an editor while in the middle of an interactive program, let the user do some editing and closing, and then capture the text that was edited? I am reminded of subversion or CVS when they open an $EDITOR session for the check-in log entry. I tried os.popen, but it fired off vim in the background--not useful. Then I tried os.system, but that only returns the return code (126 in my case) after you close the editor. Perhaps I need to write to a file and read it--shouldn't there be a cleaner way? Thanks W From rogue_pedro at yahoo.com Sat Jun 24 11:30:02 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 24 Jun 2006 08:30:02 -0700 Subject: tkinter modifying multiple widgets with one scrollbar References: <1151125610.608131.35510@r2g2000cwb.googlegroups.com> Message-ID: <1151163002.447737.306410@r2g2000cwb.googlegroups.com> spohle wrote: > hi > > how can i modify multiple widgets with one scrollbar ? > > thanks in advance > > sven If you're using Tkinter check out: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52266 Peace, ~Simon From sekhon.hari at googlemail.com Tue Jun 27 10:31:21 2006 From: sekhon.hari at googlemail.com (Hari Sekhon) Date: Tue, 27 Jun 2006 15:31:21 +0100 Subject: Unbound Local error? How? Message-ID: <44A14139.7060906@gmail.com> I've got some code as follows: import re re_regexname = re.compile('abc') ..... ..... various function defs ..... def func1(): ... func2() ... def func2(): if re_regexname.match('abc'): if __name__ == '__main__': func1() but this returns the Traceback: UnboundLocalError: local variable 're_regexname' referenced before assignment How? It was declared in the zero level indentation near the top of the script! I don't understand this, isn't a function supposed to be able to reference stuff in the containing function or the top level? From michael at araneidae.co.uk.invalid Wed Jun 28 17:52:15 2006 From: michael at araneidae.co.uk.invalid (Michael Abbott) Date: Wed, 28 Jun 2006 22:52:15 +0100 Subject: Module executed twice when imported! Message-ID: It seems to be an invariant of Python (insofar as Python has invariants) that a module is executed at most once in a Python session. I have a rather bizzare example that breaks this invariant: can anyone enlighten me as to what is going on? --- test.py --- import imptest execfile('subtest.py', dict(__name__ = 'subtest.py')) --- imptest.py --- print 'Imptest imported' --- subtest.py --- import imptest --- $ python test.py Imptest imported Imptest imported $ Hmm. If the value __name__ is omitted from the dictionary, or if its value doesn't match at least 'subtest.' then the message is printed only once (for example, passing dict(__name__='subtest') produces one "imported" message). This happens with both python 2.4 and 2.3. I don't get it. From deets at nospam.web.de Wed Jun 28 12:59:31 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 28 Jun 2006 18:59:31 +0200 Subject: Problem with sets and Unicode strings References: <44a17d05$1@news.uni-ulm.de> <44a19d55$2@news.uni-ulm.de> <44a2b101$1@news.uni-ulm.de> Message-ID: <4gfqs9F1mijo5U1@uni-berlin.de> > But says: > > Strings are compared lexicographically using the numeric equivalents > (the result of the built-in function ord()) of their characters. Unicode > and 8-bit strings are fully interoperable in this behavior. > > Doesn't this mean that Unicode and 8-bit strings can be compared and > this comparison is well defined? (even if it's is not meaningful) Obviously not - otherwise you wouldn't have the problems you'd observed, wouldn't you? What happens of course is that in case of string to unicode-comparison, the string gets coerced to an unicode value - using the default encoding! # -*- coding: latin1 -*- print "?".decode("latin1") == u"?" print "?" == u"?" So - they are fully interoperable and the comparison is well defined - when the coercion is successful. Diez From faulkner612 at comcast.net Sat Jun 24 09:04:00 2006 From: faulkner612 at comcast.net (faulkner) Date: 24 Jun 2006 06:04:00 -0700 Subject: search engine In-Reply-To: References: Message-ID: <1151154240.258799.324680@p79g2000cwp.googlegroups.com> http://www.voidspace.org.uk/cgi-bin/pysearch/search.py http://www.voidspace.org.uk/ http://www.vex.net/parnassus/ http://cheeseshop.python.org/pypi http://aspn.activestate.com/ASPN/Cookbook/Python http://www.google.com vinodh kumar wrote: > hai all, > i am student of computer science dept. i have planned to > design a search engine in python. i am seeking info about how to > proceed further. > i need to know what r the modules that can be used. > > > - From exarkun at divmod.com Thu Jun 29 15:50:06 2006 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 29 Jun 2006 15:50:06 -0400 Subject: Problem with sets and Unicode strings In-Reply-To: <44a427c0$1@news.uni-ulm.de> Message-ID: <20060629195006.29014.2072022218.divmod.quotient.15417@ohm> On Thu, 29 Jun 2006 21:19:30 +0200, Dennis Benzinger wrote: >Robert Kern wrote: >> Dennis Benzinger wrote: >>> Ok, I understand. >>> But isn't it a (minor) problem that using a set like this: >>> >>> # -*- coding: UTF-8 -*- >>> >>> FIELDS_SET = set(("F?cher", )) >>> >>> print u"F?cher" in FIELDS_SET >>> print u"F?cher" == "F?cher" >>> >>> shadows the error of not setting sys.defaultencoding()? >> >> You can't set the default encoding. If you could, then scripts that run >> on your machine wouldn't run on mine. >> [...] > >As Serge Orlov wrote in one of his posts you _can_ set the default >encoding (at least in site.py). See > But doing so is not useful so one should generally never do it. You cannot set the default encoding on any computers you don't directly control, so any software you write which depends on this will not be easily distributable. Additionally, if you decide to use two packages which use this feature and go to the trouble of modifying your own site.py for them, you won't be able to, since there can only be one default system encoding. Only one will be able to work at a time. The default encoding is ascii and should always be ascii. If you want another encoding, specify it in a call to .encode() or .decode(). Jean-Paul From steven.bethard at gmail.com Sun Jun 18 23:09:49 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 18 Jun 2006 21:09:49 -0600 Subject: mapping None values to '' In-Reply-To: <4495dfba@nntp0.pdx.net> References: <1150632320.443681.42640@r2g2000cwb.googlegroups.com> <0Rblg.5940$zy5.141663@twister1.libero.it> <4495dfba@nntp0.pdx.net> Message-ID: Scott David Daniels wrote: > Roberto Bonvallet wrote: >> imho : >>> map(lambda x:"" , [i for i in [a,b,c] if i in ("None",None) ]) >> You don't need map when using list comprehensions: >> ["" for i in [a, b, c] if i in ("None", None)] >> > More like: > > [(i, "")[i in ("None", None)] for i in [a,b,c]] Or in Python 2.5: Python 2.5a2 (trunk:46491M, May 27 2006, 14:43:55) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> a = 0 >>> b = None >>> c = None >>> a, b, c = ('' if x in (None, 'None') else x for x in (a, b, c)) >>> a, b, c (0, '', '') But someone please shoot me if I ever use something like that in production code. ;) STeVe From grflanagan at yahoo.co.uk Thu Jun 1 03:32:44 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 1 Jun 2006 00:32:44 -0700 Subject: shuffling elements of a list References: <1149045499.212967.13120@f6g2000cwb.googlegroups.com> Message-ID: <1149147164.012044.66960@u72g2000cwu.googlegroups.com> Ben Finney wrote: [snip] > > Please don't write C in Python. The 'for' statement allows iteration > directly over a sequence, no need to maintain an index. Also, the > modulus operator is called for with your cycling of the pile index. > > pile_index = 0 > for card in deck: > piles[pile_index].append(card) > pile_index = (pile_index + 1) % numpiles > no need to maintain an index ;-) piles = [ list() for _ in range(n) ] for i, card in enumerate(deck): piles[i % numpiles].append(card) Gerard From akameswaran at gmail.com Thu Jun 1 17:33:41 2006 From: akameswaran at gmail.com (akameswaran at gmail.com) Date: 1 Jun 2006 14:33:41 -0700 Subject: Replace one element of a tuple In-Reply-To: <127ulhn6h7hvj22@corp.supernews.com> References: <127ulhn6h7hvj22@corp.supernews.com> Message-ID: <1149197621.047337.135070@c74g2000cwc.googlegroups.com> Captain Dondo wrote: > I have an array(?) (sorry, I'm new* to python so I'm probably mangling > the terminology) that looks like this: > > [((1028L, datetime.datetime(2006, 5, 30, 7, 0), datetime.datetime(2006, > 5, 30, 7, 30), 'Arthur', 'Prunella Sees the Light; Return of the > Snowball', 'Prunella prepares for a sleepover with Marina; D.W. protects > a snowball.', 'Children', 'tooth.seiner.lan', None, 0L, None, 1L, 1L, > 'Default', 9L, 'SH044107', 'EP0441070123', datetime.datetime(2006, 5, > 30, 7, 31, 24), 1164179392L, 0.0, 1, datetime.date(2002, 11, 28), 0, 0L, > 0),), ((1028L, datetime.datetime(2006, 5, 4, 10, 0), > datetime.datetime(2006, 5, 4, 10, 30), 'Bob the Builder', 'Using Clues', > '', 'Children', 'tooth.seiner.lan', None, 0L, None, 1L, 1L, 'Default', > 6L, 'SH326087', 'EP3260870141', datetime.datetime(2006, 5, 4, 10, 31, > 30), 1163673536L, 0.0, 1, datetime.date(2005, 3, 19), 0, 0L, 0),)] > > I want to replace every instance of 'tooth.seiner.lan' with 'localhost'. > There may be lots and lots of these entries (they're pulled from my > mythtv database). > > I could brute-force this by rewriting the whole thing and replacing > every 9th element but there has to be a better way.... > > I've looked at various search-and-replace snippets but none that address > what I am trying to do.... > > --Yan > > *I'm not really new to python, just very very rusty. Last time I used > it was about 3 years ago, and I was equally clueless.... There's a lot of parenthesis :) not easy to read, but unless I'm seeing something odd, you have string literals in a tuple. So I don't think your going to find a better way than brute force recreation. FYI lists are between [] and are mutable Tuples are between () and are immutable. If I'm countin paren's right you have a list that contains a tuple, that contains another tuple with 1 element in it. so you can recreate the tuples... or convert the whole thing to a list of lists. From dan at catfolks.net Fri Jun 9 19:48:25 2006 From: dan at catfolks.net (Dan M) Date: Fri, 09 Jun 2006 16:48:25 -0700 Subject: os.link makes a copy, not a link Message-ID: I'm a little bit confused. According to the sources I've looked at on the net, os.link('file1', 'file2') should make a hard link from file1 to file2. But what I'm finding is that it's actually making a copy. Am I forgetting a step or something? Python 2.3.4 running on CentOS 4.3 From deets at nospam.web.de Thu Jun 22 11:27:07 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 22 Jun 2006 17:27:07 +0200 Subject: serial port servo control In-Reply-To: <1150989488.345731.49680@m73g2000cwd.googlegroups.com> References: <1150989488.345731.49680@m73g2000cwd.googlegroups.com> Message-ID: <4fvr67F1l1fgvU1@uni-berlin.de> boyle5 at llnl.gov schrieb: > So I ordered a mini SSC II (the servo controller), in order to > control some servos from the computer. I was hoping to use python to > do the control but have two questions... > > 1) How should I write to the serial port with python? I found the > module "pyserial": > http://pyserial.sourceforge.net/ > on the python cheeseshop, and it looks solid but I thought you might > have a better suggestion. pyserial is what you need. > 2) To control the servos I have to send the SSC II a string of 3 > numbers, 3 bytes long (so 3 numbers in the range 0 - 255, each as a > single byte, one after another). In C I'd do this by sending 3 > char's, as they're only 1 byte, but i'm not exactly sure how to do it > in Python. Strings in python are byte-strings. So you can use them. Additionally, I recommend looking into the module struct. Diez From robin at reportlab.com Mon Jun 12 05:23:11 2006 From: robin at reportlab.com (Robin Becker) Date: Mon, 12 Jun 2006 10:23:11 +0100 Subject: py2exe & tkinter Message-ID: <448D327F.7020209@chamonix.reportlab.co.uk> Don't know if this is the right place to ask, but has anyone considered using something like tcl's freewrap code to integrate tkinter into py2xe single executables? We currently use the (fairly clunky) nsis route to create single file executables with py2exe as input, but with the new bundle_files option it should be possible to integrate our tcl/tk stuff into a common library.zip as that seems to be the method used by freewrap. -- Robin Becker From gene.tani at gmail.com Tue Jun 20 09:39:16 2006 From: gene.tani at gmail.com (gene tani) Date: 20 Jun 2006 06:39:16 -0700 Subject: crawlers in python with graphing? In-Reply-To: References: Message-ID: <1150810756.266140.245000@b68g2000cwa.googlegroups.com> bryan rasmussen wrote: > Hi, > > Sorry, was imprecise, I meant not save the downloaded page locally. > There probably isn't one though, so I should build one myself. > Probably just need a good crawler that can be set to dump all links > into dataset that I can analyse with R. > > Cheers, > Bryan Rasmussen > There's quite a few already: webchecker, Orchid, mechanize, mygale: http://codesnipers.com/?q=node/223&&title=Detecting-Dead-Links http://pxr.openlook.org/pxr/source/Tools/webchecker/ http://sig.levillage.org/?p=599 http://www.robertblum.com/articles/2005/11/21/challenge-map-i-python-web-scraping http://www.rexx.com/~dkuhlman/quixote_htmlscraping.html From Serge.Orlov at gmail.com Sat Jun 17 19:58:07 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 17 Jun 2006 16:58:07 -0700 Subject: statically linked python References: Message-ID: <1150588687.938894.86830@r2g2000cwb.googlegroups.com> Ralph Butler wrote: > Hi: > > I have searched the docs and google but have not totally figured > out how to accomplish my task: On a linux box, I want to compile > and link python so that it uses no shared libraries, but does support > import of some "extra" modules. I have made a few attempts but > with limited success. In particular, I have tried things like > adding -static to the compiler options in the Makefile. > > At one point I managed to build a python that was close to what I > wanted, e.g. when I ran "ldd python", it said: > not a dynamic executable > In that version, when I do some imports, e.g. sys, os, etc. they > load fine. But, when I try to import some other modules, e.g. time, > they are not found. I have tried similar procedures while also > altering Modules/Setup.local (produced by configure) to contain: > time timemodule.c # -lm # time operations and variables > > There has to be a simple, "elegant" way to accomplish this which I am > simply overlooking. Any help would be appreciated. This has nothing to do with python. glibc doesn't support loading shared libraries into statically linked executables. At least it didn't support in 2002: http://www.cygwin.com/ml/libc-alpha/2002-06/msg00079.html Since it still doesn't work most likely it is still not supported, but you may ask glibc developers what is the problem. From Kiran.Karra at gmail.com Wed Jun 21 17:00:29 2006 From: Kiran.Karra at gmail.com (Kiran) Date: 21 Jun 2006 14:00:29 -0700 Subject: wx.Yield() during socket timeout Message-ID: <1150923629.735462.83370@b68g2000cwa.googlegroups.com> Hello All, I am creating a socket connection in order to read and write to a location. My problem is,the gui becomes unresponsive if the socket times out. I know that a good solution is to have the socket read and write with a thread. However, I have tried this and have a problem where ONLY on linux does the program crash, it DOES NOT crash on windows xp. I have been trying to figure out why for about a week and have just given up. Instead, I am now tryign to use wx.Yield() which will allow the gui to be updated. However, during timeouts, the gui still hangs. Does anybody have any clever ideas on how I could call the function wx.Yield() during a timeout so that the GUI stays responsive? I have already tried timers, and they dont work. thanks for your help, Kiran From Aiwass333 at gmail.com Thu Jun 15 15:50:28 2006 From: Aiwass333 at gmail.com (RunLevelZero) Date: 15 Jun 2006 12:50:28 -0700 Subject: a good programming text editor (not IDE) In-Reply-To: <_xgkg.2317$No6.48542@news.tufts.edu> References: <_xgkg.2317$No6.48542@news.tufts.edu> Message-ID: <1150401028.451141.193730@y41g2000cwy.googlegroups.com> Your SciTE problem is easily fixable by choosing " options / Open Global Options File " and then there are plenty of settings. Use the SciTE.html file and it will explain them all and there are many but the defaults usually work well to start out. I have had no issues with Linux. I use Debian. Here is a snippet of the first few lines of the global options file. "# Globals command.name.2.*.py=PyChecker command.2.*.py=C:\Python23\Scripts\pychecker.bat --stdlib --blacklist --varlist "$(FilePath)" tab.timmy.whinge.level=1 # Window sizes and visibility if PLAT_WIN position.left=30 position.top=25 if PLAT_GTK position.left=15 position.top=30 position.width=1200 position.height=950" As you can see if you are running windows "if PLAT_WIN" those are the settings for your window etc... Also grab this file. http://scintilla.sourceforge.net/gen_python_api.zip You can run it and it will build an API that you put in the root of SciTE and it will auto complete and it will give you help tips if you want them. I can't say that this is better than VIM but SciTE works great if you are mostly a python programmer. From greg at cosc.canterbury.ac.nz Sat Jun 10 05:25:54 2006 From: greg at cosc.canterbury.ac.nz (greg) Date: Sat, 10 Jun 2006 21:25:54 +1200 Subject: Adding extra frames to traceback in C module In-Reply-To: References: Message-ID: <448A9022.6050002@cosc.canterbury.ac.nz> Roger Binns wrote: > One thing I would like to do in my extension module is > add extra frames to the traceback when an extension > occurs. > > I did find snippets of code > doing things like PyTraceback_Here but they use a real > Python frame which I don't have and don't know how to > synthesize. This is the code Pyrex uses to add frames to the traceback. It creates a fake frame object and fills in just enough of it to keep the traceback printing code happy. Or you could just use Pyrex for your extension module in the first place, and get it done for you automatically. ----------------------------------------------------------- #include "compile.h" #include "frameobject.h" #include "traceback.h" static void __Pyx_AddTraceback(char *funcname) { PyObject *py_srcfile = 0; PyObject *py_funcname = 0; PyObject *py_globals = 0; PyObject *empty_tuple = 0; PyObject *empty_string = 0; PyCodeObject *py_code = 0; PyFrameObject *py_frame = 0; py_srcfile = PyString_FromString(%(FILENAME)s); if (!py_srcfile) goto bad; py_funcname = PyString_FromString(funcname); if (!py_funcname) goto bad; py_globals = PyModule_GetDict(%(GLOBALS)s); if (!py_globals) goto bad; empty_tuple = PyTuple_New(0); if (!empty_tuple) goto bad; empty_string = PyString_FromString(""); if (!empty_string) goto bad; py_code = PyCode_New( 0, /*int argcount,*/ 0, /*int nlocals,*/ 0, /*int stacksize,*/ 0, /*int flags,*/ empty_string, /*PyObject *code,*/ empty_tuple, /*PyObject *consts,*/ empty_tuple, /*PyObject *names,*/ empty_tuple, /*PyObject *varnames,*/ empty_tuple, /*PyObject *freevars,*/ empty_tuple, /*PyObject *cellvars,*/ py_srcfile, /*PyObject *filename,*/ py_funcname, /*PyObject *name,*/ %(LINENO)s, /*int firstlineno,*/ empty_string /*PyObject *lnotab*/ ); if (!py_code) goto bad; py_frame = PyFrame_New( PyThreadState_Get(), /*PyThreadState *tstate,*/ py_code, /*PyCodeObject *code,*/ py_globals, /*PyObject *globals,*/ 0 /*PyObject *locals*/ ); if (!py_frame) goto bad; py_frame->f_lineno = %(LINENO)s; PyTraceBack_Here(py_frame); bad: Py_XDECREF(py_srcfile); Py_XDECREF(py_funcname); Py_XDECREF(empty_tuple); Py_XDECREF(empty_string); Py_XDECREF(py_code); Py_XDECREF(py_frame); } -- Greg From jim.lewis at miclog.com Sun Jun 4 05:59:00 2006 From: jim.lewis at miclog.com (Jim Lewis) Date: 4 Jun 2006 02:59:00 -0700 Subject: Pyrex list/array In-Reply-To: <448239EB.6010706@lexicon.net> References: <1149360983.373137.200740@i39g2000cwa.googlegroups.com> <448239EB.6010706@lexicon.net> Message-ID: <1149415140.458073.65310@c74g2000cwc.googlegroups.com> Thanks for your comments. > You probably didn't expect the Inquisition... Correct ;-) > 1. What is your speed requirement and how far short of that are you at the moment? ~10 times faster. > 2. Are you sure there is no Python or third-party module that does what you want? Yes. > 3. Is your algorithm the best possible? I think so although of course one can never be certain. > 4. Is your Python implementation of that algorithm the best possible? Have you exposed it to the critical gaze of the speed-freaks in this newsgroup? Thanks for the good suggestion but I want to try pyrex first. > 5. Does your architecture support psyco? If so, have you tried that and what were the results? Already using psyco. > The question might be better asked on the Pyrex mailing list. I did not find it - where is it? > Almost any Python code is also valid Pyrex code. For a start, just compile your function with Pyrex and compare the speed. It's slower. > What you do next is going to depend very much on what operations you are performing on the list and the objects it contains. Simple list of ints. Comparing sections of lists between each other. From jmdeschamps at gmail.com Mon Jun 19 23:10:11 2006 From: jmdeschamps at gmail.com (jmdeschamps at gmail.com) Date: 19 Jun 2006 20:10:11 -0700 Subject: Newbie Question In-Reply-To: <1150771029.756430.19960@p79g2000cwp.googlegroups.com> References: <1150750938.973049.114780@y41g2000cwy.googlegroups.com> <129e55eahc35f00@corp.supernews.com> <1150753085.332654.283270@f6g2000cwb.googlegroups.com> <1150767309.831092.188530@h76g2000cwa.googlegroups.com> <1150767801.754519.165440@y41g2000cwy.googlegroups.com> <1150771029.756430.19960@p79g2000cwp.googlegroups.com> Message-ID: <1150773011.027316.253470@u72g2000cwu.googlegroups.com> Saint Malo wrote: > BTW my program isn't about red blue yellow etc. I'm just using it as > an example. I guess i didn't asked the question correctly or am not > expressing myself correctly. Let me try one more. > > Ok. > > Contents of text file follow: > > red blue purble > yellow blue green > > > > Now lets imagine i wrote some code to look for the word red. Once the > program has found red i want it to print something like the following > line. > > > If you add red and blue you obtain the color purple... > > > How do i turn each color in the line into a separate string? Now is > that possible? > ... Ok myself! Let's start at the beginning 1- a text string is text, not colors, right? 2- how does a computer know that you are looking for a color? Because you give it a label say 'red' (which is a text string) and it looks for that pattern of caracters in the string you are giving it as a target. 3- so you already HAVE the string you want, no? So, what I guess you question really is might look like the following: if I find colors words in a line, find what color is produced by the combination of all those I found in the line IF this is the case then what you may want is something like this: mycolors=["red", "green"] for line in file: listofwords = line.split(" ") # is a space is seperating the words in the actual line activecolors=[] # an empty list to use as local container for word in listofwords: if word in mycolors: activecolor.append(word) # keep a note of what color was found in this line dosomething(activecolors) Before I continue with that line of answer, does this seem closer to what you care to do? jm From roy at panix.com Sat Jun 3 22:02:29 2006 From: roy at panix.com (Roy Smith) Date: Sat, 03 Jun 2006 22:02:29 -0400 Subject: Proposed new PEP: print to expand generators References: Message-ID: In article , "James J. Besemer" wrote: > I propose that we extend the semantics of "print" such that if the object to > be printed is a generator then print would iterate over the resulting > sequence of sub-objects and recursively print each of the items in order. I believe the functionality you desire already exists, or something very close to it, in the pprint (pretty printer) module. From eval.apply at gmail.com Fri Jun 23 12:22:54 2006 From: eval.apply at gmail.com (Joe Marshall) Date: 23 Jun 2006 09:22:54 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: <1151026856.064429.36460@c74g2000cwc.googlegroups.com> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150998222.352746.65520@i40g2000cwc.googlegroups.com> <1151026856.064429.36460@c74g2000cwc.googlegroups.com> Message-ID: <1151079774.429512.68840@c74g2000cwc.googlegroups.com> Marshall wrote: > Joe Marshall wrote: > > > > That's the important point: I want to run broken code. > > I want to make sure I understand. I can think of several things > you might mean by this. It could be: > 1) I want to run my program, even though I know parts of it > are broken, because I think there are parts that are not broken > and I want to try them out. I think I mean a little of each of these. Nearly *every* program I have ever used is buggy, so this is actually a normal state of affairs even when I'm not debugging or developing. > 2) I want to run my program, even though it is broken, and I > want to run right up to a broken part and trap there, so I can > use the runtime facilities of the language to inspect what's > going on. I do this quite often. Sometimes I'll develop `in the debugger'. I'll change some piece of code and run the program until it traps. Then, without exiting the debugger, I'll fix the immediate problem and restart the program at the point it trapped. This technique takes a bit of practice, but if you are working on something that's complex and has a lot of state, it saves a lot of time because you don't have to reconstruct the state every time you make a change. > > I want to run > > as much of the working fragments as I can, and I want a `safety net' to > > prevent me from performing undefined operations, but I want the safety > > net to catch me at the *last* possible moment. > > This statement is interesting, because the conventional wisdom (at > least as I'm used to hearing it) is that it is best to catch bugs > at the *first* possible moment. But I think maybe we're talking > about different continua here. The last last last possible moment > is after the software has shipped to the customer, and I'm pretty > sure that's not what you mean. I think maybe you mean something > more like 2) above. It is often the case that the proximate cause of a bug is nowhere near where the fix needs to be applied. This is especially true with the really hard bugs. A static type system will tell me that there (may) exist a path through the code that results in an error, but the runtime check that fails will provide a witness. From fredrik at pythonware.com Thu Jun 1 15:31:39 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 01 Jun 2006 21:31:39 +0200 Subject: New to Python: Do we have the concept of Hash in Python? In-Reply-To: References: Message-ID: A.M wrote: > This is my 1st day that I am seriously diving into Python and I have to > finish this application by the end of today. Maybe it wasn't a good idea to > choose the language that I don't know when I have to deliver my work in such > short time. are your boss aware of this ? From deets at nospam.web.de Mon Jun 12 05:45:06 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 12 Jun 2006 11:45:06 +0200 Subject: Using PHP in Python References: <1150104925.811155.3550@y43g2000cwc.googlegroups.com> <4f4qvbF1hjj7tU1@uni-berlin.de> <1150105267.463906.66700@f14g2000cwb.googlegroups.com> Message-ID: <4f4reeF1hgn68U1@uni-berlin.de> > I have some custom PHP functions that I didn't want to re-write in > Python. But maybe I should just rewrite them :) Certainly yes. And you'd be amazed how easier it is in python, I believe. Diez From alainpoint at yahoo.fr Tue Jun 20 09:34:15 2006 From: alainpoint at yahoo.fr (alainpoint at yahoo.fr) Date: 20 Jun 2006 06:34:15 -0700 Subject: =?iso-8859-1?q?Re:_comparing_of_python_GUI=B4s?= In-Reply-To: <1150810106.501767.133490@c74g2000cwc.googlegroups.com> References: <1150806788.026172.140150@h76g2000cwa.googlegroups.com> <4fq979F1k6o98U1@uni-berlin.de> <1150810106.501767.133490@c74g2000cwc.googlegroups.com> Message-ID: <1150810455.264674.220810@g10g2000cwb.googlegroups.com> Bayazee wrote: > ThanX ... > any idea for choosing one of them ? > best in linux & windows > i must write a cross platform project . > it is a chat server and client with a user end site . > i started by writing a web site and creating a database in MySQL (FC4) > . > now i want to write a client with gui . similir to yahoo messenger or > ... > whats your suggest ? You probably didn't notice but Tim's post was meant to be humorous ;-) Go back to my advice. Once you're proficient with Google (it might take you some time), go and search for previous discussions on the same subject. Alain From andre.roberge at gmail.com Fri Jun 30 07:27:47 2006 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: 30 Jun 2006 04:27:47 -0700 Subject: Way for see if dict has a key In-Reply-To: <4F7pg.21676$_J1.272665@twister2.libero.it> References: <6V6pg.21624$_J1.271925@twister2.libero.it> <44a5041f$0$29637$636a55ce@news.free.fr> <4F7pg.21676$_J1.272665@twister2.libero.it> Message-ID: <1151666867.604260.116320@h44g2000cwa.googlegroups.com> Michele Petrazzo wrote: > Bruno Desthuilliers wrote: > >> but what the better > > > > Depends on the context. > > > > If know only one context: see if the key are into the dict... What other > context do you know? > > Michele Perhaps Bruno meant this: try: ... my_dict[key] ... except: ... when we expect that the key will most often be in my_dict so that exception will be raised rarely, otherwise use if key in dict Andr? From meyer at mesw.de Thu Jun 15 17:13:26 2006 From: meyer at mesw.de (meyer at mesw.de) Date: 15 Jun 2006 14:13:26 -0700 Subject: Which compiler will Python 2.5 / Windows (Intel) be built with? In-Reply-To: <4491b9e1$1@nntp0.pdx.net> References: <1150367139.495114.148550@g10g2000cwb.googlegroups.com> <44917535$1@nntp0.pdx.net> <1150391891.130185.4640@f6g2000cwb.googlegroups.com> <4491b9e1$1@nntp0.pdx.net> Message-ID: <1150406005.948538.188950@h76g2000cwa.googlegroups.com> Hi Scott, thanks for keeping up the friendly discussion. Comments below. Scott David Daniels wrote: > The disruption in Python 2.4 in switching from one compiler (VC6) to > another VS2003 was not insubstantial. By sticking with VS2003, sometime > users can at least use the same tool for Python 2.4 and Python 2.5. It > does seem inevitable we will have to switch for 2.6. We are very far > along in the process of releasing Python 2.5 (beta1 is due out soon), > and rebuilding and testing with a new translation system is too big a > change at this point. I understand that you are far in the release cycle and that this change would maybe even delay the whole release process. Those are good points. OTOH I think that sometimes it's better to change decisions in light of new facts. Of course I don't know exactly when this decision was fixed, but I guess since then Microsoft has created two new facts that cannot be ignored: * It wasn't clear that Microsoft would stop distributing the free 2003 toolkit in favor of the 2005 toolkit. I cannot remember that they did something like this in the past, so this is something that came as a surprise. * At least to me it wasn't clear that Microsoft would release a new version of Visual Studio so early, and that it would link to a new, incompatible C runtime. One can like or not like Microsoft politics, but I think in case of those new and surprising facts a re-evaluation of the decision for compiling Python with VS2003 might very well be justified. > Note there was strong resistance to leaving VC6 for Python 2.4. That > resistance was overcome only by the fact that it was no longer possible > to purchase suitable versions of VC6. I'm not sure how that backs the point you made. Infact, you're saying that people accepted that Python 2.4 was compiled with VS2003 because VC6 could not longer be bought. How is that different from the current situation where the VS2003 toolkit cannot longer be downloaded and it is at least becoming increasingly difficult to buy versions of VS2003? You also seem to imply that there is a large group of people that want you to stay with VS2003 for compiling Python 2.5. Of course I have no actual figures, but at least in this thread it seems to me that every single person who wrote in this thread until now was pro-2005 and against-2003. Markus From neuruss at gmail.com Mon Jun 5 20:27:07 2006 From: neuruss at gmail.com (Neuruss) Date: 5 Jun 2006 17:27:07 -0700 Subject: C# equivalent to range() In-Reply-To: References: <1149468919.951745.163700@g10g2000cwb.googlegroups.com> <1149481675.192638.275140@c74g2000cwc.googlegroups.com> <1149509893.031953.19310@i40g2000cwc.googlegroups.com> Message-ID: <1149553627.015779.27460@i40g2000cwc.googlegroups.com> Fredrik Lundh wrote: > do you think the few of us who haven't already done so would miss > anything if we plonked you now? Oh, no... How am I supposed to live without you, Freddie? From dnew at san.rr.com Tue Jun 20 13:38:15 2006 From: dnew at san.rr.com (Darren New) Date: Tue, 20 Jun 2006 17:38:15 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: <1150824033.452278.45310@c74g2000cwc.googlegroups.com> References: <7zpshbsvjy.fsf@app-1.diku.dk><4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <1150809118.677124.142230@u72g2000cwu.googlegroups.com> <1150815461.210286.53120@r2g2000cwb.googlegroups.com> <1150822150.701434.296460@u72g2000cwu.googlegroups.com> <1150824033.452278.45310@c74g2000cwc.googlegroups.com> Message-ID: Rob Thorpe wrote: > Darren New wrote: >>Rob Thorpe wrote: >>>The values themselves have no type information associated with them. >>int x = (int) (20.5 / 3); > In that case it knew because it could see at compile time. Well, yes. That's the point of static typing. > In general though it doesn't. Sure it does. There are all kinds of formal rules about type promotions and operator version selection. In deed, in *general* every value has a type associated with it (at compile time). Some values have a type associated with them due to the declaration of the variable supplying the value, but that's far from the general case. Note that in main() { char x = 'x'; foo(x); } the value passed to "foo" is not even the same type as the declaration of "x", so it's far from the general case that variables even determine the values they provide to the next part of the calculation. > If I divide x / y it only knows which to use because of types declared > for x and y. Yes? So? All you're saying is that the value of the expression "x" is based on the declared type for the variable "x" in scope at that point. That doesn't mean values don't have types. It just means that *some* values' types are determined by the type of the variable the value is stored in. As soon as you do anything *else* with that value, such as passing it to an operator, a function, or a cast, the value potentially takes on a type different from that of the variable from which it came. > I suppose some are conversions and some reinterpretations. What I > should have said it that there are cases where cast reinterprets. There are cases where the cast is defined to return a value that has the same bit pattern as its argument, to the extent the hardware can support it. However, this is obviously limited to the values for which C actually defines the bit patterns of its values, namely the scalar integers. Again, you're taking a special case and treating all the rest (which are a majority) as aberations. For the most part, casts do *not* return the same bit pattern as the value. For the most part union {T1 x; T2 y;}; can be used to do transformations that T2 y; T1 x = (T1) y; does not. Indeed, the only bit patterns that don't change are when casting from signed to unsigned versions of the same underlying scalar type and back. Everything else must change, except perhaps pointers, depending on your architecture. (I've worked on machines where char* had more bits than long*, for example.) (Funny that comp.lang.c isn't on this thread. ;-) -- Darren New / San Diego, CA, USA (PST) My Bath Fu is strong, as I have studied under the Showerin' Monks. From deets at nospam.web.de Mon Jun 19 10:30:49 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 19 Jun 2006 16:30:49 +0200 Subject: comparing two arrays References: <1150721380.948808.231760@h76g2000cwa.googlegroups.com> <4fnlbiF1j83q2U1@uni-berlin.de> Message-ID: <4fnqoqF1k8n10U1@uni-berlin.de> Diez B. Roggisch wrote: > print [i for i, _ in enumerate((None for v in zip(a, b) where v == > (1,1)))] > > should give you the list of indices. I musunderstood your question. Use print [i for i, _ in enumerate((None for x, y in zip(a, b) where x == y))] instead. Diez From nospam at nospam.com Thu Jun 8 12:45:57 2006 From: nospam at nospam.com (3c273) Date: Thu, 8 Jun 2006 09:45:57 -0700 Subject: Instead of saving text files i need as html References: <1149777499.506986.292830@j55g2000cwa.googlegroups.com> Message-ID: "Shani" wrote in message news:1149777499.506986.292830 at j55g2000cwa.googlegroups.com... > I have the following code which takes a list of urls > "http://google.com", without the quotes ofcourse, and then saves there > source code as a text file. I wan to alter the code so that for the > list of URLs an html file is saved. > > -----begin----- > import urllib > urlfile = open(r'c:\temp\url.txt', 'r') > for lines in urlfile: > try: > outfilename = lines.replace('/', '-') > urllib.urlretrieve(lines.strip('/n'), 'c:\\temp\\' \ > + outfilename.strip('\n')[7:] + '.txt') > except: > pass > -----end----- > Or is this what you mean? -----begin----- import urllib urlfile = open('c:\\temp\\url.txt', 'r') newurlfile = open('c:\\temp\\newurls.html', 'w') newurlfile.write(' \n\n') for lines in urlfile: try: if lines == '\n': pass else: lines = ''\ + lines.strip() + '' + '
\n' newurlfile.write(lines) except: pass newurlfile.write(' \n') urlfile.close() newurlfile.close() -----end----- Louis From claird at lairds.us Thu Jun 1 21:03:22 2006 From: claird at lairds.us (Cameron Laird) Date: Fri, 2 Jun 2006 01:03:22 +0000 Subject: Tkinter - changing existing Dialog? References: Message-ID: In article , Michael Yanowitz wrote: . . . >2) Change the text of a label or button that is already drawn? > > based on actions taken by the user. Can it be done without destroying >the present dialog or the objects in it and creating a new one? . . . import Tkinter root = Tkinter.Tk() counter = 0 # This is one of several ways one can access the Button's label. def set_text(): b.configure(text = "The button has been pushed %d time(s)." % counter) def actions(): global counter counter += 1 set_text() b = Tkinter.Button(root, command = actions) set_text() b.pack() root.mainloop() From Bulkan at gmail.com Tue Jun 27 21:25:21 2006 From: Bulkan at gmail.com (placid) Date: 27 Jun 2006 18:25:21 -0700 Subject: problem with http server Message-ID: <1151457921.079418.300420@m73g2000cwd.googlegroups.com> Hi all, Im having trouble with the following code for handling GET requests from a client to my HTTP server. What i want to do is restrict access only to a folder and contents(files) within this folder. But when trying to open files (eg text files) i get file not found error from send_head() method of SimpleHTTPServer. The reason behind this is when opening the file the path to the file is only C:\file.txt when it should be C:\folder\file.txt. And when i remove the code that checks if path contains "txt" it works (i can access files without errors). Any help will be greatly appreciated! def list_directory(self, path): """Helper to produce a directory listing (absent index.html). Return value is either a file object, or None (indicating an error). In either case, the headers are sent, making the interface the same as for send_head(). """ f = StringIO() p = self.translate_path(self.path) if p.find("txt") == -1: f.write("httpserver.py: Access Denied" ) f.write("

httpserver.py: Access Denied

" ) else: try: list = os.listdir(path) except os.error: self.send_error(404, "No permission to list directory") return None list.sort(key=lambda a: a.lower()) displaypath = cgi.escape(urllib.unquote(self.path)) f.write("Directory listing for %s\n" %displaypath) f.write("

Directory listing for %s

\n" % displaypath) f.write("
\n
    \n") for name in list: fullname = os.path.join(path, name) displayname = linkname = name # Append / for directories or @ for symbolic links if os.path.isdir(fullname): displayname = name + "/" linkname = name + "/" if os.path.islink(fullname): displayname = name + "@" # Note: a link to a directory displays with @ and links with / f.write('
  • %s\n' % (urllib.quote(linkname), \ cgi.escape(displayname))) f.write("
\n
\n") length = f.tell() f.seek(0) self.send_response(200) self.send_header("Content-type", "text/html") self.send_header("Content-Length", str(length)) self.end_headers() return f
-Cheers P.S: ive posted this twice with the subject line HTTP Server, i apoligise if this will annoy anyone. From grante at visi.com Thu Jun 1 16:11:23 2006 From: grante at visi.com (Grant Edwards) Date: Thu, 01 Jun 2006 20:11:23 -0000 Subject: integer to binary... References: <1149189570.376091.319890@j55g2000cwa.googlegroups.com> <127ugf9jgu7av18@corp.supernews.com> <1149190940.548582.27200@h76g2000cwa.googlegroups.com> Message-ID: <127uifbgvsp7va9@corp.supernews.com> On 2006-06-01, Tim Chase wrote: >>>> for example I want to convert number 7 to 0111 so I can make some >>>> bitwise operations... >>> Just do it: >>> >>>>>> 7 & 3 >>> 3 >>>>>> 7 | 8 >>> 15 >> I know I can do that but I need to operate in every bit separeted. > > > I suppose there might be other operations for which having them > as strings could be handy. E.g. counting bits: > > bitCount = len([c for c in "01001010101" if c=="1"]) > > or parity checking with those counted bits...sure, it can be done > with the raw stuff, but the operations often tend to be more obscure. I would think an array or list of bits would be a lot more useful for doing "bitwise operations": bitCount = sum([0,1,0,0,1,0,1,0,1,0,1]) parity = reduce(operator.xor,[0,1,0,0,1,0,1,0,1,0,1]) > Other reasons for wanting an arbitrary integer in binary might be > for plain-old-display, especially if it represents bitmap data. Yes. I thought C should have had a %b format since the beginning, but nobody listens. But that's not what the OP said he wanted it for. -- Grant Edwards grante Yow! Now I'm concentrating at on a specific tank battle visi.com toward the end of World War II! From jeffrey at fro.man Thu Jun 1 11:34:35 2006 From: jeffrey at fro.man (Jeffrey Froman) Date: Thu, 01 Jun 2006 08:34:35 -0700 Subject: New to Python: Do we have the concept of Hash in Python? References: Message-ID: <127u27pjm8gu1c1@corp.supernews.com> A.M wrote: > I am asking this because I learned that DB-API in Python doesn't offer > access to cursor columns by name. The only option is access by index. I > hope that I've got it wrong! While it's not part of the DB-API as far as I know, the MySQLdb package (and perhaps other DB access modules as well, I don't know) provides a "DictCursor" class that returns query results as a tuple of column-keyed dictionaries (hashes, already demonstrated by Brian). Jeffrey From tactics40 at gmail.com Thu Jun 29 13:50:46 2006 From: tactics40 at gmail.com (tac-tics) Date: 29 Jun 2006 10:50:46 -0700 Subject: list comprehension In-Reply-To: <1151600332.552024.119990@y41g2000cwy.googlegroups.com> References: <1151600332.552024.119990@y41g2000cwy.googlegroups.com> Message-ID: <1151603446.189159.240580@75g2000cwc.googlegroups.com> a wrote: > can someone tell me how to use them > thanks sigh... You do a google on them: http://docs.python.org/tut/node7.html#SECTION007140000000000000000 They are the program equivalent of set builder notation in math: {x | x in S} would be written [x for x in S] in python. From dev at null.com Tue Jun 27 17:22:34 2006 From: dev at null.com (Mike Currie) Date: Tue, 27 Jun 2006 14:22:34 -0700 Subject: Python UTF-8 and codecs References: <5Hgog.627$Gv.173@fed1read09> Message-ID: Okay, Here is a sample of what I'm doing: Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> filterMap = {} >>> for i in range(0,255): ... filterMap[chr(i)] = chr(i) ... >>> filterMap[chr(9)] = chr(136) >>> filterMap[chr(10)] = chr(133) >>> filterMap[chr(136)] = chr(9) >>> filterMap[chr(133)] = chr(10) >>> line = '''this has ... tabs and line ... breaks''' >>> filteredLine = ''.join([ filterMap[a] for a in line]) >>> import codecs >>> f = codecs.open('foo.txt', 'wU', 'utf-8') >>> print filteredLine this?has??tabs?and?line?breaks >>> f.write(filteredLine) Traceback (most recent call last): File "", line 1, in ? File "C:\Python24\lib\codecs.py", line 501, in write return self.writer.write(data) File "C:\Python24\lib\codecs.py", line 178, in write data, consumed = self.encode(object, self.errors) UnicodeDecodeError: 'ascii' codec can't decode byte 0x88 in position 4: ordinal not in range(128) >>> "Mike Currie" wrote in message news:5Hgog.627$Gv.173 at fed1read09... >I did make a mistake, it should have been 'wU'. > > The starting data is ASCII. > > What I'm doing is data processing on files with new line and tab > characters inside quoted fields. The idea is to convert all the new line > and characters to 0x85 and 0x88 respectivly, then process the files. > Finally right before importing them into a database convert them back to > new line and tab's thus preserving the field values. > > Will python not handle the control characters correctly? > > > "Serge Orlov" wrote in message > news:mailman.7516.1151440194.27775.python-list at python.org... >> On 6/27/06, Mike Currie wrote: >>> I'm trying to write out files that have utf-8 characters 0x85 and 0x08 >>> in >>> them. Every configuration I try I get a UnicodeError: ascii codec can't >>> decode byte 0x85 in position 255: oridinal not in range(128) >>> >>> I've tried using the codecs.open('foo.txt', 'rU', 'utf-8', >>> errors='strict') >>> and that doesn't work and I've also try wrapping the file in an >>> utf8_writer >>> using codecs.lookup('utf8') >>> >>> Any clues? >> >> Use unicode strings for non-ascii characters. The following program >> "works": >> >> import codecs >> >> c1 = unichr(0x85) >> f = codecs.open('foo.txt', 'wU', 'utf-8') >> f.write(c1) >> f.close() >> >> But unichr(0x85) is a control characters, are you sure you want it? >> What is the encoding of your data? > > From ray_usenet at yahoo.com Thu Jun 1 05:00:28 2006 From: ray_usenet at yahoo.com (Ray) Date: 1 Jun 2006 02:00:28 -0700 Subject: How do you practice programming? In-Reply-To: <447eabee$0$19567$636a55ce@news.free.fr> References: <1149151097.741307.79440@f6g2000cwb.googlegroups.com> <447eabee$0$19567$636a55ce@news.free.fr> Message-ID: <1149152428.348192.106970@h76g2000cwa.googlegroups.com> bruno at modulix wrote: > 1/ programming > 2/ programming > 3/ lurking here, reading posts and sometimes trying to answer, reading > source code of the oss apps/frameworks I'm working with, searching > practical solutions in the cookbook etc > 4/ programming Yeah, but that's what most of us are doing too, we are programmers after all. But you know, it's like a boxer cannot get better just by going into a lot of fights, he needs good instruction from a good coach. So what would you do? (I guess it's your number #3 above). > > -- > bruno desthuilliers > python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for > p in 'onurb at xiludom.gro'.split('@')])" From antroy at gmail.com Fri Jun 16 05:45:41 2006 From: antroy at gmail.com (Ant) Date: 16 Jun 2006 02:45:41 -0700 Subject: Python is fun (useless social thread) ;-) In-Reply-To: References: Message-ID: <1150451141.641080.117990@p79g2000cwp.googlegroups.com> > No, I learned it because Perl was too dirty and Java to complicated. > Now it is part of my daily job. Ditto. I was fed up of writing, compiling and running a java application just in order to do a quick script. I'd used perl, but quite frankly perl's a ridiculous language. Ruby looked promising, but perl had already poisoned my mind against the syntax... Python was clean, object oriented if you want it, and mature. > > Also, how did you go about learning it? > > Programming, reading this newsgroup, reading the python cookbook, > reading python source files of the standard library. > > Are there still some things you feel you need to learn or improve? I feel like I've got a pretty good grasp of the core language now, but there's always something that pops up in the group that I find I've not dabbled in (such as the itertools, which I discovered on the group last week(?) and have been using to great effect already!). From ilias at lazaridis.com Sun Jun 4 09:17:54 2006 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Sun, 04 Jun 2006 16:17:54 +0300 Subject: PUDGE - Project Status, Alternative Solutions In-Reply-To: <447786E9.9010208@lazaridis.com> References: <447786E9.9010208@lazaridis.com> Message-ID: <4482DD82.6010003@lazaridis.com> Ilias Lazaridis wrote: > What is going on with the pudge project? Any chance to get an comment on this? > Mr. Patrik O'Brien (Orbtech LLC) had told me that there is no similar > tool available within the python domain, thus I have invested some > effort to create a Website template, and to enable pudge to generate > colored code: > > http://audit.lazaridis.com/schevo/wiki/SchevoWebsiteReview > > I like to reuse the results for personal projects, but I am wondering > that the pudge email-list is death (since the server update) - and that > no one of the project reacts to personal and public postings. > > Additionally, the schevo project removes the pudge stuff, mscott, the > developer which has introduced pudge removes it again (although this was > done with several other tools in the past, too): > > http://schevo.org/trac/changeset/2127 > > - > > Is there a similar tool available, with which I can generate python > documentation / websites or both based on templates and reST? > > Or an overview of such tools? > > I mean such an organized tool is essential for developmente with python. > > . > -- http://lazaridis.com From johnjsal at NOSPAMgmail.com Thu Jun 15 13:12:26 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 15 Jun 2006 17:12:26 GMT Subject: a good programming text editor (not IDE) Message-ID: <_xgkg.2317$No6.48542@news.tufts.edu> I know there's a request for a good IDE at least once a week on the ng, but hopefully this question is a little different. I'm looking for suggestions for a good cross-platform text editor (which the features for coding, such as syntax highlighting, etc.) but not a full IDE with all the fancy jazz (GUI developer, UML diagrams, etc.). Ideally, it would be something I could even put on a flash drive and move from computer to computer, but this isn't necessary. Just something I can immediately use in either Windows or Linux (or Mac, if necessary). Based on another thread, I tried out Scite, but no matter what I do it doesn't seem to remember the window size and position, or any options I choose (like showing line numbers). It seems to always reset itself each time I open it. And naturally there are Emacs and Vim, but I just don't know if I need to invest *that* much time into learning one of them (probably Vim, since I hear it's lighter and faster). I've tried a few others, like TextPad and Crimson, and right now I use UltraEdit, which I love actually, except for minor issues here and there. But it'd be nice to make the move, as much as possible, to free, open-source, cross-platform software. Thanks for any suggestions, and again I'm sorry if this feels like the same question as usual (it's just that in my case, I'm not looking for something like SPE, Komodo, Eric3, etc. right now). From jcrocholl at googlemail.com Tue Jun 13 12:15:17 2006 From: jcrocholl at googlemail.com (Johann C. Rocholl) Date: 13 Jun 2006 09:15:17 -0700 Subject: Writing PNG with pure Python References: <1149853401.521169.112530@i39g2000cwa.googlegroups.com> <1149889778.182865.181600@f6g2000cwb.googlegroups.com> <1149910872.025017.60160@i40g2000cwc.googlegroups.com> <1150152913.315502.16840@u72g2000cwu.googlegroups.com> Message-ID: <1150215317.349097.326970@p79g2000cwp.googlegroups.com> How about this here construct? #!/usr/bin/env python # png.py - PNG encoder in pure Python # Copyright (C) 2006 Johann C. Rocholl # # This file is licensed alternatively under one of the following: # 1. GNU Lesser General Public License (LGPL), Version 2.1 or newer # 2. GNU General Public License (GPL), Version 2 or newer # 3. Apache License, Version 2.0 or newer # 4. The following license (aka MIT License) # # --------------------- start of license ----------------------------- # Copyright (C) 2006 Johann C. Rocholl # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, # including without limitation the rights to use, copy, modify, merge, # publish, distribute, sublicense, and/or sell copies of the Software, # and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # ----------------------- end of license ----------------------------- # # You may not use this file except in compliance with at least one of # the above four licenses. From fredrik at pythonware.com Mon Jun 19 06:58:48 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 19 Jun 2006 12:58:48 +0200 Subject: Simple script to make .png thumbnails from .zip archive... In-Reply-To: <1150660266.413889.217280@c74g2000cwc.googlegroups.com> References: <1150660266.413889.217280@c74g2000cwc.googlegroups.com> Message-ID: K P S wrote: > What I want is a little more involved, I guess, since I > don't know the name of the file (for the zip.read command) the first example on this page shows you how to get the names of all files in a zip file: http://effbot.org/librarybook/zipfile.htm From xivulon at gmail.com Fri Jun 2 14:40:28 2006 From: xivulon at gmail.com (ago) Date: 2 Jun 2006 11:40:28 -0700 Subject: win32com: how to connect to a specific instance of a running object? In-Reply-To: <1149260253.337452.65770@c74g2000cwc.googlegroups.com> References: <1149254270.790703.145700@j55g2000cwa.googlegroups.com> <1149260253.337452.65770@c74g2000cwc.googlegroups.com> Message-ID: <1149273628.486179.224680@h76g2000cwa.googlegroups.com> solved, if it can be useful to others here is my code: import pythoncom import win32com.client def getWorkbook(workbookName): lenstr = len(workbookName) workbook = None rot = pythoncom.GetRunningObjectTable() rotenum = rot.EnumRunning() while True: monikers = rotenum.Next() if not monikers: break ctx = pythoncom.CreateBindCtx(0) name = monikers[0].GetDisplayName(ctx, None); if name[-lenstr:] == workbookName: obj = rot.GetObject(monikers[0]) workbook = win32com.client.Dispatch(obj.QueryInterface(pythoncom.IID_IDispatch)) return workbook From Bulkan at gmail.com Sat Jun 24 03:18:15 2006 From: Bulkan at gmail.com (placid) Date: 24 Jun 2006 00:18:15 -0700 Subject: * in Python In-Reply-To: <449bff99$0$19544$636a55ce@news.free.fr> References: <1151061836.557835.295820@p79g2000cwp.googlegroups.com> <1151065046.668902.23010@g10g2000cwb.googlegroups.com> <449beca5$0$13891$626a54ce@news.free.fr> <1151072320.621378.218520@r2g2000cwb.googlegroups.com> <449bff99$0$19544$636a55ce@news.free.fr> Message-ID: <1151133495.005872.227780@u72g2000cwu.googlegroups.com> Bruno Desthuilliers wrote: > placid wrote: > > Bruno Desthuilliers wrote: > > > (snip) > >>Why don't you try by yourself in the Python shell ? One of the nice > >>things with Python is that it's quite easy to explore and experiment. > > > > > > i did try it in a Python shell after i learnt what it was. Like i said > > *args will be a list, but when i try **args with the following code it > > doesnt work > > "doesn't work" is the most useless description of a problem. > > > def test(**args): > > keys = args.keys() > > for key in keys: > > print key+"="+args(key) > > you want args[key], not args(key) > > And you forget to tell how you called this code and what you got. Too much world cup means sleepless nights down here in Australia or i would have seen the error with args(key) which suppose to be args[key] ! > > FWIW: > Python 2.4.3 (#1, Jun 3 2006, 17:26:11) > [GCC 3.4.6 (Gentoo 3.4.6-r1, ssp-3.4.5-1.0, pie-8.7.9)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> def test(**kw): > ... for item in kw.items(): > ... print "%s : %s" % item > ... > >>> test() > >>> test(parrot="dead", walk="silly", nose="big") > nose : big > parrot : dead > walk : silly > >>> test(**{'answer':42}) > answer : 42 > >>> Thanks for that now i know what * means. From bj_666 at gmx.net Mon Jun 19 15:04:29 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 19 Jun 2006 21:04:29 +0200 Subject: Overriding a function... References: <1150742558.198061.239660@p79g2000cwp.googlegroups.com> Message-ID: In <1150742558.198061.239660 at p79g2000cwp.googlegroups.com>, programmer.py at gmail.com wrote: > 1) If mymodule is subsequently imported, will my `override' function be > used, or will python magically `fix' (or break depending on your > perspective) mymodule and use the original mymodule.test function? It will not `fix` it. Importing an already imported module doesn't reload the module. > 2) Once I assign mymodule.test with override, will modules that > imported my module *PRIOR* to the assignment get override, or will they > keep the original function test()? They see the `override()` function. Ciao, Marc 'BlackJack' Rintsch From johnjsal at NOSPAMgmail.com Tue Jun 27 11:45:33 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 27 Jun 2006 15:45:33 GMT Subject: Python is fun (useless social thread) ;-) In-Reply-To: <44a12298$0$8346$636a55ce@news.free.fr> References: <1150381872.958342.180420@p79g2000cwp.googlegroups.com> <44917776$1@nntp0.pdx.net> <4492c1c6$0$11008$626a54ce@news.free.fr> <1151345365.630616.14400@i40g2000cwc.googlegroups.com> <44a12298$0$8346$636a55ce@news.free.fr> Message-ID: Bruno Desthuilliers wrote: >> Ever seen this from Fuzzyman? It explicitly uses the dict comparison. >> >> http://www.voidspace.org.uk/python/articles/OOP.shtml#introduction > > Nope - and the site seems to be down actually. But thanks for the > pointer anyway. It works for me, at least now. From salvatore.didio at wanadoo.fr Tue Jun 13 08:55:54 2006 From: salvatore.didio at wanadoo.fr (Salvatore) Date: 13 Jun 2006 05:55:54 -0700 Subject: "Adding" dictionnaries Message-ID: <1150203354.861658.181110@h76g2000cwa.googlegroups.com> Hello, Does anybody had the problem of adding the content of two dictionnaries. ? Regards From digitalsubjunctive at gmail.com Sun Jun 25 03:35:13 2006 From: digitalsubjunctive at gmail.com (MilkmanDan) Date: 25 Jun 2006 00:35:13 -0700 Subject: Python taught in schools? Message-ID: <1151220913.406987.162420@u72g2000cwu.googlegroups.com> I'll be a college freshman this fall, attending Florida Institute of Tech studying electrical engineering. I was considering taking some classes in programming and computer science, and I happened to notice that everything taught is using C++. After further research, it seems to me that C++ seems to be the dominating language in universities. By comparison, our local community college teaches a few classes in VB, Java, Javascript, C++, and for some reason, PASCAL. I'm certianly not against any of this, but out of curiousity does anyone know of a school that teaches Python? From fredrik at pythonware.com Fri Jun 23 07:41:52 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 23 Jun 2006 13:41:52 +0200 Subject: * in Python In-Reply-To: <1151061836.557835.295820@p79g2000cwp.googlegroups.com> References: <1151061836.557835.295820@p79g2000cwp.googlegroups.com> Message-ID: placid wrote: > Can someone tell me what * in the following code means/does a Google > search didnt turn up anything as i dont know what the * is called see sections 4.7.2 and 4.7.3 in the tutorial: http://docs.python.org/tut/node6.html#SECTION006740000000000000000 for more details, see the description of the "def" statement in the language reference. From fredrik at pythonware.com Thu Jun 8 06:42:13 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 08 Jun 2006 12:42:13 +0200 Subject: language-x-isms In-Reply-To: <1149762625.346302.135220@y43g2000cwc.googlegroups.com> References: <1149753206.451066.120960@h76g2000cwa.googlegroups.com> <1149759486.695563.110640@g10g2000cwb.googlegroups.com> <1149760633.796809.166430@h76g2000cwa.googlegroups.com> <1149762625.346302.135220@y43g2000cwc.googlegroups.com> Message-ID: Alan Kennedy wrote: > Your comment makes "using a user-defined enumerate [on cpython] is > slower than using the built-in version" makes no sense in relation to > the code I posted try combining with the second sentence in my post. From grflanagan at yahoo.co.uk Tue Jun 6 01:25:29 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 5 Jun 2006 22:25:29 -0700 Subject: Concatenating dictionary values and keys, and further operations In-Reply-To: References: Message-ID: <1149571529.782630.144400@j55g2000cwa.googlegroups.com> Girish Sahani wrote: > Gerard Flanagan wrote: >> Girish Sahani wrote: >> > I wrote the following code to concatenate every 2 keys of a dictionary >> and >> > their corresponding values. >> > e.g if i have tiDict1 = tiDict1 = {'a':[1,2],'b':[3,4,5]} i should get >> > tiDict2={'ab':[1,2][3,4,5]} and similarly for dicts with larger no. of >> > features. >> > Now i want to check each pair to see if they are connected...element >> of >> > this pair will be one from the first list and one from the >> second....e.g >> > for 'ab' i want to check if 1 and 3 are connected,then 1 and 4,then 1 >> and >> > 5,then 2 and 3,then 2 and 4,then 2 and 5. >> > The information of this connected thing is in a text file as follows: >> > 1,'a',2,'b' >> > 3,'a',5,'a' >> > 3,'a',6,'a' >> > 3,'a',7,'b' >> > 8,'a',7,'b' >> > . >> > . >> > This means 1(type 'a') and 2(type 'b') are connected,3 and 5 are >> connected >> > and so on. >> > I am not able to figure out how to do this.Any pointers would be >> helpful >> >> >> Girish >> >> It seems you want the Cartesian product of every pair of lists in the >> dictionary, including the product of lists with themselves (but you >> don't say why ;-)). >> >> I'm not sure the following is exactly what you want or if it is very >> efficient, but maybe it will start you off. It uses a function >> 'xcombine' taken from a recipe in the ASPN cookbook by David >> Klaffenbach (2004). >> > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/302478 > > -- > http://mail.python.org/mailman/listinfo/python-list > >Thanks a lot Gerard and Roberto.but i think i should explain the exact >thing with an example. >Roberto what i have right now is concatenating the keys and the >corresponding values: >e.g {'a':[1,2],'b':[3,4,5],'c':[6,7]} should give me >{'ab':[1,2][3,4,5] 'ac':[1,2][6,7] 'bc':[3,4,5][6,7]} >The order doesnt matter here.It could be 'ac' followed by 'bc' and 'ac'. >Also order doesnt matter in a string:the pair 'ab':[1,2][3,4,5] is same as >'ba':[3,4,5][1,2]. >This representation means 'a' corresponds to the list [1,2] and 'b' >corresponds to the list [3,4,5]. >Now, for each key-value pair,e.g for 'ab' i must check each feature in the >list of 'a' i.e. [1,2] with each feature in list of 'b' i.e. [3,4,5].So I >want to take cartesian product of ONLY the 2 lists [1,2] and [3,4,5]. >Finally i want to check each pair if it is present in the file,whose >format i had specified. >The code Gerard has specified takes cartesian products of every 2 lists. Hi Garish, it's better to reply to the Group. >Now, for each key-value pair,e.g for 'ab' i must check each feature in the >list of 'a' i.e. [1,2] with each feature in list of 'b' i.e. [3,4,5].So I >want to take cartesian product of ONLY the 2 lists [1,2] and [3,4,5]. I'm confused. You say *for each* key-value pair, and you wrote above that the keys were the 'concatenation' of "every 2 keys of a dictionary". Sorry, too early for me. Maybe if you list every case you want, given the example data. All the best. Gerard From tjreedy at udel.edu Mon Jun 19 11:14:37 2006 From: tjreedy at udel.edu (tjreedy) Date: Mon, 19 Jun 2006 11:14:37 -0400 Subject: Amara installation References: <1150719788.482305.9560@r2g2000cwb.googlegroups.com> Message-ID: wrote in message news:1150719788.482305.9560 at r2g2000cwb.googlegroups.com... > O/S WinXP Home > Vsn of Python: 2.4 > > Wish to install Amara. Using amara-allinone-1.0.win32-py2.4.exe > (2965KB) > > Forder structure before installation: > > c: > python24 > DLLs > Doc > Include > Lib > site-packages > [previously installed stuff] > libs > scripts > tcl > tools > > When I run install, the install program indicates: > > Python directory: c:\python24\ > Installation directory: c:\python24\lib\site-packages\ > > After install, folder structrue is: > > Vsn of Python: 2.4 > > Wish to install Amara. Using amara-allinone-1.0.win32-py2.4.exe > (2965KB) > > Forder structure after installation: > > c: > python24 > DLLs > Doc > Include > Lib > site-packages > [previously installed stuff] > libs > python24 <<<-- > lib <<<-- > site-packages <<<-- new amara files/folders appear > amara <<<-- to be installed here > ft <<<-- > scripts <<<-- > share <<<-- > scripts > tcl > tools > > I was expecting the new amara files/folders to be installed within the > existing c:\python24\ folder structure...wasn't expecting it to create > a new ...\python24\ folder within the parent ...\python24\ folder. That is probably because you told it to, without knowing what exactly was being asked. It looks like this installer was intended for someone who does not already have Python installed. You might inquire as to whether there is one for people who do. > My questions: > 1) has anyone else observed this when installing? > 2) should I move the newly installed files/folders into the > previously-existing folder structure? as long as I don't remove > files/folders, is there any risk of causing a previously installed site > package that worked to no longer work? I don't think so. As long as the installer did not register file locations, this should work. If there are any shortcuts or start menu entries, you will have to edit. tjr From johnjsal at NOSPAMgmail.com Thu Jun 15 13:51:13 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 15 Jun 2006 17:51:13 GMT Subject: a good programming text editor (not IDE) In-Reply-To: References: <_xgkg.2317$No6.48542@news.tufts.edu> Message-ID: Sybren Stuvel wrote: > Vim is definitely the best. If you're a GUI man, you can use GVim. Ok, you guys are slowly converting me, but I do have one question: which "version" of VIM should I use, or does it matter? I mean, there seem to be at least two versions, a text version and the GUI version you mention. Are the options shared between the two, or is it that you are more or less "set" in one once you choose it, and if you move to the other you have to redefine your preferences, etc.? From marc.t.davies at gmail.com Mon Jun 12 09:07:12 2006 From: marc.t.davies at gmail.com (MTD) Date: 12 Jun 2006 06:07:12 -0700 Subject: Searching and manipulating lists of tuples Message-ID: <1150117632.693617.45310@c74g2000cwc.googlegroups.com> Hello, I'm wondering if there's a quick way of resolving this problem. In a program, I have a list of tuples of form (str,int), where int is a count of how often str occurs e.g. L = [ ("X",1),("Y",2)] would mean "X" occurs once and "Y" occurs twice If I am given a string, I want to search L to see if it occurs already. If it does, I find the corresponding tuple and increment the integer part. If not, I append the new element with int = 1. e.g. algorithm(L, "X") would produce output L = [("X",2),("Y",2)] algorithm(L,"Z") would produce L = [("X",1),("Y",2),("Z",1)] I tried to create an algorithm of the following form: >>> def algorith(list,str): ... flag = True ... for l in list: ... if l[0] == str: ... l[1] += 1 ... flag = False ... if flag: ... list.append((str,1)) ... But: >>> algorith(L,"X") gives: Traceback (most recent call last): File "", line 1, in ? File "", line 5, in algorith TypeError: object does not support item assignment So clearly that doesn't work... any ideas? From sjmachin at lexicon.net Mon Jun 26 20:37:48 2006 From: sjmachin at lexicon.net (John Machin) Date: Tue, 27 Jun 2006 10:37:48 +1000 Subject: 'r' vs 'rb' in csv (was Re: Python SHA-1 as a method for unique file identification ? [help!]) In-Reply-To: <1151354361.950035.274210@u72g2000cwu.googlegroups.com> References: <1150873779.832601.154920@b68g2000cwa.googlegroups.com> <1151354361.950035.274210@u72g2000cwu.googlegroups.com> Message-ID: <44a07ddc@news.eftel.com> On 27/06/2006 6:39 AM, Mike Orr wrote: > Tim Peters wrote: >> [EP ] >>> This inquiry may either turn out to be about the suitability of the >>> SHA-1 (160 bit digest) for file identification, the sha function in >>> Python ... or about some error in my script >> It's your script. Always open binary files in binary mode. It's a >> disaster on Windows if you don't (if you open a file in text mode on >> Windows, the OS pretends that EOF occurs at the first instance of byte >> chr(26) -- this is an ancient Windows behavior that made an odd kind >> of sense in the mists of history, and has persisted in worship of >> Backward Compatibility despite that the original reason for it went >> away _long_ ago). > > On a semi-related note, I have a database on Linux that imports from a > Macintosh CSV file. The 'csv' module says to always open files in > binary mode, but this didn't work in my case: I had to open it as 'rU' > (text with universal newlines) or 'csv' misparsed it. I'd like the > program to be portable to Windows and Mac. Is there a way around this? > Will I really burn in hell for using 'rU'? Yes, you will burn in hell for using any old kludge that gets results (by accident) instead of reading the manual to find a principled solution: """ lineterminator The string used to terminate lines in the CSV file. It defaults to '\r\n'. """ In the case of a Mac CSV file, '\r' is probably required. You will burn in hell for asking questions w/o supplying sufficient information, like (a) repr(first few lines of your Mac CSV file) (b) what was the result from the csv module ("didn't work" doesn't cut it). > > What was the odd bit of sense? I know you end console input by typing > ctrl-Z, but I thought it was just like Unix ctrl-D which ends the input > but doesn't actually insert that character. > Pace timbot, the "ancient Windows behavior" was inherited via MS-DOS from CP/M. Sectors on disk were 128 bytes. File sizes were recorded as numbers of sectors, not numbers of bytes. The convention was that the end of a text file was indicated by ^Z. You are correct, modern software shouldn't and usually doesn't gratuitously write ^Z to files, but there is is some software out there that still does, hence the preservation of the convention on reading. More importantly for CSV files, the data may contain *embedded* CRs and LFs that the users had in their spreadsheet file. Reading that with "r" or "rU" will certainly result in "didn't work". HTH, John From jes at nl.demon.net Thu Jun 1 19:15:17 2006 From: jes at nl.demon.net (Jim Segrave) Date: Thu, 01 Jun 2006 23:15:17 -0000 Subject: grouping a flat list of number by range References: <1149196642.001466.53990@c74g2000cwc.googlegroups.com> <1149201416.196975.123370@c74g2000cwc.googlegroups.com> <127urvnrbvjgr07@corp.supernews.com> <1149202780.780252.242110@f6g2000cwb.googlegroups.com> Message-ID: <127ut85lpcmoa5b@corp.supernews.com> In article <1149202780.780252.242110 at f6g2000cwb.googlegroups.com>, Paddy wrote: > >What I ran was more like the version below, but i did a quick >separation of the line that has the ';' in it and goofed. > >>>> def interv2(inlist): >... for i,val in enumerate(inlist): >... if i==0: >... tmp = val >... elif val != valinc: >... yield [tmp, valinc]; tmp = val >... valinc = val+1 >... yield [tmp, valinc] >... >>>> list(interv2(inlist)) >[[3, 4], [6, 9], [12, 14], [15, 16]] Fails on an empty list, as tmp is not defined when it hits the yield -- Jim Segrave (jes at jes-2.demon.nl) From lucaberto at libero.it Fri Jun 16 11:14:55 2006 From: lucaberto at libero.it (luca72) Date: 16 Jun 2006 08:14:55 -0700 Subject: Pycrypto In-Reply-To: <1150466793.537546.149690@p79g2000cwp.googlegroups.com> References: <1150446904.527285.255170@g10g2000cwb.googlegroups.com> <1150458752.342042.189650@h76g2000cwa.googlegroups.com> <1150462237.224431.213020@c74g2000cwc.googlegroups.com> <1150466793.537546.149690@p79g2000cwp.googlegroups.com> Message-ID: <1150470895.257327.302460@h76g2000cwa.googlegroups.com> Hello again i have solve doing this: from Crypto.Cipher import AES stri=(chr(int('9b',16))+chr(int('d3',16))+chr(int('2d',16))+chr(int('24',16))+chr(int('af',16))+chr(int('c9',16))+chr(int('e9',16))+chr(int('d7',16))+chr(int('46',16))+chr(int('69',16))+chr(int('71',16))+chr(int('32',16))+chr(int('45',16))+chr(int('5f',16))+chr(int('27',16))+chr(int('0b',16))) luca = str(stri) crypt = AES.new(luca, AES.MODE_ECB) testo=(chr(int('ea',16))+chr(int('52',16))+chr(int('3a',16))+chr(int('66',16))+chr(int('4d',16))+chr(int('ab',16))+chr(int('aa',16))+chr(int('44',16))+chr(int('76',16))+chr(int('d3',16))+chr(int('12',16))+chr(int('26',16))+chr(int('a1',16))+chr(int('e3',16))+chr(int('ba',16))+chr(int('b0',16))) testo = str(testo) c = crypt.encrypt(testo) I don't know if this is the best way , but anyway it work Regards Luca From deets at nospam.web.de Tue Jun 13 19:45:38 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 14 Jun 2006 01:45:38 +0200 Subject: question on dict subclassing and overriding __setitems__ In-Reply-To: References: Message-ID: <4f911aF12jediU1@uni-berlin.de> Eric S. Johansson schrieb: > I apologize if this is an FAQ but googling has not turned up anything, > at least to my keywords. > > I need to parse a configuration file from an existing application and > I'm treating it as a dictionary. I created my class with a parent class > of dict. Everything works okay except I discover I need to force keys > to uppercase when setting a value. > > I override __setitems__ and, as you'd expect, I get a recursive loop. > I'm obviously missing a clue on how to break the recursion. My > admittedly simpleminded method overloading looks like: > > def __setitem__ (self, index, value): > """force keys to uppercase""" > self[index.upper()] = value dict.__setitem__(self, index.upper()) = value Or better even super(subclass, self).__setitem__(key.upper(), value) DIez From steven.bethard at gmail.com Sun Jun 18 15:11:29 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 18 Jun 2006 13:11:29 -0600 Subject: aligning SGML to text Message-ID: I have some plain text data and some SGML markup for that text that I need to align. (The SGML doesn't maintain the original whitespace, so I have to do some alignment; I can't just calculate the indices directly.) For example, some of my text looks like: TNF binding induces release of AIP1 (DAB2IP) from TNFR1, resulting in cytoplasmic translocation and concomitant formation of an intracellular signaling complex comprised of TRADD, RIP1, TRAF2, and AIPl. And the corresponding SGML looks like: TNF binding induces release of AIP1 ( DAB2IP ) from TNFR1 , resulting in cytoplasmic translocation and concomitant formation of an intracellular signaling complex comprised of TRADD , RIP1 , TRAF2 , and AIPl . Note that the SGML inserts spaces not only within the SGML elements, but also around punctuation. I need to determine the indices in the original text that each SGML element corresponds to. Here's some working code to do this, based on a suggestion for a related problem by Fredrik Lundh[1]:: def align(text, sgml): sgml = sgml.replace('&', '&') tree = etree.fromstring('%s' % sgml) words = [] if tree.text is not None: words.extend(tree.text.split()) word_indices = [] for elem in tree: elem_words = elem.text.split() start = len(words) end = start + len(elem_words) word_indices.append((start, end, elem.tag)) words.extend(elem_words) if elem.tail is not None: words.extend(elem.tail.split()) expr = '\s*'.join('(%s)' % re.escape(word) for word in words) match = re.match(expr, text) assert match is not None for word_start, word_end, label in word_indices: start = match.start(word_start + 1) end = match.end(word_end) yield label, start, end >>> text = '''TNF binding induces release of AIP1 (DAB2IP) from TNFR1, resulting in cytoplasmic translocation and concomitant formation of an intracellular signaling complex comprised of TRADD, RIP1, TRAF2, and AIPl.''' >>> sgml = ''' TNF binding induces release of AIP1 ( DAB2IP ) from TNFR1 , resulting in cytoplasmic translocation and concomitant formation of an intracellular signaling complex comprised of TRADD , RIP1 , TRAF2 , and AIPl . ''' >>> list(align(text, sgml)) [('PROTEIN', 0, 3), ('PROTEIN', 31, 35), ('PROTEIN', 37, 43), ('PROTEIN', 50, 55), ('PROTEIN', 128, 159), ('PROTEIN', 173, 178), ('PROTEIN', 180, 184), ('PROTEIN', 186, 191)] The problem is, this doesn't work when my text is long (which it is) because regular expressions are limited to 100 groups. I get an error like:: Traceback (most recent call last): ... AssertionError: sorry, but this version only supports 100 named groups I also played around with difflib.SequenceMatcher for a while, but couldn't get a solution based on that working. Any suggestions? [1]http://mail.python.org/pipermail/python-list/2005-December/313388.html Thanks, STeVe From andrewdalke at gmail.com Mon Jun 19 19:39:25 2006 From: andrewdalke at gmail.com (andrewdalke at gmail.com) Date: 19 Jun 2006 16:39:25 -0700 Subject: Seeking regex optimizer In-Reply-To: References: <1150650439.651839.38180@y41g2000cwy.googlegroups.com> <1150750294.232093.304230@p79g2000cwp.googlegroups.com> Message-ID: <1150760365.168277.171940@p79g2000cwp.googlegroups.com> Replying to me Mirco Wahab wrote: > If you pull the strings into (?>( ... )) (atomic groups), > this would't happen. Given that Python's re engine doesn't support this feature it doesn't really help the original poster's problem. Even if some future Python did support it, the limit to 100 named groups is unaffected by backtracking. >>> import re >>> re.compile("(.)"*100) Traceback (most recent call last): File "", line 1, in ? File "/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/sre.py", line 180, in compile return _compile(pattern, flags) File "/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/sre.py", line 225, in _compile p = sre_compile.compile(pattern, flags) File "/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/sre_compile.py", line 506, in compile raise AssertionError( AssertionError: sorry, but this version only supports 100 named groups >>> There was no backtracking in "(.)"*100. Andrew dalke at dalkescientific.com From yan at NsOeSiPnAeMr.com Thu Jun 1 17:04:40 2006 From: yan at NsOeSiPnAeMr.com (Captain Dondo) Date: Thu, 01 Jun 2006 14:04:40 -0700 Subject: Replace one element of a tuple Message-ID: <127ulhn6h7hvj22@corp.supernews.com> I have an array(?) (sorry, I'm new* to python so I'm probably mangling the terminology) that looks like this: [((1028L, datetime.datetime(2006, 5, 30, 7, 0), datetime.datetime(2006, 5, 30, 7, 30), 'Arthur', 'Prunella Sees the Light; Return of the Snowball', 'Prunella prepares for a sleepover with Marina; D.W. protects a snowball.', 'Children', 'tooth.seiner.lan', None, 0L, None, 1L, 1L, 'Default', 9L, 'SH044107', 'EP0441070123', datetime.datetime(2006, 5, 30, 7, 31, 24), 1164179392L, 0.0, 1, datetime.date(2002, 11, 28), 0, 0L, 0),), ((1028L, datetime.datetime(2006, 5, 4, 10, 0), datetime.datetime(2006, 5, 4, 10, 30), 'Bob the Builder', 'Using Clues', '', 'Children', 'tooth.seiner.lan', None, 0L, None, 1L, 1L, 'Default', 6L, 'SH326087', 'EP3260870141', datetime.datetime(2006, 5, 4, 10, 31, 30), 1163673536L, 0.0, 1, datetime.date(2005, 3, 19), 0, 0L, 0),)] I want to replace every instance of 'tooth.seiner.lan' with 'localhost'. There may be lots and lots of these entries (they're pulled from my mythtv database). I could brute-force this by rewriting the whole thing and replacing every 9th element but there has to be a better way.... I've looked at various search-and-replace snippets but none that address what I am trying to do.... --Yan *I'm not really new to python, just very very rusty. Last time I used it was about 3 years ago, and I was equally clueless.... From diffuser78 at gmail.com Wed Jun 28 11:59:54 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 28 Jun 2006 08:59:54 -0700 Subject: String Question In-Reply-To: <1151509682.897441.165480@y41g2000cwy.googlegroups.com> References: <1151508909.273667.270910@x69g2000cwx.googlegroups.com> <1151509682.897441.165480@y41g2000cwy.googlegroups.com> Message-ID: <1151510394.859964.146260@j72g2000cwa.googlegroups.com> I will try this one too...thanks for your response. Iain King wrote: > diffuser78 at gmail.com wrote: > > mac_string = '001485e55503' (This is the mac address of a computer.) > > > > I am using wake on LAN python script to start computer remote.It uses > > format like this .... > > > > s.sendto('\xff'*6 + '\x00\x014\x85\xe5\x55\x03'*16, ('192.168.1.255', > > 80)) > > > > where '\x00\x14\x85\xe5\x55\x03' is the MAC address to be used. > > > > > > What I do is break the string into 6 parts like this, > > > > str01=mac_string[0:2] > > str02=mac_string[2:4] > > str03=mac_string[4:6] > > str04=mac_string[6:8] > > str05=mac_string[8:10] > > str06=mac_string[10:12] > > > > and if I use it like this > > > > s.sendto('\xff'*6 + '\xstr01\xstr02\xstr03\xstr04\xstr05\xstr06'*16, > > ('192.168.1.255', 80)) > > I get an error > > > > > > I also tried like this > > s.sendto('\xff'*6 + 'mac_string'*16, ('192.168.1.255', 80)) > > > > Thiis also didnt work. > > > > > > Since the MAC adddress are hexadecimal, how should I go about it here. > > > > Please help, every help is appreciated. Thanks > > See http://docs.python.org/lib/typesseq-strings.html > > You probably want: > > s.sendto('\xff'*6 + ('\x%s\x%s\x%s\x%s\x%s\x%s' % (str01, str02, str03, > sttr04, str05, str06))*16, ('192.168.1.255', 80)) > > Iain From chris.lasher at gmail.com Thu Jun 15 17:11:39 2006 From: chris.lasher at gmail.com (Chris Lasher) Date: 15 Jun 2006 14:11:39 -0700 Subject: Regular expression for not-group Message-ID: <1150405899.027971.256160@r2g2000cwb.googlegroups.com> Is it possible to write a regular expression such that a "match" is found provided the string does not match a group in the regex? Let me give a concrete example. Suppose I want to find a match to any filename that does not end in .py, (ignoring the obvious use of the .endswith('.py') string method). I tried the things that were obvious to me, none of which worked. \.^(py) \.(^py) \.[^p][^y] The last one deceived me at first because it will match "spam.spam", but not "spam.parrot". I'm a bit stumped at this point. If this can be done with a regular expression, I'd love to know how, and even if it can't be, that would be very helpful to know, too. Many thanks in advance, Chris From ftc at chez.com Thu Jun 15 06:59:52 2006 From: ftc at chez.com (ftc) Date: Thu, 15 Jun 2006 12:59:52 +0200 Subject: Database read and write In-Reply-To: References: Message-ID: <44913d77$0$25186$626a54ce@news.free.fr> Stan Cook a ?crit : > Ok . I know I'm talking ancient history, but some of us are stuck > working with them. Is there anything for python which will ope, read, > and write to a Dbase 3 or 4 file? I really need your assistance on this > one. If you work on Windows, there are dbf odbc drivers installed so you can access your dbf files through ODBC driver I think. From john106henry at hotmail.com Fri Jun 30 23:33:51 2006 From: john106henry at hotmail.com (John Henry) Date: 30 Jun 2006 20:33:51 -0700 Subject: Concatenating strings Message-ID: <1151724830.900116.225960@m79g2000cwm.googlegroups.com> Sorry if this is a dumb question. I have a list of strings (some 10,000+) and I need to concatenate them together into one very long string. The obvious method would be, for example: alist=["ab","cd","ef",.....,"zzz"] blist = "" for x in alist: blist += x But is there a cleaner and faster way of doing this? Thanks, From maxerickson at gmail.com Sun Jun 18 19:42:50 2006 From: maxerickson at gmail.com (Max Erickson) Date: Sun, 18 Jun 2006 23:42:50 +0000 (UTC) Subject: mapping None values to '' References: <1150632320.443681.42640@r2g2000cwb.googlegroups.com> <0Rblg.5940$zy5.141663@twister1.libero.it> <1908cb6b0606181400y39c2c50dw138ed17825a8534d@mail.gmail.com> Message-ID: "Roberto Bonvallet" wrote: > You don't need map when using list comprehensions: > > ["" for i in [a, b, c] if i in ("None", None)] > That loses list elements that aren't in the tests: >>> a=7 >>> b="None" >>> c=None >>> ["" for i in [a,b,c] if i in ("None",None)] ['', ''] >>> max From serge.orlov at gmail.com Tue Jun 27 18:11:38 2006 From: serge.orlov at gmail.com (Serge Orlov) Date: Tue, 27 Jun 2006 15:11:38 -0700 Subject: Python UTF-8 and codecs In-Reply-To: References: <5Hgog.627$Gv.173@fed1read09> Message-ID: On 6/27/06, Mike Currie wrote: > Okay, > > Here is a sample of what I'm doing: > > > Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)] on > win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> filterMap = {} > >>> for i in range(0,255): > ... filterMap[chr(i)] = chr(i) > ... > >>> filterMap[chr(9)] = chr(136) > >>> filterMap[chr(10)] = chr(133) > >>> filterMap[chr(136)] = chr(9) > >>> filterMap[chr(133)] = chr(10) This part is incorrect, it should be: filterMap = {} for i in range(0,128): filterMap[chr(i)] = chr(i) filterMap[chr(9)] = unichr(136) filterMap[chr(10)] = unichr(133) filterMap[unichr(136)] = chr(9) filterMap[unichr(133)] = chr(10) From onurb at xiludom.gro Wed Jun 28 06:19:13 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Wed, 28 Jun 2006 12:19:13 +0200 Subject: [Pyrex] pyrex functions to replace a method (Re: replace a method in class: how?) In-Reply-To: References: <44A06A6B.6010200@bryant.edu> <44A11564.9030009@bryant.edu> Message-ID: <44a257a2$0$28763$626a54ce@news.free.fr> Greg Ewing wrote: > Brian Blais wrote: > >> I have found a very similar problem trying to replace a method using a >> function defined in pyrex. > > > Functions defined in Pyrex are C-implemented functions, > which don't trigger the method binding magic when you > access them through a class. The same thing happens if > you try to use a built-in function as a method. > > What *should* work is to define the method inside a > class in Pyrex (plain class, not extension type) and > extract it out of the class's __dict__. That's because > Pyrex pre-wraps a function defined in a class in an > unbound method object before putting it in the class. Or write the needed descriptor and wrap the function in (Q&D, needs a lot of improvements): def CFuncWrapper(func, instance): def _wrappedCFunc(*args, **kw): return func(instance, *args, **kw) return _wrappedCFunc class CFuncMethodType(object): def __init__(self, func): self.func = func def __get__(self, instance, cls=None): if instance: return CFuncWrapper(self.func, instance) else: assert(cls is not None) return self.func >>> class Foo(object): pass ... >>> Foo.isa = CFuncMethodType(isinstance) >>> Foo.isa(Foo(), Foo) True >>> f.isa(list) False >>> f.isa(Foo) True >>> -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From fperez.net at gmail.com Wed Jun 7 01:46:07 2006 From: fperez.net at gmail.com (Fernando Perez) Date: Tue, 06 Jun 2006 23:46:07 -0600 Subject: IPython 0.7.2 is out. Message-ID: Hi all, The IPython team is happy to release version 0.7.2, with a lot of new enhancements, as well as many bug fixes. We hope you all enjoy it, and please report any problems as usual. WHAT is IPython? ---------------- 1. An interactive shell superior to Python's default. IPython has many features for object introspection, system shell access, and its own special command system for adding functionality when working interactively. 2. An embeddable, ready to use interpreter for your own programs. IPython can be started with a single call from inside another program, providing access to the current namespace. 3. A flexible framework which can be used as the base environment for other systems with Python as the underlying language. 4. A shell for interactive usage of threaded graphical toolkits. IPython has support for interactive, non-blocking control of GTK, Qt and WX applications via special threading flags. The normal Python shell can only do this for Tkinter applications. Where to get it --------------- IPython's homepage is at: http://ipython.scipy.org and downloads are at: http://ipython.scipy.org/dist We've provided: - Source download (.tar.gz) - An RPM (for Python 2.4, built under Ubuntu Dapper 6.06). - A Python Egg (http://peak.telecommunity.com/DevCenter/PythonEggs). - A native win32 installer. The egg is 'light', as it doesn't include documentation and other ancillary data. If you want a full ipython installation, use the source tarball or your distribution's favorite system. We note that IPython is now officially part of most major Linux and BSD distributions, so packages for this version should be coming soon, as the respective maintainers have the time to follow their packaging procedures. Many thanks to Jack Moffit, Norbert Tretkowski, Andrea Riciputi, Dryice Liu and Will Maier for the packaging work, which helps users get IPython more conveniently. Many thanks to Enthought for their continued hosting support for IPython. Release notes ------------- As always, the full ChangeLog is at http://ipython.scipy.org/ChangeLog. The highlights of this release follow. Also see the "What's New" page at http://projects.scipy.org/ipython/ipython/wiki/WhatsNew for more details on some of these features. * Walter Doerwald's ipipe module, which provides a handy way to browse and manipulate tabular data, e.g. groups of files or environment variables (this is currently mostly a *nix feature, due to its need for ncurses). Walter is now a member of the IPython team. * The IPython project is the new home for the UNC readline extension, which allows win32 users to access readline facilities (tab completion, colored prompts, and more). UNC readline has been renamed PyReadline, and has a number of important new features, especially for users of non-US keyboards. See this page for more details: http://projects.scipy.org/ipython/ipython/wiki/PyReadline/Intro * A new extension and configuration API. * Hardened persistence. Persistence of data now uses "pickleshare", a shelve-like module that allows concurrent access to the central ipython database by multiple ipython instances. * Simpler output capture: "files=!ls" will now capture the 'ls' call into the 'files' variable. * New magic functions: %timeit, %upgrade, %quickref, %cpaste, %clip, %clear. Also, a 'raw' mode has been added to %edit, %macro, %history. * Batch files. If the file ends with .ipy, you can launch it by "ipython myfile.ipy". It will be executed as if it had been typed interactively (it can contain magics, aliases, etc.) * New pexpect-based 'irunner' module, to run scripts and produce all the prompts as if they had been typed one by one. This lets you reproduce a complete interactive session from a file, which can be very useful when producing documentation, for example. The module provides default runners for ipython, plain python and SAGE (http://sage.scipy.org). Users can subclass the base runner to produce new ones for any interactive system whose prompts are predictable (such as gnuplot, a system shell, etc.). * New option to log 'raw' input into IPython's logs. The logs will then be valid .ipy batch scripts just as you typed them, instead of containing the converted python source. * Fixes and improvements to (X)Emacs support. PDB auto-tracking is back (it had broken in 0.7.1, and auto-indent now works inside emacs ipython buffers. You will need to update your copy of ipython.el, which you can get from the doc/ directory. A copy is here, for convenience: http://ipython.scipy.org/dist/ipython.el * The ipapi system offers a new to_user_ns() method in the IPython object, to inject variables from a running script directly into the user's namespace. This lets you have internal variables from a script visible interactively for further manipulation after %running it. * Thanks to Will Maier, IPython is now officially part of OpenBSD ports. * A number of threading deadlock fixes. This is of particular interest to matplotlib users. * Compatibility updates with current Gnuplot.py. * We now are (finally! * Various other small fixes and enhancements. See the full ChangeLog for details. Enjoy, and as usual please report any problems. The IPython team. From quentel.pierre at wanadoo.fr Sun Jun 25 04:53:57 2006 From: quentel.pierre at wanadoo.fr (Pierre Quentel) Date: 25 Jun 2006 01:53:57 -0700 Subject: Can you help me with the below code? Urgent! In-Reply-To: <1151224178.479401.119620@r2g2000cwb.googlegroups.com> References: <1151224178.479401.119620@r2g2000cwb.googlegroups.com> Message-ID: <1151225637.492538.122890@p79g2000cwp.googlegroups.com> This is because in "states" you store a reference to frame.f_locals, not the value it takes. When you print states, all the items are the same reference to the same object and have the same value If you want to store the values at each cycle you should store a copy of frame.f_locals, which will give you a different object After import sys add the line : import copy and instead of states.append(frame.f_locals) write states.append(copy.copy(frame.f_locals)) Another example of this side-effect of storing references and not values : Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> states = [] >>> x = [0] >>> for i in range(10): ... x[0] = i ... states.append(x) ... >>> print states [[9], [9], [9], [9], [9], [9], [9], [9], [9], [9]] >>> Pierre From a at tempinbox.com Mon Jun 26 14:58:23 2006 From: a at tempinbox.com (a) Date: 26 Jun 2006 11:58:23 -0700 Subject: psyco+webpy Message-ID: <1151348303.344822.18720@u72g2000cwu.googlegroups.com> hi i tried psyco+webpy here is the error that i got please let me know if any of you has success run psyco+webpy thanks import web, psyco urls = ( '/', 'view', '/add','add' ) psyco.full() psyco.log() psyco.profile() Launching server: http://0.0.0.0:8080/ Traceback (most recent call last): File "C:\Python24\lib\site-packages\web.py", line 2054, in run_wsgi_app result = self.server.app(env, self.wsgi_start_response) File "C:\Python24\lib\site-packages\web.py", line 1894, in wsgifunc result = func() File "C:\Python24\lib\site-packages\web.py", line 1872, in func = lambda: handle(getattr(mod, name), mod) File "C:\Python24\lib\site-packages\web.py", line 1051, in handle return tocall(*([urllib.unquote(x) for x in args] + fna)) File "C:\mark\web1\codepsyco.py", line 27, in GET web.render('view.html') File "C:\Python24\lib\site-packages\web.py", line 1707, in render terms.update(sys._getframe(1).f_locals) File "C:\Python24\Lib\site-packages\psyco\support.py", line 129, in __getattr_ _ raise AttributeError, ("local variables of functions run by Psyco " AttributeError: local variables of functions run by Psyco cannot be accessed in any way, sorry Traceback (most recent call last): File "C:\Python24\lib\SocketServer.py", line 463, in process_request_thread self.finish_request(request, client_address) File "C:\Python24\lib\SocketServer.py", line 254, in finish_request self.RequestHandlerClass(request, client_address, self) File "C:\Python24\lib\SocketServer.py", line 521, in __init__ self.handle() File "C:\Python24\lib\BaseHTTPServer.py", line 316, in handle self.handle_one_request() File "C:\Python24\lib\BaseHTTPServer.py", line 310, in handle_one_request method() File "C:\Python24\lib\site-packages\web.py", line 2090, in do_GET self.run_wsgi_app() File "C:\Python24\lib\site-packages\web.py", line 2072, in run_wsgi_app internalerror() File "C:\Python24\lib\site-packages\web.py", line 1601, in debugerror out = str(djangoerror()) File "C:\Python24\lib\site-packages\web.py", line 1587, in djangoerror return render(DJANGO_500_PAGE, asTemplate=True, isString=True) File "C:\Python24\lib\site-packages\web.py", line 1707, in render terms.update(sys._getframe(1).f_locals) File "C:\Python24\Lib\site-packages\psyco\support.py", line 129, in __getattr_ _ raise AttributeError, ("local variables of functions run by Psyco " AttributeError: local variables of functions run by Psyco cannot be accessed in any way, sorry From onurb at xiludom.gro Thu Jun 22 04:17:05 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Thu, 22 Jun 2006 10:17:05 +0200 Subject: Is it possible to split a class definition? In-Reply-To: <1150927868.807640.45760@c74g2000cwc.googlegroups.com> References: <1150927868.807640.45760@c74g2000cwc.googlegroups.com> Message-ID: <449a5202$0$19831$626a54ce@news.free.fr> jerry.levan at gmail.com wrote: > Hi, > > Is it possible to split a Class definition over two or more text files? Yes, but not directly. Could you tell us why you think you have such a need ? > (if so, how:) Please answer my previous question first !-) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From aleax at mac.com Wed Jun 14 10:59:04 2006 From: aleax at mac.com (Alex Martelli) Date: Wed, 14 Jun 2006 07:59:04 -0700 Subject: "groupby" is brilliant! References: <1150180151.643245.148210@y43g2000cwc.googlegroups.com> <1150267850.745328.281240@i40g2000cwc.googlegroups.com> Message-ID: <1hgwvx5.1xwye5mw9qm1hN%aleax@mac.com> Frank Millman wrote: > Benji York wrote: > > Frank Millman wrote: > > > reader = csv.reader(open('trans.csv', 'rb')) > > > rows = [] > > > for row in reader: > > > rows.append(row) > > > > Why do you create a list of rows instead of just iterating over the > > reader directly? > > -- > > Benji York > > A - didn't think of it - good idea > > B - can't always do it - > B1 - if the file is not sorted, I have to sort the rows first > B2 - if I need to update the file, I can modify the rows in place, and > then call > csv.writer(open('trans.csv','wb')).writerows(rows) > > BTW, I know that B2 is simplistic - to be safe I should rename, then > write, then unlink. I will do that for production code. > > BTW2, an alternative to B2 is > reader = csv.reader(open('trans.csv', 'rb')) > newtrans = open('newtrans.csv','wb') > writer = csv.writer(newtrans) > for row in reader: > [process and modify row] > writer.writerow(row) > newtrans.close() > [unlink and rename] > > Could be useful if the file is large. Food for thought. BTW, if and when you do need a list for some other purpose, rows = list(reader) may be slightly better than the for/append loop; and if you need a sorted list, perhaps rows = sorted(reader) similarly. Alex From fredrik at pythonware.com Wed Jun 28 03:43:51 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 28 Jun 2006 09:43:51 +0200 Subject: global name is not defined - error - but for array References: <1151471317.328398.132670@x69g2000cwx.googlegroups.com> Message-ID: "a" wrote: > def fn(): > for i in range(l) > global count > count[i]= .... > > how do i declare count to be global if it is an array a couple of notes: 1) global statements should be placed at the top of the function 2) objects don't appear out of nowhere; you need to initialize the "count" list before you can assign stuff to it. this is what causes the exception; the global statement has nothing to do with that. 3) it's called "list" on Python, not "array". 4) if you read the tutorial, you'll learn better ways to loop over lists, and build new lists. see the chapters "An Informal Introduction to Python", "More Control Flow Tools", and "Data Structures". 5) posting one copy of your question is enough; if you feel that you want to try out different subject lines, do that for yourself, before posting your message to the list. 6) this list isn't hosted by googlegroups, so cancelling a post in googlegroups doesn't mean that other people won't see it. there's a world outside google too, you know... From fredrik at pythonware.com Sat Jun 10 15:11:52 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 10 Jun 2006 21:11:52 +0200 Subject: Killing a thread In-Reply-To: <1149965895.702667.3970@u72g2000cwu.googlegroups.com> References: <7c8a9a970606091338t174fbcb0wc73cdb8b385f8ccd@mail.gmail.com> <7c8a9a970606091354u73308bf8o2758eea5ef690c39@mail.gmail.com> <1149889827.2754.6.camel@kenshin.CASA> <448A0D8A.4000008@mvista.com> <1149965895.702667.3970@u72g2000cwu.googlegroups.com> Message-ID: crazymykl at gmail.com wrote: >> it cannot be done in a portable way, so that's not very likely. > def __run(self): > """Hacked run function, which installs the trace.""" > sys.settrace(self.globaltrace) > self.__run_backup() > self.run = self.__run_backup I'm not sure using a non-portable API to run the code under a "custom debugger" qualifies as a "portable implementation", though... have you benchmarked this, btw? From iainking at gmail.com Mon Jun 5 10:28:40 2006 From: iainking at gmail.com (Iain King) Date: 5 Jun 2006 07:28:40 -0700 Subject: Large Dictionaries In-Reply-To: References: <1147699064.107490@teuthos> <1147772420.405097@teuthos> <1147818548.532882.94180@i39g2000cwa.googlegroups.com> <1147874585.728471@teuthos> <1148514158.790760.205630@i40g2000cwc.googlegroups.com> <447af556$1@nntp0.pdx.net> Message-ID: <1149517720.086866.3510@j55g2000cwa.googlegroups.com> Lawrence D'Oliveiro wrote: > In article <447af556$1 at nntp0.pdx.net>, > Scott David Daniels wrote: > > >For example, time timsort (Python's internal sort) on pre-sorted > >data; you'll find it is handled faster than random data. > > But isn't that how a reasonable sorting algorithm should behave? Less > work to do if the data is already sorted? An already sorted list can be pathological for Quicksort, depending on how you code it. Iain From michaelcthompson at gmail.com Tue Jun 13 04:46:39 2006 From: michaelcthompson at gmail.com (Mike T) Date: 13 Jun 2006 01:46:39 -0700 Subject: Python 411. In-Reply-To: <1150152755.474292.39010@j55g2000cwa.googlegroups.com> References: <1150152755.474292.39010@j55g2000cwa.googlegroups.com> Message-ID: <1150188399.809316.172840@f14g2000cwb.googlegroups.com> What exactly is 411 in this context? A reference to higher education perhaps? Or perhaps part of the American constitution? What exactly? Also for that matter what is 101? Cheers, Mike From rschroev_nospam_ml at fastmail.fm Sat Jun 17 14:36:41 2006 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sat, 17 Jun 2006 18:36:41 GMT Subject: Which compiler will Python 2.5 / Windows (Intel) be built with? In-Reply-To: <4494424f$1@nntp0.pdx.net> References: <1150367139.495114.148550@g10g2000cwb.googlegroups.com> <44917535$1@nntp0.pdx.net> <1150391891.130185.4640@f6g2000cwb.googlegroups.com> <4492414C.10505@v.loewis.de> <1150444191.618761.22810@c74g2000cwc.googlegroups.com> <4494424f$1@nntp0.pdx.net> Message-ID: Scott David Daniels schreef: > Roel Schroeven wrote: >> Isn't Python for other platforms built with GCC? Seems to me that if it >> GCC is good enough for other platforms, it's good enough for Windows. > > You clearly misunderstand the interface to the Windows OS & GUI system. Very well possible. > Microsoft provides that interface through its language systems, and has > used that edge to knock off other compilers (such as WatCom) by > providing header files that are not standard C compatible. It seems that many people successfully use mingw. At work I use a Borland compiler all the time, without compatibility problems with Windows' APIs. But what I meant was not related to interface compatibilities, but to the performance of the generated code: many people say that the code generated by gcc is not as well optimized as code generated by Microsoft's compilers. Yet I never hear complaints about that from people who use Python on e.g. Linux, where Python is compiled with gcc. So, while there might be valid reasons not to use mingw, as far as I can see the optimization capabilities of the compiler are not a compelling reason. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From cdsmith at twu.net Thu Jun 22 22:31:01 2006 From: cdsmith at twu.net (Chris Smith) Date: Thu, 22 Jun 2006 20:31:01 -0600 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> Message-ID: Anton van Straaten wrote: > Vesa Karvonen wrote: > > > > This static vs dynamic type thing reminds me of one article written by > > Bjarne Stroustrup where he notes that "Object-Oriented" has become a > > synonym for "good". More precisely, it seems to me that both camps > > (static & dynamic) think that "typed" is a synonym for having > > "well-defined semantics" or being "safe" and therefore feel the need > > to be able to speak of their language as "typed" whether or not it > > makes sense. > > I reject this comparison. There's much more to it than that. I agree that there's more to it than that. I also agree, however, that Vesa's observation is true, and is a big part of the reason why it's difficult to discuss this topic. I don't recall who said what at this point, but earlier today someone else posted -- in this same thread -- the idea that static type "advocates" want to classify some languages as untyped in order to put them in the same category as assembly language programming. That's something I've never seen, and I think it's far from the goal of pretty much anyone; but clearly, *someone* was concerned about it. I don't know if much can be done to clarify this rhetorical problem, but it does exist. The *other* bit that's been brought up in this thread is that the word "type" is just familiar and comfortable for programmers working in dynamically typed languages, and that they don't want to change their vocabulary. The *third* thing that's brought up is that there is a (to me, somewhat vague) conception going around that the two really ARE varieties of the same thing. I'd like to pin this down more, and I hope we get there, but for the time being I believe that this impression is incorrect. At the very least, I haven't seen a good way to state any kind of common definition that withstands scrutiny. There is always an intuitive word involved somewhere which serves as an escape hatch for the author to retain some ability to make a judgement call, and that of course sabotages the definition. So far, that word has varied through all of "type", "type error", "verify", and perhaps others... but I've never seen anything that allows someone to identify some universal concept of typing (or even the phrase "dynamic typing" in the first place) in a way that doesn't appeal to intuition. > The point > is that the reasoning which programmers perform when working with an > program in a latently-typed language bears many close similiarities to > the purpose and behavior of type systems. Undoubtedly, some programmers sometimes perform reasoning about their programs which could also be performed by a static type system. This is fairly natural, since static type systems specifically perform tractable analyses of programs (Pierce even uses the word "tractable" in the definition of a type system), and human beings are often (though not always) best-served by trying to solve tractable problems as well. > There are reasons to connect > it to type theory, and if you can't see those reasons, you need to be > more explicit about why. Let me pipe up, then, as saying that I can't see those reasons; or at least, if I am indeed seeing the same reasons that everyone else is, then I am unconvinced by them that there's any kind of rigorous connection at all. > I'm suggesting that if a language classifies and tags values in a way > that supports the programmer in static reasoning about the behavior of > terms, that calling it "untyped" does not capture the entire picture, > even if it's technically accurate in a restricted sense (i.e. in the > sense that terms don't have static types that are known within the > language). It is, nevertheless, quite appropriate to call the language "untyped" if I am considering static type systems. I seriously doubt that this usage in any way misleads anyone into assuming the absence of any mental processes on the part of the programmer. I hope you agree. If not, then I think you significantly underestimate a large category of people. > The first point I was making is that *automated* checking has very > little to do with anything, and conflating static types with automated > checking tends to lead to a lot of confusion on both sides of the > static/dynamic fence. I couldn't disagree more. Rather, when you're talking about static types (or just "types" in most research literature that I've seen), then the realm of discussion is specifically defined to be the very set of errors that are automatically caught and flagged by the language translator. I suppose that it is possible to have an unimplemented type system, but it would be unimplemented only because someone hasn't felt the need nor gotten around to it. Being implementABLE is a crucial part of the definition of a static type system. I am beginning to suspect that you're make the converse of the error I made earlier in the thread. That is, you may be saying things regarding the psychological processes of programmers and such that make sense when discussing dynamic types, and in any case I haven't seen any kind of definition of dynamic types that is more acceptable yet; but it's completely irrelevant to static types. Static types are not fuzzy -- if they were fuzzy, they would cease to be static types -- and they are not a phenomenon of psychology. To try to redefine static types in this way not only ignores the very widely accepted basis of entire field of existing literature, but also leads to false ideas such as that there is some specific definable set of problems that type systems are meant to solve. Skipping ahead a bit... > I agree, to make the comparison perfect, you'd need to define a type > system. But that's been done in various cases. I don't think that has been done, in the case of dynamic types. It has been done for static types, but much of what you're saying here is in contradiction to the definition of a type system in that sense of the word. > The problem we're dealing with in this case is that anything that's not > formally defined is essentially claimed to not exist. I see it as quite reasonable when there's an effort by several participants in this thread to either imply or say outright that static type systems and dynamic type systems are variations of something generally called a "type system", and given that static type systems are quite formally defined, that we'd want to see a formal definition for a dynamic type system before accepting the proposition that they are of a kind with each other. So far, all the attempts I've seen to define a dynamic type system seem to reduce to just saying that there is a well- defined semantics for the language. I believe that's unacceptable for several reasons, but the most significant of them is this. It's not reasonable to ask anyone to accept that static type systems gain their essential "type system-ness" from the idea of having well-defined semantics. From the perspective of a statically typed language, this looks like a group of people getting together and deciding that the real "essence" of what it means to be a type system is... and then naming something that's so completely non- essential that we don't generally even mention it in lists of the benefits of static types, because we have already assumed that it's true of all languages except C, C++, and assembly language. -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation From robert.thorpe at antenova.com Thu Jun 22 11:35:55 2006 From: robert.thorpe at antenova.com (Rob Thorpe) Date: 22 Jun 2006 08:35:55 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <7zpshbsvjy.fsf@app-1.diku.dk><4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <1150902019.850531.204740@g10g2000cwb.googlegroups.com> <1150910976.455179.55870@r2g2000cwb.googlegroups.com> Message-ID: <1150990555.368011.48350@b68g2000cwa.googlegroups.com> Dr.Ruud wrote: > Rob Thorpe schreef: > > Dr.Ruud: > >> Marshall: > > >>> "dynamic types." I don't have a firm definition for > >>> that term, but my working model is runtime type tags. In which > >>> case, I would say that among statically typed languages, > >>> Java does have dynamic types, but C does not. C++ is > >>> somewhere in the middle. > >> > >> C has union. > > > > That's not the same thing. > > That is your opinion. In the context of this discussion I don't see any > problem to put C's union under "dynamic types". Lets put it like this:- 1. In C++ and Java it is possible to make a variable that can A)Take on many different types and B)Where the programmer can test what the type is. 2. In C it is possible to make a variable that can do 1A but not 1B. This is a statement of fact, not opinion. I call languages that do #1 dynamically typed, in line with common usage. > > The value of a union in C can be any of a > > set of specified types. But the program cannot find out which, and > > the language doesn't know either. > > > > With C++ and Java dynamic types the program can test to find the type. > > When such a test is needed for the program with the union, it has it. What do you mean? There is no way to test the type of the value inside a union in C. From rogue_pedro at yahoo.com Thu Jun 29 12:36:19 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 29 Jun 2006 09:36:19 -0700 Subject: Bug reporting impossible References: Message-ID: <1151598979.369897.140770@x69g2000cwx.googlegroups.com> Nick Maclaren wrote: ... > Create a file called '' in your current directory containing > 'print "Oh, yeah?\n"' and then import a module that doesn't exist. > Don't include the single quotes. Why would you have a file named '' in your current directory? ~Simon From michael at araneidae.co.uk.invalid Fri Jun 30 15:32:41 2006 From: michael at araneidae.co.uk.invalid (Michael Abbott) Date: Fri, 30 Jun 2006 20:32:41 +0100 Subject: Module executed twice when imported! References: <1151534230.603274.144810@x69g2000cwx.googlegroups.com> <05epg.2385$No6.49436@news.tufts.edu> Message-ID: In article <05epg.2385$No6.49436 at news.tufts.edu>, John Salerno wrote: > > (http://docs.python.org/lib/built-in-funcs.html#l2h-24) > > "It is different from the import statement in that it does not use the > > module administration --" > > Just after the above statement, it also says: > > "it reads the file unconditionally and does not create a new module." > > so perhaps that means that it isn't really being imported the second > time, just that the contents are being executed? Interesting thought. I'm not convinced, though: firstly, I read that statement as describing what happens to the file named in the execfile() statement; and secondly, the problem *only* happens if the global dictionary passed to execfile() has a '__name__' and if the value of that key is sufficiently close to the name of the file being passed to execfile(). I found that passing __name__='whatever' resulted in normal import behaviour, and so does __name__='subtest', but curiously enough passing __name__='subtest.' results in the double import. From onurb at xiludom.gro Wed Jun 28 06:36:53 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Wed, 28 Jun 2006 12:36:53 +0200 Subject: a class variable question In-Reply-To: <1151474768.546012.254380@p79g2000cwp.googlegroups.com> References: <1151474768.546012.254380@p79g2000cwp.googlegroups.com> Message-ID: <44a25bc6$0$29790$626a54ce@news.free.fr> micklee74 at hotmail.com wrote: > hi > i have define a class like this > # class A: class A(object): > _var1 = 0 > def __init__(self): > ## some initialization > self.func1() > # def func1(): def func1(self): > ..... # _var1 = 1 self.__class__._var1 = 1 # or if func1() does'nt use any instance attributes: # @classmethod # def func1(cls): # .... # cls._var1 = 1 > def getvarValue(self): # return _var1 return self.__class__._var1 > I wanted var1 to be "global" inside Class A. The name is "class attribute". -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From vasudevram at gmail.com Thu Jun 29 13:18:53 2006 From: vasudevram at gmail.com (vasudevram) Date: 29 Jun 2006 10:18:53 -0700 Subject: Python database access In-Reply-To: References: <1151295558.067744.91470@b68g2000cwa.googlegroups.com> <1151331311.172035.178060@y41g2000cwy.googlegroups.com> <1151335288.099526.207890@m73g2000cwd.googlegroups.com> <44a15ede$0$15784$14726298@news.sunsite.dk> Message-ID: <1151601533.158686.211670@b68g2000cwa.googlegroups.com> Yes, Steve is right. Sorry for the mistake. In my case, I don't use Active Python, I use the vanilla Python for Windows (the .msi installer from python.org) and then immediately install the win32all package, link to which is usually on the same page as the MSI. I do this as a routine, whenever I upgrade my Windows Python version. Mainly use win32all for the PythonWin IDE (a pretty decent one, particularly the debugging support) which comes with it, though the win32all package also has some support for using COM from Python. So when I did an "import ODBC", since I had not separately installed an ODBC module, I thought it was part of the Standard Library - whereas its a part of win32all. Vasudev --- Vasudev Ram Independent software consultant Personal page: http://www.geocities.com/vasudevram PDF conversion toolkit: http://sourceforge.net/projects/xtopdf (written in Python, requires Python v2.2 or higher, ReportLab toolkit (http://www.reportlab.org) v1.17 or higher). Blog on software innovation: http://jugad.livejournal.com --- Steve Holden wrote: > Damjan wrote: > >>The odbc module is part of the Python Standard Library. > > > > > > Since when? > > > > > Nope, it's a standard part of Mark Hammond's win32all extensions. As > such it probably comes with ActivePython for Windows, which many people > use as their standard distro. > > regards > Steve > -- > Steve Holden +44 150 684 7255 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Love me, love my blog http://holdenweb.blogspot.com > Recent Ramblings http://del.icio.us/steve.holden From per9000 at gmail.com Wed Jun 21 03:44:57 2006 From: per9000 at gmail.com (per9000) Date: 21 Jun 2006 00:44:57 -0700 Subject: How to truncate/round-off decimal numbers? References: Message-ID: <1150875897.866447.312150@g10g2000cwb.googlegroups.com> Hi, just a thought: if you *always* work with "floats" with two decimals, you are in fact working with integers, but you represent them as a floats - confusing for the internal representation. So why not work with int(float * 100) instead? This way you only have to take care of roundoffs etc when dividing. "int (+|-|*) int" = int "int / int" = int / int + int % int Integers are nice, me like integers. /per9000 From jstroud at ucla.edu Mon Jun 26 21:23:03 2006 From: jstroud at ucla.edu (James Stroud) Date: Mon, 26 Jun 2006 18:23:03 -0700 Subject: Beginner question: use function to read text file In-Reply-To: References: Message-ID: Luke wrote: > I'm pretty stuck at the moment and wondering if anyone can spot the problem. > Trying to create a function that will read a text file into a list and > return that list. > > I wrote the following function and saved it as 'fileloader.py' > > def fileload(fname): > infile=open(fname) > dates =[] > times=[] > open=[] > high=[] > low=[] > close=[] > vol=[] > count=0 > for line in infile: > item=line.split() > dates.append(item[0]) > times.append(item[1]) > open.append(item[2]) > high.append(item[3]) > low.append(item[4]) > close.append(item[5]) > vol.append(item[6]) > #print > dates[count],times[count],open[count],high[count],low[count],vol[count] > count=count+1 > > > return dates,times,open,high,low,close > > > Then I executed the following script (merge contract v1.py): > > import fileloader > filename='c:/Python24/test/testdata2.txt' > fileloader.fileload(filename) > > > I then get the following error messages: > > Traceback (most recent call last) > File "C:\Python24\test\merge contract v1.py", in line3, in? > fileloader.fileload(filename) > File ("C:\Python24\text\fileloader.py", in line2, in fileload > infile=open(fname) > UnboundLocalError: local variable 'open' referenced before assignment > Script terminated > > Thanks for any help, > Luke > > def fileload(fname): infile=open(fname) # <=== dates =[] times=[] open=[] # <=== You have assigned open (which, by the way, is a builtin!) in a function *after* you have referenced it. You have over-ridden the open name with the assignment, but you have referenced it 'before assignment', as your error mesage says. This is a favorite trip-up of newer pythong programmers. Perhaps replace open=[] with something like open_=[] etc. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From aaronwmail-usenet at yahoo.com Fri Jun 30 14:29:11 2006 From: aaronwmail-usenet at yahoo.com (aaronwmail-usenet at yahoo.com) Date: 30 Jun 2006 11:29:11 -0700 Subject: sum fonction in gadfly References: <1151137825.177814.217180@u72g2000cwu.googlegroups.com> <449d253d$1@nntp0.pdx.net> <1151154192.030596.223840@r2g2000cwb.googlegroups.com> <1151614282.661048.103630@b68g2000cwa.googlegroups.com> <1151689981.253966.146830@d56g2000cwd.googlegroups.com> Message-ID: <1151692151.751726.74500@d30g2000cwa.googlegroups.com> Robert Hicks wrote: > aaronwmail-usenet at yahoo.com wrote: > > .... why are people so concerned > > that it's not changing? > > > > I didn't mean to be irritating and I wasn't concerned about it not > changing but I could probably have stated the question a little better. > For some reason I thought it was a dead project so maybe "still being > maintained" would be a better statement. I dunno. You're not the only one. Why do I keep seeing "gadfly...dead" in the same sentence? What if it doesn't need maintenance? Does that make it dead? No offense to you personally, you are just repeating what everyone else has been saying for years for reasons that totally escape me. Several times people have suggested that gadfly be added to the python standard library and then the question comes up... who will maintain it? And I answer I'll maintain it if anyone finds serious problems with it and then a few months later I hear that it was decided that gadfly was a dead project. This has been going on since about '97. It's irritating and tiresome. Sorry, I'm grumpy today. -- Aaron Watters === my mazarati goes 185 I lost my license now I don't drive -- from "Life's been good" From __peter__ at web.de Thu Jun 1 17:53:41 2006 From: __peter__ at web.de (Peter Otten) Date: Thu, 01 Jun 2006 23:53:41 +0200 Subject: grouping a flat list of number by range References: <1149196642.001466.53990@c74g2000cwc.googlegroups.com> Message-ID: joh12005 at yahoo.fr wrote: > i'm looking for a way to have a list of number grouped by consecutive > interval, after a search, for example : > > [3, 6, 7, 8, 12, 13, 15] > > => > > [[3, 4], [6,9], [12, 14], [15, 16]] > > (6, not following 3, so 3 => [3:4] ; 7, 8 following 6 so 6, 7, 8 => > [6:9], and so on) > > i was able to to it without generators/yield but i think it could be > better with them, may be do you an idea? Don't hold back your code. Would it work to replace each occurrence of result_list.append([start, stop]) with yield [start, stop] ? Peter From apardon at forel.vub.ac.be Mon Jun 26 08:59:37 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 26 Jun 2006 12:59:37 GMT Subject: String negative indices? References: <1151054259.765401.252230@b68g2000cwa.googlegroups.com> Message-ID: On 2006-06-23, Filip Wasilewski wrote: > drtimhill at comcast.net wrote: > >> Logically, I should be able to enter x[-2:-0] to get the last and next to last characters. However, since Python doesn't distinguish between positive and negative zero, this doesn't work. Instead, I have to enter x[-2:]. > > Hooray! Logically there is no such thing as positive or negative zero, > or did I miss something in the primary? > > PS. x[len(x)-2 : len(x)-0] This seems to defeat the purpose of allowing negative indexes. My understanding was that negative indexes were introduced to avoid things like seq[len(seq) - i] -- Antoon Pardon From fredrik at pythonware.com Mon Jun 12 11:55:38 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 12 Jun 2006 17:55:38 +0200 Subject: Function to remove elements from a list not working (corrected) In-Reply-To: <43266.10.209.4.2.1150104899.squirrel@10.105.1.3> References: <1150102280.505268.174420@u72g2000cwu.googlegroups.com> <43266.10.209.4.2.1150104899.squirrel@10.105.1.3> Message-ID: Girish Sahani wrote: > Btw going slightly off-topic, when i try to run a code like below with > around 50 elements (pairs) in l4,python just hangs. Any ideas why this is > happening...the data is not that large :(( building a filtered new list by repeatedly removing stuff from a copy of the original list isn't exactly the fastest way to do things, but there's no way the following code will "hang" with 50 items instead of 10, unless your computer is ludicrously slow (it takes about 0.000113 seconds on my machine). maybe you meant to write 50k items ? (11 seconds on my machine) >> pairList = [[1,2],[3,4],[3,5],[3,6],[9,7],[8,9],[8,7],[7,9],[11,10]] >> l4 = >> [[4,2],[4,7],[4,10],[4,12],[9,2],[9,7],[9,10],[9,12],[11,2],[11,7]] >> for pair in l4[:]: >> if pair not in pairList: >> l4.remove(pair) >> print "l4 is",l4 From pc at p-cos.net Fri Jun 23 08:27:38 2006 From: pc at p-cos.net (Pascal Costanza) Date: Fri, 23 Jun 2006 14:27:38 +0200 Subject: Saying "latently-typed language" is making a category mistake In-Reply-To: <86Qmg.10725$o4.1907@newsread2.news.pas.earthlink.net> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <86Qmg.10725$o4.1907@newsread2.news.pas.earthlink.net> Message-ID: <4g251pF1knc6tU1@individual.net> Patricia Shanahan wrote: > Vesa Karvonen wrote: > ... >> An example of a form of informal reasoning that (practically) every >> programmer does daily is termination analysis. There are type systems >> that guarantee termination, but I think that is fair to say that it is >> not >> yet understood how to make a practical general purpose language, whose >> type system would guarantee termination (or at least I'm not aware of >> such >> a language). It should also be clear that termination analysis need not >> be done informally. Given a program, it may be possible to formally >> prove >> that it terminates. > > To make the halting problem decidable one would have to do one of two > things: Depend on memory size limits, or have a language that really is > less expressive, at a very deep level, than any of the languages > mentioned in the newsgroups header for this message. Not quite. See http://en.wikipedia.org/wiki/ACL2 Pascal -- 3rd European Lisp Workshop July 3 - Nantes, France - co-located with ECOOP 2006 http://lisp-ecoop06.bknr.net/ From onurb at xiludom.gro Thu Jun 8 13:46:02 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 08 Jun 2006 19:46:02 +0200 Subject: Instead of saving text files i need as html In-Reply-To: <1149777499.506986.292830@j55g2000cwa.googlegroups.com> References: <1149777499.506986.292830@j55g2000cwa.googlegroups.com> Message-ID: <4488625b$0$19574$636a55ce@news.free.fr> Shani wrote: > I have the following code which takes a list of urls > "http://google.com", without the quotes ofcourse, and then saves there > source code as a text file. I wan to alter the code so that for the > list of URLs an html file is saved. What you write in a text file is up to you - and AFAICT, HTML is still a text format. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From asma61 at dsl.pipex.com Fri Jun 2 19:56:06 2006 From: asma61 at dsl.pipex.com (DaveM) Date: Sat, 03 Jun 2006 00:56:06 +0100 Subject: beginner code problem References: <2006060218415316807-victimorcrime@yahoocom> Message-ID: On Fri, 2 Jun 2006 18:41:53 -0400, RJ wrote: > I'm trying to teach myself Python (probably running into the old dog >new tricks issue) and I'm trying to start with the very basics to get a >handle on them. > > I'm trying to write code to get the computer to flip a coin 100 times >and give me the output of how many times heads and tails. After solving >a few syntax errors I seem to be stuck in an endless loop and have to >kill python. A few times I would get it to print 'heads 0 (or 1) times >and tails 1 (or 0) times' 100 times. > >Here's the code I wrote: > >import random > >flip = random.randrange(2) >heads = 0 >tails = 0 >count = 0 > >while count < 100: > > if flip == 0: > heads += 1 > > else: > tails += 1 > > > count += 1 > > > >print "The coin landed on heads", heads, 'times ' \ > "and tails", tails, 'times' Several problems here. "flip" is defined just once, so you'll either have 100 heads or tails and your whitespace is all wrong - that's important in Python. Here's how it should look: import random def coinflip(): heads = 0 tails = 0 for goes in range(100): if random.randrange(2) == 1: heads += 1 else: tails += 1 print "heads", heads print "tails", tails if __name__ == "__main__": coinflip() From michele.petrazzo at TOGLIunipex.it Mon Jun 5 03:42:09 2006 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Mon, 05 Jun 2006 07:42:09 GMT Subject: FreeImagePy and PIL In-Reply-To: References: Message-ID: David Isaac wrote: > I am just starting to think about image processing. What are the > overlaps and differences in intended functionality between > FreeImagePy and PIL? > > Thanks, Alan Isaac > > http://tinyurl.com/m5kal For any other questions, I'm here :) Bye, Michele From marco.wahl at gmail.com Wed Jun 28 02:17:34 2006 From: marco.wahl at gmail.com (Marco Wahl) Date: 27 Jun 2006 23:17:34 -0700 Subject: a class variable question In-Reply-To: <1151474768.546012.254380@p79g2000cwp.googlegroups.com> References: <1151474768.546012.254380@p79g2000cwp.googlegroups.com> Message-ID: <1151475454.163434.309870@p79g2000cwp.googlegroups.com> Hi, just some lines added below. hth micklee74 at hotmail.com wrote: > hi > i have define a class like this > > class A: > _var1 = 0 > def __init__(self): > ## some initialization > self.func1() > > def func1(): self > ..... > _var1 = 1 A._var1 = 1 > .... > > def getvarValue(self): > return _var1 return A._var1 > I wanted var1 to be "global" inside Class A. > when i do > > AnInstance = A() > AnInstance.getvarValue() > > it gives me 0. It should be 1. What am i doing wrong here..thanks From jzgoda at o2.usun.pl Thu Jun 29 14:37:11 2006 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Thu, 29 Jun 2006 20:37:11 +0200 Subject: XML validationg against XSD file in Python In-Reply-To: <1151530107.316152.311040@b68g2000cwa.googlegroups.com> References: <1151530107.316152.311040@b68g2000cwa.googlegroups.com> Message-ID: colincolehour at gmail.com napisa?(a): > I have tried searching for tips or tutorials on validating an XML file > against and XSD file in python but I haven't had any luck. Can someone > point me in the right direction to how this would be achieved. I've > read that Python has built in libraries for DTD validation but nothing > about XSD. lxml has support for schema-based validation. -- Jarek Zgoda http://jpa.berlios.de/ From jes at nl.demon.net Fri Jun 2 07:44:33 2006 From: jes at nl.demon.net (Jim Segrave) Date: Fri, 02 Jun 2006 11:44:33 -0000 Subject: grouping a flat list of number by range References: <1149196642.001466.53990@c74g2000cwc.googlegroups.com> <1149201416.196975.123370@c74g2000cwc.googlegroups.com> <447F79C9.6080407@lexicon.net> <1149232358.817706.92680@j55g2000cwa.googlegroups.com> Message-ID: <12809513gd23kc1@corp.supernews.com> In article <1149232358.817706.92680 at j55g2000cwa.googlegroups.com>, Paddy wrote: > >John Machin wrote: >> On 2/06/2006 8:36 AM, Paddy wrote: > >> >> Oh the siren call of every new feature in the language! >> enumerate() just to get a first-time test, and then botch it?? >> >> Read the following; the replacement version uses a simple old-fashioned >> inelegant flag, works with an empty sequence, and doesn't depend on the >> input being sliceable or indexable. >> >> HTH, >> John >> > >Thanks, un-botchable John. What if the poster doesn't send a null list? >What if the correct result for a null list is "spam"; or an exception? >What if.... ... we toned down the language? I'd still rate Ben Cartwright's solution as the best. The one I posted tried to do the same, but I didn't see the right way to iterate over the supplied list inside the function, wheras he did. It's short, simple and correct. If you really wanted to return 'spam' or an exception in his solution, it's a simple if statement at the start of the function. -- Jim Segrave (jes at jes-2.demon.nl) From exarkun at divmod.com Sat Jun 17 01:40:46 2006 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Sat, 17 Jun 2006 01:40:46 -0400 Subject: transfer rate limiting in socket.py In-Reply-To: <1150491228.229045.163110@h76g2000cwa.googlegroups.com> Message-ID: <20060617054046.29014.711454275.divmod.quotient.2330@ohm> On 16 Jun 2006 13:53:48 -0700, Peter Silva wrote: >Hi folks, > >I have a need in a network data distribution application to send out >data to folks who want it using the protocol of their choice. I?d >like it to support a variety of protocols and I don?t want to >implement any of them :-) >http, ftp (via ftplib) , https (dunno how yet), ssl, ssh, sftp (via >paramiko) > >The thing is... I want rate-limiting so that in the case of a failure >of a single client >I don?t penalize the other clients, or if my server (which is acting >as a client pushing to remote servers.) goes down, it doesn?t saturate >the link when it comes back. > >So I want to have all the protocols limit the number of bytes they send >per second. >It looks like the easiest way to do this is to dive into socket.py... >and look! it says: > ># Wrapper module for _socket, providing some additional facilities ># implemented in Python. > >note the ?additional facilities implemented in python? ... > >so we just add logic to: >-- add a ?maxrate? argument to the constructor and/or an attribute to >modify the setting... >-- tally bytes, and time, and know when we are going ?too fast? >-- when too fast.. in the ?flush? routine, in the synchronous case, >sleep for the correct time to come back under budget. in the async, >return without writing. > -- do something similar for reading. > > Anybody think this would be fun? Use Twisted instead. It supports every protocol you mentioned, and rate limiting too. Jean-Paul From chris.cavalaria at free.fr Wed Jun 7 05:35:53 2006 From: chris.cavalaria at free.fr (Christophe) Date: Wed, 07 Jun 2006 11:35:53 +0200 Subject: Writing to a certain line? In-Reply-To: <448697f7$0$10260$626a54ce@news.free.fr> References: <1149576072.168354.14470@f6g2000cwb.googlegroups.com> <44854184$0$29904$636a55ce@news.free.fr> <1149630414.246008.270720@f6g2000cwb.googlegroups.com> <448697f7$0$10260$626a54ce@news.free.fr> Message-ID: <44869dd3$0$31210$626a54ce@news.free.fr> bruno at modulix a ?crit : > Tommy B wrote: > >>bruno at modulix wrote: > > > (snip) > > >>>import os >>>old = open("/path/to/file.txt", "r") >>>new = open("/path/to/new.txt", "w") >>>for line in old: >>> if line.strip() == "Bob 62" >>> line = line.replace("62", "66") >>> new.write(line) >>>old.close() >>>new.close() >>>os.rename("/path/to/new.txt", "/path/to/file.txt") >>> > > (snip) > >>Umm... I tried using this method and it froze. Infiinite loop, I'm >>guessing. > > > Wrong guess - unless, as Fredrik suggested, you have an infinite disk > with an infinite file on it. If so, please share with, we would be > *very* interested !-) Use /dev/zero as source and /dev/null as destination :D From jim at trainplayer.com Fri Jun 23 08:11:52 2006 From: jim at trainplayer.com (Jim) Date: 23 Jun 2006 05:11:52 -0700 Subject: bug in Makepy In-Reply-To: References: <1150972502.331130.138410@b68g2000cwa.googlegroups.com> <1150979462.521276.261960@y41g2000cwy.googlegroups.com> Message-ID: <1151064712.470064.321180@g10g2000cwb.googlegroups.com> > Always interpret it as hex, or always interpret it as decimal. I see what you mean. But I don't think I'll worry about it. -- Jim From larry.bates at websafe.com Tue Jun 13 18:01:17 2006 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 13 Jun 2006 17:01:17 -0500 Subject: DispatchEx('.Application') In-Reply-To: <1150220324.353472.253180@h76g2000cwa.googlegroups.com> References: <1150220324.353472.253180@h76g2000cwa.googlegroups.com> Message-ID: iainws at gmail.com wrote: > When using win32com and DispatchEx to work with a webbrowser, eg: > > from win32com.client import DispatchEx > > ie = DispatchEx('InternetExplorer.Application') > > can anyone suggest the right answer to this? > > mf = DispatchEx('MozillaFirefox.Application') > > It is an invalid class string, but I don't know how to find the right > class string for Mozilla (or any other window for that matter)? Can > somebody suggest to me an easy way to 'get' this information. > > After that I intend to do this: > > mf.Navigate('www.groups.google.com.au/etc'') > > Will all of these functions work with Firefox or is it only Internet > Explorer(I can use either but I prefer Firefox?) > This might help: http://mail.python.org/pipermail/python-win32/2005-June/003413.html -Larry Bates From Serge.Orlov at gmail.com Wed Jun 14 21:45:06 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 14 Jun 2006 18:45:06 -0700 Subject: Bundling an application with third-party modules References: <1150285229.237626.36440@y41g2000cwy.googlegroups.com> <1150330824.653252.212300@f6g2000cwb.googlegroups.com> Message-ID: <1150335906.300363.270410@f6g2000cwb.googlegroups.com> Ben Finney wrote: > "Serge Orlov" writes: > > > Ben Finney wrote: > > > That's a large part of my question. How can I lay out these > > > modules sensibly during installation so they'll be easily > > > available to, but specific to, my application? > > > > Put them in a directory "lib" next to the main module and start the > > main module with the following blurb: > > ------------------------------------------------ > > import sys, os > > sys.path.insert(1, os.path.join(sys.path[0],"lib")) > > ------------------------------------------------ > > The application consists of many separate programs to perform various > tasks, some larger than others. There's no sensible place for a "main > module". Perhaps I'm using my own jargon. By "main module" I mean every module used to start any application within your project. If you want relocatable solution, create empty .topdir file in the top directory and put this blurb into every application: ------------------------ import sys, os top_dir = sys.path[0] while True: if os.path.exists(os.path.join(top_dir,".topdir")): break top_dir = os.path.dirname(top_dir) sys.path.insert(1, os.path.join(top_dir,"lib")) ------------------------ I don't think you need to worry about duplication, I used this code. It is verion 1.0 and it is final :) You won't need to change it. > There probably will be a library directory for common code, > though. Are you suggesting that the third-party libraries should go > within the application-native library? Not really. I was just feeling lazy to type a generic solution, so I assumed one project == one application. > What's a good way to get from upstream source code (some of which is > eggs, some of which expects 'distutils' installation, and some of > which is simple one-file modules) to a coherent set of application > library code, that is automatable in an install script? Well, I did it manually, it's not that time consuming if you keep in mind that you also need to test new version and by testing I also mean finding integration bugs days later. Anyway, if you feel like automating I think you can do something using distutils command "install --home=/temp/dir" and then copying to your common library directory in a flat manner (--home option puts files in subdirectories that don't make sense for a bundled lib) From jeem.moffitt at gmail.com Tue Jun 6 12:28:17 2006 From: jeem.moffitt at gmail.com (jeem) Date: 6 Jun 2006 09:28:17 -0700 Subject: Using Komodo 3.5 - Setting breakpoints in multiple *.py files Message-ID: <1149611297.071477.32300@j55g2000cwa.googlegroups.com> I am using ActiveState Komodo 3.5 to work on a large python 2.4 application with an extensive UI... I am attempting to debug the application and am setting breakpoints in 4 different *.py files.. Breakpoints in the main file are working OK, but any breakpoints in imported files are not... The three imported files are open in Komodo and are in the same local directory as the main file (in the python24/Lib/site-packages tree)... The code sections I am trying to debug are invoked by some UI events... When I start the debugging section and navigate to the features I am trying to debug, the breakpoint are ignored... I can execute a "Break now" command and the IDE is smart enough to find and display imported *.py resources... but normal breakpoints are ignored... I am new to Komodo and Python, and the IDE debugging features are certainly not working as expected, based upon my experience with Visual Studio and JBuilder... I've searched the included Help system and so far haven't had any luck... Thanks! From jmbc at nospam.fr Wed Jun 7 15:38:32 2006 From: jmbc at nospam.fr (jean-michel bain-cornu) Date: Wed, 07 Jun 2006 21:38:32 +0200 Subject: wxpython wxgrid question In-Reply-To: <1149393484.553463.286220@i39g2000cwa.googlegroups.com> References: <1149366330.999234.299880@u72g2000cwu.googlegroups.com> <1149393484.553463.286220@i39g2000cwa.googlegroups.com> Message-ID: <44872b73$0$7769$7a628cd7@news.club-internet.fr> rbann11 at hotmail.com a ?crit : > Tim Roberts wrote: >> rbann11 at hotmail.com wrote: >>> I am looking for example code that consists of just a frame and a >>> grid(10x2). The grid must fill the its parent even if the frame is >>> resized. >> Have you gone through the wxPython demo application? It contains examples >> of every standard control and almost every behavior you might want. >> -- >> - Tim Roberts, timr at probo.com >> Providenza & Boekelheide, Inc. > > Yes, and i have even checked out "wxpython in action". All of the > examples tend to leave white space on the right of the frame. I tried > basic a example with sizers and it didnt work. That why I was > wondering if someone had got it to work. > > > Roger > Hi Roger, A key point is that the Grid manages itself its available space according to the size it can have. If you just tried to create a simple grid within a simple frame, you probably got a grid filling all the frame space, and it's what you want. Why that ? If you do it (for instance with the script below), and you try to manually reduce/increase the size of the window, you should see scrollbars at the edge of the window ; these scrollbars come from the grid, because they take in account the labels row and col (wxGrid comes from wxScrolledWindow). You can see that no more space is available beyond the scrollbar, so the grid takes the whole space. And why the white space on the right ? This space is not on the right of the grid, but on the right of the last col. We could think it's like that because it's not possible to compute an appropriate col size for the grid cols, but it's not displayed exactly the same in linux and in windows. In one case it's over the last col (not enough space) and in the other case it's beyond (too much space). I think that as the program must work on all the environments, the interface must stay enough global, and sometimes the display is not perfectly done. The advantage is that if we let wx decide, we won't have to think how to set the widgets. Regards, jm #---------------------------------------------------------------------- import wx,wx.grid #---------------------------------------------------------------------- class MainWindow(wx.Frame): def __init__(self,parent,id,title): wx.Frame.__init__(self,parent,wx.ID_ANY,title) #-- self.grid= wx.grid.Grid(id=wx.ID_ANY,parent=self) self.grid.CreateGrid(numRows=10,numCols=2) self.grid.Fit() self.Fit() #-- self.Show(1) #---------------------------------------------------------------------- app = wx.PySimpleApp() frame=MainWindow(None,-1,'Grid sizer') app.MainLoop() del app #---------------------------------------------------------------------- From onurb at xiludom.gro Wed Jun 28 11:53:28 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Wed, 28 Jun 2006 17:53:28 +0200 Subject: how do i make an array global In-Reply-To: References: <1151472238.400461.42350@p79g2000cwp.googlegroups.com> <44a25ab4$0$1017$626a54ce@news.free.fr> Message-ID: <44a2a5f9$0$9017$626a54ce@news.free.fr> Georg Brandl wrote: > Bruno Desthuilliers wrote: > >>a wrote: >> >>>def fn(): >>> for i in range(l) >> >>l is not defined - you should have an error here. >> >> >>> global count >>> count[i]= .... >>> >>>how do i declare count to be global if it is an array >> >>Just like it was an integer > > > No. If he's only mutating "count", he doesn't need a global > declaration. Did I said so ? I just answered the OP's question. If that's the 'int' that confuse you, then s/int/dict/ - what I meant is that the global statement doesn't care about types... > >>>subsequently i should access or define count as an array >> >>You need to define count before. >> >> >>>error: >>>global name 'count' is not defined >> >>He... >> >>*but* >>You probably should not do that anyway. Globals are *evil*. > > Do you realize that every variable you set in a module's namespace is a > global when used by a function? Going to teach me Python, Georg ?-) Then let's be accurate first, and s/variable you set/name you bind/ > Globals are *not* evil. Yes they are. >>And functions modifying globals is the worst possible thing. >>There are very few chances you *need* a global here. > > Look at the use case first. The use case here is to avoid either passing a list as param or building and returning it - and the OP is obviously a newbie, so better for him to learn the RightThing(tm) from the beginning IMHO. > For small scripts, sometimes re-assigning global names or mutating objects > refered to by global names is essential. s/is essential/seems easier/ Then you or anyone else has to make a quick fix or update, and everything starts to break down. Too bad. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From sambo at void.com Wed Jun 14 19:38:11 2006 From: sambo at void.com (Sambo) Date: Wed, 14 Jun 2006 19:38:11 -0400 Subject: split with "*" in string and ljust() puzzles Message-ID: I have couple of puzzles in my code. def load_headers( group_info ): if os.path.isfile( group_info.pointer_file ): ptr_file = open( group_info.pointer_file, "r" ) else: print group_info.mess_list return linecount = 0 ptr_file.seek( 512 ) print ptr_file.tell() line = ptr_file.readline() while line != "" : if line[0:1] == "<": print linecount print len(line), line print line.split( " ", 3 ) group_info.mess_list.append( line.split( " ", 3 ) ) line = ptr_file.readline() ptr_file.close() when reading the following line from file: 2338 * Re: PCB Pad Size for TQFP Package?? the split command returns [' ','','','2338 * Re: PCB Pad Size for TQFP Package??'] instead of [', '2338', '*','Re: PCB Pad Size for TQFP Package??'] I have just (finally) realized that it is splitting and removing on single space but that seams useless, and split items 1 and 2 are empty strings not spaces?? regex somewhere it shouldn't be? The other problem is in this piece of code which is trying to pad the first 512 bytes: line = group_info.group_name+" sf"+ group_info.first + " sl"+ \ group_info.last + " sc" + group_info.count + "dt" + \ group_info.date_checked + group_info.time_checked line = line + "\n" line = string.ljust( line, 512 - len(os.linesep) ) print len( os.linesep ) line += "\n" print len( line ) ptr_file.write( line ) print "**** "+repr(ptr_file.tell())+ " ****" print "message list\n" the ljust function returns string 511 bytes long, besides the fact that the logic is not exactly correct what is going on here. Is ljust trying to be smart about the EOL inside the string already? I have tried the following, which should be about right ( account for the 1 bytes added after justification and two added by file write.) line = string.ljust( line, 512 - len(os.linesep) - len(os.linesep) - 1 ) But, in this case I end up 2 bytes short of 512. Thanks for any help. From jstroud at ucla.edu Thu Jun 22 13:56:44 2006 From: jstroud at ucla.edu (James Stroud) Date: Thu, 22 Jun 2006 10:56:44 -0700 Subject: How to generate all permutations of a string? In-Reply-To: References: Message-ID: Girish Sahani wrote: >>In article , >> "Girish Sahani" wrote: >> >> >>> I want to generate all permutations of a string. >> >>def permute(Seq) : >> """generator which yields successive permutations of the elements >> of Seq.""" >> if len(Seq) == 0 : >> yield () >> else : >> for i in range(0, len(Seq)) : >> for rest in permute(Seq[:i] + Seq[i + 1:]) : >> yield (Seq[i],) + rest >> #end for >> #end for >> #end if >>#end permute > > thanks lawrence...however this func doesnt return the permuted strings, so > i added some code as follows to generate a list of all the permutations: > > def permute(seq): > l = [] > if len(seq) == 0: > yield [] > else: > for i in range(0,len(seq)): > for rest in permute(seq[:i] + seq[i+1:]): > yield (seq[i],) + rest > for t in permute(seq): > l.append(''.join(t)) > return l > > This gives me a syntax error! > I need to output a list that has all the permutations of the input string. > > > > >>-- >>http://mail.python.org/mailman/listinfo/python-list >> > > p = ["".join(s) for s in permute('abcdefg')] -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From ljr2600 at gmail.com Mon Jun 12 01:09:49 2006 From: ljr2600 at gmail.com (ljr2600 at gmail.com) Date: 11 Jun 2006 22:09:49 -0700 Subject: Screen Scraping for Modern Applications? In-Reply-To: References: <1150077617.598735.85540@h76g2000cwa.googlegroups.com> Message-ID: <1150088989.408815.290690@c74g2000cwc.googlegroups.com> Cameron Laird wrote: > In article <1150077617.598735.85540 at h76g2000cwa.googlegroups.com>, > wrote: > . > . > . > >For a side project I'm working on I need to be able to scrape a modern > >computer desktop. Is there any basic material already available to do > >this? I'd rather not need to write my own to interact with hardware. > . > . > . > Oh, no. > > Very hard. Very, very hard. > > At least as you've expressed it here, this is an exceptionally > difficult task. What does "scrape" mean to you? Do you want > to reproduce the display remotely, or extract text, or some other > possibility? Does "modern computer" mean Windows to you? Scrape means simply scraping pixel colors from locations on the screen. I'll worry about assembling it into meaningful information. Previously, I used Java, and it has a very handy built in class called Robot that can, amongst other things, report the color of on screen pixels. Thusly, I assumed the task could be accomplished reasonably easily. From george.sakkis at gmail.com Tue Jun 13 22:52:24 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 13 Jun 2006 19:52:24 -0700 Subject: question on dict subclassing and overriding __setitems__ References: <4f911aF12jediU1@uni-berlin.de> Message-ID: <1150253544.462201.33730@p79g2000cwp.googlegroups.com> Eric S. Johansson wrote: > Diez B. Roggisch wrote: > > Or better even > > > > super(subclass, self).__setitem__(key.upper(), value) > > hmm. http://fuhm.net/super-harmful/ Interesting link, didn't know about it. I've always found super() ugly and doubted that it was in practice better suited for multiple inheritance than explicit method call, but I kept using it nonetheless since it was "blessed" for new style classes. Unless of course the code broke for one of the reasons mentioned in the article, in which case I reverted back to the "old way". Good to know that I can safely get rid of practically all super() calls. Any python-dev-er's take on super()'s utility and future in Py3K ? George From michele.petrazzo at TOGLIunipex.it Fri Jun 30 07:10:56 2006 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Fri, 30 Jun 2006 11:10:56 GMT Subject: Way for see if dict has a key In-Reply-To: <44a5041f$0$29637$636a55ce@news.free.fr> References: <6V6pg.21624$_J1.271925@twister2.libero.it> <44a5041f$0$29637$636a55ce@news.free.fr> Message-ID: <4F7pg.21676$_J1.272665@twister2.libero.it> Bruno Desthuilliers wrote: >> but what the better > > Depends on the context. > If know only one context: see if the key are into the dict... What other context do you know? Michele From richard at pyweek.org Tue Jun 13 04:18:58 2006 From: richard at pyweek.org (richard at pyweek.org) Date: Tue, 13 Jun 2006 18:18:58 +1000 Subject: Pygame.draw challenge Message-ID: <200606131818.58324.richard@pyweek.org> THE CHALLENGE: Create a game in 64kbytes of source code using only pygame. No additional libraries, no external files (even ones loaded from a network). That means no PyOpenGL, no PNGs, no OGGs. THE DEADLINE: Start as soon as you read this announcement. Human-readable, Linux-compatible entries must be received by richard at pyweek.org before midnight on the 25th of June, 2006. That's Australian Eastern Standard Time, which is UTC +10. Multiple entries are allowed. Teams are allowed. Monkeys are allowed! Ponies, sadly, are not allowed. THE RESULTS: All entries will be posted to a page on the http://www.pyweek.org/ website. Entry gameplay instructions and license must be included in the source or in the game itself. I will probably choose one of the entries as my favourite, and declare this in various obscure fora and private email messages. No other mention of rankings or favourites will be made. THANKS: Thanks to Phil Hassey for the challenge inspiration! -- Visit the PyWeek website: http://www.pyweek.org/ From jzgoda at o2.usun.pl Thu Jun 15 12:02:28 2006 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Thu, 15 Jun 2006 18:02:28 +0200 Subject: Python is fun (useless social thread) ;-) In-Reply-To: <36fkg.2312$No6.48470@news.tufts.edu> References: <36fkg.2312$No6.48470@news.tufts.edu> Message-ID: John Salerno napisa?(a): >> And I still don't get this "web application" hype, and all these "web >> frameworks" scare me, as I internally don't trust any magic. > > Yeah, I dabbled with CGI, but I haven't seriously looked into anything > like TurboGears yet. Of course, my problem is that I don't *need* to > learn TurboGears, Django, etc...I just feel the desire to learn them > (which is bad, in a way, because then I have no reason to use them!) And > of course learning a framework like this means learning a lot of other > parts too, like CherryPy, Mochi or something like that, etc. :) Yea, that's right -- all these frameworks are of no use for me too. I think I should learn at least some basics of them (like how WSGI stack works), but my spare time is at most 2 hours at evening, so I choose things that are closer to my current tasks, like new GUI framework (i.e. Kiwi for PyGTK or Wax for wxPython) or new networking library. Anyway, noone is expected to be an expert in every aspect. ;) -- Jarek Zgoda http://jpa.berlios.de/ From g.brandl-nospam at gmx.net Wed Jun 28 15:40:01 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Wed, 28 Jun 2006 21:40:01 +0200 Subject: how do i make an array global In-Reply-To: <44a2a5f9$0$9017$626a54ce@news.free.fr> References: <1151472238.400461.42350@p79g2000cwp.googlegroups.com> <44a25ab4$0$1017$626a54ce@news.free.fr> <44a2a5f9$0$9017$626a54ce@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > Georg Brandl wrote: >> Bruno Desthuilliers wrote: >> >>>a wrote: >>> >>>>def fn(): >>>> for i in range(l) >>> >>>l is not defined - you should have an error here. >>> >>> >>>> global count >>>> count[i]= .... >>>> >>>>how do i declare count to be global if it is an array >>> >>>Just like it was an integer >> >> >> No. If he's only mutating "count", he doesn't need a global >> declaration. > > Did I said so ? I just answered the OP's question. If that's the 'int' > that confuse you, then s/int/dict/ - what I meant is that the global > statement doesn't care about types... Ok, I misunderstood you. >>>>subsequently i should access or define count as an array >>> >>>You need to define count before. >>> >>> >>>>error: >>>>global name 'count' is not defined >>> >>>He... >>> >>>*but* >>>You probably should not do that anyway. Globals are *evil*. >> >> Do you realize that every variable you set in a module's namespace is a >> global when used by a function? > > Going to teach me Python, Georg ?-) Then let's be accurate first, and > s/variable you set/name you bind/ Well, thanks. As if that made a difference. >> Globals are *not* evil. > > Yes they are. Really? May I tell you that in the stdlib, there are at least 13526 globals overall? >>>And functions modifying globals is the worst possible thing. >>>There are very few chances you *need* a global here. >> >> Look at the use case first. > > The use case here is to avoid either passing a list as param or building > and returning it - and the OP is obviously a newbie, so better for him > to learn the RightThing(tm) from the beginning IMHO. There's no reason to not use a global if it's the easiest thing to do. >> For small scripts, sometimes re-assigning global names or mutating objects >> refered to by global names is essential. > > s/is essential/seems easier/ > > Then you or anyone else has to make a quick fix or update, and > everything starts to break down. Too bad. Everything starts to break down? If the change was buggy, it'll be debugged and corrected. That's nothing particularly related to globals. Remember, we're talking about one-file scripts here. Georg From saint.infidel at gmail.com Wed Jun 28 18:28:12 2006 From: saint.infidel at gmail.com (infidel) Date: 28 Jun 2006 15:28:12 -0700 Subject: Generator naming convention? In-Reply-To: <1151520720.749818.131460@i40g2000cwc.googlegroups.com> References: <1151520720.749818.131460@i40g2000cwc.googlegroups.com> Message-ID: <1151533692.535262.258690@y41g2000cwy.googlegroups.com> > Any idea? Do you have a naming convention for generators? Sometimes I use the prefix 'iter', like dictionaries have .items() and .iteritems(). sometimes I use 'x', like range() vs. xrange(). You could simply use 'i' like some of the functions in the iteritems module (imap(), izip(), etc). I guess it depends on the project, what you're doing, your mood at the moment, and the alignment of Jupiter and Mercury in Aquarius. From fredrik at pythonware.com Wed Jun 28 12:10:55 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 28 Jun 2006 18:10:55 +0200 Subject: Immutability References: <4Qj*cEjkr@news.chiark.greenend.org.uk> Message-ID: Nick Maclaren wrote: > |> a property looks like an attribute, not a method, so you're trying to call whatever > |> your "joe()" method returns. > > Well, yes, that was pretty obvious - but what was NOT obvious is why it > should do that for one of two identical methods. identical? you only applied @property to one of the methods, and then you're surprised that only one of the methods were turned into a property? > |> (that's what "a function for getting an attribute value" in the property documentation > |> refers to). > > Well, as joe is an attribute of the class fred, and the decorator is applied > to the declaration of joe within fred, I assumed that it referred to getting > joe from fred. That certainly doesn't appear to be the case @property turns your "joe" method into a getter method for the (virtual) attribute "joe". when you access the attribute, the getter method will be called. whatever that method returns will be the attribute's value. that's what the documentation says, and that's what your code is doing. From onurb at xiludom.gro Fri Jun 2 05:47:47 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 02 Jun 2006 11:47:47 +0200 Subject: how to define a static field of a given class In-Reply-To: <1149239221.045268.6170@g10g2000cwb.googlegroups.com> References: <1149239221.045268.6170@g10g2000cwb.googlegroups.com> Message-ID: <448009b7$0$12763$636a55ce@news.free.fr> feel_energetic wrote: > Hi, > > I already knew how to define a static method of a class( using > staticmethod() ), FWIW, it's probably one of the most useless construct in Python IMHO. classmethod are really much more useful to me. > but I find there isn't a built-in func to build a > static field ( something like staticfield() ) Please define "static field", I just don't understand what it could be. Now if what you want is a class attribute (ie: an attribute that is shared by all instances of a class), just declare it at the class level: class MyClass(object): shared_attrib = 42 # can be accessed via the class # or via an instance MyClass.shared_attrib m = MyClass() m.shared_attrib # but you don't want to rebind it via an instance m.shared_attrib = 33 m.shared_attrib MyClass.shared_attrib # note that the problem is only with rebinding - mutating is ok class MyOtherClass(object): shared_attrib = [42] mo = MyOtherClass() mo.shared_attrib mo.shared_attrib.append(33) mo.shared_attrib MyOtherClass.shared_attrib HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From david.nospam.hopwood at blueyonder.co.uk Sat Jun 24 18:50:01 2006 From: david.nospam.hopwood at blueyonder.co.uk (David Hopwood) Date: Sat, 24 Jun 2006 22:50:01 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> Message-ID: David Hopwood wrote: > Anton van Straaten wrote: > >>I'm suggesting that if a language classifies and tags values in a way >>that supports the programmer in static reasoning about the behavior of >>terms, that calling it "untyped" does not capture the entire picture, >>even if it's technically accurate in a restricted sense (i.e. in the >>sense that terms don't have static types that are known within the >>language). >> >>Let me come at this from another direction: what do you call the >>classifications into number, string, vector etc. that a language like >>Scheme does? And when someone writes a program which includes the >>following lines, how would you characterize the contents of the comment: >> >>; third : integer -> integer >>(define (third n) (quotient n 3)) > > I would call it an informal type annotation. But the very fact that > it has to be expressed as a comment, and is not checked, What I meant to say here is "and is not used in any way by the language implementation," > means that > the *language* is not typed (even though Scheme is dynamically tagged, > and even though dynamic tagging provides *partial* support for a > programming style that uses this kind of informal annotation). -- David Hopwood From onurb at xiludom.gro Wed Jun 28 13:01:40 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Wed, 28 Jun 2006 19:01:40 +0200 Subject: Immutability In-Reply-To: References: <4Qj*cEjkr@news.chiark.greenend.org.uk> <44a2a956$0$29814$626a54ce@news.free.fr> Message-ID: <44a2b5f5$0$6509$626a54ce@news.free.fr> Fredrik Lundh wrote: > Bruno Desthuilliers wrote: > > >>>class fred : >>> @property >>> def joe (self) : >>> print "Inside /joe\n" >> >> >>properties dont work properly on old-style classes (lookup 'new-style >>classes' on python.org, in the documentation menu), hence the strange >>behaviour you observe. > > > property getters work just fine on old-style classes (setters and deleters don't > work, but that's not what he's using). Thanks - I was too lazy to actually reread all the doc or derive this from observation !-) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From dnew at san.rr.com Tue Jun 20 13:02:23 2006 From: dnew at san.rr.com (Darren New) Date: Tue, 20 Jun 2006 17:02:23 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: <1150822150.701434.296460@u72g2000cwu.googlegroups.com> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <1150809118.677124.142230@u72g2000cwu.googlegroups.com> <1150815461.210286.53120@r2g2000cwb.googlegroups.com> <1150822150.701434.296460@u72g2000cwu.googlegroups.com> Message-ID: Rob Thorpe wrote: > The compiler > relys entirely on the types of the variables to know how to correctly > operate on the values. The values themselves have no type information > associated with them. int x = (int) (20.5 / 3); What machine code operations does the "/" there invoke? Integer division, or floating point division? How did the variables involved in the expression affect that? >>Casting in C takes values of one type to values of another type. > No it doesn't. Casting reinterprets a value of one type as a value of > another type. No it doesn't. int x = (int) 20.5; There's no point at which bits from the floating point representation appear in the variable x. int * x = (int *) 0; There's nothing that indicates all the bits of "x" are zero, and indeed in some hardware configurations they aren't. -- Darren New / San Diego, CA, USA (PST) My Bath Fu is strong, as I have studied under the Showerin' Monks. From timr at probo.com Wed Jun 28 03:24:48 2006 From: timr at probo.com (Tim Roberts) Date: Wed, 28 Jun 2006 07:24:48 GMT Subject: languages with full unicode support References: <1151251736.590910.36050@u72g2000cwu.googlegroups.com> Message-ID: "Xah Lee" wrote: >Languages with Full Unicode Support > >As far as i know, Java and JavaScript are languages with full, complete >unicode support. That is, they allow names to be defined using unicode. >(the JavaScript engine used by FireFox support this) > >As far as i know, here's few other lang's status: > >C ? No. This is implementation-defined in C. A compiler is allowed to accept variable names with alphabetic Unicode characters outside of ASCII. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From 4daniel at gmail.com Wed Jun 28 22:14:29 2006 From: 4daniel at gmail.com (Daniel) Date: 28 Jun 2006 19:14:29 -0700 Subject: decimal by default Message-ID: <1151547269.842597.319600@y41g2000cwy.googlegroups.com> I'm writing an application that (among other things) evaluates mathematical expressions. The user enters strings containing literals and names that later get evaluated using the Python interpreter. Here's a short (very simplified) example: >>> from decimal import Decimal >>> names = dict(a=Decimal('3.625'), b=Decimal(2)) >>> expr = '(a + 2.625) / b' # expression entered by end-user >>> eval(expr, names) Traceback (most recent call last): ... TypeError: You can interact Decimal only with int, long or Decimal data types. I understand why I got the error, so there's no need to explain that. It is a requirement that the 'names' dict contains Decimal values. And of course it's unacceptable to expect my users to enter Decimal('...') every time they enter a non-integer number. My initial solutioin is to use a regular expression to wrap each float value with Decimal('...') before the expression is evaluated. But I don't like that solution for two reasons: 1. It seems error prone and inelegant. Paraphrase: if you've got a problem and you think "Ahh, I'll use regular expressions..." now you've got two problems. 2. Error reporting is not as intuitive (I'm using the Python interpreter and therefore my users see Python exceptions when their expressions don't evaluate). After the expressions have been shot up with all the extra Decimal junk to make them evaluate correctly they are not nearly as recognizable (or easy to read) and the user is likely to think "but I didn't even write that expression...where is that Decimal('...') stuff coming from?" Ideally I'd like to have a way to tell the interpreter to use Decimal by default instead of float (but only in the eval() calls). I understand the performance implications and they are of no concern. I'm also willing to define a single global Decimal context for the expressions (not sure if that matters or not). Is there a way to do what I want without rolling my own parser and/or interpreter? Is there some other alternative that would solve my problem? Thanks, ~ Daniel From digitalorganics at gmail.com Mon Jun 12 10:54:54 2006 From: digitalorganics at gmail.com (digitalorganics at gmail.com) Date: 12 Jun 2006 07:54:54 -0700 Subject: Very nice python IDE (windows only) In-Reply-To: <1150123358.105703.285570@y43g2000cwc.googlegroups.com> References: <1149694235.741274.325200@u72g2000cwu.googlegroups.com> <1149701880.540109.10100@y43g2000cwc.googlegroups.com> <1149704292.676501.138530@h76g2000cwa.googlegroups.com> <448d5f3d$0$815$3a628fcd@textreader.nntp.hccnet.nl> <1150123358.105703.285570@y43g2000cwc.googlegroups.com> Message-ID: <1150124094.480721.261440@h76g2000cwa.googlegroups.com> By the way, does anyone know if / how you can change the key bindings in PythonWin? In PyScripter, I was quite pleased that the autocomplete lets you make your selection by pressing enter (natural), yet in PythonWin you have to press tab (unnatural). Thanks. digitalorganics at gmail.com wrote: > Great IDE! I love it. Two things that make me very happy: > > 1. Unlike PythonWin and Stan's Python Editor (SPE), PyScripter shows > not just methods but also attributes in the class browser. [I'll > mention that Eric3 also does this, but I don't use Eric3 much because > the editor component doesn't allow scrolling through my code with a > mouse wheel (something I'm extremely used to being able to do at this > point).] > > 2. Extremely useful tooltips! You can receive context sensitive > information on methods, variables, and classes just by hovering over > them with your mouse! Awesome, truly awe inspiring. > > > I also like the modern look! Very slick and configurable. The variable > window below is nice too... > > Thanks for mentioning! > > > Cheers, > > DigiO From n.estner at gmx.de Sun Jun 4 16:30:00 2006 From: n.estner at gmx.de (nikie) Date: 4 Jun 2006 13:30:00 -0700 Subject: Python less error-prone than Java References: <1149424883.529756.13700@j55g2000cwa.googlegroups.com> Message-ID: <1149453000.162259.105090@y43g2000cwc.googlegroups.com> Christoph Zwerschke wrote: > nikie wrote: > > Let's look at two different examples: Consider the following C# code: > > > > static decimal test() { > > decimal x = 10001; > > x /= 100; > > x -= 100; > > return x; > > > > It returns "0.01", as you would expect it. > > Yes, I would expect that because I have defined x as decimal, not int. > > > Now, consider the python equivalent: > > > > def test(): > > x = 10001 > > x /= 100 > > x -= 100 > > return x > > No, that's not the Python equivalent. The equivalent of the line > > decimal x = 10001 > > in Python would be > > x = 10001.0 > > or even: > > from decimal import Decimal > x = Decimal(10001) Hm, then I probably didn't get your original point: I thought your argument was that a dynamically typed language was "safer" because it would choose the "right" type (in your example, an arbitrary-pecision integer) automatically. As you can see from the above sample, it sometimes picks the "wrong" type, too. Now you tell me that this doesn't count, because I should have told Python what type to use. But shouldn't that apply to the Java binary-search example, too? I mean, you could have told Java to used a 64-bit or arbitrary-length integer type instead of a 32-bit integer (which would actually be equivalent to the Python code), so it would do the same thing as the Python binary search implementation. > ... > By the way, the equivalent Python code to your C# program gives on my > machine the very same result: > >>> x = 10001.0; x /= 100; x -= 100; print x > 0.01 Try entering "x" in the interpreter, and read up about the difference between str() and repr(). > > > Even if you used "from __future__ import division", it would actually > > return "0.010000000000005116", which, depending on the context, may > > still be an intolerable error. > > With from __future__ import division, I also get 0.01 printed. Anyway, > if there are small discrepancies then these have nothing to do with > Python but rather with the underlying floating-point hardware and C > library, the way how you print the value and the fact that 0.01 can > principally not be stored exactly as a float (nor as a C# decimal), only > as a Python Decimal. The is OT, but what makes you think a C# decimal can't store 0.01? > > I can even think of an example where C's (and Java's) bounded ints are > > the right choice, while Python's arbitraty-precision math isn't: > > Assume you get two 32-bit integers containing two time values (or > > values from an incremental encoder, or counter values). How do you > > find out how many timer ticks (or increments, or counts) have occured > > between those two values, and which one was earlier? In C, you can > > just write: > > > > long Distance(long t1, long t0) { return t1-t0; } > > > > And all the wraparound cases will be handled correctly (assuming there > > have been less than 2^31 timer ticks between these two time values). > > "Distance" will return a positive value if t1 was measured after t0, a > > negative value otherwise, even if there's been a wraparound in > > between. Try the same in Python and tell me which version is simpler! > > First of all, the whole problem only arises because you are using a > statically typed counter ;-) And it only is easy in C when your counter > has 32 bits. But what about a 24 bit counter? Easy, multiply it with 256 and it's a 32-bit counter ;-) Fortunately, 24-bit-counters are quite rare. 16-bit or 32-bit counters on the other hand are quite common, especially when you're working close to the hardware (where C is at home). All I wanted to point out is that bounded integers do have their advantages, because some people in this thread apparently have never stumbled over them. From pipedreamergrey at gmail.com Mon Jun 5 13:01:06 2006 From: pipedreamergrey at gmail.com (PipedreamerGrey) Date: 5 Jun 2006 10:01:06 -0700 Subject: Expanding Search to Subfolders Message-ID: <1149526866.681348.273590@c74g2000cwc.googlegroups.com> This is the beginning of a script that I wrote to open all the text files in a single directory, then process the data in the text files line by line into a single index file. os.chdir("C:\\Python23\\programs\\filetree") mydir = glob.glob("*.txt") index = open("index.rtf", 'w') for File in mydir: count = 1 file = open(File) fileContent = file.readlines() for line in fileContent: if not line.startswith("\n"): if count == 1: I'm now trying to the program to process all the text files in subdirectories, so that I don't have to run the script more than once. I know that the following script will SHOW me the contents of the subdirectories, but I can't integrate the two: def print_tree(tree_root_dir): def printall(junk, dirpath, namelist): for name in namelist: print os.path.join(dirpath, name) os.path.walk(tree_root_dir, printall, None) print_tree("C:\\Python23\\programs\\filetree") I've taught myself out of online tutorials, so I think that this is a matter of a command that I haven't learned rather a matter of logic. Could someone tell me where to learn more about directory processes or show me an improved version of my first script snippet? Thanks From iant at the-wire.com Thu Jun 8 11:31:25 2006 From: iant at the-wire.com (moonman) Date: 8 Jun 2006 08:31:25 -0700 Subject: cos: "Integer Required"?!?!?!? In-Reply-To: <2aqdnQ8uYZLpoxXZnZ2dnUVZ_qadnZ2d@comcast.com> References: <1149777499.262577.318070@u72g2000cwu.googlegroups.com> <2aqdnQ8uYZLpoxXZnZ2dnUVZ_qadnZ2d@comcast.com> Message-ID: <1149780685.768525.276850@h76g2000cwa.googlegroups.com> print self.ACphi, type(self.ACphi) yields: 19412557 value = XPLMGetDataf(self.ACphi); print value type(value ) yields: -0.674469709396 print math.radians(XPLMGetDataf(self.ACphi)), type(math.radians(XPLMGetDataf(self.ACphi))) yields: TypeError : an integer is required Am I totally missing something about 'math'. Does it really expect an int? Moonman Larry Bates wrote: > First: Always post cut-paste tracebacks so we can see actual > error message. > > Second: print out self.ACphi, XPLMGetDataf(self.ACphi) and > math.radians(XPLMGetDataf(self.ACphi)) before this statement > and you will find the problem. > > -Larry Bates > > > moonman wrote: > > Hello all, > > > > I've just jumped into Python trying to develop X-Plane plugins. > > > > All was chugging along well until I tried to use math.cos() > > > > snippet: > > > > import math > > > > .... > > > > cos_phi = math.cos(math.radians(XPLMGetDataf(self.ACphi))) # Error > > occurs here > > > > > > > > Now XPLMGetDataf should be returning float. > > > > Is there something that I'm completely missing about how Python does > > tyonig or something? > > > > Thanks in advance, > > > > Moonman > > From ilias at lazaridis.com Thu Jun 8 14:03:45 2006 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Thu, 08 Jun 2006 21:03:45 +0300 Subject: CONSTRUCT - Python's way of Ruby's "alias_method" In-Reply-To: References: Message-ID: Duncan Booth wrote: > Ilias Lazaridis wrote: > >> I would like to know, if this construct is valid, or if it can result in >> problems (that I do not see as a newcomer): >> >> 1082 try: >> 1083 from django.rework.evolve import evolvedb >> 1084 except ImportError: >> 1085 def evolvedb(): >> 1086 "Evolve Command Dummy" >> 1087 print 'Command evolvedb not imported' >> 1088 evolvedb.args ='' > > The only real problem here is that if django.rework.evolve imports > something else which doesn't exist you get your fallback code instead of > reporting the error. In other words there is a chance that you could mask a > deeper problem. > > If this worries you then you could do: > > try: > from django.rework.evolve import evolvedb > except ImportError, e: > if str(e).rsplit(' ')[-1] != 'django.rework.evolve': > raise > ... rest of code here ... I thin I understand. If the exception is _not_ caused by 'django.rework.evolve', then it will be raised, thus I can see what caused it. Very nice! . -- http://lazaridis.com From jim at trainplayer.com Fri Jun 23 09:44:01 2006 From: jim at trainplayer.com (Jim) Date: 23 Jun 2006 06:44:01 -0700 Subject: embedded Python calling app via COM In-Reply-To: <1151033409_11077@sp6iad.superfeed.net> References: <1150887820.604214.276880@i40g2000cwc.googlegroups.com> <1151033409_11077@sp6iad.superfeed.net> Message-ID: <1151070241.248469.17070@u72g2000cwu.googlegroups.com> > Pythoncom.GetActiveObject will retrieve the running instance of the app. Thanks Roger, that does seem to do the trick. I haven't tested to see what happens if there are two instances of the app running, I'm hoping it will return the frontmost visible one. -- Jim From david.bear at asu.edu Wed Jun 21 20:34:46 2006 From: david.bear at asu.edu (David Bear) Date: Wed, 21 Jun 2006 17:34:46 -0700 Subject: popen2 question Message-ID: <3026518.PBSJIyfHH0@teancum> I'm using popen2 and getting an extra 1 at the end of my output. I didn't see where this was explained in the docs so I clearly don't understand the behavior. My code is simple. (input, output) = os.popen2('whackyperlprogram') results = output.read() rc = output.close() print results The documentation said that the return code would returned with the stdout handled was closed. This does not explain why I am getting a '1' appended to the end of the results. And yes, there is some functionality bundled in a perl program that I need -- and I don't have time to reimplement what was written in perl. When I run the perl code directly, I get the output I want. When I run it through the os.popen2 module, I get an additional 1 appended. (It's all string output) Is this normal behavior for this module? What am I missing? -- David Bear -- let me buy your intellectual property, I want to own your thoughts -- From johnjsal at NOSPAMgmail.com Thu Jun 1 10:01:36 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 01 Jun 2006 14:01:36 GMT Subject: creating a new database with mysqldb In-Reply-To: References: Message-ID: <4rCfg.2206$No6.47203@news.tufts.edu> Frithiof Andreas Jensen wrote: > "John Salerno" wrote in message > news:gcKag.2113$No6.46302 at news.tufts.edu... >> Since the connect method of mysqldb requires a database name, it > seems >> like you can't use it without having a database already created. > > The web hotel I use create *one* database together with the account. > > I.O.W: > > I cannot create any databases; I can create/delete as many tables as I > like within the database (up to the disk space that I have). This is > pretty normal, I think. > > No, I can create 25 databases. From paul at boddie.org.uk Mon Jun 5 11:01:48 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 5 Jun 2006 08:01:48 -0700 Subject: Python to C converter References: <1149506038.843016.298470@c74g2000cwc.googlegroups.com> <1149513389.922653.272900@u72g2000cwu.googlegroups.com> Message-ID: <1149519708.770884.163130@g10g2000cwb.googlegroups.com> gene tani wrote: > http://pyfaq.infogami.com/can-python-be-compiled-to-machine-code-c-or-some-other-language > shd probably mention Shedskin, boost, ctypes, any others? I've added a comment, which is seemingly all that can be done right now on that page. See also this overview I wrote about Python and attempts at compilation/translation: http://groups.google.co.uk/group/comp.lang.python/msg/51785816bf5de6b1 Paul From marshall.spight at gmail.com Wed Jun 21 11:41:15 2006 From: marshall.spight at gmail.com (Marshall) Date: 21 Jun 2006 08:41:15 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: <7zzmg6amm1.fsf@app-3.diku.dk> References: <7zpshbsvjy.fsf@app-1.diku.dk><4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <1150809118.677124.142230@u72g2000cwu.googlegroups.com> <1150815461.210286.53120@r2g2000cwb.googlegroups.com> <1150823297.816352.75370@u72g2000cwu.googlegroups.com> <7zzmg6amm1.fsf@app-3.diku.dk> Message-ID: <1150904475.363283.234730@y41g2000cwy.googlegroups.com> Torben ?gidius Mogensen wrote: > > That's not true. ML has variables in the mathematical sense of > variables -- symbols that can be associated with different values at > different times. What it doesn't have is mutable variables (though it > can get the effect of those by having variables be immutable > references to mutable memory locations). While we're on the topic of terminology, here's a pet peeve of mine: "immutable variable." immutable = can't change vary-able = can change Clearly a contradiction in terms. If you have a named value that cannot be updated, it makes no sense to call it "variable" since it isn't *able* to *vary.* Let's call it a named constant. Marshall From fredrik at pythonware.com Thu Jun 8 06:17:59 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 08 Jun 2006 12:17:59 +0200 Subject: language-x-isms In-Reply-To: <1149760633.796809.166430@h76g2000cwa.googlegroups.com> References: <1149753206.451066.120960@h76g2000cwa.googlegroups.com> <1149759486.695563.110640@g10g2000cwb.googlegroups.com> <1149760633.796809.166430@h76g2000cwa.googlegroups.com> Message-ID: Alan Kennedy wrote: > Who's using a user-defined enumerate on cpython? anyone targeting older Python platforms. > On cpython, the reference to enumerate doesn't generate a NameError, > python Python 2.2.3 (#42, May 30 2003, 18:12:08) >>> enumerate Traceback (most recent call last): File "", line 1, in ? NameError: name 'enumerate' is not defined From sreeram at tachyontech.net Mon Jun 5 08:56:51 2006 From: sreeram at tachyontech.net (K.S.Sreeram) Date: Mon, 05 Jun 2006 18:26:51 +0530 Subject: How to add few pictures into one In-Reply-To: <1149511692.796038.155930@c74g2000cwc.googlegroups.com> References: <1149511692.796038.155930@c74g2000cwc.googlegroups.com> Message-ID: <44842A13.6060901@tachyontech.net> Lad wrote: > Hello , > is it possible to add( with PYTHON language) several image files into > one? Google for 'Python Imaging Library'... Regards Sreeram -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 260 bytes Desc: OpenPGP digital signature URL: From frank at niessink.com Sat Jun 17 11:12:13 2006 From: frank at niessink.com (Frank Niessink) Date: Sat, 17 Jun 2006 17:12:13 +0200 Subject: wxpython: how do i write this without the id parameter? In-Reply-To: <448e430d$1@nntp0.pdx.net> References: <448e430d$1@nntp0.pdx.net> Message-ID: <44941BCD.3080805@niessink.com> Scott David Daniels: > John Salerno wrote: >> I was reading in the wxPython wiki that most of the time you don't have >> to include the id parameter at all, and you can just use keyword >> arguments for other parameters. But I'm having trouble converting this >> code into that method (i.e., without the id parameter).... >> >> import wx >> >> class InputForm(wx.Frame): >> def __init__(self, parent, id, title): >> wx.Frame.__init__(self, parent, id, title) I usually do it like this: class InputForm(wx.Frame): def __init__(self, *args, **kwargs): super(InputForm, self).__init__(*args, **kwargs) ... Cheers, Frank From grante at visi.com Tue Jun 27 10:22:19 2006 From: grante at visi.com (Grant Edwards) Date: Tue, 27 Jun 2006 14:22:19 -0000 Subject: How do you use this list ? References: Message-ID: <12a2foromcuj30b@corp.supernews.com> On 2006-06-27, Bo Yang wrote: > I have join this list for about 4 months , and everyday I > receive hundreds of mails . There is no means to read all of > them , so I just read something interesting for me . But if so > , there are too much mails pile up in my inbox , I want to ask > how do you use this list , reading every mail come in or just > read what you think interesting ? Find an NNTP server and read it as a newsgroup. If all else fails you can read it via gmane.org. Actually having mailing lists send you mail is insane. -- Grant Edwards grante Yow! I wonder if I ought at to tell them about my visi.com PREVIOUS LIFE as a COMPLETE STRANGER? From noah.gift at gmail.com Thu Jun 22 08:38:12 2006 From: noah.gift at gmail.com (Noah Gift) Date: Thu, 22 Jun 2006 08:38:12 -0400 Subject: smtplib problem for newbie In-Reply-To: References: Message-ID: It turns out it is a cgi issue. If I run this code outside of the cgi-bin it runs just fine. The webhosting company I am using allows python cgi code to run, but I might need to check with them about how it works. Does anyone have advice on python cgi vs. psp vs. python web application frameworks? I do plan on getting my head wrapped around writing python in the web application environment but am a bit confused still. Also, wondering how django compares to ruby on rails etc. Sorry, newbie bewilderment.... Noah On 6/22/06, Noah Gift wrote: > Hi, > > I am writing a few different scripts that need to send email > confirmation and I wanted to use smtplib instead of cheating and using > os.system('mail -s "foo"....) Some of the examples I have seen don't > seem to work for me. (Note, I am new to Python and probably doing > something stupid...thanks :) ) Here is one I grabbed > http://effbot.org/librarybook/smtplib.htm > > import smtplib > import string, sys > > HOST = "localhost" > > FROM = "effbot at spam.egg" > TO = "fredrik at spam.egg" > > SUBJECT = "for your information!" > > BODY = "next week: how to fling an otter" > > body = string.join(( > "From: %s" % FROM, > "To: %s" % TO, > "Subject: %s" % SUBJECT, > "", > BODY), "\r\n") > > print body > > server = smtplib.SMTP(HOST) > server.sendmail(FROM, [TO], body) > server.quit() > > If I change this to suit my needs it looks like this: > > #!/usr/bin/python > import smtplib > import string, sys > > HOST = "localhost" > > FROM = "johny.carson at turner.com" > TO = "noah.gift at gmail.com" > > SUBJECT = "for your information!" > > BODY = "next week: how to fling an otter" > > body = string.join(( > "From: %s" % FROM, > "To: %s" % TO, > "Subject: %s" % SUBJECT, > "", > BODY), "\r\n") > > print body > > server = smtplib.SMTP(HOST) > server.sendmail(FROM, [TO], body) > server.quit() > > When I run it I get this: > > Traceback (most recent call last): > File "./3mail.py", line 2, in ? > import smtplib > File "/usr/lib64/python2.3/smtplib.py", line 49, in ? > from email.base64MIME import encode as encode_base64 > File "/usr/lib64/python2.3/email/base64MIME.py", line 28, in ? > from email.Utils import fix_eols > File "/usr/lib64/python2.3/email/Utils.py", line 10, in ? > import random > File "/usr/lib64/python2.3/random.py", line 818, in ? > _inst = Random() > File "/usr/lib64/python2.3/random.py", line 87, in __init__ > self.seed(x) > File "/usr/lib64/python2.3/random.py", line 100, in seed > a = long(time.time() * 256) # use fractional seconds > TypeError: 'module' object is not callable > From david.nospam.hopwood at blueyonder.co.uk Sun Jun 25 11:45:21 2006 From: david.nospam.hopwood at blueyonder.co.uk (David Hopwood) Date: Sun, 25 Jun 2006 15:45:21 GMT Subject: Saying "latently-typed language" is making a category mistake In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <86Qmg.10725$o4.1907@newsread2.news.pas.earthlink.net> <0neng.213767$8W1.1948@fe1.news.blueyonder.co.uk> Message-ID: Matthias Blume wrote: > David Hopwood writes: >>Patricia Shanahan wrote: >>>Vesa Karvonen wrote: >>>... >>> >>>>An example of a form of informal reasoning that (practically) every >>>>programmer does daily is termination analysis. [...] >>>>Given a program, it may be possible to formally >>>>prove that it terminates. >>> >>>To make the halting problem decidable one would have to do one of two >>>things: Depend on memory size limits, or have a language that really is >>>less expressive, at a very deep level, than any of the languages >>>mentioned in the newsgroups header for this message. >> >>I don't think Vesa was talking about trying to solve the halting problem. >> >>A type system that required termination would indeed significantly restrict >>language expressiveness -- mainly because many interactive processes are >>*intended* not to terminate. > > Most interactive processes are written in such a way that they > (effectively) consist of an infinitely repeated application of some > function f that maps the current state and the input to the new state > and the output. > > f : state * input -> state * output > > This function f itself has to terminate, i.e., if t has to be > guaranteed that after any given input, there will eventually be an > output. In most interactive systems the requirements are in fact much > stricter: the output should come "soon" after the input has been > received. > > I am pretty confident that the f for most (if not all) existing > interactive systems could be coded in a language that enforces > termination. Only the loop that repeatedly applies f would have to be > coded in a less restrictive language. This is absolutely consistent with what I said. While f could be coded in a system that *required* termination, the outer loop could not. As I mentioned in a follow-up, event loop languages such as E enforce this program structure, which would almost or entirely eliminate the need for annotations in a type system that proves termination of some subprograms. -- David Hopwood From bob at passcal.nmt.edu Tue Jun 27 13:46:16 2006 From: bob at passcal.nmt.edu (Bob Greschke) Date: Tue, 27 Jun 2006 11:46:16 -0600 Subject: Extracting 3-byte integers References: Message-ID: >I have some binary data read from a file that is arranged like > > <3-byte int> <3-byte int> <3-byte int> etc. > > The "ints" are big-endian and there are 169 of them. Is there any clever > way to convert these to regular Python ints other than (struct) unpack'ing > them one at a time and doing the math? Thanks guys! I was looking for a 'one liner' of some kind, but I guess there isn't one (too bad you can't tell array or struct.unpack how many bytes you want an integer to be). Yeah, these are signed ints so I'll have to convert them. To me balancing my checkbook involves higher "math". :) Bob From justin.azoff at gmail.com Thu Jun 22 19:19:50 2006 From: justin.azoff at gmail.com (Justin Azoff) Date: 22 Jun 2006 16:19:50 -0700 Subject: Python to PHP Login System (HTTP Post) References: Message-ID: <1151018390.792574.102920@b68g2000cwa.googlegroups.com> Jeethu Rao wrote: > You need to use httplib. > http://docs.python.org/lib/httplib-examples.html > > Jeethu Rao Not at all. They need to read the documentation for urrlib: http://docs.python.org/lib/module-urllib.html http://docs.python.org/lib/node483.html "The following example uses the "POST" method instead:".... Additionally, they probably need to use cookielib, otherwise the logged in state will not be persistant. -- - Justin From tim.peters at gmail.com Thu Jun 1 12:23:07 2006 From: tim.peters at gmail.com (Tim Peters) Date: Thu, 1 Jun 2006 12:23:07 -0400 Subject: An oddity in list comparison and element assignment In-Reply-To: <1149177617.985251.74560@c74g2000cwc.googlegroups.com> References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> Message-ID: <1f7befae0606010923o5f870b80x70f1a9d95e589cf6@mail.gmail.com> [michael.f.ellis at gmail.com] > ... > As I see it, reference copying is a very useful performance and memory > optimization. But I don't think it should undermine the validity of > assert(a==b) as a predictor of invariance under identical operations. So, as Alex said last time, Try concisely expressing your "should" -- constructively, as pseudocode that one could use to check for your "strengthened equality", not in abstract terms of constraints -- and if (as I strongly suspect) you cannot find a definition that is as simple, concise and natural as the two-liner above, this might help convince you that your desired definition would NOT be the most obvious, natural and fundamental, and therefore would not be appropriate to pick as part of the language's core. Indeed, it's an interesting problem to code up, if one wants any generality (for example, identity of immutable items _whose items or attributes are in turn immutable_ probably should not matter even for your "strengthened" equality... but that's pretty hard to express!-). So try that. In reality, you can either learn to change your expectations, or avoid virtually all object-oriented programming languages. Object identity is generally fundamental to the intended semantics of such languages, not just an optimization. Think about a simpler case: a = [1] b = a assert(a == b) a.remove(1) b.remove(1) Oops. The last line dies with an exception, despite that a==b at the third statement and that ".remove(1)" is applied to both a and b. If you think a should not equal b at the third statement "because" of this, you're going to lead a life of increasing but needless despair ;-) From fuzzyman at gmail.com Tue Jun 27 08:06:05 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 27 Jun 2006 05:06:05 -0700 Subject: Tkinter - Button Overrelief Message-ID: <1151409965.666818.179750@y41g2000cwy.googlegroups.com> Hello all, I have some Tkinter buttons that display images. I would like to change these to 'active' images when the mouse is over the button. I see that the button widget can take an 'overrelief' argument in the constructor. What values can this take ? Also - can anyone provide an example of using the equivalent of a 'mouseover' event to change the image used by a button in Tkinter ? I'm afraid google has not helped me much here. Much Appreciated, Fuzzyman http://www.voidspace.org.uk/python/index.shtml From girish at cse.iitb.ac.in Fri Jun 9 03:58:51 2006 From: girish at cse.iitb.ac.in (Girish Sahani) Date: Fri, 9 Jun 2006 13:28:51 +0530 (IST) Subject: Error in Chain of Function calls In-Reply-To: References: <53637.10.209.4.2.1149834663.squirrel@10.105.1.3> Message-ID: <52920.10.209.4.2.1149839931.squirrel@10.105.1.3> > Girish Sahani wrote: > >> However i am getting an error at the line marked with ***. > > what error ? ...line 266, in colocationMiner prunedNew = genColocations(prunedK) genColocations is a function defined before which returns prunedNew. > >> Also,i am getting a ValueError in the code below: >> >> for s in prunedNew: >> substrings = [s[:i]+s[i+1:] for i in range(len(s))] >> for string in substrings: >> if string not in prunedK: >> prunedNew.remove(s) >> continue >> continue >> >> The error is: >> prunedNew.remove(s) >> ValueError: list.remove(x): x not in list > > the ValueError means exactly what it says -- have you verified that the > value of "s" really is present in the list? did you really mean to > remove "s" and not, say, "string" ? Yes. I want to remove s from the prunedNew list if that condition is not satisfied. > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From jzgoda at o2.usun.pl Thu Jun 15 16:36:13 2006 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Thu, 15 Jun 2006 22:36:13 +0200 Subject: Which compiler will Python 2.5 / Windows (Intel) be built with? In-Reply-To: <4491b9e1$1@nntp0.pdx.net> References: <1150367139.495114.148550@g10g2000cwb.googlegroups.com> <44917535$1@nntp0.pdx.net> <1150391891.130185.4640@f6g2000cwb.googlegroups.com> <4491b9e1$1@nntp0.pdx.net> Message-ID: Scott David Daniels napisa?(a): > The disruption in Python 2.4 in switching from one compiler (VC6) to > another VS2003 was not insubstantial. By sticking with VS2003, sometime > users can at least use the same tool for Python 2.4 and Python 2.5. It > does seem inevitable we will have to switch for 2.6. We are very far > along in the process of releasing Python 2.5 (beta1 is due out soon), > and rebuilding and testing with a new translation system is too big a > change at this point. > > Note there was strong resistance to leaving VC6 for Python 2.4. That > resistance was overcome only by the fact that it was no longer possible > to purchase suitable versions of VC6. Fcuk, now it's nearly impossible to buy VC2003 toolkit. What now? Shouldn't Python dev team switch to current MS compiler? Sorry, gals and guys, but if you force us to buy something irrelevant like VC2003, you will not get our sympathy. How should I explain my boss that we need to buy one Pro license more, just to be able to build our Python app? Please, don't left us with pants down. -- Jarek Zgoda http://jpa.berlios.de/ From richardjones at optushome.com.au Mon Jun 26 00:51:34 2006 From: richardjones at optushome.com.au (Richard Jones) Date: Mon, 26 Jun 2006 14:51:34 +1000 Subject: Pygame.draw challenge is over! References: <1fmu92dode2idgq260vfnb6ona6qljtd7k@4ax.com> Message-ID: <449f67d5$0$22363$afc38c87@news.optusnet.com.au> spiffy wrote: > Congrats to Seth Yastrov for 'gravity.py' ... THE ONLY ONE THAT > WORKED! I did test that they all worked on my machine before putting them online... What issues are you having? What OS? What version of Python and PyGame? I've added this to the README.txt that comes with the files: """ These entries generally require: Python 2.4+ PyGame 1.7+ and NOTHING ELSE. """ Richard From dthierbach at usenet.arcornews.de Mon Jun 26 07:13:26 2006 From: dthierbach at usenet.arcornews.de (Dirk Thierbach) Date: Mon, 26 Jun 2006 13:13:26 +0200 Subject: Termination and type systems References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <86Qmg.10725$o4.1907@newsread2.news.pas.earthlink.net> <0neng.213767$8W1.1948@fe1.news.blueyonder.co.uk> <1151171209.684163.143410@c74g2000cwc.googlegroups.com> <4ving.213803$8W1.62401@fe1.news.blueyonder.co.uk> Message-ID: <20060626111326.18B1.0.NOFFLE@dthierbach.news.arcor.de> David Hopwood wrote: > Marshall wrote: >> David Hopwood wrote: >>> A type system that required an annotation on all subprograms that >>> do not provably terminate, OTOH, would not impact expressiveness >>> at all, and would be very useful. >> Interesting. I have always imagined doing this by allowing an >> annotation on all subprograms that *do* provably terminate. Maybe the paper "Linear types and non-size-increasing polynomial time computation" by Martin Hofmann is interesting in this respect. >From the abstract: We propose a linear type system with recursion operators for inductive datatypes which ensures that all definable functions are polynomial time computable. The system improves upon previous such systems in that recursive definitions can be arbitrarily nested; in particular, no predicativity or modality restrictions are made. It does not only ensure termination, but termination in polynomial time, so you can use those types to carry information about this as well. > If the annotation marks not-provably-terminating subprograms, then it > calls attention to those subprograms. This is what we want, since it is > less safe/correct to use a nonterminating subprogram than a terminating > one (in some contexts). That would be certainly nice, but it may be almost impossible to do in practice. It's already hard enough to guarantee termination with the extra information present in the type annotation. If this information is not present, then the language has to be probably restricted so severely to ensure termination that it is more or less useless. - Dirk From george.sakkis at gmail.com Thu Jun 22 19:48:47 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 22 Jun 2006 16:48:47 -0700 Subject: Specifing arguments type for a function References: <200606201328.02784.maric@aristote.info> <1150804645.542646.38570@g10g2000cwb.googlegroups.com> <449afb64$0$16558$636a55ce@news.free.fr> Message-ID: <1151020127.152656.26860@m73g2000cwd.googlegroups.com> Bruno Desthuilliers wrote: > George Sakkis a ?crit : > > This is ok - in theory. In practice I've found that e.g. strings are > > more often than not handled as scalars although they are typically > > iterables. > >>> hasattr('', '__iter__') > False >>> hasattr('', '__iter__') or hasattr('', '__getitem__') True > > Also tuples may or may not be considered as iterables, > > depending on what they are used for. > > >>> hasattr((), '__setitem__') > False > >>> hasattr('', '__setitem__') > False What does __setitem__ have to do with iterability ? From ptmcg at austin.rr._bogus_.com Fri Jun 16 10:29:49 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 16 Jun 2006 14:29:49 GMT Subject: Extracting values from text file References: Message-ID: "Preben Randhol" wrote in message news:slrne94rcg.2qnb.randhol at bacchus.pvv.ntnu.no... > What I first though was if there was possible to make a filter such as: > > Apples (apples) > (ducks) Ducks > (butter) g butter > > The data can be put in a hash table. > > Or maybe there are better ways? I generally want something that is > flexible so one can easily make a filter settings if the text file > format changes. > Here is a simple filter builder using pyparsing. Pyparsing runs in two passes: first, to parse your filter patterns; then to use the generated grammar to parse some incoming source string. Pyparsing comes with a similar EBNF compiler, written by Seo Sanghyeon. I'm sorry this is not really a newbie example, but it does allow you to easily construct simple filters, and the implementation will give you something to chew on... :) Pyparsing wont be as fast as re's, but I cobbled this filter compiler together in about 3/4 of an hour, and may serve as a decent prototype for a more full-featured package. -- Paul Pyparsing's home Wiki is at http://pyparsing.wikispaces.com. ----------------- from pyparsing import * sourceText = """ Apples 34 56 Ducks Some more text. 0.5 g butter """ patterns = """\ Apples (apples) (ducks:%) Ducks (butter:#) g butter""" def compilePatternList(patternList, openTagChar="(", closeTagChar=")", greedy=True): def compileType(s,l,t): return { "%" : Word(nums+"-",nums).setName("integer"), "#" : Combine(Optional("-")+Word(nums)+"."+Optional(Word(nums))).setName("float"), "$" : Word(alphas).setName("alphabetic word"), "*" : Word(printables).setName("char-group") }[t[0]] backgroundWord = Word(alphanums).setParseAction(lambda s,l,t:Literal(t[0])) matchType = Optional(Suppress(":") + oneOf("% # $ *"),default="*").setParseAction(compileType) matchPattern = Combine(openTagChar + Word(alphas,alphanums).setResultsName("nam") + matchType.setResultsName("typ") + closeTagChar) matchPattern.setParseAction(lambda s,l,t: (t.typ).setResultsName(t.nam) ) patternGrammar = OneOrMore( backgroundWord | matchPattern ).setParseAction(lambda s,l,t:And([expr for expr in t])) patterns = [] for p in patternList: print p, pattExpr = patternGrammar.parseString(p)[0] print pattExpr patterns.append(pattExpr) altern = (greedy and Or or MatchFirst) return altern( patterns ) grammar = compilePatternList( patterns.split("\n") ) print grammar allResults = ParseResults([]) for t,s,e in grammar.scanString(sourceText): print t allResults += t print print allResults.keys() for k in allResults.keys(): print k,allResults[k] ----------------- Prints: Apples (apples) {"Apples" char-group} (ducks:%) Ducks {integer "Ducks"} (butter:#) g butter {float "g" "butter"} {{"Apples" char-group} ^ {integer "Ducks"} ^ {float "g" "butter"}} ['Apples', '34'] ['56', 'Ducks'] ['0.5', 'g', 'butter'] ['butter', 'apples', 'ducks'] butter 0.5 apples 34 ducks 56 From johnjsal at NOSPAMgmail.com Thu Jun 15 12:03:27 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 15 Jun 2006 16:03:27 GMT Subject: code folding, a unique problem to python? Message-ID: Specifically, I'm using UltraEdit and perhaps there's no way perfect way to implement code folding with it, given how it uses its syntax highlighting file to do so (i.e., you have to specify an "Opening" and "Closing" character in which to enfold code, such as braces). But my question is more general: is it possible to implement code folding with Python given that it has no real block delimiters? Or is this still a matter of which particular editor/IDE you use? For my part I've tried (as was suggested elsewhere) to use 'def' as an opening and closing keyword, but this of course will enfold everything between two defs, even if you have more code between your function definitons (such as a new class definition). So maybe I'm stuck in UE, but I'm curious if there is some general way to do this, or is Python just too simple and concise for its own good? :) From tjreedy at udel.edu Mon Jun 26 15:40:23 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 26 Jun 2006 15:40:23 -0400 Subject: TypeError: Cannot create a consistent method resolution order (MRO)for bases object References: <1151345197.691600.200060@y41g2000cwy.googlegroups.com> Message-ID: wrote in message news:1151345197.691600.200060 at y41g2000cwy.googlegroups.com... > What are the reason one would get this error: TypeError: Cannot create > a consistent method resolution order (MRO) for bases object ?? Because the interpreter cannot ;-) > I can provide the code if needed.... Details beget details ;-) Yes, the class statement (header line up to ':') that bombed and the same (first line) for classes it inherits from (and their base classes). The conflict should be in the latter. tjr From david.nospam.hopwood at blueyonder.co.uk Wed Jun 21 17:56:49 2006 From: david.nospam.hopwood at blueyonder.co.uk (David Hopwood) Date: Wed, 21 Jun 2006 21:56:49 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: <1150908952.804184.218990@r2g2000cwb.googlegroups.com> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150908952.804184.218990@r2g2000cwb.googlegroups.com> Message-ID: Rob Thorpe wrote: > Vesa Karvonen wrote: > >>In comp.lang.functional Anton van Straaten wrote: >> >>>Let me add another complex subtlety, then: the above description misses >>>an important point, which is that *automated* type checking is not the >>>whole story. I.e. that compile time/runtime distinction is a kind of >>>red herring. >> >>I agree. I think that instead of "statically typed" we should say >>"typed" and instead of "(dynamically|latently) typed" we should say >>"untyped". [...] >>>It's certainly close enough to say that the *language* is untyped. >> >>Indeed. Either a language has a type system and is typed or has no >>type system and is untyped. I see very little room for confusion >>here. In my experience, the people who confuse these things are >>people from the dynamic/latent camp who wish to see types everywhere >>because they confuse typing with safety or having well-defined >>semantics. > > No. It's because the things that we call latent types we use for the > same purpose that programmers of static typed languages use static > types for. > > Statically typed programmers ensure that the value of some expression > is of some type by having the compiler check it. Programmers of > latently typed languages check, if they think it's important, by asking > what the type of the result is. > > The objection here is that advocates of statically typed language seem > to be claiming the "type" as their own word, and asking that others use > their definitions of typing, which are really specific to their > subjects of interest. As far as I can tell, the people who advocate using "typed" and "untyped" in this way are people who just want to be able to discuss all languages in a unified terminological framework, and many of them are specifically not advocates of statically typed languages. -- David Hopwood From aahz at pythoncraft.com Tue Jun 20 12:20:41 2006 From: aahz at pythoncraft.com (Aahz) Date: 20 Jun 2006 09:20:41 -0700 Subject: How to truncate/round-off decimal numbers? References: Message-ID: In article , Girish Sahani wrote: > >I want to truncate every number to 2 digits after the decimal point. I >tried the following but it doesnt work. > >>>> a = 2 >>>> b = 3 >>>> round(a*1.0 / b,2) >0.67000000000000004 > >Inspite of specifying 2 in 2nd attribute of round, it outputs all the >digits after decimal. You should also consider switching to the decimal module if you care about getting correct results. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I saw `cout' being shifted "Hello world" times to the left and stopped right there." --Steve Gonedes From vasudevram at gmail.com Mon Jun 12 12:01:20 2006 From: vasudevram at gmail.com (vasudevram) Date: 12 Jun 2006 09:01:20 -0700 Subject: Bridge: Ruby to Python communication References: <1150126134.802843.122890@h76g2000cwa.googlegroups.com> Message-ID: <1150128080.185666.5170@c74g2000cwc.googlegroups.com> digitalorganics at gmail.com wrote: > Hello all. I want a ruby and a python module to be able to communicate > with each other, access classes, instances and the like. Is there a > bridge for this? I'm aware of rupy, but the documentation seems rather > inadequate for the uninitiated. Are there other libraries/bridges or > maybe a rupy tutorial? Thank you. Hi, Don't know if there is a specific Ruby/Python bridge, but one way that will work for some needs is to use XML-RPC. Its not very difficult to understand and to program. XML-RPC is a lightweight distributed computing method, much simpler than say, CORBA. Also has less features, but may suffice for your needs. It has support for many languages and, as long as the needed libraries are there for your language, you can use any language for the client and any language for the server. I know for sure that XML-RPC supports Python and have used it with Python myself. Check out http://xmlrpc.com (and also Google for more resources on this topic) to learn more, download source code examples, and to check if there is Ruby support for it. HTH Vasudev Ram Independent software consultant http://www.geocities.com/vasudevram PDF conversion tools: http://sourceforge.net/projects/xtopdf From gdamjan at gmail.com Mon Jun 12 12:01:22 2006 From: gdamjan at gmail.com (Damjan) Date: Mon, 12 Jun 2006 18:01:22 +0200 Subject: ANN: PyQt v4.0 Released - Python Bindings for Qt v4 References: Message-ID: <448d8fd3$0$15789$14726298@news.sunsite.dk> > QtNetwork > A set of classes to support TCP and UDP socket programming and higher > level protocols (eg. HTTP). Since QtNetwork is asynchronous how does it compare to twisted? I find Qt's signals and slots easier to understand and work with than twisted deferreds. -- damjan From solisgb at gmail.com Fri Jun 30 06:32:29 2006 From: solisgb at gmail.com (luis) Date: 30 Jun 2006 03:32:29 -0700 Subject: conecting with a MsAcces DB by dao In-Reply-To: <1151655436.083906.143380@75g2000cwc.googlegroups.com> References: <1151650208.783778.186690@d56g2000cwd.googlegroups.com> <1151655436.083906.143380@75g2000cwc.googlegroups.com> Message-ID: <1151663549.731904.259030@d56g2000cwd.googlegroups.com> Iain King ha escrito: > luis wrote: > > Hi > > I'm using activestate python 2.4 on win xp 2 ed. and Ms Access 2002 > > (reading first http://starship.python.net/crew/bwilk/access.html) > > I have writed the following code > > > > def append_from_Access(self): > > try: > > import ... > > conn = win32com.client.Dispatch(r'ADODB.Connection') > > DSN = "PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA > > SOURCE=C:/Afile.mdb;" > > conn.Open(DSN) > > except Exception, inst: > > ... > > try: > > sql_statement='SELECT * FROM Mytable' > > rs = win32com.client.Dispatch(r'ADODB.Recordset') > > rs.Open(sql_statement, conn, 1, 3) > > while not rs.EOF: > > id=rs.Fields(colName.Value) #colName, valid column name > > ... > > rs.MoveNext() > > rs.Close() > > conn.Close() > > > > except Exception, inst: > > ... > > > > I'm using it for reading tables or queries in a mdb file. > > With some mdb it works fine and return a no empty recordset, but with > > others mdb files, the recordsets are void (opening the tables or > > recorsets with Ms Access are not void). > > Some help is welcome, > > Thanks in advance > > Luis > > I don't know if it's the problem your asking about, but your > rs.MoveNext() should be inside the while loop, no? Yes, is inside > > Iain From tim.peters at gmail.com Wed Jun 21 18:39:14 2006 From: tim.peters at gmail.com (Tim Peters) Date: Wed, 21 Jun 2006 18:39:14 -0400 Subject: random.jumpahead: How to jump ahead exactly N steps? In-Reply-To: References: Message-ID: <1f7befae0606211539v17d37148rf677eefd4d5e1331@mail.gmail.com> [Matthew Wilson] > The random.jumpahead documentation says this: > > Changed in version 2.3: Instead of jumping to a specific state, n steps > ahead, jumpahead(n) jumps to another state likely to be separated by > many steps.. > > I really want a way to get to the Nth value in a random series started > with a particular seed. Is there any way to quickly do what jumpahead > apparently used to do? No known way, and it seems unlikely that any quick way will be found in my lifetime ;-) for the Mersenne Twister. In Pythons <= 2.2, the underlying generator was the algebraically _very_ much simpler original Wichman-Hill generator, and jumping ahead by exactly n steps was just a matter of a few modular integer exponentiations. That took time proportional to log(n), so was extremely fast. It was also much more _necessary_ using W-H, since W-H's period was only around 10**13, while the Twister's period is around 10**6001: even if you're going to use a billion random numbers per sequence, the Twister's period has a way-way-beyond astronomical number of non-overlapping subsequences of that length. The chance of hitting an overlap is correspondingly miniscule. > I devised this function, but I suspect it runs really slowly: Well, it takes exactly as much time as it takes to call random() n times. > def trudgeforward(n): > '''Advance the random generator's state by n calls.''' > for _ in xrange(n): random.random() > > So any speed tips would be very appreciated. What are you trying to achieve in the end? Take it as a fact that there is no known way to advance the Twister by n states faster than what you've already found. From chris.uppal at metagnostic.REMOVE-THIS.org Thu Jun 22 10:49:15 2006 From: chris.uppal at metagnostic.REMOVE-THIS.org (Chris Uppal) Date: Thu, 22 Jun 2006 15:49:15 +0100 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <0%Wlg.3521$MF6.947@tornado.socal.rr.com> <44992e6c$0$664$bed64819@news.gradwell.net> Message-ID: <449aaea0$0$656$bed64819@news.gradwell.net> Andreas Rossberg wrote: [me:] > > It's worth noting, too, that (in some sense) the type of an object can > > change over time[*]. > > No. Since a type expresses invariants, this is precisely what may *not* > happen. If certain properties of an object may change then the type of > the object has to reflect that possibility. Otherwise you cannot > legitimately call it a type. Well, it seems to me that you are /assuming/ a notion of what kinds of logic can be called type (theories), and I don't share your assumptions. No offence intended. Actually I would go a little further than that. Granted that whatever logic one wants to apply in order to prove about a program execution is abstract -- and so timeless -- that does not (to my mind) imply that it must be /static/. However, even if we grant that additional restriction, that doesn't imply that the analysis itself must not be cognisant of time. I see no reason, even in practise, why a static analysis should not be able to see that the set of acceptable operations (for some definition of acceptable) for some object/value/variable can be different at different times in the execution. If the analysis is rich enough to check that the temporal constraints are [not] satisfied, then I don't see why you should want to use another word than "type" to describe the results of its analysis. -- chris From manstey at csu.edu.au Mon Jun 26 02:10:28 2006 From: manstey at csu.edu.au (manstey) Date: 25 Jun 2006 23:10:28 -0700 Subject: list problem 4 newbie Message-ID: <1151302228.249512.277690@p79g2000cwp.googlegroups.com> I can't figure out why my code is not working. I thought I had the list copied correctly: Here is my code: ============ a=[[u'HF', []], [u')F', [u'75']], [u'RE', []], [u'C', []]] b=a[:] for index in reversed(range(0,len(a)-1)): if '75' in b[index][1]: b[index][1].remove('75') b[index][1].append('99') print a,'\n',b ============ but when it finishes, I get [[u'HF', []], [u')F', ['99']], [u'RE', []], [u'C', []]] [[u'HF', []], [u')F', ['99']], [u'RE', []], [u'C', []]] instead of the desired: [[u'HF', []], [u')F', ['75']], [u'RE', []], [u'C', []]] [[u'HF', []], [u')F', ['99']], [u'RE', []], [u'C', []]] why is this? From eoinrogers at gmail.com Wed Jun 7 13:08:19 2006 From: eoinrogers at gmail.com (Byte) Date: 7 Jun 2006 10:08:19 -0700 Subject: GUI Program Error In-Reply-To: References: <1149536396.375285.319390@y43g2000cwc.googlegroups.com> <920hg.2238$No6.47697@news.tufts.edu> Message-ID: <1149700099.634036.88090@f6g2000cwb.googlegroups.com> Thanks, this works. Now, since the tutorial I was using is clearly rubbish, any better ones? For a (relative) newbie please. Also, how do I code a GUI Hello World program? -- /usr/bin/byte From ygao2004 at gmail.com Sat Jun 17 22:30:45 2006 From: ygao2004 at gmail.com (ygao) Date: 17 Jun 2006 19:30:45 -0700 Subject: how can get the module global symbol table from a function or method which it is called? Message-ID: <1150597845.758056.135740@p79g2000cwp.googlegroups.com> when a function or method is called,how can get the module global symbol table from which it is called,not the module where it is defined(this is easy). thanks! From steve at holdenweb.com Wed Jun 28 07:18:19 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 28 Jun 2006 12:18:19 +0100 Subject: Immutability In-Reply-To: References: Message-ID: Georg Brandl wrote: > Nick Maclaren wrote: > >>In article , >>Robert Kern writes: >>|> Nick Maclaren wrote: >>|> > The way that I read it, Python allows only values (and hence types) >>|> > to be immutable, and not class members. The nearest approach to the >>|> > latter is to use the name hiding conventions. >>|> > >>|> > Is that correct? >>|> >>|> You can also make properties that don't allow writing. >>|> >>|> class Foo(object): >>|> >>|> def __init__(self, bar): >>|> self._bar = bar >>|> >>|> @property >>|> def bar(self): >>|> return self._bar >> >>Thanks very much. And, what's more, I have even found its documentation! >>Whatsnew2.2. The 2.4.2 reference is, er, unhelpful. > > > Is it? > > http://docs.python.org/lib/built-in-funcs.html > > documents "property" quite well. > I can't really agree that "quite good" documentation doesn't refer to the use of property as a decorator. It's obvious that a ncessary upgrade to the docs didn't happen (and we can all understand why, I am sure). regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From gherron at islandtraining.com Sun Jun 11 15:20:42 2006 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 11 Jun 2006 12:20:42 -0700 Subject: math.pow(x,y) In-Reply-To: References: <1150049976.916474.186580@j55g2000cwa.googlegroups.com> Message-ID: <448C6D0A.9000407@islandtraining.com> Wojciech Mu?a wrote: > fl1p-fl0p wrote: > >> import math >> math.pow(34564323, 456356) >> >> will give math range error. >> >> how can i force python to process huge integers without math range >> error? Any modules i can use possibly? >> > > You have to use operator **, i.e. 34564323**456356 > That's not very practical. That computation will produce a value with more than 3.4 million digits. (That is, log10(34564323)*456356 = 3440298.) Python will attempt this, but I was not patient enough to see if it could calculate an answer today (or even this week). I doubt that you really *want* all 3.4 million digits. So what is it you really want? A scientific or engineering result as a floating point number accurate to some reasonable number of digits? That integer value modulo some other integer (as used in various cryptology schemes)? Gary Herron From steve at holdenweb.com Wed Jun 28 04:18:31 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 28 Jun 2006 09:18:31 +0100 Subject: error in ConfigParser In-Reply-To: <1151462106.410114.240200@j72g2000cwa.googlegroups.com> References: <1151462106.410114.240200@j72g2000cwa.googlegroups.com> Message-ID: pipehappy wrote: > Hello everyone: > > I came across the module ConfigParser and can use it correctly. > > import ConfigParser > fp = open('test.cfg','w+') > config = ConfigParser.ConfigParser() > config.readfp(fp) > config.add_section('test') > config.set('test', 'haha', 'hehe') > print config.sections() > config.write(fp) > > ['test'] > Traceback (most recent call last): > File "configparser.py", line 8, in ? > config.write(fp) > File "C:\Python24\lib\ConfigParser.py", line 369, in write > fp.write("[%s]\n" % section) > IOError: (0, 'Error') > > I trace into the module and when executing the line "fp.write("[%s]\n" > % section)", I find every parameter is correct: fp is still a open file > object and section is 'test', I may miss something, but I just cannot > figure it out. Can someone tell me what's going wrong here? > What is the exact intent of your code? Note that the "w+" mode is documented as truncating the file, which means that your starting configuration will always be null. My first thoughts were therefore related to file position, For what it's worth, however, note that on my system (Cygwin 2.4.3) this code only breaks the *second* time: >>> import ConfigParser >>> fp = open('test.cfg','w+') >>> config = ConfigParser.ConfigParser() >>> config.readfp(fp) >>> config.add_section('test') >>> config.set('test', 'haha', 'hehe') >>> print config.sections() ['test'] >>> config.write(fp) >>> ### should really have closed fp here? >>> import ConfigParser >>> fp = open('test.cfg','w+') >>> config = ConfigParser.ConfigParser() >>> config.readfp(fp) >>> config.add_section('test') Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.4/ConfigParser.py", line 226, in add_section raise DuplicateSectionError(section) ConfigParser.DuplicateSectionError: Section 'test' already exists >>> config.set('test', 'haha', 'hehe') >>> print config.sections() ['test'] >>> config.write(fp) >>> >>> Adding a seel to the start of the file before the failing statement seems to fix the problem, so I guess my conjecture was right. Try import ConfigParser fp = open('test.cfg','w+') config = ConfigParser.ConfigParser() config.readfp(fp) config.add_section('test') config.set('test', 'haha', 'hehe') print config.sections() fp.seek(0) config.write(fp) fp.close() But then fix that "w+" if this is more than just a test app! regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From duncan.booth at invalid.invalid Tue Jun 13 03:26:47 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 13 Jun 2006 07:26:47 GMT Subject: urllib behaves strangely References: <87wtbmdlyz.fsf@reportlab.com> Message-ID: John J. Lee wrote: >> It looks like wikipedia checks the User-Agent header and refuses to >> send pages to browsers it doesn't like. Try: > [...] > > If wikipedia is trying to discourage this kind of scraping, it's > probably not polite to do it. (I don't know what wikipedia's policies > are, though) They have a general policy against unapproved bots, which is understandable since badly behaved bots could mess up or delete pages. If you read the policy it is aimed at bots which modify wikipedia articles automatically. http://en.wikipedia.org/wiki/Wikipedia:Bots says: > This policy in a nutshell: > Programs that update pages automatically in a useful and harmless way > may be welcome if their owners seek approval first and go to great > lengths to stop them running amok or being a drain on resources. On the other hand something which is simply retrieving one or two fixed pages doesn't fit that definition of a bot so is probably alright. They even provide a link to some frameworks for writing bots e.g. http://sourceforge.net/projects/pywikipediabot/ From scott.daniels at acm.org Thu Jun 8 12:29:08 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Thu, 08 Jun 2006 09:29:08 -0700 Subject: GUI Program Error In-Reply-To: References: <1149536396.375285.319390@y43g2000cwc.googlegroups.com> <920hg.2238$No6.47697@news.tufts.edu> <1149700099.634036.88090@f6g2000cwb.googlegroups.com> Message-ID: <44884bbc$1@nntp0.pdx.net> John Salerno wrote: > >> >>> It may be a platform-specific issue: On Unix/Linux, a window *does* >>> appear when you instantiate Tk, at least with tcl/tk 8.3 and 8.4 >>> (which is the latest stable version AFAIK). Here you should have chimed in with your OS and Python versions. >> same on Windows, but it often appears *beneath* the window you're >> typing into, so you have to look for it in the task bar. >> >> this also relies on Python being able to keep the Tkinter event loop >> going behind the scenes; different command-line implementations have >> different limitations. >> >> for example, on Windows, the event loop runs only when you're at an >> empty Python prompt; as soon as you start typing the next command, the >> interpreter switches over to "text input mode", and the event loop is >> paused until you press return. > > I thought it might be something like that. A window doesn't appear for > me at all, but it may be because I haven't updated Tkinter since > installing Python, so maybe it's a little older. When running on Windows 2000 (at least), with Python 2.3 or greater, Idle now (by default) stays more separate from the process running the user's code. As a result, debugging and namespaces are more stable, but the users space doesn't have a display loop running. To help out in cases like this, Idle has the "-n" switch which means roughly "no subprocess." If you are on windows (I have no idea what system you are running on), you can create a shortcut like I have (I call it Py24One). I just copied the Idle shortcut, and changed the "target" from: C:\Python24\pythonw.exe C:\Python24\Lib\idlelib\idle.pyw to: C:\Python24\pythonw.exe C:\Python24\Lib\idlelib\idle.pyw -n That "target", by the way, can also be typed directly to the command line to start Idle in "no subprocess" mode. The big advantage to using Idle this way is that (because Idle is already running a display loop), you can see the effects of your commands immediately. So the comments in your intro will hold true. --Scott David Daniels scott.daniels at acm.org From pkarjala at paju.oulu.fi Tue Jun 20 03:15:28 2006 From: pkarjala at paju.oulu.fi (Pekka Karjalainen) Date: Tue, 20 Jun 2006 07:15:28 +0000 (UTC) Subject: Tail recursion Re: list of polynomial functions References: <1150390140.459461.169900@i40g2000cwc.googlegroups.com> <1150777400.370686.162340@i40g2000cwc.googlegroups.com> Message-ID: In article <1150777400.370686.162340 at i40g2000cwc.googlegroups.com>, Matteo wrote: >This last approach could, at least theoretically, create an arbitrarily >long list of polys, without overflowing any kind of stack. In practice, >python does not seem to perform tail recursion optimizations, and conks >out after makepolys(997) on my machine. > You can find out the conking-out limit and change it, within reason. >>> import sys >>> help (sys.getrecursionlimit) [...] >>> help (sys.setrecursionlimit) [...] Here is a recipe for tail recursion optimization at ASPN: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691 Python doesn't do any kind of tail recursion optimization by default because Guido has decided it shouldn't (at least so far). I'm sure it has been discussed in detail in Python development forums & lists, but I don't know those details. This Google search is a start, but it gives too many hits for me to shift through now: http://www.google.fi/search?q=site%3Apython.org+tail+recursion Pka From levub137 at wi.rr.com Sun Jun 11 08:27:23 2006 From: levub137 at wi.rr.com (Raymond L. Buvel) Date: Sun, 11 Jun 2006 12:27:23 GMT Subject: [ANN] clnum-1.2.1 Class Library For Numbers Python Binding Message-ID: The clnum package adds rational numbers and arbitrary precision floating point numbers in real and complex form to Python. Also provides arbitrary precision floating point replacements for the functions in the math and cmath standard library modules. Home page: http://calcrpnpy.sourceforge.net/clnum.html Changes in 1.2.1 Updated the unit test so it works on both 32 and 64 bit platforms. Only the source package was updated since there are no other changes. From frank at chagford.com Mon Jun 26 05:29:23 2006 From: frank at chagford.com (Frank Millman) Date: 26 Jun 2006 02:29:23 -0700 Subject: style question In-Reply-To: References: Message-ID: <1151314163.701348.195370@u72g2000cwu.googlegroups.com> Hari Sekhon wrote: > Is it better to do: > > message = """This is line1. > This is line2 > This is line3\n""" > > or > > message = "This is line1.\n > message = message + "This is line2\n" > message = message + "This is line3\n" > > > Since the first method does not follow python's clean and easy looking > indentation structure but the second just looks crude and ugly anyway. > > If I indent the first version so the text is lined up to match code > indentation then this comes out in the input and isn't aligned there. How about message = ("This is line1. " "This is line2 " "This is line3\n") The brackets mean that the lines are automatically treated as continuous, without the need for the ugly '\' continuation character. The opening/closing quotes on each line mean that the strings are contatenated into one long string. Frank Millman From mitsura at skynet.be Mon Jun 26 08:48:17 2006 From: mitsura at skynet.be (mitsura at skynet.be) Date: 26 Jun 2006 05:48:17 -0700 Subject: Help with conversion VB script to Python : COM objects Message-ID: <1151326097.306855.11880@y41g2000cwy.googlegroups.com> Hi, I need to re-write a VB script into Python (because I really don't like VB). The VB script is used to create a Windows COM object. (I am more of Unix guy, so COM objects are a little bit alien for me). At a certain point in the VB script, I have the following line: objPolTypes = objPmad.Cvar(objPmad.GetPolicyTypeList) Does anybody what the equivalent in Python would be? I tried: objPolTypes = objPmad.Cvar(objPmad.GetPolicyTypeList() ) but then I get the following error: " Traceback (most recent call last): File "C:\Python24\MyProgs\FodFin\test.py", line 11, in ? objPolTypes = objPmad.cvar(objPmad.GetPolicyTypeList() ) File "", line 2, in cvar pywintypes.com_error: (-2147352571, 'Type mismatch.', None, 1) " I also tried : objPolTypes = objPmad.GetPolicyTypeList() this works but I end of with a list of COM object and have no clue how to query/use them or what methods are defined for those type of objects. Any help really appreciated. With kind regards, KRis From deets at nospam.web.de Tue Jun 27 10:40:12 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 27 Jun 2006 16:40:12 +0200 Subject: Unbound Local error? How? References: Message-ID: <4gcuanF1m5nl5U1@uni-berlin.de> Hari Sekhon wrote: > import re > re_regexname = re.compile('abc') > > ..... > ..... various function defs > ..... > > def func1(): > ... > func2() > ... > > def func2(): > if re_regexname.match('abc'): > > > if __name__ == '__main__': > func1() The above clearly is not what you have. See the attached version of the above that works. So - go check for a typo or something like that. Diez -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: test.py URL: From tim.leeuwvander at nl.unisys.com Sat Jun 10 05:02:27 2006 From: tim.leeuwvander at nl.unisys.com (Tim N. van der Leeuw) Date: 10 Jun 2006 02:02:27 -0700 Subject: Allowing zero-dimensional subscripts In-Reply-To: <4evff5F1gmkhbU1@individual.net> References: <1149801040.936452.26270@i40g2000cwc.googlegroups.com> <1149807149.516004.48590@f6g2000cwb.googlegroups.com> <1149832139.948242.64160@f6g2000cwb.googlegroups.com> <1149844947.822478.128580@g10g2000cwb.googlegroups.com> <4evff5F1gmkhbU1@individual.net> Message-ID: <1149930147.353137.227210@j55g2000cwa.googlegroups.com> greg wrote: > Carl Banks wrote: > > > Think of it this way: an array with n-dimensions of length 3 would have > > 3**n total entries. How many entries would a 0-dimensional array have? > > 3**0 == 1. > > Er, hang on a minute. Along which dimension of this > 0-dimensional array does it have a length of 3? :-) > > -- > Greg Against all zero of them... ;-) Cheers, --Tim From exarkun at divmod.com Sat Jun 17 03:53:08 2006 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Sat, 17 Jun 2006 03:53:08 -0400 Subject: Legitimate use of the "is" comparison operator? In-Reply-To: <1150530591.422197.304300@p79g2000cwp.googlegroups.com> Message-ID: <20060617075308.29014.1287982850.divmod.quotient.2368@ohm> On 17 Jun 2006 00:49:51 -0700, Mike Duffy wrote: >I just recently realized that the comparison operator "is" actually >works for comparing numeric values. Now, I know that its intended use >is for testing object identity, but I have used it for a few other >things, such as type checking, and I was just wondering whether or not >it is considered bad practice in the Python Community to use it for >numerics as well. > >Example: > >a = range(5) >b = range(5) > >if len(a) is len(b): > print "They're the same size!" >else: > print "They're not the same size!" > No, this is wrong. >>> a = range(100) >>> b = range(100) >>> len(a) is len(b) False Use "is" to determine if two variables refer to exactly the same object, never to determine if two objects are equal. Jean-Paul From robert.kern at gmail.com Wed Jun 28 03:47:21 2006 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 28 Jun 2006 02:47:21 -0500 Subject: to py or not to py ? In-Reply-To: References: Message-ID: Chandrashekhar kaushik wrote: > pyton does allow this using cPickle , but it bloats the data like > anythin !!! > for example a class containing 2 integers which i expect will be 8 bytes > long .. > cPickle.dumps returns a string thats 86 bytes wide !!!! ( this is the > binary version protocol 1 ) > > anyway to improve serialization ?? Use protocol 2. Also, since it looks like you will be dealing with homogeneous arrays of numerical data, you should think about using numpy to store that data. With protocol 2, cPickle only adds 129 bytes per array no matter the size. http://www.scipy.org/NumPy -- 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 From scott.daniels at acm.org Fri Jun 23 13:56:14 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Fri, 23 Jun 2006 10:56:14 -0700 Subject: serial port servo control In-Reply-To: <1150989488.345731.49680@m73g2000cwd.googlegroups.com> References: <1150989488.345731.49680@m73g2000cwd.googlegroups.com> Message-ID: <449c2639$1@nntp0.pdx.net> Several have suggested struct, I'd suggest you look at array: import array v = array.array('B', [1, 2, 3]) for i in range(17): v[i % 3] *= max(1, i // 3) v.tostring() --Scott David Daniels scott.daniels at acm.org From overly.crazy.steve at gmail.com Thu Jun 1 20:35:03 2006 From: overly.crazy.steve at gmail.com (overly.crazy.steve at gmail.com) Date: 1 Jun 2006 17:35:03 -0700 Subject: execfile then import back In-Reply-To: <1149208230.216141.5400@f6g2000cwb.googlegroups.com> References: <1149208230.216141.5400@f6g2000cwb.googlegroups.com> Message-ID: <1149208503.207296.204200@i39g2000cwa.googlegroups.com> > ########## x.py and y.py (they are identical) ########## > import testexec > print "1:", v, testexec.v > testexec.v = 7 Oops, testexec should be changed to t instead. That is: ########## x.py and y.py (they are identical) ########## import t print "1:", v, t.v t.v = 7 From tkpmep at hotmail.com Fri Jun 2 13:39:36 2006 From: tkpmep at hotmail.com (tkpmep at hotmail.com) Date: 2 Jun 2006 10:39:36 -0700 Subject: PyExcelerator Message-ID: <1149269975.981840.286750@j55g2000cwa.googlegroups.com> I write data to Excel files using PyExcelerator 0.6.3.a and have done so successfully for small files (10-15 cells). I'm experiencing an error when writing a big chunk of data (10,000 cells) to Excel. By way of comparison, the same data writes perfectly well to a csv file using Python's built in csv module. I run the program in PyScripter, and the traceback shows the following sequence of calls: main (my routine) writeData (my routine) save Line 563 get_biff_data Line 548 get_biff_data Line 1357 __row_blocks_rec Line 1276 get_cells_biff_data Line 200 get_biff_data Line 106 SystemError: frexp() result out of range The line it stops at in get_biff_data is the line that starts with packed = def get_biff_data(self): rk_encoded = 0 packed = struct.pack(' References: <1151343860.239200.179270@c74g2000cwc.googlegroups.com> <1151354495.050012.216620@i40g2000cwc.googlegroups.com> <1151359559.762281.233630@y41g2000cwy.googlegroups.com> Message-ID: <1151392971.363265.54470@y41g2000cwy.googlegroups.com> Alex Pavluck wrote: > Peter, Why do you make such claims without any reason to do so? This > is my own thing. So, I guess I am a student but just a student of my > own accord. So, please don't reply if you don't have anything to > contribute. First: This is not "YOUR OWN THING". This group really can help, but this group AFAIK does not write homeworks. It is nothing wrong you are just a student, we are all students somehow :) Second: Few other posters were posting similar requests to this group last few days (maybe your classmates :)) so the chance it just a coincidence is very low. If I am wrong, sorry about that. Third: This group can help, but some effort (study, googling this group etc.) on your side is necessary as well. Other posters suggested you the way, where to go, but you didn't try to change your code a bit. Please read the following as well: http://www.albion.com/netiquette/corerules.html To your code: > > As for the - mynum I guess that could happen but I am just doing this > so that they will never match on first try. I guess I should just > hardcode it. > > This is what happens if I step though: > > mynum = 93 ***1*** use # sign for your comments in the code followed by the comment text. All the stuff after the # is ignored when the code is executed. Nobody can execute (examine) your code whit your comments like ***1*** To hardcode "mynum" value is IMHO very bad idea and your code will be useless if the value will be "discovered". Other suggested how to generate random number at the beginning of the code. > yournum = input("I am thinking of a number between 1 and 100.\n Guess > which number: ") ***2*** > > def strt(): ***3*** ***6*** > if yournum == mynum: ***7*** > print "Wow! You got it!" > elif yournum < mynum: ***8*** > print "Nope. Too low" ***9*** > again() ***10*** ***15*** > elif yournum > mynum: > print "Oh, your too high" > > def again(): ***4*** ***11*** > global yournum ***12*** > yournum = input("guess again: ") ***13*** > strt() ***14*** > > strt() ***5*** > > > ***15*** is the problem. It doesn't start at the top but rather where > is leaves the loop. print statement can help to solve your problem, put it (with some text that will navigate you) on the rows where you are not sure the program is not running properly. Print out the values of the mynum and yournum as well. This will be just for your "debugging" purposes. Finally you will remove it. For example you can put: print "starting the strt function", "mynum = ", mynum, "yournum =", yournum on the first row of your strt function, so you will see the code is going through there. Finally: Try to thing what will happen if the person will input character rather than integer. Again: good luck in your effort Petr Jakes > > > > > > Petr Jakes wrote: > > It smells like many student are trying to do their homework last few > > days here ... Can we now the name of your school? :) > > > > AFAIK this group does not solve homeworks here :) > > > > Just few points: > > > > at the beginning try to test the input value > > you can use "in range" or using "0 < yournum < 101" > > > > you should test if the input is an integer as well.. > > http://tinyurl.com/j468c > > > > Other suggested here which way to go. > > > > Good luck :) > > > > Petr Jakes From onurb at xiludom.gro Fri Jun 9 08:44:09 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 09 Jun 2006 14:44:09 +0200 Subject: Error in Chain of Function calls In-Reply-To: References: <53637.10.209.4.2.1149834663.squirrel@10.105.1.3> Message-ID: <44896d1a$0$4935$636a55ce@news.free.fr> Girish Sahani wrote: >>Girish Sahani wrote: >> >> >>>However i am getting an error at the line marked with ***. >> >>what error ? > > ...line 266, in colocationMiner Great. We now know at which line of an unknown file an unknown error happens. Will use my PythonPsychicPowers(tm) now to see waht's there... > >>>Also,i am getting a ValueError in the code below: (snip) >>>The error is: >>>prunedNew.remove(s) >>>ValueError: list.remove(x): x not in list >> >>the ValueError means exactly what it says -- have you verified that the >>value of "s" really is present in the list? did you really mean to >>remove "s" and not, say, "string" ? > > Yes. I want to remove s from the prunedNew list if that condition is not > satisfied. Anyway the error message is very clear : you're trying to remove a non-existant item from a list. Don't try to remove non-existent items, and you'll be fine. Hint 1 : in-place modifying a list you're iterating upon is a sure way to get into trouble Hint 2 : once you removed an item from that list, you shouldn't have to worry about deciding once again if you need to remove it... -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From ken.carlino at gmail.com Thu Jun 8 22:40:17 2006 From: ken.carlino at gmail.com (ken.carlino at gmail.com) Date: 8 Jun 2006 19:40:17 -0700 Subject: Exeucte a system command in python script In-Reply-To: <1149820344.244437.120220@g10g2000cwb.googlegroups.com> References: <1149815748.856808.200140@j55g2000cwa.googlegroups.com> <1149820344.244437.120220@g10g2000cwb.googlegroups.com> Message-ID: <1149820817.793432.38530@i39g2000cwa.googlegroups.com> I am using python 2.4, so I don' t need to insteall that module separately. ken.carlino at gmail.com wrote: > Thanks I get this error 'NameError: global name 'call' is not defined" > > I already import 'subprocess'. > > Can you pleaes tell me what am I missing? > > Robert Kern wrote: > > ken.carlino at gmail.com wrote: > > > Hi, > > > > > > I would like to execute a shell command like this in python: > > > cmd = 'ant release -Dbuild=build_proxyonly -Drev=5.1.130f > > > -Dprops=\"-MIDP20_LARGE;PUSH_FEATURE=false;MIDlet-Version=5.0;version=5.0;MIDlet-Icon=midicon15x15.png;-FOUR_WAY_NAV_FEATURE\" > > > -DThree_Branding=true' > > > > > > Which of the execl command described here should I use? > > > http://pydoc.org/1.6/os.html > > > > None. You should use the subprocess module in 2.4 (I really do hope that you're > > not using 1.6). > > > > http://docs.python.org/lib/module-subprocess.html > > > > It also works in Pythons as old as 2.2, but you'll have to install it > > separately. The website for the separate release is down at the moment, but when > > it comes back up: > > > > http://www.lysator.liu.se/~astrand/popen5/ > > > > -- > > 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 From maric at aristote.info Thu Jun 8 11:13:49 2006 From: maric at aristote.info (Maric Michaud) Date: Thu, 8 Jun 2006 17:13:49 +0200 Subject: how to switch from os.tmpnam to os.tmpfile In-Reply-To: <1149777877.945829.25390@h76g2000cwa.googlegroups.com> References: <1149773439.534989.54450@i40g2000cwc.googlegroups.com> <1149777877.945829.25390@h76g2000cwa.googlegroups.com> Message-ID: <200606081713.50745.maric@aristote.info> Well, I never used gnuplot and I didn't use Tkinter for a while, but : Le Jeudi 08 Juin 2006 16:44, Harold Fellermann a ?crit?: > ? ? ? ? tmp = os.tmpnam() > ? ? ? ? gnuplot = subprocess.Popen( > ? ? ? ? ? ? "gnuplot", shell=True, > ? ? ? ? ? ? stdin=subprocess.PIPE, stdout=file(tmp,"w") > ? ? ? ? ) > ? ? ? ? stdout,stderr = gnuplot.communicate(""" > ? ? ? ? ? ? set terminal tkcanvas interact > ? ? ? ? ? ? set output "%s" > ? ? ? ? ? ? """ % tmp + commands) assuming tmp is a os.tmpfile and you connect it to the the stdout of your gnuplot command, something like : gnuplot = subprocess.Popen( "gnuplot", shell=True, stdin=subprocess.PIPE, stdout=tmp ) stdout,stderr = gnuplot.communicate(""" set terminal tkcanvas interact set output /dev/stdout """ % tmp + commands) should do the job. > ? ? ? ? assert not stderr > ? ? ? ? self.tk.call("source",tmp) You still need to find a way to pass directly a file object to this call. Also note if that works, and if you don't need to flush the datas on disk (if they fit in memory), you can use a file-like buffer (StringIO) instead of a tmpfile, this will save resources. This said, you should consider writing your temporary file in a directory owned by you and not world writeable, which is perfectly safe. -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From michele.simionato at gmail.com Wed Jun 21 04:07:02 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 21 Jun 2006 01:07:02 -0700 Subject: dynamic inheritance In-Reply-To: <_sCdnYfsraI5AQXZnZ2dnUVZ_o-dnZ2d@comcast.com> References: <_IidnWMwvOnfRBXZnZ2dneKdnZydnZ2d@comcast.com> <44892d3a$0$5594$626a54ce@news.free.fr> <_sCdnYfsraI5AQXZnZ2dnUVZ_o-dnZ2d@comcast.com> Message-ID: <1150877222.185843.139710@m73g2000cwd.googlegroups.com> alf wrote: > I did not think about any particular problem, just thought it would be > cool to abstract out the base class. In fact you can do that in C++ (to > some extend) using templates and parameterizing the base class. Python is ways cooler than C++. This is a sensible use case where you may want to change the base class at runtime: >>> class Base(object): ... pass >>> class BasePlusDebugMethods(Base): ... pass ... >>> class C(Base): ... pass >>> C.__bases__ = (BasePlusDebugMethods,) >>> C.mro() [, , , ] (i.e. in a running program with a problem you can add debug methods and possibily even fix the problem without restarting the program). Michele Simionato From ldo at geek-central.gen.new_zealand Fri Jun 30 05:21:44 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 30 Jun 2006 21:21:44 +1200 Subject: Interprocess communication on multi-user machine References: <44a41cae$0$29145$9b4e6d93@newsread4.arcor-online.net> Message-ID: In article <44a41cae$0$29145$9b4e6d93 at newsread4.arcor-online.net>, Michael Butscher wrote: >Normally any user could connect to an open socket on a machine >regardless which user established the socket (the user's program, to be >precise). That's not true. On *nix systems, a socket is a file, and is subject to the usual file ownership and protection mechanisms. From steve at REMOVETHIScyber.com.au Sat Jun 24 21:27:16 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 25 Jun 2006 11:27:16 +1000 Subject: 2Qs References: Message-ID: On Sat, 24 Jun 2006 21:24:33 +0200, SuperHik wrote: > 1st question: > > If a make an exe with i.e. py2exe, can I get any kind of error/bug > report from the exe file saved into a file error.log and how? Write the program to write a log file as it runs? > 2nd question: [snip] > if x>10 and y>10 and z>10 and summ(tritup(x,y,z)): print "OK" Others have already suggested you use the built-in sum() function. I'll suggest you don't need it at all, because it is redundant. If the sum is zero, either all three values are zero or at least one of the values is negative. In either case the first test will fail. There are no circumstances where each of x, y and z are greater than 10 but the sum is zero; nor are there any circumstances where the sum is zero but x, y and z are still all greater than 10. -- Steven. From luismgz at gmail.com Thu Jun 1 09:59:53 2006 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 1 Jun 2006 06:59:53 -0700 Subject: DB-API: how can I find the column names in a cursor? In-Reply-To: References: Message-ID: <1149170393.230636.74000@c74g2000cwc.googlegroups.com> I don't know if it works this way with Oracle, but the python dbpai has the cursor.description method that can help. For example: cur.execute( "your query here" ) columns = [i[0] for i in cur.description] cur.description gives a lot of data about your recordset, and the first field is the column name. Hope this helps... Luis A.M wrote: > Hi > > > > I use a code similar to this to retrieve data from Oracle database: > > > > import cx_Oracle > > > > con = cx_Oracle.connect("me/secret at tns") > > cur = con.cursor() > > outcur = con.cursor() > > cur.execute(""" > > BEGIN > > MyPkg.MyProc(:cur); > > END;""", cur=outcur) > > > > for row in out_cur: > > print row > > > > > > The problem is I don't know how to find out what are the column name and > type that comes out of query (each row in cursor). > > > > Is there any possibility that my Python code can find out the column name > and type in each row in cursor? > > > > The other problem is accessing data in each row by column name. In Ruby I > can say: > > > > Print row["ColName"] > > > > In Python; however, I must access to row contents by integer index, like > PRINT ROW[0], which reduces my program's readability. > > > > Can I access to row's contents by column name? > > > > Any help would be appreciated, > > Alan From scott.daniels at acm.org Thu Jun 15 18:30:28 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Thu, 15 Jun 2006 15:30:28 -0700 Subject: Which compiler will Python 2.5 / Windows (Intel) be built with? In-Reply-To: <4491c90f$1@nntp0.pdx.net> References: <1150367139.495114.148550@g10g2000cwb.googlegroups.com> <44917535$1@nntp0.pdx.net> <1150391891.130185.4640@f6g2000cwb.googlegroups.com> <4491b9e1$1@nntp0.pdx.net> <4491c90f$1@nntp0.pdx.net> Message-ID: <4491dab7$1@nntp0.pdx.net> Scott David Daniels wrote: > Jarek Zgoda wrote: >> Sorry, gals and guys, but if you force us to buy something irrelevant >> like VC2003, you will not get our sympathy. > Oh, no. And just when our bank account was getting full from your > appreciation of our efforts. Sorry guys, I'm getting a bit too snippy from being sniped at by people who don't do the work but insist that they know the best direction for the project. I'll try to stop answering (at least in that vein) for a day or two. --Scott David Daniels scott.daniels at acm.org From jcb at iteris.com Thu Jun 1 14:50:48 2006 From: jcb at iteris.com (Metalone) Date: 1 Jun 2006 11:50:48 -0700 Subject: ctypes pointers and SendMessage In-Reply-To: References: <1149116010.351538.258990@g10g2000cwb.googlegroups.com> Message-ID: <1149187848.273374.153400@i39g2000cwa.googlegroups.com> Ok, I see what I did wrong. I forgot to define the _fields_ variable. From sreeram at tachyontech.net Tue Jun 6 15:05:50 2006 From: sreeram at tachyontech.net (K.S.Sreeram) Date: Wed, 07 Jun 2006 00:35:50 +0530 Subject: 10GB XML Blows out Memory, Suggestions? In-Reply-To: References: <1149594519.098115.8980@u72g2000cwu.googlegroups.com> <4eleh3F1eguosU1@uni-berlin.de> <4485C819.2030206@tachyontech.net> Message-ID: <4485D20E.8060604@tachyontech.net> Fredrik Lundh wrote: > both ElementTree and cElementTree support "sax-style" event generation > (through XMLTreeBuilder/XMLParser) and incremental parsing (through > iterparse). the cElementTree versions of these are even faster than > pyexpat. > > the iterparse interface is described here: > > http://effbot.org/zone/element-iterparse.htm > Thats cool! Thanks for the info! For a multi-gigabyte file, I would still recommend C/C++, because the processing code which sits on top of the XML library needs to be Python, and that could turn out to be a significant overhead in such extreme cases. Of course, the exact strategy to follow would depend on the specifics of the case, and all this speculation may not really apply! :) Regards Sreeram -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 260 bytes Desc: OpenPGP digital signature URL: From gherron at islandtraining.com Tue Jun 27 02:19:04 2006 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 26 Jun 2006 23:19:04 -0700 Subject: Select in Python In-Reply-To: <1151388082.261840.306260@75g2000cwc.googlegroups.com> References: <1151388082.261840.306260@75g2000cwc.googlegroups.com> Message-ID: <44A0CDD8.5090300@islandtraining.com> Dio wrote: > #!/usr/bin/env python2 > > from sys import stdin > from select import select > > while 1: > (rr, wr, er) = select([stdin], [], []) > for fd in rr: > print fd > > program block in the first select(), after I type something and "enter > ", it never block in select() again,why? > > Because select blocks until there is something to read on stdin, and as long as there is something to be read on stdin, it will not block. Since your program never reads in the data on stdin, your "enter\n" just sits there waiting to be read, and select always inform you of that fact by returning stdin in the rr list. If you want select to start blocking again, you must read all bytes from stdin whenever select says there are bytes to be read. Gary Herron From micklee74 at hotmail.com Tue Jun 13 23:42:51 2006 From: micklee74 at hotmail.com (micklee74 at hotmail.com) Date: 13 Jun 2006 20:42:51 -0700 Subject: proper way to use popen4 Message-ID: <1150256571.647128.199410@u72g2000cwu.googlegroups.com> hi i have to execute some SQL statements against a database using a SQL client i want to use the os.popen4 module can someone correct the way i use os.popen4? thanks fin = "select * from some_table" #sql statement client = "osql server user password" #sql client syntax fin, fout = os.popen4(client) fin.close() <--- i need to close the stdin first right? print fout.read() I get no results when i did the above... thanks From serge.orlov at gmail.com Tue Jun 27 22:35:54 2006 From: serge.orlov at gmail.com (Serge Orlov) Date: Tue, 27 Jun 2006 19:35:54 -0700 Subject: Ascii Encoding Error with UTF-8 encoder In-Reply-To: References: <44a1bbcb$1@news.eftel.com> Message-ID: On 6/27/06, Mike Currie wrote: > Thanks for the thorough explanation. > > What I am doing is converting data for processing that will be tab (for > columns) and newline (for row) delimited. Some of the data contains tabs > and newlines so, I have to convert them to something else so the file > integrity is good. Usually it is done by escaping: translate tab -> \t, new line -> \n, back slash -> \\. Python strings already have a method to do it in just one line: >>> s=chr(9)+chr(10)+chr(92) >>> print s.encode("string_escape") \t\n\\ when you're ready to convert it back you call decode("string_escape") > Not my idea, I've been left with the implementation however. The idea is actually not bad as long as you know how to cope with unicode. From sjmachin at lexicon.net Tue Jun 27 19:14:21 2006 From: sjmachin at lexicon.net (John Machin) Date: Wed, 28 Jun 2006 09:14:21 +1000 Subject: Ascii Encoding Error with UTF-8 encoder In-Reply-To: References: Message-ID: <44a1bbcb$1@news.eftel.com> On 28/06/2006 7:46 AM, Mike Currie wrote: > Can anyone explain why I'm getting an ascii encoding error when I'm trying > to write out using a UTF-8 encoder? > >>>> f = codecs.open('foo.txt', 'wU', 'utf-8') >>>> print filteredLine > this?has??tabs?and?line?breaks >>>> f.write(filteredLine) > Traceback (most recent call last): > File "", line 1, in ? > File "C:\Python24\lib\codecs.py", line 501, in write > return self.writer.write(data) > File "C:\Python24\lib\codecs.py", line 178, in write > data, consumed = self.encode(object, self.errors) > UnicodeDecodeError: 'ascii' codec can't decode byte 0x88 in position 4: > ordinal > not in range(128) > Your fundamental problem is that you are trying to decode an 8-bit string to UTF-8. The codec tries to convert your string to Unicode first, using the default encoding (ascii), which fails. Get this into your head: You encode Unicode as ascii, latin1, cp1252, utf8, gagolitic, whatever into an 8-bit string. You decode whatever from an 8-bit string into Unicode. Here is a run-down on your problem, using just the encode/decode methods instead of codecs for illustration purposes: (1) Equivalent to what you did. |>> '\x88'.encode('utf-8') Traceback (most recent call last): File "", line 1, in ? UnicodeDecodeError: 'ascii' codec can't decode byte 0x88 in position 0: ordinal not in range(128) (2) Same thing, explicitly trying to decode your 8-bit string as ASCII. |>> '\x88'.decode('ascii').encode('utf-8') Traceback (most recent call last): File "", line 1, in ? UnicodeDecodeError: 'ascii' codec can't decode byte 0x88 in position 0: ordinal not in range(128) (3) Encoding Unicode as UTF-8 works, as expected. |>> u'\x88'.encode('utf-8') '\xc2\x88' (4) But you need to know what your 8-bit data is supposed to be encoded in, before you start. |>> '\x88'.decode('cp1252').encode('utf-8') '\xcb\x86' |>> '\x88'.decode('latin1').encode('utf-8') '\xc2\x88' I am rather puzzled as to what you are trying to achieve. You appear to believe that you possess one or more 8-bit strings, encoded in latin1, which contain the C0 controls \x09 (HT) and \x0a (LF) AND the corresponding C1 controls \x88 (HTS) and \x85 (NEL). You want to change LF to NEL, and NEL to LF and similarly with the other pair. Then you want to write the result, encoded in UTF-8, to a file. The purpose behind that baroque/byzantine capering would be .... what? From onurb at xiludom.gro Tue Jun 27 04:42:45 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Tue, 27 Jun 2006 10:42:45 +0200 Subject: replace a method in class: how? In-Reply-To: References: <44A06A6B.6010200@bryant.edu> <44a08221$0$19040$636a55ce@news.free.fr> Message-ID: <44a0ef86$0$25493$626a54ce@news.free.fr> Maric Michaud wrote: > Le mardi 27 juin 2006 06:21, Bruno Desthuilliers a ?crit : > >>Maric Michaud a ?crit : >>(snip) >> >> >>>In OOP Methods are defined in *classes* not in any arbitrary object >> >>Chapter and verse, please ? AFAIK, the first O in OOP stands for >>"object", not for "class" !-) >> > > Hard to find it, indeed. > > >>Classes are just an implementation convenience, and the fact that the >>class-based model is the most usual one doesn't imply it's the only >>valid one. > > Maybe, never been told of another one, do you think of javascript prototypes ? There other prototype-based languages. And truth is that while having classes, Python's object model is much more closer to javascript's one than to Java or C++. > Well, there are no methods in this model, only functions. Nope. There are closures, not simple functions. And FWIW, what do you think methods are in Python ? Yes, functions, wrapped in a special descriptor. > >>So there's no reason one shouldn't override (or add) a method >>on a per-object basis. As a matter of fact, it's perfectly legal (and >>can be very convenient) to do so in Python. > > I never saw the term "method" used for anything except for what it means for > classes, Help on class instancemethod in module __builtin__: class instancemethod(object) | instancemethod(function, instance, class) | | Create an instance method object. > and moreover, the class model, even if it's just an implementation, > it's the one chosen by python. There's a superficial similarity with "mainstream" static OOPLs like Java/C++ etc. But Python's classes, and their relation to instances, are as dynamic as can be, and really very different from what's in most books. > For the common understanding of the model, IMHO, classes bind methods, > instances bind functions. ??? In Python, a class is nothing more than an object that: 1/ act as an object factory 2/ serves as delegatee for instances. FWIW, the proper constructor (__new__, not __init__) is free to return instances of any other class (as long as the initializer signature is compatible). -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From cweimann at k12hq.com Mon Jun 12 15:18:35 2006 From: cweimann at k12hq.com (Christopher Weimann) Date: Mon, 12 Jun 2006 15:18:35 -0400 Subject: Advanced lockfiles In-Reply-To: <448DABC1.9030801@ilm.com> References: <448DABC1.9030801@ilm.com> Message-ID: <20060612191835.GD17103@tektite.k12usa.internal> On 06/12/2006-11:00AM, David Hirschfield wrote: > > I want some kind of lockfile implementation that will allow one process > to lock a file (or create an appropriately named lockfile that other > processes will find and understand the meaning of), but there are some > important requirements: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/193488 or http://cheeseshop.python.org/pypi/pear/0.7 From steve at REMOVETHIScyber.com.au Fri Jun 23 11:45:56 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 24 Jun 2006 01:45:56 +1000 Subject: String negative indices? References: <1151054259.765401.252230@b68g2000cwa.googlegroups.com> Message-ID: On Fri, 23 Jun 2006 02:17:39 -0700, Filip Wasilewski wrote: > drtimhill at comcast.net wrote: > >> Logically, I should be able to enter x[-2:-0] to get the last and next to last characters. However, since Python doesn't distinguish between positive and negative zero, this doesn't work. Instead, I have to enter x[-2:]. > > Hooray! Logically there is no such thing as positive or negative zero, > or did I miss something in the primary? No, not in the primary, or even in the secondary, but possibly in the tertiary. For many purposes, it doesn't make sense to distinguish +0 from -0. But for other purposes, it does. For instance, in floating point maths, it may be useful for negative numbers that underflow to be distinguished from positive numbers that underflow. See, for example, http://www.savrola.com/resources/negative_zero.html In statistical mechanics, some systems can have negative absolute temperatures, including negative zero. Counter-intuitively, negative absolute temperatures aren't colder than absolute zero, but hotter than any positive temperature. So, strangely enough, a temperature of -0K is hotter than a infinitely hot temperature! (Those wacky physicists and their mathematics...) See http://en.wikipedia.org/wiki/Negative_absolute_temperature for a description. And in case you think this is just a modern version of angels dancing on the head of a pin, negative absolute temperatures are essential for lasers. In pure mathematics, zero is usually considered unsigned. However, in "non-standard analysis" using so-called "hyperreal" or "surreal" numbers, mathematicians use infinitesimals which are [sloppy hand-waving] like signed zeroes. To put it another way, only slightly less sloppy, infinitesimals are zero, but not all the same zero. When doing calculus with complex numbers, it is very important to distinguish which direction you are taking your limits in, and so lim z -> 0+0i is not necessarily the same as lim z -> 0-0i. -- Steven From cfbolz at gmx.de Mon Jun 26 11:56:01 2006 From: cfbolz at gmx.de (Carl Friedrich Bolz) Date: Mon, 26 Jun 2006 17:56:01 +0200 Subject: pypy-0.9.0: stackless, new extension compiler In-Reply-To: <2mwtb5igmo.fsf@starship.python.net> References: <2mwtb5igmo.fsf@starship.python.net> Message-ID: Hi all! Michael Hudson wrote: > The PyPy development team has been busy working and we've now packaged > our latest improvements, completed work and new experiments as > version 0.9.0, our fourth public release. Unfortunately the download links for the release tarballs did not work until very recently. They are now working though. You can download the 0.9 release of PyPy under: http://codespeak.net/download/pypy/pypy-0.9.0.tar.bz2 http://codespeak.net/download/pypy/pypy-0.9.0.tar.gz http://codespeak.net/download/pypy/pypy-0.9.0.zip For detailed notes about how to get started into the world of PyPy see here: http://codespeak.net/pypy/dist/pypy/doc/getting-started.html Sorry for the fuss and cheers, Carl Friedrich Bolz From mcPas.De.Spam at mclaveauPas.De.Spam.com Mon Jun 12 14:26:05 2006 From: mcPas.De.Spam at mclaveauPas.De.Spam.com (Michel Claveau) Date: Mon, 12 Jun 2006 20:26:05 +0200 Subject: Bridge: Ruby to Python communication References: <1150126134.802843.122890@h76g2000cwa.googlegroups.com> <1150129661.338531.289510@j55g2000cwa.googlegroups.com> Message-ID: Hi! Sorry for my bad english. Look here : http://www.mvps.org/scripting/languages/ Python, with PyWin32, can use ActiveScripting. But... only windows... -- @-salutations Michel Claveau From shejo284 at gmail.com Sun Jun 25 12:56:10 2006 From: shejo284 at gmail.com (Sheldon) Date: 25 Jun 2006 09:56:10 -0700 Subject: array manipulation without for loops In-Reply-To: <1hhhes5.1hw0kbeniihqiN%aleax@mac.com> References: <1151251578.463273.24370@m73g2000cwd.googlegroups.com> <1151253182.496596.185420@r2g2000cwb.googlegroups.com> <1hhhes5.1hw0kbeniihqiN%aleax@mac.com> Message-ID: <1151254570.730665.298450@r2g2000cwb.googlegroups.com> Alex, I am using Numeric and have created 3 arrays: zero((1215,1215),Float) Two arrays are compared and one is used to hold the mean difference between the two compared arrays. Then I compare 290 or 340 pairs of arrays. I know that memory is a problem and that is why I don't open all of these arrays at the same time. I cannot install Numpy due to my working conditions. Sorry I should have made it clear that is was Numeric I was working with. /Sheldon Alex Martelli wrote: > Sheldon wrote: > > > Hi Gary, > > > > I am really trying to cut the time down as I have 600+ arrays with > > dimensions (1215,1215) to compare and I do a lot more things with the > > arrays. If I understand you correctly, there is no way around a for > > loop? > > In pure Python (w/o extension packages) there are no 2-D arrays; so > either you're using lists of lists (and I wonder how you fit even one of > them in memory, if they're 1215 by 1215, much less 600!) or you're > already using some extension (Numeric, numarray, numpy) and aren't > telling us which one. If you're using pure Python add your extension of > choice, if you're using an extension already tell us which one, and in > each case there will be ways to perform your manipulation tasks faster > than Python-level for loops would afford. > > > Alex From aisaac0 at verizon.net Fri Jun 9 18:44:44 2006 From: aisaac0 at verizon.net (David Isaac) Date: Fri, 09 Jun 2006 22:44:44 GMT Subject: Most elegant way to generate 3-char sequence References: <1149889784.391965.271570@h76g2000cwa.googlegroups.com> Message-ID: alpha = string.lowercase x=(a+b+c for a in alpha for b in alpha for c in alpha) From metagroboliser at netscape.net Wed Jun 21 04:09:20 2006 From: metagroboliser at netscape.net (Meta) Date: Wed, 21 Jun 2006 08:09:20 GMT Subject: Are any python-LVM bindings available? Message-ID: I need to execute LVM operations from within python ... are there any packages containing direct bindings available or is forking a shell the only solution? Any thoughts would be much appreciated. cheers. From robert.thorpe at antenova.com Fri Jun 16 06:40:46 2006 From: robert.thorpe at antenova.com (Rob Thorpe) Date: 16 Jun 2006 03:40:46 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: <7zu06lqxhu.fsf@app-1.diku.dk> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> Message-ID: <1150454445.151167.283520@r2g2000cwb.googlegroups.com> Torben ?gidius Mogensen wrote: > Pascal Costanza writes: > > > Torben ?gidius Mogensen wrote: > > > > > On a similar note, is a statically typed langauge more or less > > > expressive than a dynamically typed language? Some would say less, as > > > you can write programs in a dynamically typed language that you can't > > > compile in a statically typed language (without a lot of encoding), > > > whereas the converse isn't true. > > > > It's important to get the levels right here: A programming language > > with a rich static type system is more expressive at the type level, > > but less expressive at the base level (for some useful notion of > > expressiveness ;). > > > > > However, I think this is misleading, > > > as it ignores the feedback issue: It takes longer for the average > > > programmer to get the program working in the dynamically typed > > > language. > > > > This doesn't seem to capture what I hear from Haskell programmers who > > say that it typically takes quite a while to convince the Haskell > > compiler to accept their programs. (They perceive this to be > > worthwhile because of some benefits wrt correctness they claim to get > > in return.) > > That's the point: Bugs that in dynamically typed languages would > require testing to find are found by the compiler in a statically > typed language. So whil eit may take onger to get a program thatgets > past the compiler, it takes less time to get a program that works. In my experience the opposite is true for many programs. Having to actually know the precise type of every variable while writing the program is not necessary, it's a detail often not relevant to the core problem. The language should be able to take care of itself. In complex routines it can be useful for the programmer to give types and for the compiler to issue errors when they are contradicted. But for most routines it's just an unnecessary chore that the compiler forces on the programmer. From ziga.seilnacht at gmail.com Tue Jun 27 01:39:23 2006 From: ziga.seilnacht at gmail.com (Ziga Seilnacht) Date: 26 Jun 2006 22:39:23 -0700 Subject: Traversing Inheritance Model References: <1151380076.454803.93680@i40g2000cwc.googlegroups.com> Message-ID: <1151386762.939566.264370@c74g2000cwc.googlegroups.com> digitalorganics at gmail.com wrote: > What's the best way to traverse the web of inheritance? I want to take > a class and traverse its bases and then the bases' bases etc.... > looking for a particular class. What first came to mind was nested for > loops. However, I want to know if there's some pre-existing method for > doing this or if this isn't even possible (might send me in circles > perhaps?).Thanks all. The __mro__ descriptor does what you want. Example: >>> class A(object): ... pass ... >>> class B(object): ... pass ... >>> class C(A, B): ... pass ... >>> C.__mro__ (, , , ) See: http://www.python.org/download/releases/2.2.3/descrintro/ and http://www.python.org/download/releases/2.3/mro/ for details. Ziga From grante at visi.com Thu Jun 29 12:43:02 2006 From: grante at visi.com (Grant Edwards) Date: Thu, 29 Jun 2006 16:43:02 -0000 Subject: Bug reporting impossible References: <1151598979.369897.140770@x69g2000cwx.googlegroups.com> Message-ID: <12a80omks8fm48f@corp.supernews.com> On 2006-06-29, Simon Forman wrote: > Nick Maclaren wrote: > ... >> Create a file called '' in your current directory >> containing 'print "Oh, yeah?\n"' and then import a module that >> doesn't exist. Don't include the single quotes. > > Why would you have a file named '' in your current directory? Why shouldn't you? -- Grant Edwards grante Yow! Uh-oh!! I forgot at to submit to COMPULSORY visi.com URINALYSIS! From rossberg at ps.uni-sb.de Thu Jun 22 11:36:36 2006 From: rossberg at ps.uni-sb.de (Andreas Rossberg) Date: Thu, 22 Jun 2006 17:36:36 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: <1150987852.784870.7610@y41g2000cwy.googlegroups.com> References: <7zpshbsvjy.fsf@app-1.diku.dk><4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <0%Wlg.3521$MF6.947@tornado.socal.rr.com> <44992e6c$0$664$bed64819@news.gradwell.net> <1150916327.332627.124400@g10g2000cwb.googlegroups.com> <1150987852.784870.7610@y41g2000cwy.googlegroups.com> Message-ID: Marshall wrote: >> >>>What prohibits us from describing an abstract type as a set of values? >> >>If you identify an abstract type with the set of underlying values then >>it is equivalent to the underlying representation type, i.e. there is no >>abstraction. > > I don't follow. Are you saying that a set cannot be described > intentionally? How is "the set of all objects that implement the > Foo interface" not sufficiently abstract? Is it possible you are > mixing in implementation concerns? "Values" refers to the concrete values existent in the semantics of a programming language. This set is usually infinite, but basically fixed. To describe the set of "values" of an abstract type you would need "fresh" values that did not exist before (otherwise the abstract type would be equivalent to some already existent type). So you'd need at least a theory for name generation or something similar to describe abstract types in a types-as-sets metaphor. - Andreas From conveycj at npt.nuwc.navy.mil Thu Jun 22 16:24:32 2006 From: conveycj at npt.nuwc.navy.mil (Christian Convey) Date: Thu, 22 Jun 2006 16:24:32 -0400 Subject: Status of optional static typing in Python? In-Reply-To: <449af81d$0$31818$626a54ce@news.free.fr> References: <449af81d$0$31818$626a54ce@news.free.fr> Message-ID: <449AFC80.3030002@npt.nuwc.navy.mil> Perhaps I'm deluded but I don't think so. I'll tell you my situation and I'd appreciate your take on it... I'm looking into the design a network simulator. The simulator has a few requirements: (1) I need to be able to swap in a variety of replacement components during different simulations. I.e., RadioFrequencyChannelModel, WiredNetworkChannelModel, etc. This drives me to want the notion of inherited interfaces, partly as a form of documentation. (2) I want a form of encapsulation (which I realize isn't necessarily guaranteed in all possible static typing implementations). I.e., I want to ensure that any code which accesses a ChannelModel only calls those methods that are part of the ChannelModel interface. If there's a method RadioFrequencyChannelModel.setBroadcastDistance(...), which isn't part of the generic ChannelModel interface, I don't want most of my code to be able to start using that particular method, if the code need to be able to work with all possible ChannelModel implementations. (3) I like Interfaces as a matter of documentation. It helps me to thing things through. I've got a lot of components that must support interchangeable implementations: channels, modems, MAC layers, link layers, etc. If I have an abstract MAC_layer interface, it helps me think carefully about what every MAC layer ought to provide, and it also helps me explain to other people what a MAC layer in my simulator must provide. That is, it helps me better explain to other people how the system's major components relate to each other. Now, I could use Java or C# to get functionality such as interfaces, but I loath giving up the general productive goodness of Python. That's why I'm looking for something like interfaces. But even if we disagree about the wisdom of my intentions, do you know if/when Guido's planning to work that stuff into Python? The last post I noticed from him on the topic was from 2005. At least back then he sounded pretty into it. Thanks, Christian Bruno Desthuilliers wrote: > Christian Convey a ?crit : >> Hi guys, >> >> I'm looking at developing a somewhat complex system, and I think some >> static typing will help me keep limit my confusion. > > Then I think you're suffering from an alas too common delusion. Static > typing (at least declarative static typing) will only makes your system > more complex. But if you want some help in managing complexity, you may > want to look at interfaces systems (Zope3 interfaces or Peak's Protocol) > and multidispatch (Peak's Protocol dispatch package). > -- Christian Convey Computer Scientist, Naval Undersea Warfare Centers Newport, RI (401) 832-6824 conveycj at npt.nuwc.navy.mil From scott.daniels at acm.org Thu Jun 15 13:28:14 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Thu, 15 Jun 2006 10:28:14 -0700 Subject: Python is fun (useless social thread) ;-) In-Reply-To: <449179b2$1@nntp0.pdx.net> References: <449179b2$1@nntp0.pdx.net> Message-ID: <449193e3$1@nntp0.pdx.net> Scott David Daniels wrote: > John Salerno wrote: ... And I didn't quote him at all, so my post looks like it was attributed to him, rather than in response to his message. --Scott David Daniels scott.daniels at acm.org From m.yanowitz at kearfott.com Fri Jun 2 08:20:42 2006 From: m.yanowitz at kearfott.com (Michael Yanowitz) Date: Fri, 2 Jun 2006 08:20:42 -0400 Subject: Tkinter - changing existing Dialog? In-Reply-To: <20f4l3-nga.ln1@lairds.us> Message-ID: Thanks. That is what I was looking for. The configure command (as you and John pointed out), should do what I need. The first response of starting a new thread was not what I was looking for. Michael Yanowitz -----Original Message----- In article , Michael Yanowitz wrote: >Hello: > > > I have a Tkinter GUI Dialog with many buttons and labels and text >widgets. >What I would like to do is, can I: > >1) Disable/deactivate/hide a button, text widget that is already drawn (and > of course the opposite enable/activate/show it)? . . . import Tkinter root = Tkinter.Tk() def actions(): print "Someone pushed the button." b.configure(state = Tkinter.DISABLED) b = Tkinter.Button(root, text = "Push me", command = actions) b.pack() root.mainloop() From gdr at integrable-solutions.net Sat Jun 24 15:37:45 2006 From: gdr at integrable-solutions.net (Gabriel Dos Reis) Date: 24 Jun 2006 21:37:45 +0200 Subject: Saying "latently-typed language" is making a category mistake References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <86Qmg.10725$o4.1907@newsread2.news.pas.earthlink.net> <0neng.213767$8W1.1948@fe1.news.blueyonder.co.uk> <1151171209.684163.143410@c74g2000cwc.googlegroups.com> Message-ID: "Marshall" writes: | David Hopwood wrote: | > | > A type system that required an annotation on all subprograms that do not | > provably terminate, OTOH, would not impact expressiveness at all, and would | > be very useful. | | Interesting. I have always imagined doing this by allowing an | annotation on all subprograms that *do* provably terminate. If | you go the other way, you have to annotate every function that | uses general recursion (or iteration if you swing that way) and that | seems like it might be burdensome. Further, it imposes the | annotation requirement even where the programer might not | care about it, which the reverse does not do. simple things should stay simple. Recursions that provably terminate are among the simplest ones. Annotations in those cases could be allowed, but not required. Otherwise the system might become very irritating to program with. -- Gaby From max at alcyone.com Thu Jun 1 16:47:10 2006 From: max at alcyone.com (Erik Max Francis) Date: Thu, 01 Jun 2006 13:47:10 -0700 Subject: An oddity in list comparison and element assignment In-Reply-To: <1149177617.985251.74560@c74g2000cwc.googlegroups.com> References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> Message-ID: <6dKdnVnjh5LTz-LZnZ2dnUVZ_qmdnZ2d@speakeasy.net> michael.f.ellis at gmail.com wrote: > With all due respect to your well-deserved standing in the Python > community, I'm not convinced that equality shouldn't imply invariance > under identical operations. Doo you really want 2 == 2.0 to be False? -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Without victory there is no survival. -- Winston Churchill From gneuner2/ at comcast.net Sun Jun 25 03:26:33 2006 From: gneuner2/ at comcast.net (George Neuner) Date: Sun, 25 Jun 2006 03:26:33 -0400 Subject: What is Expressiveness in a Computer Language References: <4498356b$0$659$bed64819@news.gradwell.net> <0%Wlg.3521$MF6.947@tornado.socal.rr.com> <44992e6c$0$664$bed64819@news.gradwell.net> <1150990929.210041.198580@m73g2000cwd.googlegroups.com> Message-ID: <1kcs92pmg156qdg89ksfuuslgv6njcvkt3@4ax.com> On 22 Jun 2006 08:42:09 -0700, rossberg at ps.uni-sb.de wrote: >Darren New schrieb: >> I'm pretty sure in Pascal you could say >> >> Type Apple = Integer; Orange = Integer; >> and then vars of type apple and orange were not interchangable. > >No, the following compiles perfectly fine (using GNU Pascal): > > program bla; > type > apple = integer; > orange = integer; > var > a : apple; > o : orange; > begin > a := o > end. You are both correct. The original Pascal specification failed to mention whether user defined types should be compatible by name or by structure. Though Wirth's own 1974 reference implementation used name compatibility, implementations were free to use structure compatibility instead and many did. There was a time when typing differences made Pascal code completely non-portable[1]. When Pascal was finally standardized in 1983, the committees followed C's (dubious) example and chose to use structure compatibility for simple types and name compatibility for records. [1] Wirth also failed to specify whether boolean expression evaluation should be short-circuit or complete. Again, implementations went in both directions. Some allowed either method by switch, but the type compatibility issue continued to plague Pascal until standard conforming compilers emerged in the mid 80's. George -- for email reply remove "/" from address From blais at furius.ca Sat Jun 17 17:43:14 2006 From: blais at furius.ca (Martin Blais) Date: Sat, 17 Jun 2006 17:43:14 -0400 Subject: Cycles between package imports Message-ID: <8393fff0606171443s76bce999rb7b2d86738fcf772@mail.gmail.com> Hi I'm a tad confused over a problem involving cycles between packages. Assume the following sets of files:: driver.py a/__init__.py a/alice.py b/__init__.py b/bob.py Basically, two packages a and b. Driver simply imports one of the two. This is the file that gets run:: ,---- (driver.py) | | import a.alice | `---- The package initialization files (__init__.py) both contain nothing. a.alice imports b.bob, and b.bob imports a.alice. The following works fine: ,---- (a/alice.py) | | import b.bob | `---- ,---- (b/bob.py) | | import a.alice | `---- However, if I change b/bob.py to import using "from" syntax, i.e.: ,---- (b/bob.py) | | from a import alice | `---- It does not work anymore:: Traceback (most recent call last): File "driver.py", line 3, in ? import a.alice File "/tmp/experiments/import-cycle/a/alice.py", line 9, in ? import b.bob File "/tmp/experiments/import-cycle/b/bob.py", line 9, in ? from a import alice ImportError: cannot import name alice So cycles between packages do not behave as cycles between modules--there is a subtlety. At the time that b/bob.py attempts to import a.alice, a.alice is still being imported (i.e. executed), and there is a difference between import a.alice and from a import alice I don't see why the reference to module a.alice could not be available via the "from" syntax, even if it is still incompletely initialized at the time of import. Can anyone shed some light onto this? Is there a rule for determining when a module becomes available to import from a package using the "from" syntax? From duncan.booth at invalid.invalid Thu Jun 8 09:15:51 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 8 Jun 2006 13:15:51 GMT Subject: CONSTRUCT - Python's way of Ruby's "alias_method" References: Message-ID: Ilias Lazaridis wrote: > Is there any way (beside a patch) to alter the behaviour to an > existing function. Is ther a python construct similar to the > "alias_method" of Ruby: This is a Python list. Would you care to explain what alias_method does? > > (example from an simple evolution support for a ruby orm) > > #---------------------------------------------------------------------- > -------- # use "alias_method" to enlink the code > #---------------------------------------------------------------------- > -------- > > class SqliteAdapter > alias_method :old_create_table, :create_table > def create_table(*args) > table_evolve(*args) > result = old_create_table(*args) > return result > end > end > This looks like alias_method does nothing much more than an assignment. If you want to override a method in a base class then you can do it something like: class SqliteAdapter(BaseClass): old_create_table = BaseClass.create_table def create_table(self, *args) self.table_evolve(*args) result = self.old_create_table(*args) return result but the more usual way is just to call the original method directly in the base class. class SqliteAdapter(BaseClass): def create_table(self, *args) self.table_evolve(*args) result = BaseClass.create_table(self, *args) return result If that isn't what you are trying to achieve you'll have to explain more. From Dennis.Benzinger at gmx.net Wed Jun 7 12:27:20 2006 From: Dennis.Benzinger at gmx.net (Dennis Benzinger) Date: Wed, 07 Jun 2006 18:27:20 +0200 Subject: creating and naming objects In-Reply-To: <1149696358.065614.76150@h76g2000cwa.googlegroups.com> References: <1149696358.065614.76150@h76g2000cwa.googlegroups.com> Message-ID: <4486fe6d@news.uni-ulm.de> Brian wrote: > [...] > For example, lets say that I have a class that creates a student > object. > > Class Student: > def setName(self, name) > self.name = name > def setId(self, id) > self.id = id > > Then I instantiate that object in a method: > > def createStudent(): > foo = Student() > /add stuff > > Now, suppose that I want to create another Student. Do I need to name > that Student something other than foo? What happens to the original > object? If I do not supplant the original data of Student (maybe no id > for this student) does it retain the data of the previous Student > object that was not altered? I guess I am asking how do I > differentiate between objects when I do not know how many I need to > create and do not want to hard code names like Student1, Student2 etc. > [...] Just return your Student object from createStudent() and put it in a list. For example: all_students = [] for i in range(10): one_student = createStudent() # Do what you want with one_student here all_students.append(one_student) print all_students BTW: Why don't you use a constructor to create Student objects? Bye, Dennis From sreeram at tachyontech.net Sat Jun 17 09:45:10 2006 From: sreeram at tachyontech.net (K.S.Sreeram) Date: Sat, 17 Jun 2006 19:15:10 +0530 Subject: Pycrypto In-Reply-To: <1150462237.224431.213020@c74g2000cwc.googlegroups.com> References: <1150446904.527285.255170@g10g2000cwb.googlegroups.com> <1150458752.342042.189650@h76g2000cwa.googlegroups.com> <1150462237.224431.213020@c74g2000cwc.googlegroups.com> Message-ID: <44940766.1020106@tachyontech.net> wittempj at hotmail.com wrote: > ValueError: Input strings must be a multiple of 16 in length As James Stroud noted, a CBC mode cipher is still a block cipher, and the input *must* be a multiple of the block size. OpenSSL provides a standard padding mechanism so that there are no input size limitations for any cipher. Have a look at http://tachyon.in/ncrypt/ It provides access to the OpenSSL ciphers (including padding). Regards Sreeram -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 260 bytes Desc: OpenPGP digital signature URL: From d__ at mac.com Tue Jun 20 08:48:53 2006 From: d__ at mac.com (David Vincent) Date: Tue, 20 Jun 2006 22:48:53 +1000 Subject: unittest behaving oddly Message-ID: <22c2f60195c6e06053af7687a157ad46@mac.com> -----BEGIN PGP SIGNED MESSAGE----- Hello I'm hoping to get some insight into a situation that seems odd to me. My Python experience is limited; I've just started using the unittest module. I've had some experience with unit test support in other languages. Two computers that I use are similarly configured; each has Python 2.3 installed as distributed with the operating system, as far as I can tell. The operating system is Mac OS X 10.3.9 in each case. The hardware differs; they are both PowerPC computers. On these machines unittest is behaving oddly, both in the same way. If I copy the example from the unittest documentation and feed it to Python, I get errors about methods in unittest. I think the example is intended to pass its tests, but on my machines the code in the example is not locating methods from unittest properly. I've done some simple things, like inspecting the unittest code in the library; it seems to make sense. For instance, the 'assertEquals' method is defined as a member of TestCase. What could be going wrong? I wonder if I should try to track down problems in the example, or in the Python library installation on these machines, or somewhere else. Below is a transcript illustrating the problem. Regards David PS: transcript illustrating the problem > Mina:~/Documents/source/unittest-debug dvincent$ cat example.py > # unittest example from documentation > > import unittest > > class IntegerArithmenticTestCase(unittest.TestCase): > def testAdd(self): ## test method names begin 'test*' > assertEquals((1 + 2), 3) > assertEquals(0 + 1, 1) > def testMultiply(self): > assertEquals((0 * 10), 0) > assertEquals((5 * 8), 40) > > if __name__ == '__main__': > unittest.main() > > Mina:~/Documents/source/unittest-debug dvincent$ python example.py > EE > ====================================================================== > ERROR: testAdd (__main__.IntegerArithmenticTestCase) > ---------------------------------------------------------------------- > Traceback (most recent call last): > File "example.py", line 7, in testAdd > assertEquals((1 + 2), 3) > NameError: global name 'assertEquals' is not defined > > ====================================================================== > ERROR: testMultiply (__main__.IntegerArithmenticTestCase) > ---------------------------------------------------------------------- > Traceback (most recent call last): > File "example.py", line 10, in testMultiply > assertEquals((0 * 10), 0) > NameError: global name 'assertEquals' is not defined > > ---------------------------------------------------------------------- > Ran 2 tests in 0.045s > > FAILED (errors=2) > Mina:~/Documents/source/unittest-debug dvincent$ python -V > Python 2.3 > Mina:~/Documents/source/unittest-debug dvincent$ - -- David A Vincent dvincent at toshiba-tap.com Software Engineer telephone +61 2 9850-2593 RESEARCH AND DEVELOPMENT TOSHIBA (AUSTRALIA) PTY. LIMITED "The situation is hopeless, we must take the next step." P.Casals -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (Darwin) iQCVAwUBRJfutpjExRNGDpoZAQFb/QP9H360XupArE3NuLZvI3PPpPIs2Ht9JcLw P7hY1iz9Bl7A/7RBNVjJeegYByJwHX+8Zlgb/uBXMlTyS8KiCsILOgeT3v+ycaZg W7VKcY4lCm1FZJRJkGvvwKtySTb54uuLoGU6kPEqrBS0vHxbhNrKacT4vNZN9UM4 NNBttvVDijk= =1l9n -----END PGP SIGNATURE----- From sekhon.hari at googlemail.com Wed Jun 21 12:02:24 2006 From: sekhon.hari at googlemail.com (Hari Sekhon) Date: Wed, 21 Jun 2006 17:02:24 +0100 Subject: memory error with zipfile module In-Reply-To: References: <446e07ab$0$12795$636a55ce@news.free.fr> <1148072514.207383.26370@j55g2000cwa.googlegroups.com> <446e51e6$0$6831$636a55ce@news.free.fr> <4499689D.1000206@gmail.com> Message-ID: <44996D90.4000802@gmail.com> Fredrik Lundh wrote: > Hari Sekhon wrote: > > >> I take it that it's still a work in progress to be able to pythonify >> everything, and until then we're just gonna have to rely on shell and >> those great C coded coreutils and stuff like that. Ok, I'm rather fond >> of Bash+coreutils, highest ratio of code lines to work I've ever >> seen.... it's the real strength of Linux. Shame about Windows... >> > > you make very little sense. > > > > how so, this is effectively what we do when we run os.system(). Usually people are running system commands on unix like machines using coreutils written in C to do things that are either difficult or near impossible to do in python... I've seen people using everything from zip to touch, either out of laziness or out of the fact it wouldn't work very well in python, this zip case is a good example. Sometimes when doing system scripts, they're effectively Bash scripting, but taking longer to do in many more lines of code cos it's in python. That makes very little sense. -------------- next part -------------- An HTML attachment was scrubbed... URL: From fuzzyman at gmail.com Mon Jun 5 18:05:40 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 5 Jun 2006 15:05:40 -0700 Subject: C# equivalent to range() In-Reply-To: <1149509893.031953.19310@i40g2000cwc.googlegroups.com> References: <1149468919.951745.163700@g10g2000cwb.googlegroups.com> <1149481675.192638.275140@c74g2000cwc.googlegroups.com> <1149509893.031953.19310@i40g2000cwc.googlegroups.com> Message-ID: <1149545140.011616.130610@y43g2000cwc.googlegroups.com> Neuruss wrote: > Erik Max Francis wrote: > > > I'm curious, who are "us"? > > > > The regular readers of comp.lang.python. If you don't think we haven't > > seen this a zillion times before, you're kidding yourself. > > > > If you want help on a language, ask in that language's newsgroup/mailing > > list/forum/whatever. > > > > It surprises me how often people don't ask useful questions, or > > deliberately and knowingly ask questions in the wrong places, and then > > actually _defend_ their actions after they're politely but firmly > > informed how to fix the problem. You're really not making yourself look > > any better by continuing this thread ... > > Just to finish this thread: > 1) It wasn't a blunt question. I started the post apologizing for the > (not entirely) off opic question. > 2) I wasn't politely informed. It was pretty harshly. > 3) If you mean that "us" are the zillion registered users of this > mailing list, well buddy, you know a whole lot of people! > 4) At least one of these people replied kindly and correctly to my > question within seconds. Three of four more spent several minutes > whining. > The other zilion persons who were not interested (other than the four I > mentioned above) silently and peacefully ignored the question on went > on with their happy lifes. > FWIW I agree. If anyone didn't want to answer the question they didn't need to. Why be rude to someone asking a polite question. It's not as if there isn't much more *worse* noise on this group. Fuzzyman http://www.voidspace.org.uk/python/index.shtml > ? bient?t, > Neuruss From jcrocholl at googlemail.com Mon Jun 12 21:57:29 2006 From: jcrocholl at googlemail.com (Johann C. Rocholl) Date: 12 Jun 2006 18:57:29 -0700 Subject: Writing PNG with pure Python In-Reply-To: <1150152913.315502.16840@u72g2000cwu.googlegroups.com> References: <1149853401.521169.112530@i39g2000cwa.googlegroups.com> <1149889778.182865.181600@f6g2000cwb.googlegroups.com> <1149910872.025017.60160@i40g2000cwc.googlegroups.com> <1150152913.315502.16840@u72g2000cwu.googlegroups.com> Message-ID: <1150163849.760259.25250@i40g2000cwc.googlegroups.com> > > I have now decided to license my project (including the pure python PNG > > library) under the Apache License 2.0 which is less restrictive than > > the GPL in terms of sublicensing. > > But it is also incompatible with the GPL: > > http://www.fsf.org/licensing/licenses/index_html#GPLIncompatibleLicenses Thank you for enlightening me. I was under the wrong impression that the Apache License was compatible with the GPL, perhaps because it is OSI-approved, which means a different thing as I now understand. > If you're convinced that a permissive licence suits your code best, > please consider something whose side-effects you understand. If the > additional patent grant or licence termination clauses (which the FSF > don't regard as a bad thing, just something incompatible with the > current GPL/LGPL) are specifically what you want, then the Apache > Licence may be what you're after; otherwise, you should choose > something less baroque and better understood, perhaps from this list: > > http://www.fsf.org/licensing/licenses/index_html#GPLCompatibleLicenses I do believe that my code will be useful for more people if it's under a permissive license, but obviously also if it's under a GPL-compatible license. Therefore it's perhaps a good idea to change the license of my software again. Currently, I am considering the following options: - LGPL - Modified BSD License - X11 License (aka MIT License) I appreciate the simplicity of the BSD and MIT Licenses, except for the names. "BSD License" can be confused with the original BSD License, while "MIT License" according to the FSF "is misleading, since MIT has used many licenses for software." But perhaps these drawbacks are just mentioned on the FSF page to get more people to use the GPL or LGPL. :-) I don't want to start a holy war about the benefits of the GPL, but I would like some more input about the choices of licensing. Perhaps I'll put the larger part of my Project under the GPL and only some standalone library parts (like the PNG encoder) under the LGPL. If I ever want to contribute some of the code to the Python Software Foundation, I can still license it to them under the Apache License, right? But how about the parts of the code that others contribute to my software while it's licensed under the LGPL? Cheers, Johann From cfc at shell01.TheWorld.com Mon Jun 19 19:24:00 2006 From: cfc at shell01.TheWorld.com (Chris F Clark) Date: 19 Jun 2006 19:24:00 -0400 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150749670.053433.242210@p79g2000cwp.googlegroups.com> <1150754918.338770.89870@i40g2000cwc.googlegroups.com> Message-ID: Chris Smith wrote: > Marshall wrote: > > While I am quite sympathetic to this point, I have to say that > > this horse left the barn quite some time ago. > > I don't think so. Perhaps it's futile to go scouring the world for uses > of the phrase "dynamic type" and eliminating them. It's not useless to > point out when the term is used in a particularly confusing way, though, > as when it's implied that there is some class of "type errors" that is > strictly a subset of the class of "errors". Terminology is often > confused for historical reasons, but incorrect statements eventually get > corrected. Ok, so you (Chris Smith) object to the term "dynamic type". From a historical perspective it makes sense, perticular in the sense of tags. A dynamic type system involves associating tags with values and expresses variant operations in terms of those tags, with certain disallowed combinations checked (dynamicly) at run-time. A static type system eliminates some set of tags on values by syntactic analysis of annotations (types) written with or as part of the program and detects some of the disallowed compuatations (staticly) at compile time. Type errors are the errors caught by ones personal sense of which annotations are expressible, computable, and useful. Thus, each person has a distinct sense of which errors can (and/or should) be staticly caught. A personal example, I read news using Emacs, which as most readers in these newsgroups will know is a dialect of lisp that includes primitives to edit files. Most of emacs is quite robust, perhaps due to it being lisp. However, some commands (reading news being one of them) are exceptionally fragile and fail in the most undebuggable ways, often just complaining about "nil being an invalid argument" (or "stack overflow in regular expression matcher".) This is particularly true, when I am composing lisp code. If I write some lisp code and make a typographical error, the code may appear to run on some sample case and fail due to a path not explored in my sample case when applied to real data. I consider such an error to be a "type error" because I believe if I used a languages that required more type annotations, the compiler would have caught my typographical error (and no I'm not making a pun on type and typographical). Because I do a lot of this--it is easy enough for me to conjure up a small lisp macro to make some edit that it is a primary tool in my toolkit, I wish I could make my doing so more robust. It would not bother me to have to type more to do so. I simply make too many stupid errors to use emacs lisp as effectively as I would like. Now, this has nothing to do with real lisp programming, and so I do not wish to offend those who do that. However, I personally would like a staticly typed way of writing macros (and more importantly of annotating some of the existing emacs code) to remove some of the fragilities that I experience. I'm not taking avantage of the exploratory nature of lisp, except in the sense that the exploratory nature has created lots of packages which mostly work most of the time. Now, I will return this group to its much more erudite discussion of the issue. Thank you, -Chris ***************************************************************************** Chris Clark Internet : compres at world.std.com Compiler Resources, Inc. Web Site : http://world.std.com/~compres 23 Bailey Rd voice : (508) 435-5016 Berlin, MA 01503 USA fax : (978) 838-0263 (24 hours) ------------------------------------------------------------------------------ From jstroud at ucla.edu Fri Jun 23 00:56:38 2006 From: jstroud at ucla.edu (James Stroud) Date: Thu, 22 Jun 2006 21:56:38 -0700 Subject: How to generate all permutations of a string? In-Reply-To: References: Message-ID: Girish Sahani wrote: >>>thanks lawrence...however this func doesnt return the permuted strings, >>>so >>>i added some code as follows to generate a list of all the permutations: >>> >>>def permute(seq): >>> l = [] >>> if len(seq) == 0: >>> yield [] >>> else: >>> for i in range(0,len(seq)): >>> for rest in permute(seq[:i] + seq[i+1:]): >>> yield (seq[i],) + rest >>> for t in permute(seq): >>> l.append(''.join(t)) >>> return l >>> >>>This gives me a syntax error! >>>I need to output a list that has all the permutations of the input >>>string. >>> >>> >>> >>> >>> >>>>-- >>>>http://mail.python.org/mailman/listinfo/python-list >>>> >>> >>> >>p = ["".join(s) for s in permute('abcdefg')] > > > This fails to work too. I'm trying to call permute func from another func, > python gives me a TypeError as follows: > > def permute(seq): > l = [] > if len(seq) == 0: > yield [] > else: > for i in range(0,len(seq)): > for rest in permute(seq[:i] + seq[i+1:]): > yield (seq[i],) + rest > > def main(stringList): > for string in stringList: > permList = list(permute(string)) > l = ["".join(s) for s in permList] > > >>>>l = ['abc','abd','bcd'] >>>>main(l) > > TypeError: can only concatenate tuple (not "list") to tuple > I think I should have provided a context for my example. It was to be used with Lawrence D'Olivero's code and not yours. James >>> def permute(Seq) : ... """generator which yields successive permutations of the elements ... of Seq.""" ... if len(Seq) == 0 : ... yield () ... else : ... for i in range(0, len(Seq)) : ... for rest in permute(Seq[:i] + Seq[i + 1:]) : ... yield (Seq[i],) + rest ... >>> def main(stringList): ... for string in stringList: ... l = ["".join(s) for s in permute(string)] ... print l ... >>> l ['abc', 'abd', 'bcd'] >>> main(l) ['abc', 'acb', 'bac', 'bca', 'cab', 'cba'] ['abd', 'adb', 'bad', 'bda', 'dab', 'dba'] ['bcd', 'bdc', 'cbd', 'cdb', 'dbc', 'dcb'] From piet at cs.uu.nl Fri Jun 2 18:53:14 2006 From: piet at cs.uu.nl (Piet van Oostrum) Date: Sat, 03 Jun 2006 00:53:14 +0200 Subject: after del list , when I use it again, prompt 'not defined'.how could i delete its element, but not itself? References: <1149235087.256704.309360@g10g2000cwb.googlegroups.com> <1149236355.221540.136120@y43g2000cwc.googlegroups.com> Message-ID: >>>>> SuperHik (S) escribi?: >S> bearophileHUGS at lycos.com wrote: >>> python wrote: >>>> after del list , when I use it again, prompt 'not defined'.how could i >>>> delete its element,but not itself? >>> >>> This is a way: >>>>>> a = range(10) >>>>>> del a[:] >S> or simply >S> a = [] >>>>>> a >>> [] Then you *have* deleted the list and created a new one, which is different from keeping the list and deleting the elements: >>> a = range(10) >>> b = a >>> del a[:] >>> a [] >>> b [] >>> a.append(100) >>> a [100] >>> b [100] >>> a=[] >>> b [100] >>> -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From dthierbach at usenet.arcornews.de Tue Jun 27 02:55:32 2006 From: dthierbach at usenet.arcornews.de (Dirk Thierbach) Date: Tue, 27 Jun 2006 08:55:32 +0200 Subject: Termination and type systems References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <86Qmg.10725$o4.1907@newsread2.news.pas.earthlink.net> <0neng.213767$8W1.1948@fe1.news.blueyonder.co.uk> <1151171209.684163.143410@c74g2000cwc.googlegroups.com> <4ving.213803$8W1.62401@fe1.news.blueyonder.co.uk> <20060626111326.18B1.0.NOFFLE@dthierbach.news.arcor.de> Message-ID: <20060627065532.5BA.0.NOFFLE@dthierbach.news.arcor.de> David Hopwood wrote: > Dirk Thierbach wrote: > That's interesting, but linear typing imposes some quite severe > restrictions on programming style. From the example of 'h' on page 2, > it's clear that the reason for the linearity restriction is just to > ensure polynomial-time termination, and is not needed if we only want > to prove termination. Yes. It's just an example of what can be actually done with a typesystem. >> It's already hard enough to guarantee termination with the extra >> information present in the type annotation. If this information is >> not present, then the language has to be probably restricted so >> severely to ensure termination that it is more or less useless. > I think you're overestimating the difficulty of the problem. The fact > that *in general* it can be arbitrarily hard to prove termination, can > obscure the fact that for large parts of a typical program, proving > termination is usually trivial. Yes. The problem is the small parts where it's not trivial (and the size of this part depends on the actual problem the program is trying to solve). Either you make the language so restrictive that these parts are hard (see your remark above) or impossible to write, or you'll be left with a language where the compiler cannot prove termination of those small parts, so it's not a "type system" in the usual sense. Of course one could write an optional tool that automatically proves termination of the easy parts, and leaves the rest to the programmer, but again, that's a different thing. - Dirk From richardjones at optushome.com.au Tue Jun 20 05:00:01 2006 From: richardjones at optushome.com.au (Richard Jones) Date: Tue, 20 Jun 2006 19:00:01 +1000 Subject: 5 DAYS TO GO: pygame.draw challenge Message-ID: <4497b905$0$20683$afc38c87@news.optusnet.com.au> THE CHALLENGE: Create a game in up to 64kbytes of source code using only pygame (and python stdlib). No additional libraries, no external files (even ones loaded from a network). That means no PyOpenGL, no PNGs, no OGGs, etc. Feel free to jump on IRC @ freenode.net channel #pyweek. I hope to have a wiki up soon. THE DEADLINE: Start as soon as you read this announcement. Human-readable, Linux-compatible, single .py file entries must be received by richard at pyweek.org before midnight on the 25th of June, 2006. That's Australian Eastern Standard Time, which is UTC +10. Multiple entries are allowed. Teams are allowed. Monkeys are allowed! Ponies, sadly, are not allowed. THE RESULTS: All entries will be posted to a page on the http://www.pyweek.org/ website. Entry gameplay instructions and license must be included in the source or in the game itself. I will probably choose one of the entries as my favourite, and declare this in various obscure fora and private email messages. No other mention of rankings or favourites will be made. THANKS: Thanks to Phil Hassey for the challenge inspiration! -- Visit the PyWeek website: http://www.pyweek.org/ From maric at aristote.info Thu Jun 8 10:32:24 2006 From: maric at aristote.info (Maric Michaud) Date: Thu, 8 Jun 2006 16:32:24 +0200 Subject: how to switch from os.tmpnam to os.tmpfile In-Reply-To: <1149773439.534989.54450@i40g2000cwc.googlegroups.com> References: <1149773439.534989.54450@i40g2000cwc.googlegroups.com> Message-ID: <200606081632.25690.maric@aristote.info> Le Jeudi 08 Juin 2006 15:30, Harold Fellermann a ?crit?: > to os.tmpfile() which is supposed to be safer, but I do not know how to > get > the path information from the file object returned by tmpfile(). any > clues? There is no path for tmpfile, once it's closed, the file and its content are lost. from the doc : " The file has no directory entries associated with it and will be automatically deleted once there are no file descriptors for the file." You must maintain a reference to it in your program untill you don't need it anymore. -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From rvtol+news at isolution.nl Fri Jun 23 20:58:02 2006 From: rvtol+news at isolution.nl (Dr.Ruud) Date: Sat, 24 Jun 2006 02:58:02 +0200 Subject: What is Expressiveness in a Computer Language References: <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150908952.804184.218990@r2g2000cwb.googlegroups.com> <1150991074.705803.211570@m73g2000cwd.googlegroups.com> <1151083239.829296.33030@i40g2000cwc.googlegroups.com> <1151083931.162325.268050@g10g2000cwb.googlegroups.com> <1151086320.564736.272500@y41g2000cwy.googlegroups.com> <1151100483.057344.310970@g10g2000cwb.googlegroups.com> Message-ID: Marshall schreef: > Rob Thorpe: >> Can I make a type in C that can only have values between 1 and 10? >> How about a variable that can only hold odd numbers, or, to make it >> more difficult, say fibonacci numbers? > > Well, of course you can't in *C*; you can barely zip you pants with C. > But I believe you can do the above in C++, can't you? You can write self-modifying code in C, so I don't see how you can not do that in C. ;) -- Affijn, Ruud "Gewoon is een tijger." From arvind.mulay at gmail.com Sat Jun 24 06:58:47 2006 From: arvind.mulay at gmail.com (arvind) Date: 24 Jun 2006 03:58:47 -0700 Subject: Python web server Message-ID: <1151146727.087240.264800@r2g2000cwb.googlegroups.com> When I run the script on server,only HTML part gets executed. But the python code appears as it is on the screen in the text format. How to run the CGI script on web server using Python2.4.3? From marshall.spight at gmail.com Tue Jun 27 11:04:49 2006 From: marshall.spight at gmail.com (Marshall) Date: 27 Jun 2006 08:04:49 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <1151384511.223582.305760@m73g2000cwd.googlegroups.com> Message-ID: <1151420689.919204.12770@x69g2000cwx.googlegroups.com> Ketil Malde wrote: > "Marshall" writes: > > > There are also what I call "packaging" issues, such as > > being able to run partly-wrong programs on purpose so > > that one would have the opportunity to do runtime analysis > > without having to, say, implement parts of some interface > > that one isn't interested in testing yet. These could also > > be solved in a statically typed language. (Although > > historically it hasn't been done that way.) > > I keep hearing this, but I guess I fail to understand it. How > "partly-wrong" do you require the program to be? > > During development, I frequently sprinkle my (Haskell) program with > 'undefined' and 'error "implement later"' - which then lets me run the > implemented parts until execution hits one of the 'undefined's. > > The "cost" of static typing for running an incomplete program is thus > simply that I have to name entities I refer to. I'd argue that this > is good practice anyway, since it's easy to see what remains to be > done. (Python doesn't seem to, but presumably a serious dynamically > typed system would warn about references to entities not in scope?) I'll give you my understanding of it, but bear in mind that I only program in statically typed languages, and I in fact do exactly what you decribe above: stub out unimplemented methods. The issue is that, while stubbing out things may not be expensive, it is not free either. There is some mental switching cost to being in a state where one writes some code, wants to execute it, but can't, because of type system constraints that are globally applicable but not locally applicable to the task at hand, or to the specific subprogram one is working on right at that moment. Since I'm very used to doing it, it doesn't seem like an issue to me, but programmers in dynamical languages complain bitterly about this. It is my feeling that programming languages should try to be inclusive, and since this feature is easily enough accomodated, (as a 'lenient' switch to execution) it ought to be. Marshall From onurb at xiludom.gro Mon Jun 19 04:38:04 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Mon, 19 Jun 2006 10:38:04 +0200 Subject: code is data In-Reply-To: <1150606118.456390.262620@y41g2000cwy.googlegroups.com> References: <1150574111.415068.255900@p79g2000cwp.googlegroups.com> <1150606118.456390.262620@y41g2000cwy.googlegroups.com> Message-ID: <4496626e$0$30351$636a55ce@news.free.fr> Ravi Teja wrote: > BJ?rn Lindqvist wrote: > >>>Personally, I would like to see macros in Python (actually Logix >>>succeeding is good enough). But I am no language designer and the >>>community has no interest in it. When I absolutely need macros, I will >>>go elsewhere. >> >>One must wonder, when is that? When do you absolutely need macros? > > > Whenever there is significant boiler plate code that functions and > classes cannot eliminate alone. > Whenever there is a more elegant way to express your code. > > Python 2.5 introduced conditional expressions and with statement. With > macros, one would not have to wait for the language team to implement > them. More so for features which only a small part of the community has > an interest in. > > I *like* 1..5 (ada, ruby) instead of range(5). If I had macros, I would > have done it myself for *my* code. And that's the downside with macros - and with anything that's not officially part of the language or it's standard lib : everybody implements it it's own way, and you end up with dozens non-standard ways of doing the same thing. Not to say this is absolutely bad, but there's a balance to be found here. One could do function decorators long before we had official syntactic sugar for it, but it only started to be a common idiom with the @decorator syntax. Python 2.5 introduces a 'partial' type, that is quite easy to implement with 2.4 (and probably with older versions too), but having it in the builtins or standard lib means it will become the standard way to do it - no need to deal with half a dozen half-backed implementations of it no more. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From pjb at informatimago.com Wed Jun 14 16:36:52 2006 From: pjb at informatimago.com (Pascal Bourguignon) Date: Wed, 14 Jun 2006 22:36:52 +0200 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <2006061410510511272-raffaelcavallaro@pasdespamsilvousplaitmaccom> Message-ID: <878xnzv5i3.fsf@thalassa.informatimago.com> Joachim Durchholz writes: > Raffael Cavallaro schrieb: >> a program which would be perfectly permissible in a dynamically >> typed language such as common lisp - for example - heterogeneous >> lists and forward references to as yet non-existent functions. > > Um... heterogenous lists are not necessarily a sign of > expressiveness. The vast majority of cases can be transformed to > homogenous lists (though these might then contain closures or OO > objects). In lisp, all lists are homogenous: lists of T. -- __Pascal Bourguignon__ http://www.informatimago.com/ ADVISORY: There is an extremely small but nonzero chance that, through a process known as "tunneling," this product may spontaneously disappear from its present location and reappear at any random place in the universe, including your neighbor's domicile. The manufacturer will not be responsible for any damages or inconveniences that may result. From esmond.not.pitt at not.bigpond.com Sun Jun 11 06:49:22 2006 From: esmond.not.pitt at not.bigpond.com (EJP) Date: Sun, 11 Jun 2006 10:49:22 GMT Subject: Xah Lee network abuse In-Reply-To: References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148495974.975395.12920@i40g2000cwc.googlegroups.com> <1149998343.493200.144990@h76g2000cwa.googlegroups.com> Message-ID: Erik Max Francis wrote: > EJP wrote: > >> Many states have criminal as well as civil libel. >> http://en.wikipedia.org/wiki/Slander_and_libel > > The idea of using Wikipedia to back up a legal point is rather amusing > ... but still, none of the relevant parties involved live in countries > which have any form of criminal libel. OK, OK, just proffered as information, not a conclusive proof. It's the *courts* that back up legal points of course, not anything said or found here. From david.nospam.hopwood at blueyonder.co.uk Fri Jun 23 20:50:10 2006 From: david.nospam.hopwood at blueyonder.co.uk (David Hopwood) Date: Sat, 24 Jun 2006 00:50:10 GMT Subject: Travails of the JVM type system (was: What is Expressiveness in a Computer Language) In-Reply-To: <449c4826$0$657$bed64819@news.gradwell.net> References: <7zpshbsvjy.fsf@app-1.diku.dk><4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <0%Wlg.3521$MF6.947@tornado.socal.rr.com> <44992e6c$0$664$bed64819@news.gradwell.net> <449aaea0$0$656$bed64819@news.gradwell.net> <449bde5e$1$663$bed64819@news.gradwell.net> <1151082956.067238.45100@b68g2000cwa.googlegroups.com> <449c4826$0$657$bed64819@news.gradwell.net> Message-ID: <6%%mg.458332$tc.115682@fe2.news.blueyonder.co.uk> Chris Uppal wrote: > Maybe you are thinking that I mean that /because/ the JVM does verification, > etc, at "runtime" the system is hybrid ? > > Anyway that is /not/ what I mean. I'm (for these purposes) completely > uninterested in the static checking done by the Java to bytecode translator, > javac. I'm interested in what happens to the high-level, statically typed, OO, > language called "java bytecode" when the JVM sees it. That language has a > strict static type system which the JVM is required to check. That's a > /static/ check in my book -- it happens before the purportedly correct code is > accepted, rather than while that code is running. > > I am also completely uninterested (for these immediate purposes) in the run > time checking that the JVM does (the stuff that results in > NoSuchMethodException, and the like). In the wider context of the thread, I do > want to call that kind of thing (dynamic) type checking -- but those checks are > not why I call the JVMs type system hybrid either. > > Oh well, having got that far, I may as well take another stab at "hybrid". > Since the JVM is running a static type system without access to the whole text > of the program, there are some things that it is expected to check which it > can't. So it records preconditions on classes which might subsequently be > loaded. It does, but interestingly, it wasn't originally intended to. It was intended to be possible to check each classfile based only on that class' explicit dependencies, without having to record constraints on the loading of future classes. However, the designers made various mistakes with the design of ClassLoaders which resulted in the original JVM type system being unsound, and hence insecure. The problem is described in (which spells my name wrong, I just noticed). The constraint-based approach, proposed by Liang and Bracha in , was adopted in order to fix this. There were other, simpler, solutions (for example, restricting ClassLoader delegation to a strict tree structure), but the responsible people at Sun felt that they were insufficiently expressive. I thought, and still think, that they were mistaken. It is important for the type system to be no more complicated than necessary if there is to be any confidence in the security of implementations. In any case, as shown by , current JVM implementations do *not* reliably support the patterns of ClassLoader delegation that were intended to be enabled by Liang and Bracha's approach. [This "bug" (it should be classed as an RFE) is, inexplicably given how few programs are affected by it, the most voted-for bug in Sun's tracking system. I get the impression that most of the commentators don't understand how horribly complicated it would be to fix. Anyway, it hasn't been fixed for 4 years.] -- David Hopwood From cjmackey at seas.upenn.edu Wed Jun 28 23:49:49 2006 From: cjmackey at seas.upenn.edu (Carl Mackey) Date: Wed, 28 Jun 2006 20:49:49 -0700 Subject: mmap -- memory mapped file Message-ID: <44A34DDD.8090108@seas.upenn.edu> hi, i'm new to this list and new to python as well. i have a question on the memory mapped file ability python has. when i use a mmap on a file, will it copy the whole thing to ram or just whatever part of it i'm working on? basically, i'm wondering if it would be ok for me to have multiple mmap's open on very large files as i read or write from them. From sekhon.hari at googlemail.com Wed Jun 21 07:45:12 2006 From: sekhon.hari at googlemail.com (Hari Sekhon) Date: Wed, 21 Jun 2006 12:45:12 +0100 Subject: What's the best way to wrap a whole script in try..except? In-Reply-To: References: Message-ID: <44993148.8000003@gmail.com> Jon Ribbens wrote: > In article , Hari Sekhon wrote: > >> I want to wrap a whole script in try ... except. What is the best way of >> doing this? >> > > You could do this maybe: > > import sys > > def excepthook(exc_type, exc_value, tb): > import modules_needed_to_notify_exception > ... > > sys.excepthook = excepthook > > import modules_needed_by_script > ... > having tested this more, I was worried about a recursive call to exception should an exception be raised inside the function but luckily python deals and give you a double traceback. batteries included indeed. Thanks again Hari -------------- next part -------------- An HTML attachment was scrubbed... URL: From anton at appsolutions.com Fri Jun 23 07:50:44 2006 From: anton at appsolutions.com (Anton van Straaten) Date: Fri, 23 Jun 2006 11:50:44 GMT Subject: Saying "latently-typed language" is making a category mistake In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> Message-ID: Vesa Karvonen wrote: > I think that we're finally getting to the bottom of things. While reading > your reponses something became very clear to me: latent-typing and latent- > types are not a property of languages. Latent-typing, also known as > informal reasoning, is something that all programmers do as a normal part > of programming. To say that a language is latently-typed is to make a > category mistake, because latent-typing is not a property of languages. > > A programmer, working in any language, whether typed or not, performs > informal reasoning. I think that is fair to say that there is a > correspondence between type theory and such informal reasoning. The > correspondence is like the correspondence between informal and formal > math. *But* , informal reasoning (latent-typing) is not a property of > languages. Well, it's obviously the case that latent types as I've described them are not part of the usual semantics of dynamically typed languages. In other messages, I've mentioned types like "number -> number" which have no meaning in a dynamically typed language. You can only write them in comments (unless you implement some kind of type handling system), and language implementations aren't aware of such types. OTOH, a programmer reasoning explicitly about such types, writing them in comments, and perhaps using assertions to check them has, in a sense, defined a language. Having done that, and reasoned about the types in his program, he manually erases them, "leaving" code written in the original dynamically-typed language. You can think of it as though it were generated code, complete with comments describing types, injected during the erasure process. So, to address your category error objection, I would say that latent typing is a property of latently-typed languages, which are typically informally-defined supersets of what we know as dynamically-typed languages. I bet that doesn't make you happy, though. :D Still, if that sounds a bit far-fetched, let me start again at ground level, with a Haskell vs. Scheme example: let double x = x * 2 vs.: (define (double x) (* x 2)) Programmers in both languages do informal reasoning to figure out the type of 'double'. I'm assuming that the average Haskell programmer doesn't write out a proof whenever he wants to know the type of a term, and doesn't have a compiler handy. But the Haskell programmer's informal reasoning takes place in the context of a well-defined formal type system. He knows what the "type of double" means: the language defines that for him. The type-aware Scheme programmer doesn't have that luxury: before he can talk about types, he has to invent a type system, something to give meaning to an expression such as "number -> number". Performing that invention gives him types -- albeit informal types, a.k.a. latent types. In the Haskell case, the types are a property of the language. If you're willing to acknowledge the existence of something like latent types, what are they a property of? Just the amorphous informal cloud which surrounds dynamically-typed languages? Is that a satisfactory explanation of these two quite similar examples? I want to mention two other senses in which latent types become connected to real languages. That doesn't make them properties of the formal semantics of the language, but the connection is a real one at a different level. The first is that in a language without a rich formal type system, informal reasoning outside of the formal type system becomes much more important. Conversely, in Haskell, even if you accept the existence of latent types, they're close enough to static types that it's hardly necessary to consider them. This is why latent types are primarily associated with languages without rich formal type systems. The second connection is via tags: these are part of the definition of a dynamically-typed language, and if the programmer is reasoning explicitly about latent types, tags are a useful tool to help ensure that assumptions about types aren't violated. So this is a connection between a feature in the semantics of the language, and these extra-linguistic latent types. > An example of a form of informal reasoning that (practically) every > programmer does daily is termination analysis. There are type systems > that guarantee termination, but I think that is fair to say that it is not > yet understood how to make a practical general purpose language, whose > type system would guarantee termination (or at least I'm not aware of such > a language). It should also be clear that termination analysis need not > be done informally. Given a program, it may be possible to formally prove > that it terminates. Right. And this is partly why talking about latent types, as opposed to the more general "informal reasoning", makes sense: because latent types are addressing the same kinds of things that static types can capture. Type-like things. > I'm now more convinced than ever that "(latently|dynamically)-typed > language" is an oxymoron. The terminology really needs to be fixed. I agree that fixing is needed. The challenge is to do it in a way that accounts for, rather than simply ignores, the many informal correlations to formal type concepts that exist in dynamically-typed languages. Otherwise, the situation won't improve. Anton From avelldiroll at yahoo.fr Wed Jun 21 19:30:38 2006 From: avelldiroll at yahoo.fr (Avell Diroll) Date: Thu, 22 Jun 2006 01:30:38 +0200 Subject: Python at compile - possible to add to PYTHONPATH In-Reply-To: <1150930496.559207.73320@m73g2000cwd.googlegroups.com> References: <1150930496.559207.73320@m73g2000cwd.googlegroups.com> Message-ID: <4499d697$0$11922$626a54ce@news.free.fr> rh0dium wrote: (snip) > I want to add /foo/bar to the PYTHONPATH build so I don't have to add > it later on. Is there a way to do this? (snip) If i understand correctly, you want to add a directory to your PYTHONPATH for a specific script without modifying the system PYTHONPATH global variable ... To import the Gazonk() class defined in /foo/bar/baz.py without adding /foo/bar to PYTHONPATH you can try this: ### import sys sys.path.append('/foo/bar') import baz quux = baz.Gazonk() ### hope it helped ... From anton at appsolutions.com Sat Jun 24 12:43:21 2006 From: anton at appsolutions.com (Anton van Straaten) Date: Sat, 24 Jun 2006 16:43:21 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150904134.520639.71070@b68g2000cwa.googlegroups.com> <1151056505.908723.162580@u72g2000cwu.googlegroups.com> Message-ID: David Hopwood wrote: > I can accept that dynamic tagging provides some support for latent typing > performed "in the programmer's head". But that still does not mean that > dynamic tagging is the same thing as latent typing No, I'm not saying it is, although I am saying that the former supports the latter. > or that languages > that use dynamic tagging are "latently typed". This simply is not a > property of the language (as you've already conceded). Right. I see at least two issues here: one is that as a matter of shorthand, compressing "language which supports latent typing" to "latently-typed language" ought to be fine, as long as the term's meaning is understood. But beyond that, there's an issue here about the definition of "the language". When programming in a latently-typed language, a lot of action goes on outside the language - reasoning about static properties of programs that are not captured by the semantics of the language. This means that there's a sense in which the language that the programmer programs in is not the same language that has a formal semantic definition. As I mentioned in another post, programmers are essentially mentally programming in a richer language - a language which has informal (static) types - but the code they write down elides this type information, or else puts it in comments. We have to accept, then, that the formal semantic definitions of dynamically-checked languages are incomplete in some important ways. Referring to those semantic definitions as "the language", as though that's all there is to the language in a broader sense, is misleading. In this context, the term "latently-typed language" refers to the language that a programmer experiences, not to the subset of that language which is all that we're typically able to formally define. Anton From fredrik at pythonware.com Thu Jun 8 15:38:45 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 08 Jun 2006 21:38:45 +0200 Subject: wxpython: can't even create a Panel In-Reply-To: References: Message-ID: John Salerno wrote: > I'm using the sample code of the file 'simple.py' and trying to make a > single window with a panel in it, but I keep getting an error. Here's my > code: (I know I might need something else, like a Show() method for the > panel, but the error stops on the first panel line anyway. I've tried a > Layout() method but it didn't get that far). > > import wx > > class MyFrame(wx.Frame): > > def __init__(self, parent, title): > wx.Frame.__init__(self, parent, -1, title) > > panel = wx.Panel(self) hint: in python, indentation matters. From python at hope.cz Mon Jun 12 02:24:25 2006 From: python at hope.cz (Lad) Date: 11 Jun 2006 23:24:25 -0700 Subject: PIL problem after installation In-Reply-To: References: <1149954516.785869.160700@i40g2000cwc.googlegroups.com> Message-ID: <1150093465.553355.50410@f14g2000cwb.googlegroups.com> Fredrik Lundh wrote: > Lad wrote: > > > I installed PIL under Linux but now when I try it I get the error: > > > > decoder jpeg not available > > How can I correct that problem? > > if you built PIL yourself, the setup script told you how to fix this. > > - make sure you have right libraries installed (see the > "prerequisites" section in the README) > > - run setup and read the BUILD SUMMARY report carefully > > - if the setup script cannot find a component, you'll have to edit > the setup.py file and set the appropriate ROOT variable. see in- > structions in the setup.py file for details. Fredrik, Thank you for the reply. So I did the following: 1. I downloaded jpeg (from ftp://ftp.uu.net/graphics/jpeg/ ) source libraries( file jpegsrc.v6b.tar.gz) and installed them. Now in /usr/local/lib I have the following files: cjpeg ,djpeg,jpegtran,rdjpgcom and wrjpgcom 2. I opened setup.py file in Imaging 1.1.5 directory and changed JPEG_ROOT =None into JPEG_ROOT = "/usr/local/lib/" 3.ran python setup.py build_ext -i but it still says *** JPEG support not available What did I wrong? Can you please help? Thank you L. From onurb at xiludom.gro Mon Jun 19 10:20:14 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Mon, 19 Jun 2006 16:20:14 +0200 Subject: [OT] code is data In-Reply-To: References: <44965f53$0$12743$636a55ce@news.free.fr> Message-ID: <4496b29f$0$27412$626a54ce@news.free.fr> Anton Vredegoor wrote: > bruno at modulix wrote: > >> I still don't get the point. > > > Well, I've got to be careful here, lest I'd be associated with the > terr.., eh, the childp..., eh the macro-enablers. > > The idea is to have a way to transform a Python (.py) module into XML > and then do source code manipulations in XML-space using ElementTree. My my my... I'm not against the idea of dynamic source code transformation, but for heaven's sake, *why* would one put XML in the mix ??????? -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From blais at furius.ca Fri Jun 30 22:28:29 2006 From: blais at furius.ca (Martin Blais) Date: Fri, 30 Jun 2006 22:28:29 -0400 Subject: Cycles between package imports In-Reply-To: References: <1150633514.024828.95330@g10g2000cwb.googlegroups.com> Message-ID: <8393fff0606301928n416876a2ndce251aaf555f8c6@mail.gmail.com> On 6/22/06, Lawrence D'Oliveiro wrote: > In article , > "Martin Blais" wrote: > > >On 18 Jun 2006 05:25:14 -0700, John Roth wrote: > > > >> The general rule is: don't do that. It doesn't work, and the > >> hoops you have to go through to force it to work are so > >> complex and bizzare that they're not worth it. Redesign > >> the modules so you don't have cyclic dependencies. > > > >This is a matter completely aside the question. > > No it isn't. I agree with John Roth. See below. > >Whether it's worth it > >or not depends on the specific case --not included in the example-- > >and in the case where it shows up in my code, removing the cycle > >actually made sense (it does, most of the time, but not always). > > See, even you are unable to come up with an example where a cyclic > import makes sense. This is irrelevant. I'm not interested in discussing nor debating the merits of prohibiting or allowing cyclic imports with you nor with anybody else, you're wasting your time. The fact of the matter is that Python DOES allow cyclic imports, and the way that they behave depends on the particular syntax used to perform the import. This very specific particular item is what the original question was about. If you want to discuss whether Python should disallow cyclic imports to prevent users to using them, please start your own thread. cheers, > In general, the complications they introduce are simply not worth it. "worth it". Subjective. Whatever. From webraviteja at gmail.com Thu Jun 22 22:03:21 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 22 Jun 2006 19:03:21 -0700 Subject: code is data In-Reply-To: <1150860981.560847.206050@u72g2000cwu.googlegroups.com> References: <1150574111.415068.255900@p79g2000cwp.googlegroups.com> <1150606118.456390.262620@y41g2000cwy.googlegroups.com> <1150626424.563673.175060@c74g2000cwc.googlegroups.com> <1150650852.275956.249340@p79g2000cwp.googlegroups.com> <1150658597.272001.171840@r2g2000cwb.googlegroups.com> <1150772934.314520.165200@p79g2000cwp.googlegroups.com> <1150841588.382821.218340@i40g2000cwc.googlegroups.com> <1150860981.560847.206050@u72g2000cwu.googlegroups.com> Message-ID: <1151028201.631619.94720@y41g2000cwy.googlegroups.com> > I don't think that distinction is very meaningful. As a programmer I > have to understand both. > I understand the Python compiler well, and it gives me reasonably good feedback when I > get things wrong, and it has a lot of flexibility along several > orthogonal lines. > We're talking about programming languages, so it's useless to consider > a cognitive perspective without considering the compiler perspective. As some one who has followed your excellent articles, posts and tools over the last many years, I don't doubt your expertise at all. I admit I am not be entirely looking at this as a programmer. I am working in informatics for the last few years. At least in this domain, it is useful to seperate the perspectives. Sort of like designing a functional language based primarily on mathematical abstractions rather than imperative realities. Yes! Once the implementation is underway, the practical realities are unavoidable but they interfere in thinking, otherwise. > I understand you, but it's very unclear to me how you can make a thin > layer that's not horribly leaky or stunted. In my experience one or > both are likely in DSLs, and the result is horrible and only useful as > a toy. I am not making this up out of thin air. There is already an implementation, Logix, which allows you make thin layer DSLs on top of itself (which in turn sits on top of Python). It did not fly but I could not technically fault it (except maybe that it is not very optimized at the moment). Maybe with your better understanding of language implementations, you can. > I understood the distinction you were making. But you were also > speaking generally about generally programmable syntax, and I don't > think that's a good idea, and it's very unclear how that mixes with > Python. You can always do: > > model = make_model(""" > my funny syntax > """) > > And you actually get something that can be a close peer to normal > Python code. But if you are talking about Python and some novel syntax > interleaved, then the details seem to matter a lot, because the > implementation is substantial and potentially invasive. NO! I have a feeling that you are interpreting me as a language radical. I do not think that Python syntax should have too many novelties. Currently Python feels a cohesive whole. A well designed entity rather than something that evolved by accretion of features like Perl. With active attempts to prune inconsistencies for that end (Python 3000). And I value all that. But Logix does not add ANY new syntactic constructs to Python. There is a special import function that imports a macro supporting Python language variant module where one can create special syntactic constructs. I am quite satisfied with the macro capabilities of Logix. But I am just grumbling that the Python community does not find macros interesting. But without enough users, it simply dies away. From sreeram at tachyontech.net Mon Jun 19 16:18:21 2006 From: sreeram at tachyontech.net (K.S.Sreeram) Date: Tue, 20 Jun 2006 01:48:21 +0530 Subject: Calling every method of an object from __init__ In-Reply-To: <1150746953.156851.92820@r2g2000cwb.googlegroups.com> References: <1150746953.156851.92820@r2g2000cwb.googlegroups.com> Message-ID: <4497068D.3020002@tachyontech.net> Rob Cowie wrote: > class Foo(object): > def __init__(self): > #call all methods here > def test(self): > print 'The test method' > def hello(self): > print 'Hello user' class Foo(object): def __init__(self): for k in dir(self) : if not k.startswith('__') : v = getattr( self, k ) v() def test(self): print 'The test method' def hello(self): print 'Hello user' you can also add a test for 'if callable(v) :' to the for loop if you have data fields in Foo. Regards Sreeram -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 260 bytes Desc: OpenPGP digital signature URL: From vasudevram at gmail.com Sat Jun 10 12:37:58 2006 From: vasudevram at gmail.com (vasudevram) Date: 10 Jun 2006 09:37:58 -0700 Subject: PIL problem after installation In-Reply-To: References: <1149954516.785869.160700@i40g2000cwc.googlegroups.com> Message-ID: <1149957478.209940.16480@h76g2000cwa.googlegroups.com> Probably the jpeg library - libjpeg is not present on your system. Search Google for it, then download and install it. Try http://rpmfind.net also to find it: http://rpmfind.net/linux/rpm2html/search.php?query=libjpeg&submit=Search+... But Fredrik's advice is very good - whenever installing a software package, make sure to read the installation guide, release notes, etc - carefully, and then do accordingly. This can save you a lot of time and rework. ---------------------------------------------------------------------------?---------------- Vasudev Ram Independent software consultant Personal site: http://www.geocities.com/vasudevram PDF conversion tools: http://sourceforge.net/projects/xtopdf ---------------------------------------------------------------------------?---------------- Fredrik Lundh wrote: > Lad wrote: > > > I installed PIL under Linux but now when I try it I get the error: > > > > decoder jpeg not available > > How can I correct that problem? > > if you built PIL yourself, the setup script told you how to fix this. > > - make sure you have right libraries installed (see the > "prerequisites" section in the README) > > - run setup and read the BUILD SUMMARY report carefully > > - if the setup script cannot find a component, you'll have to edit > the setup.py file and set the appropriate ROOT variable. see in- > structions in the setup.py file for details. > > if you got a binary release, complain to the distributor. > > From tjreedy at udel.edu Sun Jun 4 15:09:32 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 4 Jun 2006 15:09:32 -0400 Subject: Proposed new PEP: print to expand generators References: <4482390E.7060809@cascade-sys.com> Message-ID: "Mel Wilson" wrote in message news:ibDgg.74$LV.7874 at news20.bellglobal.com... > I guess the motivation is the case of people who would set > up an iterator specifically to print from it. for i in gen: print i, print is rather trivial and gives one the option to control formatting however. tjr From edbatini at tin.it Sat Jun 24 10:32:49 2006 From: edbatini at tin.it (edoardo batini) Date: Sat, 24 Jun 2006 16:32:49 +0200 Subject: adad Message-ID: dvsdfvsdfvsdfvsf From luismgz at gmail.com Thu Jun 15 10:19:43 2006 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 15 Jun 2006 07:19:43 -0700 Subject: Python is fun (useless social thread) ;-) In-Reply-To: References: Message-ID: <1150381183.168237.120070@p79g2000cwp.googlegroups.com> Thomas Guettler wrote: > There are some things in Python I don't know very well: Decorators and > generators. But somehow I don't think that I really need them. I think that I learn best when I have a problem and I'm trying to solve it. There are features that you don't know what they're for, and you never use it, but when you come across an scenario where none of the features you know can help you, you start wondering "there must be something else..." and a quick search in google, or a python recipe, will give you the solution and a sample usage of these features. From sekhon.hari at googlemail.com Tue Jun 27 09:12:25 2006 From: sekhon.hari at googlemail.com (Hari Sekhon) Date: Tue, 27 Jun 2006 14:12:25 +0100 Subject: style question In-Reply-To: <44A12B1A.3070302@freenet.de> References: <44a01364@nntp0.pdx.net> <44A12B1A.3070302@freenet.de> Message-ID: <44A12EB9.1080304@gmail.com> Claudio Grondi wrote: > Hari Sekhon wrote: >> On 26/06/06, *Claudio Grondi* > > wrote: >> >> Scott David Daniels wrote: >> > Claudio Grondi wrote: >> > <<>> >> > >> >> When necessary to skip first line _and_ indentation: >> >> message = """ >> >> This is line 1 >> >> This is line 2 >> >> This is line 3 >> >> """.replace('\n ', '\n')[1:] # adjust here '\n ' to >> indentation >> > >> > >> > Riffing on this idea: >> > message = """ >> > This is line 1 >> > This is line 2 >> > This is line 3 >> > """.replace(""" >> > """, '\n')[1:] >> >> This was intended as an excercise for the OP in case he likes >> that kind >> of solution ... >> >> Claudio >> >> > >> > --Scott David Daniels >> > scott.daniels at acm.org >> -- >> http://mail.python.org/mailman/listinfo/python-list >> >> >> I've decided to go with >> >> message = ( >> "This is line1. " >> "This is line2 " >> "This is line3\n") >> >> since I'm declaring many different messages inside various functions >> I feel it is important to keep the indentaion and code both aligned >> properly so the code looks nice and the output looks nice. >> >> It is easier than doing replace and splicing since I want to keep it >> as simple and clean as possible, in true pythonic tradition... >> >> Thanks for the input! >> >> -h >> > Thanks for the reply and the explanation what you finally decided to > go with. > I am so happy to have the triple quotes in Python, that I use them > whenever possible - this has probably something to do with my bias > towards plain text files with human readable content, so as > readability is very important to me (and probably to many other > Pythonistas) I like most the proposed by me triple quote style as the > quotation marks in the style you prefer make the text of the 'message' > less easy to read. > > Now we can start a flame war about which style is more 'pythonic' ;-) > > Claudio > I already explained that the triple quotes don't work tidily with indentation, either the code is out of alignment or the printout is. Either way isn't good. Triple quotes are best at top level, but since I had to use many messages inside functions etc, they broke the layout of the code. I think they're both best depending on where you are putting them. I'm doing very custom messages for each different result, so it would be messy to do this at the top level. -h From onurb at xiludom.gro Mon Jun 12 12:27:11 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Mon, 12 Jun 2006 18:27:11 +0200 Subject: Searching and manipulating lists of tuples In-Reply-To: <1150117632.693617.45310@c74g2000cwc.googlegroups.com> References: <1150117632.693617.45310@c74g2000cwc.googlegroups.com> Message-ID: <448d95e0$0$29799$626a54ce@news.free.fr> MTD wrote: > Hello, > > I'm wondering if there's a quick way of resolving this problem. > > In a program, I have a list of tuples of form (str,int), where int is a > count of how often str occurs > > e.g. L = [ ("X",1),("Y",2)] would mean "X" occurs once and "Y" occurs > twice > > If I am given a string, I want to search L to see if it occurs already. > If it does, I find the corresponding tuple and increment the integer > part. If not, I append the new element with int = 1. > > e.g. > > algorithm(L, "X") would produce output L = [("X",2),("Y",2)] > algorithm(L,"Z") would produce L = [("X",1),("Y",2),("Z",1)] if you don't mind about ordering: def algorithm(items, target): d = dict(items) try: d[target] += 1 except KeyError: d[target] = 1 items[:] = d.items() Now it would probably be better to directly use a dict instead of a list of tuples if possible... > I tried to create an algorithm of the following form: > >>>>def algorith(list,str): Using 'list' and 'str' as identifiers will shadow the eponym builtin types in this function. This may or may not be a problem here, but it's usually better to avoid doing so. > ... flag = True > ... for l in list: > ... if l[0] == str: > ... l[1] += 1 tuples are immutable. Hence the exception. > ... flag = False 'break'ing here would avoid useless iterations. And also allow the use of the 'else' clause of the for loop, si you don't need a flag. > ... if flag: > ... list.append((str,1)) > ... While there are pretty good reasons to favor the dict-based solution (unless you really insist on having sub-optimal code of course !-), the following is a somewhat more pythonic rewrite of your original code: def algogo(alist, astring): for i, (name, count) in enumerate(alist): if name == astring: alist[i] = (name, count+1) break else: alist.append( (astring, 1) ) (snip) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From python.list at tim.thechases.com Thu Jun 1 15:36:07 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 01 Jun 2006 14:36:07 -0500 Subject: Member index in toples In-Reply-To: <_TFfg.2976$EF1.229574@news20.bellglobal.com> References: <_TFfg.2976$EF1.229574@news20.bellglobal.com> Message-ID: <447F41A7.3010108@tim.thechases.com> > I have a tuple like this: > > T = ("One","Two","Three","Four") > > Is there any built-in way to find what is the index of "Two" withouot > looping within the tuple? > > Is the same feature available for lists or dictionaries? Lists have a index() method. For the tuple, you can convert it to a list: indexOfTwo = list(T).index("Two") Dictionaries don't have a defined ordering, so there's no similar functionality (because results would be meaningless) unless you convert it to a list, and then you can snag its index in the arbitrarily-ordered results (or sort the results first). If you just need to test for presence, and don't need the index, you can use "Two" in T Just a few ideas... -tkc From diffuser78 at gmail.com Tue Jun 20 13:05:40 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 20 Jun 2006 10:05:40 -0700 Subject: OS specific command in Python In-Reply-To: <44979b35$0$8390$626a54ce@news.free.fr> References: <1150781429.090359.148560@c74g2000cwc.googlegroups.com> <44979b35$0$8390$626a54ce@news.free.fr> Message-ID: <1150823140.295590.307390@i40g2000cwc.googlegroups.com> I tried the following and it seemed to work import os os.system('') Any comments.... From alanalan at newsgroup.nospam Fri Jun 2 16:56:55 2006 From: alanalan at newsgroup.nospam (A.M) Date: Fri, 2 Jun 2006 16:56:55 -0400 Subject: Open Source Charting Tool References: <1L0gg.1841$Su3.159041@news20.bellglobal.com> Message-ID: Hi Larry, I can't browse to www.reporlab.org, but I found http://www.reportlab.com/ which has a commercial charting product. Is that what you referring to? Thanks, Alan "Larry Bates" wrote in message news:Z9-dnSpDpb1TPx3ZRVn-iA at comcast.com... > ReportLab Graphics can do 2D and pie charts, but I don't think it does > 3D charts yet. > > www.reporlab.org > > > Larry Bates > > A.M wrote: >> Hi, >> >> >> >> I developed a HTML reporting tool that renders Oracle data to HTML and >> Oracle. >> >> >> >> At this point I have to add charts (3d bars and pie charts) to this >> application. I don't think that I have to do it from scratch. >> >> >> >> Is there any open source charting tool that help me create charts in JPG >> or >> gif format? >> >> >> >> Thanks, >> >> Alan >> >> From ldo at geek-central.gen.new_zealand Mon Jun 5 05:29:53 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 05 Jun 2006 21:29:53 +1200 Subject: summarize text References: <1148903386.095226.249270@38g2000cwa.googlegroups.com> Message-ID: ... sorry, I thought you said "summarize Proust". :) From greg at cosc.canterbury.ac.nz Sat Jun 10 00:43:16 2006 From: greg at cosc.canterbury.ac.nz (greg) Date: Sat, 10 Jun 2006 16:43:16 +1200 Subject: ANN: PyGUI 1.7.2 Message-ID: PyGUI 1.7.2 is now available: http://www.cosc.canterbury.ac.nz/~greg/python_gui/ This version adds support for multiple mouse buttons, mouse enter and leave events, enhancements to the BlobEdit example application, and a big pile of other enhancements and bug fixes. See the CHANGES.txt file in the distribution or on the website for details. What is PyGUI? -------------- PyGUI is an experimental highly-Pythonic cross-platform GUI API. Implementations are currently available for MacOSX and Gtk. For a full description of the project goals, see the PyGUI web page at the above address. From onurb at xiludom.gro Wed Jun 21 13:04:12 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Wed, 21 Jun 2006 19:04:12 +0200 Subject: How to override the doc of an object instance. In-Reply-To: References: <200606211539.02663.maric@aristote.info> <200606211715.16926.maric@aristote.info> Message-ID: <44997c0d$0$24922$626a54ce@news.free.fr> David Huard wrote: (snip) > Has this problem come up before ? > It seems that with the new classes, this > kind of wish will generalize, AFAIK, there's no (and never have been) docstrings for non-callable attributes of a class or module. And properties are non-callable attributes. > or is it a bad coding habit to embed > objects inside classes ? Since everything in Python is OO (classes, functions and modules included), I fail to see how one could do otherwise... -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From michael at araneidae.co.uk.invalid Fri Jun 30 17:25:00 2006 From: michael at araneidae.co.uk.invalid (Michael Abbott) Date: Fri, 30 Jun 2006 22:25:00 +0100 Subject: Module executed twice when imported! References: <1151534230.603274.144810@x69g2000cwx.googlegroups.com> <05epg.2385$No6.49436@news.tufts.edu> Message-ID: In article , Georg Brandl wrote: > That's because __name__ is normally set to the module's name in the package > hierarchy. When you set it to "some1.some2", Python thinks it's > in a subpackage Ahhhh. So what I *should* have set it to is the module name *without* extension, i.e. __name__='imptest' Thank you. Now I think I understand it. From python.list at tim.thechases.com Thu Jun 8 15:44:38 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 08 Jun 2006 14:44:38 -0500 Subject: wxpython: can't even create a Panel In-Reply-To: References: Message-ID: <44887E26.1040601@tim.thechases.com> > def __init__(self, parent, title): > wx.Frame.__init__(self, parent, -1, title) > > panel = wx.Panel(self) It looks like a subtle difference between panel = wx.Panel(self) and panel = wx.Panel(self) As the error message states, there is no "self" at the class-definition level...only within the method (__init__ in this case). In the example code from which you're working, note the indentation level of the "panel = ..." line relative to the "def __init__" line, and compare with your code. Subtle, but important. :) -tkc From pc at p-cos.net Mon Jun 19 12:22:02 2006 From: pc at p-cos.net (Pascal Costanza) Date: Mon, 19 Jun 2006 18:22:02 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> Message-ID: <4fo19aF1jsudeU1@individual.net> Chris Smith wrote: > Torben ?gidius Mogensen wrote: >> That's not really the difference between static and dynamic typing. >> Static typing means that there exist a typing at compile-time that >> guarantess against run-time type violations. Dynamic typing means >> that such violations are detected at run-time. This is orthogonal to >> strong versus weak typing, which is about whether such violations are >> detected at all. The archetypal weakly typed language is machine code >> -- you can happily load a floating point value from memory, add it to >> a string pointer and jump to the resulting value. ML and Scheme are >> both strongly typed, but one is statically typed and the other >> dynamically typed. > > Knowing that it'll cause a lot of strenuous objection, I'll nevertheless > interject my plea not to abuse the word "type" with a phrase like > "dynamically typed". If anyone considers "untyped" to be perjorative, > as some people apparently do, then I'll note that another common term is > "type-free," which is marketing-approved but doesn't carry the > misleading connotations of "dynamically typed." We are quickly losing > any rational meaning whatsoever to the word "type," and that's quite a > shame. The words "untyped" or "type-free" only make sense in a purely statically typed setting. In a dynamically typed setting, they are meaningless, in the sense that there are _of course_ types that the runtime system respects. Types can be represented at runtime via type tags. You could insist on using the term "dynamically tagged languages", but this wouldn't change a lot. Exactly _because_ it doesn't make sense in a statically typed setting, the term "dynamically typed language" is good enough to communicate what we are talking about - i.e. not (static) typing. > By way of extending the point, let me mention that there is no such > thing as a universal class of things that are called "run-time type > violations". At runtime, there is merely correct code and incorrect > code. No, there is more: There is safe and unsafe code (i.e., code that throws exceptions or that potentially just does random things). There are also runtime systems where you have the chance to fix the reason that caused the exception and continue to run your program. The latter play very well with dynamic types / type tags. > To the extent that anything is called a "type" at runtime, this > is a different usage of the word from the usage by which we may define > languages as being statically typed (which means just "typed"). In > typed OO languages, this runtime usage is often called the "class", for > example, to distinguish it from type. What type of person are you to tell other people what terminology to use? ;) Ha! Here I used "type" in just another sense of the word. ;) It is important to know the context in which you are discussing things. For example, "we" Common Lispers use the term "type" as defined in http://www.lispworks.com/documentation/HyperSpec/Body/26_glo_t.htm . You cannot possibly argue that "our" use of the word "type" is incorrect because in "our" context, when we talk about Common Lisp, the use of the word "type" better be consistent with that definition. (You can say that you don't like the definition, that it is unsound, or whatever, but that doesn't change anything here.) > This cleaner terminology eliminates a lot of confusion. For example, it > clarifies that there is no binary division between strongly typed > languages and weakly typed languages, since the division between a "type > error" and any other kind of error is arbitrary, depending only on > whether the type system in a particular language happens to catch that > error. For example, type systems have been defined to try to catch unit > errors in scientific programming, or to catch out-of-bounds array > indices... yet these are not commonly called "type errors" only because > such systems are not in common use. What type system catches division by zero? That is, statically? Would you like to program in such a language? > This isn't just a matter of preference in terminology. The definitions > above (which are, in my experience, used widely by most non-academic > language design discussions) actually limit our understanding of > language design by pretending that certain delicate trade-offs such as > the extent of the type system, or which language behavior is allowed to > be non-deterministic or undefined, are etched in stone. This is simply > not so. If types DON'T mean a compile-time method for proving the > absence of certain program behaviors, then they don't mean anything at > all. Pretending that there's a distinction at runtime between "type > errors" and "other errors" serves only to confuse things and > artificially limit which problems we are willing to concieve as being > solvable by types. Your problem doesn't exist. Just say "types" when you're amongst your own folks, and "static types" when you're amongst a broader audience, and everything's fine. Instead of focusing on terminology, just focus on the contents. Pascal -- 3rd European Lisp Workshop July 3 - Nantes, France - co-located with ECOOP 2006 http://lisp-ecoop06.bknr.net/ From samschul at pacbell.net Sat Jun 3 12:07:34 2006 From: samschul at pacbell.net (sam) Date: 3 Jun 2006 09:07:34 -0700 Subject: carshing the interpreter in two lines In-Reply-To: <1149343823.789918.210110@h76g2000cwa.googlegroups.com> References: <1149343823.789918.210110@h76g2000cwa.googlegroups.com> Message-ID: <1149350854.072412.263920@f6g2000cwb.googlegroups.com> tomer: It is my opinion that you would loose performance if the Python interpreter had the additional task of verifying byte code. It might be more appropriate to have a preprocessor that did the verifying as it compiled the byte code. Sam Schulenburg gangesmaster wrote: > the following (random) code crashes my interpreter > (python 2.4.3/winxp): > > from types import CodeType as code > exec code(0, 5, 8, 0, "hello moshe", (), (), (), "", "", 0, "") > > i would expect the interpreter to do some verifying, at least for > sanity (valid opcodes, correct stack size, etc.) before executing > artbitrary code... after all, it was the BDFL who said """I'm not > saying it's uncrashable. I'm saying that if you crash it, it's a > bug unless proven harebrained.""" > > > -tomer From niemand.leermann at thomas-guettler.de Thu Jun 15 10:07:07 2006 From: niemand.leermann at thomas-guettler.de (Thomas Guettler) Date: Thu, 15 Jun 2006 16:07:07 +0200 Subject: Python is fun (useless social thread) ;-) References: Message-ID: > Did you have to learn it for a job? No, I learned it because Perl was too dirty and Java to complicated. Now it is part of my daily job. > Also, how did you go about learning it? Programming, reading this newsgroup, reading the python cookbook, reading python source files of the standard library. > Was there any necessity in the specifics you learned, or did you just > dabble in something (e.g. wxPython) for fun? I tried wxPython, but switched to pygtk. And I did some cgi programming with quixote and ZODB. > Are there still some things you feel you need to learn or improve? There are some things in Python I don't know very well: Decorators and generators. But somehow I don't think that I really need them. Thomas -- Thomas G?ttler, http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de Spam Catcher: niemand.leermann at thomas-guettler.de From oscarp at acay.com.au Sun Jun 18 23:20:47 2006 From: oscarp at acay.com.au (O Plameras) Date: Mon, 19 Jun 2006 13:20:47 +1000 Subject: Change value of element in list In-Reply-To: References: Message-ID: <4496180F.3000408@acay.com.au> O Plameras wrote: > Hi, > > I'm doing python tutorial, >> http://docs.python.org/tut/node5.html > > and I have these, > > lists = ['spam', 'eggs', 100, 1234] > lists[2] = lists[2] + 23 > > I expected this, > lists = ['spam', 'eggs', 123, 1234] > > but got this, > lists = ['spam', 'eggs', 100, 1234] > > What's my problem here ? > > I have Fedora C5 with python2.4. > > Thanks. > > O Plameras > I reply to my post to say it is my mistake. Before printing 'lists' I did not do this lists[2] = lists[2] + 23 Sorry for the bother. O Plameras From behnel_ml at gkec.informatik.tu-darmstadt.de Wed Jun 28 07:32:19 2006 From: behnel_ml at gkec.informatik.tu-darmstadt.de (Stefan Behnel) Date: Wed, 28 Jun 2006 13:32:19 +0200 Subject: [Pyrex] pyrex functions to replace a method (Re: replace a method in class: how?) In-Reply-To: <44A11564.9030009@bryant.edu> References: <44A06A6B.6010200@bryant.edu> <44A11564.9030009@bryant.edu> Message-ID: <44A268C3.5010106@gkec.informatik.tu-darmstadt.de> Hi Brian, Brian Blais wrote: > import module_py # import a function from a python module > import module_pyrex # import a function from a pyrex extension module > > class This(object): > > def update1(self,val): > print val > > def update2(self,val): > print "2",val > > def update3(self,val): > print "3",val > > def local_update(obj,val): > > print "local",val > > > This.update1=local_update # replace the method from a local function > This.update2=module_py.python_update # replace the method from a python module > This.update3=module_pyrex.pyrex_update # replace the method from a pyrex module > > t=This() > > t.update1('local') # works fine > t.update2('python') # works fine > t.update3('pyrex') # gives a typeerror function takes exactly 2 arguments (1 given) > #--------------------------------------------------------------------------------- > > #module_py.py > > def python_update(self,val): > print "python module",val > #--------------------------------------------------------------------------------- > > #module_pyrex.pyx > > def pyrex_update(self,val): > print "pyrex module",val What is the 'self' for? After all, you are sticking a /function/ into the object, not a /method/. Your function will not receive a 'self' argument automatically as it is stuck into the instance and not part of the class. Stefan From chris.cavalaria at free.fr Wed Jun 14 12:01:34 2006 From: chris.cavalaria at free.fr (Christophe) Date: Wed, 14 Jun 2006 18:01:34 +0200 Subject: Numerics, NaNs, IEEE 754 and C99 In-Reply-To: <1290aik50hmk94a@corp.supernews.com> References: <12904mjhl493t49@corp.supernews.com> <1290aik50hmk94a@corp.supernews.com> Message-ID: <4490329e$0$12356$636a55ce@news.free.fr> Grant Edwards a ?crit : > The division by zero trap is really annoying. In my world the > right thing to do is to return Inf. Your world is flawed then, this is a big mistake. NaN is the only aceptable return value for a division by zero. From Thaqalainnaqvi at gmail.com Tue Jun 13 09:44:58 2006 From: Thaqalainnaqvi at gmail.com (Thaqalainnaqvi at gmail.com) Date: 13 Jun 2006 06:44:58 -0700 Subject: What's wrong in this HTML Source file of a Bank In-Reply-To: <4f7t7dF1f0g44U1@uni-berlin.de> References: <1150196896.819711.154640@c74g2000cwc.googlegroups.com> <1150204559.415713.288600@h76g2000cwa.googlegroups.com> <1150205478.055121.60300@u72g2000cwu.googlegroups.com> <4f7t7dF1f0g44U1@uni-berlin.de> Message-ID: <1150206298.560467.18420@g10g2000cwb.googlegroups.com> I have posted the same question in alt.html but no one yet replied. From sdcook55 at sbcglobal.net Tue Jun 20 20:00:11 2006 From: sdcook55 at sbcglobal.net (Stan Cook) Date: Wed, 21 Jun 2006 00:00:11 GMT Subject: Python with Eclipse In-Reply-To: <1150837621.358208.296610@u72g2000cwu.googlegroups.com> References: <1150837621.358208.296610@u72g2000cwu.googlegroups.com> Message-ID: Jason wrote: > PyDev Eclipse keeps around the python interpreter unless it gets > removed. I think part of the point is to keep around failed runs so > the user can investigate the stack. Eclipse doesn't keep this around > if you Run you script, but it will keep the interpreter alive if you > Debug your script, regardless of how it exits. (It may dispose of the > interpreter if your program exits with a normal error code.) > > Anyway, in the Debug View, you can see a list of all the python > interpreters that PyDev and Eclipse are keeping alive. There's a set > of debugging-related buttons just above: step into, step over, step > return, continue, and others. > > One of the buttons there looks like a couple of "X" symbols. This > button officially shuts down a python interpreter. (Be careful and > don't actually click the "X" symbol that closes the debug area!) > > --Jason > > Stan Cook wrote: >> I've been trying to use Eclipse with Python on Linux for a >> while and have noticed something odd. After running the >> code or debugging a few times, its responsiveness gets >> really bad. Upon checking the equivalent of the task >> manager, I find several instances of Python running. When I >> kill these instances, the responsiveness comes back. I'm >> not sure if there is a better place to post this, but it is >> Python related. Is this just an issue with Eclipse or is >> there something else I should inspect? >> >> Any help would be appreciated. >> >> Regards, >> >> S Cook > Thanks, I'll try that and keep an eye on the open sessions. Regards, S Cook From paddy3118 at netscape.net Thu Jun 29 15:19:42 2006 From: paddy3118 at netscape.net (Paddy) Date: 29 Jun 2006 12:19:42 -0700 Subject: Running DocTest on Strings In-Reply-To: <1151578889.243272.167750@y41g2000cwy.googlegroups.com> References: <1151578889.243272.167750@y41g2000cwy.googlegroups.com> Message-ID: <1151608782.326915.197440@i40g2000cwc.googlegroups.com> notanotheridiot wrote: > Hi, > I have two strings - a docstring containing doctests and a code string > containing code to be tested with those doctests. I've been trying for > a day now to run the test without concatenating the two strings, > adding: > > import doctest > doctest.testmod > > to the bottom, writing it all to a file and executing it using popen(). > > There must be some way of doing this without writing to a temporary > file, any ideas? > > thanks in advance, > > johannes Woolard Create the concatenated string then exec it? - Pad. From fredrik at pythonware.com Wed Jun 21 06:42:58 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 21 Jun 2006 12:42:58 +0200 Subject: Search substring in a string and get index of all occurances References: <4499034A.9040306@gmail.com> Message-ID: Nico Grubert wrote: > I would like to search for a substring in a string and get the index of > all occurances. > > mystring = 'John has a really nice powerbook.' > substr = ' ' # space > > I would like to get this list: > [4, 8, 10, 17, 22] the find and index methods take an optional start argument, so the obvious way to do this is to use a simple loop; e.g. result = []; pos = -1 try: while 1: pos = mystring.index(substr, pos+1) result.append(pos) except ValueError: pass # done if you prefer one-liners, you can use the RE engine instead: result = [m.start() for m in re.finditer(re.escape(substr), mystring)] this has a much higher setup overhead, but can be faster than the loop form for some kinds of data (at least in 2.4 and earlier). ...and if you're going to look for the same substring a lot, you can factor out the escape/compile step: substr_scanner = re.compile(re.escape(substr)).finditer result = [m.start() for m in substr_scanner(mystring)] if you're not 100% sure you need all the matches later on, you can use a generator expression instead of the list comprehension: result = (m.start() for m in re.finditer(re.escape(substr), mystring)) ... for pos in result: ... if pos > 1000: break # won't need the rest hope this helps! From michele.petrazzo at TOGLIunipex.it Fri Jun 30 06:59:22 2006 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Fri, 30 Jun 2006 10:59:22 GMT Subject: Way for see if dict has a key In-Reply-To: References: <6V6pg.21624$_J1.271925@twister2.libero.it> Message-ID: Fredrik Lundh wrote: > Michele Petrazzo wrote: > >> what the preferred way for see if the dict has a key? >> We have a lot of solutions: >> >> key in dict > > new syntax (2.3 and later). > So, following it, it can be used for the operations like len? len(dict) -> len(dict.keys()) ? Thanks, Michele From sleepingsquirrel at yahoo.com Tue Jun 27 12:21:57 2006 From: sleepingsquirrel at yahoo.com (Greg Buchholz) Date: 27 Jun 2006 09:21:57 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <1151368443.491445.294480@p79g2000cwp.googlegroups.com> Message-ID: <1151425317.853996.5040@b68g2000cwa.googlegroups.com> Chris F Clark wrote: > Very impressive. It looks right to me and simple enough to > understand. I must find the time to learn a modern FP language. Can > you write a fold for this that prints the data as a binary tree of > triples? I have to believe it isn't that hard.... {- Refactoring this as a fold is left as an exercise to the reader -} data Clark a b c = Nil | Cons a (Clark b c (a,a)) deriving Show clark = (Cons 42 (Cons 3.14 (Cons "abc" (Cons (1,2) (Cons (1.2,3.4) (Cons ("foo","bar") (Cons ((9,8),(7,6)) (Cons ((0.1,0.2),(0.3,0.4)) (Cons (("w","x"),("y","z")) Nil))))))))) main = print (toTree clark) data Tree a = Empty | Node a (Tree a) (Tree a) deriving Show toTree :: Clark a b c -> Tree (a,b,c) toTree (Cons x (Cons y (Cons z rest))) = Node (x,y,z) (toTree (fst (lift_c rest))) (toTree (snd (lift_c rest))) toTree _ = Empty lift_c :: Clark (a,a) (b,b) (c,c) -> (Clark a b c, Clark a b c) lift_c Nil = (Nil,Nil) lift_c (Cons (x,y) rest) = (Cons x (fst (lift_c rest)), Cons y (snd (lift_c rest))) From grante at visi.com Fri Jun 16 00:17:04 2006 From: grante at visi.com (Grant Edwards) Date: Fri, 16 Jun 2006 04:17:04 -0000 Subject: a good programming text editor (not IDE) References: <_xgkg.2317$No6.48542@news.tufts.edu> Message-ID: <1294c602evjtl03@corp.supernews.com> On 2006-06-15, Dave Hansen wrote: > Very small, very fast, very powerful, and very portable (though I'm > not sure about Mac...): Take a look at Jed from www.jedsoft.org. It's been my editor of choice for many years. Running Emacs on a machine with 8MB of RAM and 80MB of disk got a bit old. -- Grant Edwards grante Yow! Yow! I want my nose at in lights! visi.com From maric at aristote.info Fri Jun 2 06:19:09 2006 From: maric at aristote.info (Maric Michaud) Date: Fri, 2 Jun 2006 12:19:09 +0200 Subject: how to define a static field of a given class In-Reply-To: <448009b7$0$12763$636a55ce@news.free.fr> References: <1149239221.045268.6170@g10g2000cwb.googlegroups.com> <448009b7$0$12763$636a55ce@news.free.fr> Message-ID: <200606021219.09548.maric@aristote.info> Le Vendredi 02 Juin 2006 11:47, bruno at modulix a ?crit?: > FWIW, it's probably one of the most useless construct in Python IMHO. > classmethod are really much more useful to me. +1 I do prefer classmethod, both for the name and behavior (everything should be intended for polymorphism, after all, classes are just instances of type). -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From kent at kentsjohnson.com Fri Jun 2 21:54:38 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Fri, 02 Jun 2006 21:54:38 -0400 Subject: [ANN] lxml 1.0 released In-Reply-To: References: Message-ID: <4480eade$1_2@newspeer2.tds.net> Stefan Behnel wrote: > Hallo everyone, > > I have the honour to announce the availability of lxml 1.0. > > http://codespeak.net/lxml/ > > It's downloadable from cheeseshop: > http://cheeseshop.python.org/pypi/lxml Are there any plans to offer a Windows installer? Thanks, Kent From fredrik at pythonware.com Tue Jun 6 15:52:44 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 06 Jun 2006 21:52:44 +0200 Subject: 10GB XML Blows out Memory, Suggestions? In-Reply-To: <1149622092.241196.283790@c74g2000cwc.googlegroups.com> References: <1149594519.098115.8980@u72g2000cwu.googlegroups.com> <1149622092.241196.283790@c74g2000cwc.googlegroups.com> Message-ID: gregarican wrote: > 10 gigs? Wow, even using SAX I would imagine that you would be pushing > the limits of reasonable performance. depends on how you define "reasonable", of course. modern computers are quite fast: > dir data.xml 2006-06-06 21:35 1 002 000 015 data.xml 1 File(s) 1 002 000 015 bytes > more test.py from xml.etree import cElementTree as ET import time t0 = time.time() for event, elem in ET.iterparse("data.xml"): if elem.tag == "item": elem.clear() print time.time() - t0 gives me timings between 27.1 and 49.1 seconds over 5 runs. (Intel Dual Core T2300, slow laptop disks, 1000000 XML "item" elements averaging 1000 byte each, bundled cElementTree, peak memory usage 33 MB. your milage may vary.) From william.xwl at gmail.com Fri Jun 16 02:30:12 2006 From: william.xwl at gmail.com (William Xu) Date: Fri, 16 Jun 2006 14:30:12 +0800 Subject: BeautifulSoup error References: <1150436361.480316.25400@g10g2000cwb.googlegroups.com> Message-ID: <87y7vxbojv.fsf@www.williamxu.com> "Serge Orlov" writes: [...] > Upgrading python-beautifulsoup is a good idea, since there were two bug > fix releases after 3.0.1 I just downloaded latest version 3.0.3 from its homepage, seems it still has the same problem. -- William PL/I -- "the fatal disease" -- belongs more to the problem set than to the solution set. -- Edsger W. Dijkstra, SIGPLAN Notices, Volume 17, Number 5 From maric at aristote.info Thu Jun 1 07:33:38 2006 From: maric at aristote.info (Maric Michaud) Date: Thu, 1 Jun 2006 13:33:38 +0200 Subject: Function mistaken for a method In-Reply-To: <200606011329.15661.maric@aristote.info> References: <200606011329.15661.maric@aristote.info> Message-ID: <200606011333.38780.maric@aristote.info> Le Jeudi 01 Juin 2006 13:29, Maric Michaud a ?crit?: > this exactly the same as : > > ? ?def f(self, val) : > ? ? ? ?return x != 0 oops, def f(self, val) : return val != 0 -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From bborcic at gmail.com Thu Jun 1 14:34:11 2006 From: bborcic at gmail.com (Boris Borcic) Date: Thu, 01 Jun 2006 20:34:11 +0200 Subject: numpy bug Message-ID: <447f3338$1_7@news.bluewin.ch> after a while trying to find the legal manner to file numpy bug reports, since it's a simple one, I thought maybe a first step is to describe the bug here. Then maybe someone will direct me to the right channel. So, numpy appears not to correctly compute bitwise_and.reduce and bitwise_or.reduce : instead of reducing over the complete axis, these methods only take the extremities into account. Illustration : >>> from numpy import * >>> bitwise_or.reduce(array([8,256,32,8])) 8 >>> import numpy >>> numpy.__version__ '0.9.8' >>> Platform : Win XP SP2, Python 2.4.2 HTH, bb From casevh at comcast.net Sun Jun 11 20:01:41 2006 From: casevh at comcast.net (casevh at comcast.net) Date: 11 Jun 2006 17:01:41 -0700 Subject: @func call syntax In-Reply-To: <1150068780.001520.326910@g10g2000cwb.googlegroups.com> References: <1150068780.001520.326910@g10g2000cwb.googlegroups.com> Message-ID: <1150070501.791851.175570@f6g2000cwb.googlegroups.com> teekaysoh at gmail.com wrote: > Hi, > > I am new to Python, here I'd like to have a question: I noticed a > special way to call a function in a program: > > @function_name > > No argv is passed, even though the function_name asks for one. Any idea > what this @something syntax is trying to achieve. I haven't been able > to find any answer of on the google web and groups. > > TIA. @function_name is called a decorator. http://www.python.org/dev/peps/pep-0318/ http://docs.python.org/whatsnew/node6.html casevh From tjreedy at udel.edu Fri Jun 9 04:53:35 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 9 Jun 2006 04:53:35 -0400 Subject: Allowing zero-dimensional subscripts References: <1149801040.936452.26270@i40g2000cwc.googlegroups.com><1149807149.516004.48590@f6g2000cwb.googlegroups.com> <1149832139.948242.64160@f6g2000cwb.googlegroups.com> Message-ID: wrote in message news:1149832139.948242.64160 at f6g2000cwb.googlegroups.com... > The question is, is this, > conceptually, the feature that allows you to ommit the parentheses of a > tuple in some cases. To repeat: tuples are defined by commas. There are no 'parentheses of a tuple', except for empty tuples, to be omitted. Consider: a+b is a sum; in (a+b)*c, the sum is parenthesized to avoid confusion with a+b*c. Like other expressions, tuples are parenthesezed when needed to avoid similar confusion. So (1,2)+(3,4) needs parens because 1,2+3,4 would be something different. In both examples, parens are used to reverse normal precedence relations. Terry Jan Reedy From george.sakkis at gmail.com Thu Jun 22 18:14:04 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 22 Jun 2006 15:14:04 -0700 Subject: Status of optional static typing in Python? References: <449af81d$0$31818$626a54ce@news.free.fr> Message-ID: <1151014444.448607.34660@y41g2000cwy.googlegroups.com> Christian Convey wrote: > Perhaps I'm deluded but I don't think so. I'll tell you my situation > and I'd appreciate your take on it... > > I'm looking into the design a network simulator. The simulator has a > few requirements: > > (1) I need to be able to swap in a variety of replacement components > during different simulations. I.e., RadioFrequencyChannelModel, > WiredNetworkChannelModel, etc. This drives me to want the notion of > inherited interfaces, partly as a form of documentation. > > (2) I want a form of encapsulation (which I realize isn't necessarily > guaranteed in all possible static typing implementations). I.e., I want > to ensure that any code which accesses a ChannelModel only calls those > methods that are part of the ChannelModel interface. If there's a > method RadioFrequencyChannelModel.setBroadcastDistance(...), which isn't > part of the generic ChannelModel interface, I don't want most of my code > to be able to start using that particular method, if the code need to be > able to work with all possible ChannelModel implementations. > > (3) I like Interfaces as a matter of documentation. It helps me to > thing things through. I've got a lot of components that must support > interchangeable implementations: channels, modems, MAC layers, link > layers, etc. If I have an abstract MAC_layer interface, it helps me > think carefully about what every MAC layer ought to provide, and it also > helps me explain to other people what a MAC layer in my simulator must > provide. That is, it helps me better explain to other people how the > system's major components relate to each other. All your concerns (and several more) have been beaten to death in past topics about the benefits and shortcomings of static typing, you can look them up. Briefly, python doesn't prevent you from writing good documentation and have nice, clean interfaces if you want to, and indeed there are several Interface implementations around. Still it doesn't force you to do so like other "pure" OO languages, which is very handy if you don't have a crystal clear idea of how your interfaces should be laid out in advance or if the requirements change along the way, both very typical scenaria in the real world. As for encapsulation, again the idea is convention rather than language enforcement. The convention is to have all non-public elements (attributes, methods, functions, classes, etc.) starting with a single underscore. A client can still access it, but he takes the responsibility of relying on an implementation feature, which is typically less stable than the public interface. > Now, I could use Java or C# to get functionality such as interfaces, but > I loath giving up the general productive goodness of Python. That's why > I'm looking for something like interfaces. Others have already mentioned some Interface add-on packages that you can download and use right away; another option you may want to look into is the type-checking module (http://oakwinter.com/code/typecheck/). > But even if we disagree about the wisdom of my intentions, do you know > if/when Guido's planning to work that stuff into Python? The last post > I noticed from him on the topic was from 2005. At least back then he > sounded pretty into it. I wouldn't count on it if I was to start a project sometime soon. George From gokcemutlu at gmail.com Sun Jun 25 05:48:32 2006 From: gokcemutlu at gmail.com (gokcemutlu at gmail.com) Date: 25 Jun 2006 02:48:32 -0700 Subject: Can you help me with the below code? Urgent! In-Reply-To: <1151228549.630209.28090@c74g2000cwc.googlegroups.com> References: <1151224178.479401.119620@r2g2000cwb.googlegroups.com> <1151225637.492538.122890@p79g2000cwp.googlegroups.com> <1151226120.634245.97570@m73g2000cwd.googlegroups.com> <1151228549.630209.28090@c74g2000cwc.googlegroups.com> Message-ID: <1151228912.416808.173450@y41g2000cwy.googlegroups.com> Hello, Thanks for your help. I just copy things that I want to keep using copy.copy function. Trying to copy frames won't lead me to anywhere :) Gokce. Pierre Quentel schrieb: > gokcemutlu at gmail.com a ?crit : > > > Hello, > > > > You're right about it but this is a simple code which tells my problem. > > I need actually the frame itself for states and unfortunately > > copy.copy(frame) throws an exception. Pickling also doesn't work. Do > > you have any other idea? > > > > Thanks, > > > > Gokce. > > > In your original post you said you wanted to store local variables, but > it seems that you need to store more information than this : could you > specify which ones ? Since you can't copy the stack frame, maybe you > can copy only the attributes you need > > Pierre From blue99 at interia.pl Mon Jun 19 10:18:43 2006 From: blue99 at interia.pl (blue99 at interia.pl) Date: 19 Jun 2006 07:18:43 -0700 Subject: Detecting key presses In-Reply-To: <1150607857.186185.183130@g10g2000cwb.googlegroups.com> References: <1150607857.186185.183130@g10g2000cwb.googlegroups.com> Message-ID: <1150726723.505555.214340@y41g2000cwy.googlegroups.com> > Someone suggested using curses, but that does crazy things with my > output, and leaves the terminal unusable after the program closes. It's very good suggestion but you should use also initscr and endwin functions. Regards, Rob From josiah.carlson at gmail.com Fri Jun 16 00:06:50 2006 From: josiah.carlson at gmail.com (josiah.carlson at gmail.com) Date: 15 Jun 2006 21:06:50 -0700 Subject: a good programming text editor (not IDE) In-Reply-To: <_xgkg.2317$No6.48542@news.tufts.edu> References: <_xgkg.2317$No6.48542@news.tufts.edu> Message-ID: <1150430810.039713.262660@f6g2000cwb.googlegroups.com> John Salerno wrote: > I know there's a request for a good IDE at least once a week on the ng, > but hopefully this question is a little different. I'm looking for > suggestions for a good cross-platform text editor (which the features > for coding, such as syntax highlighting, etc.) but not a full IDE with > all the fancy jazz (GUI developer, UML diagrams, etc.). > > Ideally, it would be something I could even put on a flash drive and > move from computer to computer, but this isn't necessary. Just something > I can immediately use in either Windows or Linux (or Mac, if necessary). [snip] > Thanks for any suggestions, and again I'm sorry if this feels like the > same question as usual (it's just that in my case, I'm not looking for > something like SPE, Komodo, Eric3, etc. right now). I was taking a peek at c.l.py to check for replies in another thread and couldn't help notice your asking about editors. Please pardon the personal pimping, but have you looked at PyPE (pype.sf.net)? It doesn't do everything, isn't geared towards every language, but as far as I know, it is fairly cross-platform (there seems to be an outstanding bug on ubuntu 6.06, but I need to get an installation to check it out), and can offer a fairly no-frills interface for writing software. The next release will include support for working from a removable device (I plan on releasing before the end of the month), but may not have an ubuntu fix (I may not have time to get one running). - Josiah From chris.cavalaria at free.fr Wed Jun 14 12:28:40 2006 From: chris.cavalaria at free.fr (Christophe) Date: Wed, 14 Jun 2006 18:28:40 +0200 Subject: Numerics, NaNs, IEEE 754 and C99 In-Reply-To: <1290dlgfqnf79ca@corp.supernews.com> References: <12904mjhl493t49@corp.supernews.com> <1290aik50hmk94a@corp.supernews.com> <4490329e$0$12356$636a55ce@news.free.fr> <1290dlgfqnf79ca@corp.supernews.com> Message-ID: <449038f8$0$29657$636a55ce@news.free.fr> Grant Edwards a ?crit : > On 2006-06-14, Christophe wrote: > >>Grant Edwards a ?crit : >> >>>The division by zero trap is really annoying. In my world the >>>right thing to do is to return Inf. >> >>Your world is flawed then, this is a big mistake. NaN is the >>only aceptable return value for a division by zero. > > > You're probably right if you're talking about math, but I'm not > doing math. I'm doing engineering. In all of the situations > I've ever encountered, Inf was a much better choice. You should have been more precise then : "In my ideal world, when dividing a non zero value by a zero value, the result should be +Inf or -Inf according the the sign rules" On that point, you should also note that +0 and -0 are sometimes considered two different floating point numbers in Python :) From webraviteja at gmail.com Sat Jun 17 15:55:11 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 17 Jun 2006 12:55:11 -0700 Subject: code is data In-Reply-To: References: Message-ID: <1150574111.415068.255900@p79g2000cwp.googlegroups.com> Anton Vredegoor wrote: > With the inclusion of ElementTree (an XML-parser) in Python25 and recent > developments concerning JSON (a very Pythonesque but somewhat limited > XML notation scheme, let's call it statically typed XML) Python seems to > have reached a stage where it now seems to be possible to completely > swallow lesser languages code, modify it, and spit out new source code > targeting the original language the code was written in, or even make a > translation to other languages. > > The idea is that we now have a fast parser (ElementTree) with a > reasonable 'API' and a data type (XML or JSON) that can be used as an > intermediate form to store parsing trees. Especially statically typed > little languages seem to be very swallow-able. Maybe I will be able to > reimplement GFABasic (my first love computer language, although not my > first relationship) someday, just for fun. > > Then there are things like cTypes (calling functions from native DLL's) > and PyPy (implementing Python in Python). > > All this taken together, to me it starts looking like we're now entering > a territory that traditionally was exclusively in the Lisp domain. > > Yes, Python had eval and exec for a long time already, and metatypes and > generators are having some strange unexplored possibilities too, but the > day will come soon (and at last when PyPy is reaching execution speeds > close to cPython) where Python will be able to swallow smaller > languages, and finally it will be able to swallow its own tail, like > Lisp but then more powerful (because of the widely used standard data > types and the code exchange between languages that that makes possible). > > Your thoughts please. I don't share your optimism at all. Most of the things you mentioned have existed for long. Just because some of them are now included in the standard library isn't going to change things drastically. Installing them earlier was never hard at all. People like to call everything with the lightest semblence, a DSL. That gives the feel that the language is more powerful. Ruby people do it all the time. Python cannot be called a DSL language until, creating them is a natural language feature (like Lisp). And that does not seem to be happening anytime soon. Boo for example allows you to write new constructs with it's AST library. It still cannot be called a DSL "language". People have however written various language interpreters (Scheme, Forth and yes, even Basic) in Python, just for kicks. Still does not make it a DSL language anymore than it makes C a DSL language. At present, the closest thing to writing a DSL in Python is Logix http://livelogix.net/logix/ Too bad though, the project is defunct and there has never been enough interest in it. Personally, I would like to see macros in Python (actually Logix succeeding is good enough). But I am no language designer and the community has no interest in it. When I absolutely need macros, I will go elsewhere. From steve at holdenweb.com Mon Jun 5 10:02:46 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 05 Jun 2006 15:02:46 +0100 Subject: Simple question In-Reply-To: <1149514734.312783.122520@i40g2000cwc.googlegroups.com> References: <1149514734.312783.122520@i40g2000cwc.googlegroups.com> Message-ID: bigodines wrote: > Hi guys! > > I'm a complete newbie in Python and I'm trying to make a small software > to watch my network. It will be a simple snmpget report for a specific > machine. > > I would like to make a small program in python to be runed with > crontrab that will store the whole output in a txt file. I know its not > a big deal, but i've no background in python :) > > basically i would like to know how to: > > 1 - execute a command in the server The normal way would be using the command python script.py > 2 - write the whole output into a file. > Well, one way would simply be to use output redirection, such as python script.py > /tmp/file.txt Another alternative is to allow Python to open a file using f = open("some/file/name.txt", "w") and then use f.write(...) or print >> f, ... statements to send the output to the given file, finally closing it with f.close() The advantage of this latter method is that you can compute the filename (the first argument to the open() function) in Python if you want, using elements like the current date and time. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From marshall.spight at gmail.com Thu Jun 22 10:18:25 2006 From: marshall.spight at gmail.com (Marshall) Date: 22 Jun 2006 07:18:25 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: <4padnQn3SOWhkQfZnZ2dnUVZ_rqdnZ2d@speakeasy.net> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150904134.520639.71070@b68g2000cwa.googlegroups.com> <4padnQn3SOWhkQfZnZ2dnUVZ_rqdnZ2d@speakeasy.net> Message-ID: <1150985905.819268.250640@c74g2000cwc.googlegroups.com> Rob Warnock wrote: > Marshall wrote: > > > > Can you be more explicit about what "latent types" means? > > I'm sorry to say it's not at all natural or intuitive to me. > > Are you referring to the types in the programmers head, > > or the ones at runtime, or what? > > Here's what the Scheme Standard has to say: > > http://www.schemers.org/Documents/Standards/R5RS/HTML/r5rs-Z-H-4.html > 1.1 Semantics > ... > Scheme has latent as opposed to manifest types. Types are assoc- > iated with values (also called objects) rather than with variables. > (Some authors refer to languages with latent types as weakly typed > or dynamically typed languages.) Other languages with latent types > are APL, Snobol, and other dialects of Lisp. Languages with manifest > types (sometimes referred to as strongly typed or statically typed > languages) include Algol 60, Pascal, and C. > > To me, the word "latent" means that when handed a value of unknown type > at runtime, I can look at it or perform TYPE-OF on it or TYPECASE or > something and thereby discover its actual type at the moment[1], whereas > "manifest" means that types[2] are lexically apparent in the code. Hmmm. If I read the R5RS text correctly, it is simply doing the either/or thing that often happens with "static/dynamic" only using different terms. I don't see any difference between "latent" and "dynamic." Also, this phrase "types associated with values instead of variables" that I'm starting to see a lot is beginning to freak me out: the implication is that other languages have types associated with variables and not values, which doesn't describe anything I can think of. In your followup paragraph, you've contrasted runtime type introspection, vs. explicit type declarations, which seem orthorgonal to me. (Not that you said they weren't.) Marshall From fredrik at pythonware.com Thu Jun 15 17:59:21 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 15 Jun 2006 23:59:21 +0200 Subject: a good programming text editor (not IDE) In-Reply-To: References: <_xgkg.2317$No6.48542@news.tufts.edu> <1150402733.116243.9680@y41g2000cwy.googlegroups.com> Message-ID: Jarek Zgoda wrote: > You died in last century with your editor, we have tabs. real python programmers don't use tabs. From R.Brodie at rl.ac.uk Thu Jun 22 11:30:21 2006 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Thu, 22 Jun 2006 16:30:21 +0100 Subject: serial port servo control References: <1150989488.345731.49680@m73g2000cwd.googlegroups.com> Message-ID: wrote in message news:1150989488.345731.49680 at m73g2000cwd.googlegroups.com... > 1) How should I write to the serial port with python? I found the > module "pyserial": I don't think there is any need to hunt for anything better. > In C I'd do this by sending 3 char's, as they're only 1 byte, > but i'm not exactly sure how to do it in Python. Use a string type. output = chr(x) + chr(y) + chr(z) for example. There is no restriction on null bytes in strings, so they are appropriate for binary data. From fredrik at pythonware.com Sat Jun 17 02:46:29 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 17 Jun 2006 08:46:29 +0200 Subject: python texts? In-Reply-To: <44939CBA.4090709@natefico.com> References: <44939CBA.4090709@natefico.com> Message-ID: nate wrote: > I am enjoying it at the moment. I intend to be done with it in a > week. But not sure where it will put me in the grand scheme of > programming with python. > So perhaps a more direct question would be, what do I read after this > book? Should I read something before this book? Should I ditch this > book? If you get through Learning Python, you'll know the *entire* language. All you need then is practice, and the best way to practice is to read and write code. Make sure you do the exercises in Learning Python on your computer, and even more importantly: *read* existing code; go grab some program or library that you find somewhat interesting, and study the it's source code. Even if you don't understand everything, you'll pick up invaluable idioms and patterns that you can use in your own code. (And don't miss http://www.pythonchallenge.com) You should also skim the Library Reference so you know what's in there, and where to find it when you need it; if you prefer hardcopy, get Beazley's Essential Python or Martelli's Nutshell book. Skimming the Python FAQ is also a good idea. From roger.miller at nova-sol.com Thu Jun 29 17:51:49 2006 From: roger.miller at nova-sol.com (Roger Miller) Date: 29 Jun 2006 14:51:49 -0700 Subject: zipfile module doesn't allow append References: <1151564540.032393.182600@m73g2000cwd.googlegroups.com> Message-ID: <1151617908.976125.115020@y41g2000cwy.googlegroups.com> Ritesh Raj Sarraf wrote: > The line > filename = zipfile.ZipFile(zip_file_name, "a") > throws an exception if the given filename is not present already. > Shouldn't it create a file (in case one is not there) since it is > "append" mode ?? Perhaps it would be nicer that way, but it is working as documented. Catch the exception and open in 'w' mode. To anticipate your next possible problem, note that in append mode if you write a file that already exists in the archive it will not replace the existing file, but will add another one with the same name. As far as I can tell, there is no way to read the newer version because zipfile.read(name) always finds the first version. So if you are trying to update a zipfile you will probably have to read the old archive and write a new one, copying the files you want to keep and replacing the ones you want to update. (At this point you might want to consider invoking an external zip utility instead.) From jstroud at ucla.edu Sat Jun 10 19:33:13 2006 From: jstroud at ucla.edu (James Stroud) Date: Sat, 10 Jun 2006 16:33:13 -0700 Subject: Most elegant way to generate 3-char sequence In-Reply-To: References: <1149889784.391965.271570@h76g2000cwa.googlegroups.com> Message-ID: Steve Holden wrote: > James Stroud wrote: > >> SuperHik wrote: >> >>> and the winner is... :D >>> David Isaac wrote: >>> >>> >>>> alpha = string.lowercase >>>> x=(a+b+c for a in alpha for b in alpha for c in alpha) >>> >>> >>> >>> >> >> Not necessarily vying for winner, but David's solution is highly >> specific as it doesn't do so well for something like >> >> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab >> . >> . >> . >> zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzy >> zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz >> >> > You can't justify your solution by requirements gold-plating ... see the > subject line :-) > > regards > Steve Not necessarily vying for winner -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From tactics40 at gmail.com Fri Jun 23 12:37:24 2006 From: tactics40 at gmail.com (tac-tics) Date: 23 Jun 2006 09:37:24 -0700 Subject: Opening a file with system default application In-Reply-To: <1151080343.917275.296520@g10g2000cwb.googlegroups.com> References: <1151077662.598370.214490@c74g2000cwc.googlegroups.com> <1151080343.917275.296520@g10g2000cwb.googlegroups.com> Message-ID: <1151080644.805513.257140@r2g2000cwb.googlegroups.com> BartlebyScrivener wrote: > don't know Jython, but in Python, I think you want: > > import os > > os.system('mytextfile.txt') > > Whatever file you reference should open in the application associated > with it. At least that's the way it works on Win XP > > rd I didn't think about that. It would probably break like mad under *nix that fine. This will solve my issue. Thanks =-) Even still, does anyone know if there is a more platform indepedent way to do this? From cdsmith at twu.net Fri Jun 23 17:49:13 2006 From: cdsmith at twu.net (Chris Smith) Date: Fri, 23 Jun 2006 15:49:13 -0600 Subject: What is a type error? References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <7i3mg.204167$8W1.155367@fe1.news.blueyonder.co.uk> <44992e6c$2$664$bed64819@news.gradwell.net> <%Igmg.464974$xt.353729@fe3.news.blueyonder.co.uk> <449aaea0$2$656$bed64819@news.gradwell.net> <449bde60$0$663$bed64819@news.gradwell.net> <449c4826$1$657$bed64819@news.gradwell.net> Message-ID: Chris Uppal wrote: > > if (x != 0) y = 1 / x; > > else y = 999999999; > > > > is not all that much different from: > > > > try { y = 1 / x; } > > catch (ArithmeticException e) { y = 999999999; } > My immediate thought is that the same question is equally applicable (and > equally interesting -- i.e. no simple answer ;-) for static typing. I don't see that. Perhaps I'm missing something. If I were to define a type system for such a language that is vaguely Java-based but has NotZero as a type, it would basically implement your option [D], and contain the following rules: 1. NotZero is a subtype of Number 2. Zero is a subtype of Number 3. If x : Number and k : Zero, then "if (x != k) a else b" is well-typed iff "a" is well-typed when the type-environment is augmented with the proposition "x : NotZero" and "b" is well-typed when the type- environment is augmented with the new proposition "x : Zero". Yes, I know that Java doesn't do this right now in similar places (e.g., instanceof), and I don't know why not. This kind of thing isn't even theoretically interesting at all, except that it makes the proof of type-soundness look different. As far as I can see, it ought to be second-nature in developing a type system for a language. In that case, the first example is well-typed, and also runs as expected. The second bit of code is not well-typed, and thus constitutes a type error. The way we recognize it as a type error, though, is in the fact that the compiler aborts while checking the typing relation, rather than because of the kind of problem prevented. Of course, it would be possible to build a static type system in which different things are true. For example, Java itself is a system in which both terms are well-typed. >From a dynamic type perspective, the litany of possibilities doesn't really do much for defining a dynamic type system, which I thought was our goal in this bit of the thread. I may not have been clear enough that I was look for an a priori grounds to classify these two cases by the definition. I was assuming the existing behavior of Java, which says that both accomplish the same thing and react in the same way, yet intuitively we seem to think of one as a type error being "solved", whereas the other is not. Anyway, you just wrote another message that is far closer to what I feel we ought to be thinking about than my question here... so I will get to reading that one, and perhaps we can take up this point later when and if it is appropriate. -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation From juergen.huber at kirchnersoft.com Fri Jun 30 06:09:27 2006 From: juergen.huber at kirchnersoft.com (Juergen Huber) Date: Fri, 30 Jun 2006 12:09:27 +0200 Subject: delete first line in a file Message-ID: <44a4f854$0$12942$91cee783@newsreader02.highway.telekom.at> hello, i am a dummy user in python and new in this programming language and so there will be questions, that?s for you no problem! i never have before programmed in any language! sorry for this! i hope you will help me, that i also could the basics in this language! and later many more, so i hope ! :) the first question for me in this newsgroup will be the follow one: - is there a way to delete in a csv-file the first line?! big thanks, juergen From mgalves at gmail.com Sun Jun 4 19:43:36 2006 From: mgalves at gmail.com (Miguel Galves) Date: Sun, 4 Jun 2006 20:43:36 -0300 Subject: Adding attribute to objetcs Message-ID: <52655700606041643w2ce75071k9fb8a72c7a161d52@mail.gmail.com> Hello, I`m starting to learn python, and I hava a very good background in Java and C/C++ programming. I was reading Dive into python chapter about OO and I saw that in python we can do the following: class Person: pass joe = new Person() joe.name = "Joe" joe.age = 13 It seems that it is possible to add attributes to any object instance in run time, as in Javascript. It seems to me that it can be a source of errors. One that come in my mind is the follwing: class Person: name = "" joe = new Person() joe.nome = "Joe" The code above adds an attribute called nome, but the programmer may think it's name. What is the real interest of this feature ? Is there a way to block this kind of error ? Thanks, Miguel -- Miguel Galves - Engenheiro de Computa??o J? leu meus blogs hoje? Para geeks http://log4dev.blogspot.com Pra pessoas normais http://miguelgalves.blogspot.com "N?o sabendo que era imposs?vel, ele foi l? e fez..." -------------- next part -------------- An HTML attachment was scrubbed... URL: From dawodu4fun at yahoo.com Sun Jun 25 23:55:35 2006 From: dawodu4fun at yahoo.com (spiffy) Date: Mon, 26 Jun 2006 03:55:35 GMT Subject: Pygame.draw challenge is over! References: Message-ID: <1fmu92dode2idgq260vfnb6ona6qljtd7k@4ax.com> On Mon, 26 Jun 2006 10:53:50 +1000, richard at pyweek.org wrote: >It was quite successful too! Download the submissions from the pyweek.org >site: > >http://media.pyweek.org/static/pgd-200606.zip > >Congratulations to all who participated! > > > Richard Congrats to Seth Yastrov for 'gravity.py' ... THE ONLY ONE THAT WORKED! From jstroud at ucla.edu Sun Jun 11 16:58:44 2006 From: jstroud at ucla.edu (James Stroud) Date: Sun, 11 Jun 2006 13:58:44 -0700 Subject: Most elegant way to generate 3-char sequence In-Reply-To: References: <1149889784.391965.271570@h76g2000cwa.googlegroups.com> Message-ID: Fredrik Lundh wrote: > James Stroud wrote: > >> See the actual question: >> >> >How would you construct a generator to acheive this? > > > if you don't think the context provided by the subject line and the > sentence before the question is important, how come you're so sure what > "this" refers to ? > > > I'm getting the feeling that "correct" answers have nothing to do with correctness (i.e. working code) but on some vague notion of "elegance". Please point me to the page where code elegance is precisely defined so that I may construct my answers appropriately. And yes, I am too lazy to google "code elegance". James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From jack at performancedrivers.com Mon Jun 5 15:45:41 2006 From: jack at performancedrivers.com (Jack Diederich) Date: Mon, 5 Jun 2006 15:45:41 -0400 Subject: how not to run out of memory in cursor.execute In-Reply-To: References: <1149447895.037396.81550@j55g2000cwa.googlegroups.com> <1149531057.098045.322960@c74g2000cwc.googlegroups.com> Message-ID: <20060605194541.GA23818@performancedrivers.com> On Mon, Jun 05, 2006 at 07:34:05PM +0100, Steve Holden wrote: > amberite wrote: > > johnlichtenstein at gmail.com wrote: > > > >>I am using cx_Oracle and MySQLdb to pull a lot of data from some tables > >>and I find that the cursor.execute method uses a lot of memory that > >>never gets garbage collected. Using fetchmany instead of fetchall does > >>not seem to make any difference, since it's the execute that uses > >>memory. Breaking the query down to build lots of small tables doesn't > >>help, since execute doesn't give its memory back, after reading enough > >>small tables execute returns a memory error. What is the trick to get > >>memory back from execute in cx_Oracle and MySQLdb? > > > > > > cx_Oracle and MySQLdb must be handled differently, due to the fact that > > MySQL does not actually have cursors (MySQLdb fakes them for you). > > > > To handle large resultsets efficiently in cx_Oracle simply use the > > cursor iteration idiom: > > > > for row in cursor: > > # do stuff with the row > > > > cx_Oracle takes care of the fetching for you, and your memory usage > > should remain fairly constant when using this idiom. > > > > To handle large resultsets in MySQLdb, you have to resort to multiple > > queries: > > > > l = 1000 > > o = 0 > > > > cursor.execute('SELECT foo FROM Bar LIMIT %d OFFSET %d', (l, o)) > > rows = cursor.fetchall() > > while len(rows) > 0: > > # process the fetched rows > > o += l > > cursor.execute('SELECT foo FROM Bar LIMIT %d OFFSET %d', (l, o)) > > rows = cursor.fetchall() > > > > cursor.close() > > > > As you can see, the MySQLdb version is more involved, due to the lack > > of real cursor support in the MySQL database. Any database with good > > cursor support will likely have good cursor iteration support in the > > corresponding DBAPI driver. > > > > Hope this helps, > > > > L. Daniel Burr > > > The MySQLdb solution you give is way more complicated than it needs to > be, thereby skewing your opinion towards cx_Oracle unnecessarily. > > Look up the .fetchmany() method of cursors in the DB API. There is only > any need to execute a single query no matter how large the result set: > you simply need to keep calling .fetchmany(N) (where N is whatever > you've decided by testing is your optimum chunk size) until it returns > less than N rows, at which point you have exhausted the query. > > It's very little more effort to wrap this all up as a generator that > effectively allows you to use the same solution as you quote for cx_Oracle. MySQL will keep table locks until the results are all fetched so even though the DB API allows fetchone() or fetchmany() using those with MySQLdb is dangerous. -Jack From fredrik at pythonware.com Wed Jun 14 09:25:42 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 14 Jun 2006 15:25:42 +0200 Subject: Using "external" vars on module load time References: Message-ID: Marco Aschwanden wrote: > Load a module and hand in already the server_api. How can I achieve this? use execfile (or compile/exec) instead of import. From http Mon Jun 26 09:00:49 2006 From: http (Paul Rubin) Date: Mon, 26 Jun 2006 13:00:49 GMT Subject: automatic debugger? References: <1151326339.869650.278890@p79g2000cwp.googlegroups.com> Message-ID: <7xveqo2hry.fsf@ruckus.brouhaha.com> micklee74 at hotmail.com writes: > is there something like an automatic debugger module available in > python? Say if i enable this auto debugger, it is able to run thru the > whole python program, print variable values at each point, or print > calls to functions..etc...just like the pdb module, but now it's > automatic. Dunno about Python but www.askigor.com automatically finds the bugs in C programs. It's amazing. From vasudevram at gmail.com Tue Jun 13 10:51:38 2006 From: vasudevram at gmail.com (vasudevram) Date: 13 Jun 2006 07:51:38 -0700 Subject: Linux info In-Reply-To: <1150208970.621031.249840@i40g2000cwc.googlegroups.com> References: <448ec675_1@news.tm.net.my> <1150208970.621031.249840@i40g2000cwc.googlegroups.com> Message-ID: <1150210298.888677.208130@u72g2000cwu.googlegroups.com> os.system('ls -lL ' + path) should also work. But check, I may be wrong about the L option, and am not near a Linux system right now. That's "lL" - a small letter l (ell) followed by a capital letter L in the ls options above. This way may be slower than os.path.realpath if that is implemented as a system call, i.e.via Python ->C->Linux kernel, which it probably is. Slower since my way given above will create a new process to run the ls command in. Just mentioning it as another way, plus, it does have the small benefit that it'll work the same way on any other language such as Perl, Ruby, etc., which supports something similar to os.system(). Vasudev Ram http://www.geocities.com/vasudevram PDF conversion tools: http://sourceforge.net/projects/xtopdf faulkner wrote: > os.path.realpath > > TheSaint wrote: > > Hello there, > > > > I still learning, but I couldn't find anything which tells me where a > > symlink is pointing to. > > A part of os.system('ls -l ' + path) and cutting down to the need, I haven't > > got any specialized function. > > > > F From grflanagan at yahoo.co.uk Mon Jun 5 15:19:55 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 5 Jun 2006 12:19:55 -0700 Subject: Concatenating dictionary values and keys, and further operations In-Reply-To: <1149534126.129714.131860@f6g2000cwb.googlegroups.com> References: <1149534126.129714.131860@f6g2000cwb.googlegroups.com> Message-ID: <1149535195.763340.220010@y43g2000cwc.googlegroups.com> Gerard Flanagan wrote: > Girish Sahani wrote: > > I wrote the following code to concatenate every 2 keys of a dictionary and > > their corresponding values. > > e.g if i have tiDict1 = tiDict1 = {'a':[1,2],'b':[3,4,5]} i should get > > tiDict2={'ab':[1,2][3,4,5]} and similarly for dicts with larger no. of > > features. > > Now i want to check each pair to see if they are connected...element of > > this pair will be one from the first list and one from the second....e.g > > for 'ab' i want to check if 1 and 3 are connected,then 1 and 4,then 1 and > > 5,then 2 and 3,then 2 and 4,then 2 and 5. > > The information of this connected thing is in a text file as follows: > > 1,'a',2,'b' > > 3,'a',5,'a' > > 3,'a',6,'a' > > 3,'a',7,'b' > > 8,'a',7,'b' > > . > > . > > This means 1(type 'a') and 2(type 'b') are connected,3 and 5 are connected > > and so on. > > I am not able to figure out how to do this.Any pointers would be helpful > > > Girish > > It seems you want the Cartesian product of every pair of lists in the > dictionary, including the product of lists with themselves (but you > don't say why ;-)). > > I'm not sure the following is exactly what you want or if it is very > efficient, but maybe it will start you off. It uses a function > 'xcombine' taken from a recipe in the ASPN cookbook by David > Klaffenbach (2004). > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/302478 From cdsmith at twu.net Fri Jun 23 13:13:51 2006 From: cdsmith at twu.net (Chris Smith) Date: Fri, 23 Jun 2006 11:13:51 -0600 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150902275.129780.50260@p79g2000cwp.googlegroups.com> <1150918629.818145.143220@y41g2000cwy.googlegroups.com> <4fv081F1jh4ifU1@individual.net> <1150967543.947096.72840@g10g2000cwb.googlegroups.com> <4fv84rF1kp06kU1@individual.net> <1150988625.527780.148710@c74g2000cwc.googlegroups.com> <4g22l7F1j8p4mU1@individual.net> <1151081129.290382.297530@r2g2000cwb.googlegroups.com> Message-ID: Chris Smith wrote: > Programming languages do this all the time, as well. The most popular > example is the OO sense of the word polymorphism. That's all about > being able to write code that works with a range of values regardless of > (or, at least, a range that less constraining than equlity in) types. It's now dawned on me that I need not have restricted this to the OO sense of polymorphism. So let me rephrase. Polymorphism *is* when programming languages do that. -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation From aisaac0 at verizon.net Sat Jun 3 20:02:25 2006 From: aisaac0 at verizon.net (David Isaac) Date: Sun, 04 Jun 2006 00:02:25 GMT Subject: FreeImagePy and PIL Message-ID: I am just starting to think about image processing. What are the overlaps and differences in intended functionality between FreeImagePy and PIL? Thanks, Alan Isaac From onurb at xiludom.gro Wed Jun 28 12:07:49 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Wed, 28 Jun 2006 18:07:49 +0200 Subject: Immutability In-Reply-To: References: <4Qj*cEjkr@news.chiark.greenend.org.uk> Message-ID: <44a2a956$0$29814$626a54ce@news.free.fr> Nick Maclaren wrote: > In article <4Qj*cEjkr at news.chiark.greenend.org.uk>, > Sion Arrowsmith writes: > |> > |> Actually, there's an almost throw-away mention in > |> http://docs.python.org/ref/descriptor-invocation.html > |> which gives you what you need (although not, I have to say, in an > |> easily digestible form). > > Thanks very much. > > |> What I've not seen documented anywhere is the: > |> @property > |> def fset(self, value): > |> ... > |> idiom. It's not obvious from the documentation of the property > |> function that it can be used as a decorator like this. (cf. > |> classmethod and staticmethod.) > > Most especially since it isn't working very well for me, and I am trying > to track down why. When I run: > > class alf : > def pete (self) : > print "Inside pete\n" > > b = alf() > b.pete() > > class fred : > @property > def joe (self) : > print "Inside /joe\n" properties dont work properly on old-style classes (lookup 'new-style classes' on python.org, in the documentation menu), hence the strange behaviour you observe. Retry the same thing with s/class fred/class fred(object)/ -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From riteshsarraf at gmail.com Fri Jun 30 06:51:10 2006 From: riteshsarraf at gmail.com (Ritesh Raj Sarraf) Date: 30 Jun 2006 03:51:10 -0700 Subject: FIXED: Re: optparse multiple arguments In-Reply-To: References: <1151657119.837675.213700@p79g2000cwp.googlegroups.com> <1151663623.101732.264020@d56g2000cwd.googlegroups.com> Message-ID: <1151664670.846064.281720@b68g2000cwa.googlegroups.com> Fredrik Lundh wrote: > Ritesh Raj Sarraf wrote: > > >> http://docs.python.org/lib/optparse-standard-option-actions.html > > > > That won't help because by design of my program, I can't limit the > > number of arguments a user can pass to it. > > do you want options, arguments, or are you just somewhat confused ? > > I'm not sure about that. My program will accept user input. The user can input multiple arguments. maybe 1 or maybe 100, that's not definite. I do need option because this particular (multiple) argument criteria is for one single option. Thanks, Ritesh From johnjsal at NOSPAMgmail.com Thu Jun 15 17:49:47 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 15 Jun 2006 17:49:47 -0400 Subject: a good programming text editor (not IDE) In-Reply-To: References: <_xgkg.2317$No6.48542@news.tufts.edu> <1150402733.116243.9680@y41g2000cwy.googlegroups.com> Message-ID: <4491d804$0$5014$c3e8da3@news.astraweb.com> Fredrik Lundh wrote: > hints: 1) editor wars are so last century. 2) emacs has already won. Uh oh, here we go.............. ;) From find at my.address.elsewhere Wed Jun 28 14:50:42 2006 From: find at my.address.elsewhere (Matthias Blume) Date: Wed, 28 Jun 2006 13:50:42 -0500 Subject: What is Expressiveness in a Computer Language References: <7zy7vt1mz2.fsf@app-3.diku.dk> <1151384511.223582.305760@m73g2000cwd.googlegroups.com> <4gdkmiF1ldalhU3@individual.net> <4gfcclF1mpbg7U1@individual.net> <6gwog.488405$xt.80841@fe3.news.blueyonder.co.uk> <4gfiufF1mg6h9U1@individual.net> <4gfo6tF1cju7vU1@individual.net> Message-ID: Pascal Costanza writes: >> And I am convinced that updating a running system in the style of, >> e.g., Erlang, can be statically typed. > > Maybe. The interesting question then is whether you can express the > kinds of dynamic updates that are relevant in practice. Because a > static type system always restricts what kinds of runtime behavior you > can express in your language. I am still skeptical, because changing > the types at runtime is basically changing the assumptions that the > static type checker has used to check the program's types in the first > place. That's why I find the Erlang model to be more promising. I am extremely skeptical of code mutation at runtime which would "change types", because to me types are approximations of program invariants. So if you do a modification that changes the types, it is rather likely that you did something that also changed the invariants, and existing code relying on those invariants will now break. > For example, all the approaches that I have seen in statically typed > languages deal with adding to a running program (say, class fields and > methods, etc.), but not with changing to, or removing from it. Of course, there are good reasons for that: removing fields or changing their invariants requires that all /deployed/ code which relied on their existence or their invariants must be made aware of this change. This is a semantic problem which happens to reveal itself as a typing problem. By making types dynamic, the problem does not go away but is merely swept under the rug. >>>> Note that prohibiting directly self-modifying code does not prevent a >>>> program from specifying another program to *replace* it. >>> ...and this creates problems with moving data from one version of a >>> program to the next. >> How does this "create" such a problem? The problem is there in >> either >> approach. In fact, I believe that the best chance we have of >> addressing the problem is by adopting the "replace the code" model >> along with a "translate the data where necessary at the time of >> replacement". Translating the data, i.e., re-establishing the >> invariants expected by the updated/replaced code, seems much harder >> (to me) in the case of self-modifying code. Erlang got this one >> right. > > ...and the "translate the date where necessary" approach is > essentially triggered by a dynamic type test (if value x is of an old > version of type T, update it to reflect the new version of type T > [1]). QED. But this test would have to already exist in code that was deployed /before/ the change! How did this code know what to test for, and how did it know how to translate the data? Plus, how do you detect that some piece of data is "of an old version of type T"? If v has type T and T "changes" (whatever that might mean), how can you tell that v's type is "the old T" rather than "the new T"! Are there two different Ts around now? If so, how can you say that T has changed? The bottom line is that even the concept of "changing types at runtime" makes little sense. Until someone shows me a /careful/ formalization that actually works, I just can't take it very seriously. From frank at chagford.com Sat Jun 17 02:23:52 2006 From: frank at chagford.com (Frank Millman) Date: 16 Jun 2006 23:23:52 -0700 Subject: XML, JSON, or what? In-Reply-To: References: <1149749530.734275.181300@j55g2000cwa.googlegroups.com> <1149760146.136587.124710@h76g2000cwa.googlegroups.com> <1150466796.646397.149890@p79g2000cwp.googlegroups.com> Message-ID: <1150525432.850591.298770@f6g2000cwb.googlegroups.com> Daniel Dittmar wrote: > > My client-server is Python-to-Python. At present, I am using cPickle to > > transfer objects between the two. Among other things, I sometimes > > transfer a tuple. Using JSON it appears on the other side as a list. As > > I sometimes use the tuple as a dictionary key, this fails, as you > > obviously cannot use a list as a key. > [...] > > Can someone confirm this, or is there an easy workaround? > > You can always convert a list to a tuple using the tuple () builtin > right before you use it as a key. But you have to be sure that it is a > list. tuple ("abc") => ('a', 'b', 'c') is probably not what you intend > to do. > > Daniel Thanks,Daniel. After sleeping on it, I had also come to the conclusion that this is the easiest solution - if isinstance(key,list): key = tuple(key) A bit of a kludge, but I can live with it. I will keep checking to see if any other anomalies crop up. Frank From martin at v.loewis.de Mon Jun 5 04:11:50 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 05 Jun 2006 10:11:50 +0200 Subject: Python less error-prone than Java In-Reply-To: References: <1149408824.174844.178010@u72g2000cwu.googlegroups.com> Message-ID: <4483E746.8010801@v.loewis.de> Ilpo Nyyss?nen wrote: >> Buggy library code is what prompted that article. > > Yes, but it is an error type that happens very rarely still. And so it > seems that very few programs even notice that bug in that library. That's certainly the case. The bug went unnoticed in the Java library for nearly a decade, despite Java being used fairly widely. The OP's point is not that the bug might be "minor": the point is that an algorithm who was studied hundreds of times in computer science courses, repeated many times in the literature, and proven "correct" many times, still is wrong, and that the error primarily arises from using a type declaration. > If the input value range is limited, you want to get an error, if out > of range value is given. If you want to handle unlimited values, you > really need to take a look that you can do it. Think for example > storing such value to a database. So the real design flaw in Java is that int addition doesn't raise exceptions on overflow? That wouldn't have helped - the algorithm still would have been wrong, and people still would have noticed only when it happens (just as they get an exception now: array index out of bounds) Regards, Martin From tjreedy at udel.edu Sat Jun 24 12:54:41 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 24 Jun 2006 12:54:41 -0400 Subject: Python and cellular automata (It works this time!) References: <1151158859.422817.239810@y41g2000cwy.googlegroups.com> Message-ID: "defcon8" wrote in message news:1151158859.422817.239810 at y41g2000cwy.googlegroups.com... >I thought people would be interested in this little script I wrote to > reproduce the 256 simple automata that is shown in the first chapters > of "A New Kind of Science". You can see a few results without running > the script, at http://cooper-j.blogspot.com 404 not found. typo? From kentilton at gmail.com Thu Jun 29 21:59:07 2006 From: kentilton at gmail.com (Ken Tilton) Date: Thu, 29 Jun 2006 21:59:07 -0400 Subject: Reddit broke - should have remained on Lisp? In-Reply-To: <1151627462.297352.205150@i40g2000cwc.googlegroups.com> References: <1151626961.232761.255550@d56g2000cwd.googlegroups.com> <1151627462.297352.205150@i40g2000cwc.googlegroups.com> Message-ID: Luis M. Gonz?lez wrote: > Alok wrote: > >>While posting a comment on http://www.reddit.com I got an error page >>with the following curious statement on it. >> >>"reddit broke (sorry)" >>"looks like we shouldn't have stopped using lisp..." >> >>See screenshot at >>http://photos1.blogger.com/blogger/1773/1980/1600/reddit-broke.jpg >> >>Whether they truly repent not using lisp or otherwise, their site >>appears to be 3 times slower ... >> >>Alok > > > > I don't know if this is true or not, but blaming a language for a poor > development is a little bit ridiculous... > Well, Reddit said it, not us, and they were probably joking, but it may well be that the bug would not have happened if they were using Lisp. Could an infinite number of engineers doing code reviews eventually found the bug before the end of the universe? The reality is that every project has finite resources, all the better reason not to stress the team with the wrong language. kenny (making Rahul happy by being f'ed by OpenGL bugs) -- Cells: http://common-lisp.net/project/cells/ "I'll say I'm losing my grip, and it feels terrific." -- Smiling husband to scowling wife, New Yorker cartoon From scott.daniels at acm.org Sun Jun 25 13:48:07 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Sun, 25 Jun 2006 10:48:07 -0700 Subject: sum fonction in gadfly In-Reply-To: <1151234839.665889.258660@b68g2000cwa.googlegroups.com> References: <1151137825.177814.217180@u72g2000cwu.googlegroups.com> <449d253d$1@nntp0.pdx.net> <1151234839.665889.258660@b68g2000cwa.googlegroups.com> Message-ID: <449ec743$1@nntp0.pdx.net> jean-jeanot wrote: > Thank you for your help. You're welcome. > It could be useful for me to change of DB ? Which one ? Postgresql or > another ? Well, if gadfly is serving you well, you might as well stay with it. Python 2.5 comes with sqlite3, which might well be a nice small step. I find Postgresql to be a real solid DB, and a company I've been talking with likes MySQL -- which finally has transactions (one of my personal requirements before I'll call a DBMS "real"). Really, you should decide what you want the DBMS to do, and try to get those requirements out; you'll get better advice. --Scott David Daniels scott.daniels at acm.org From Bulkan at gmail.com Tue Jun 27 21:07:11 2006 From: Bulkan at gmail.com (placid) Date: 27 Jun 2006 18:07:11 -0700 Subject: HTTP server Message-ID: <1151456831.224564.214360@p79g2000cwp.googlegroups.com> Hi all, Im having trouble with the following code for handling GET requests from a client to my HTTP server. What i want to do is restrict access only to a folder and contents(files) within this folder. But when trying to open files (eg text files) i get file not found error from send_head() method of SimpleHTTPServer. The reason behind this is when opening the file the path to the file is only C:\file.txt when it should be C:\folder\file.txt. And when i remove the code that checks if path contains "txt" it works (i can access files without errors). Any help will be greatly appreciated! def list_directory(self, path): """Helper to produce a directory listing (absent index.html). Return value is either a file object, or None (indicating an error). In either case, the headers are sent, making the interface the same as for send_head(). """ f = StringIO() p = self.translate_path(self.path) if p.find("txt") == -1: f.write("httpserver.py: Access Denied" ) f.write("

httpserver.py: Access Denied

" ) else: try: list = os.listdir(path) except os.error: self.send_error(404, "No permission to list directory") return None list.sort(key=lambda a: a.lower()) displaypath = cgi.escape(urllib.unquote(self.path)) f.write("Directory listing for %s\n" %displaypath) f.write("

Directory listing for %s

\n" % displaypath) f.write("
\n
\n
\n") length = f.tell() f.seek(0) self.send_response(200) self.send_header("Content-type", "text/html") self.send_header("Content-Length", str(length)) self.end_headers() return f
From fredrik at pythonware.com Wed Jun 7 14:17:22 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 07 Jun 2006 20:17:22 +0200 Subject: Writing to a certain line? In-Reply-To: <44869dd3$0$31210$626a54ce@news.free.fr> References: <1149576072.168354.14470@f6g2000cwb.googlegroups.com> <44854184$0$29904$636a55ce@news.free.fr> <1149630414.246008.270720@f6g2000cwb.googlegroups.com> <448697f7$0$10260$626a54ce@news.free.fr> <44869dd3$0$31210$626a54ce@news.free.fr> Message-ID: Christophe wrote: > Use /dev/zero as source and /dev/null as destination :D have you tried looping over an endless null-byte stream? on a random Linux server, this statement >>> for line in open("/dev/zero"): ... print len(line) ... terminates without printing anything after about three seconds, which is a bit odd. in contrast, >>> f = open("/dev/zero") >>> len(f.readline()) raises a MemoryError exception after about 10 seconds. hmm. looks like a bug in the file iterator, really... From ilias at lazaridis.com Wed Jun 7 11:41:58 2006 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Wed, 07 Jun 2006 18:41:58 +0300 Subject: Django Quick Start with Schema Evolution Support In-Reply-To: References: <1149446706.085692.174980@h76g2000cwa.googlegroups.com> <1149505316.406428.242450@c74g2000cwc.googlegroups.com> <448429E1.90305@kered.org> <35081.132.60.240.80.1149530454.squirrel@kered.org> <4486D6F2.7000407@lazaridis.com> Message-ID: Steve Holden wrote: > Ilias Lazaridis wrote: >> Steve Holden wrote: >>> Ilias Lazaridis wrote: ... This thread is now technical. Thank you for your comments. . -- http://lazaridis.com From alanalan at newsgroup.nospam Thu Jun 1 15:32:58 2006 From: alanalan at newsgroup.nospam (A.M) Date: Thu, 1 Jun 2006 15:32:58 -0400 Subject: Using print instead of file.write(str) Message-ID: Hi, I found print much more flexible that write method. Can I use print instead of file.write method? Thank you, Alan From david.nospam.hopwood at blueyonder.co.uk Wed Jun 28 07:11:23 2006 From: david.nospam.hopwood at blueyonder.co.uk (David Hopwood) Date: Wed, 28 Jun 2006 11:11:23 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: <7xwtb2j8ir.fsf@ruckus.brouhaha.com> References: <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <1151384511.223582.305760@m73g2000cwd.googlegroups.com> <1151425350.679754.278820@i40g2000cwc.googlegroups.com> <1151450513.458623.139460@b68g2000cwa.googlegroups.com> <7xwtb2j8ir.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > David Hopwood writes: > >>Note that I'm not claiming that you can check any desirable property of >>a program (that would contradict Rice's Theorem), only that you can >>express any dynamically typed program in a statically typed language -- >>with static checks where possible and dynamic checks where necessary. > > It starts to look like sufficiently powerful static type systems are > confusing enough, that programming with them is at least as bug-prone > as imperative programming in dynamically typed languages. The static > type checker can spot type mismatches at compile time, but the > types themselves are easier and easier to get wrong. My assertion above does not depend on having a "sufficiently powerful static type system" to express a given dynamically typed program. It is true for static type systems that are not particularly complicated, and suffice to express all dynamically typed programs. I disagree with your implication that in general, static type systems for practical languages are getting too confusing, but that's a separate issue. (Obviously one can find type systems in research proposals that are too confusing as they stand.) -- David Hopwood From gandalf at designaproduct.biz Fri Jun 9 15:16:37 2006 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Fri, 09 Jun 2006 21:16:37 +0200 Subject: TypeError: unsubscriptable object In-Reply-To: <1149879150.705403.231260@g10g2000cwb.googlegroups.com> References: <1149874726.470436.279200@i40g2000cwc.googlegroups.com> <1149878331.500752.8170@j55g2000cwa.googlegroups.com> <1149879150.705403.231260@g10g2000cwb.googlegroups.com> Message-ID: <4489C915.6010703@designaproduct.biz> k.retheesh at gmail.com ?rta: > I did the same, > > The function type is < NoneType> and the description type is > so how can i print a part of this 2 output. > The unicode object IS subscriptable. It is a unicode string which has characters. The value None is not subscriptable. It probably means that you have a NULL value in your database. Try the following: def nulltoemptystr(value): if value is None: return "" else: return value[:10] print template % (ID, IID, nulltoemptystr(Function), nulltoemptystr(Description),ErrorNumber, StatusCD) You can also try to do the same in SQL. For example, this works with FireBird, PostgreSQL and many others: select coalesce(Function,"") as Function from TableName instead of select Function from TableName But first of all, I would recommend you to go over the Python tutorial. It explains these things and more. http://docs.python.org/tut/tut.html Best, Laszlo From rossberg at ps.uni-sb.de Thu Jun 22 05:31:19 2006 From: rossberg at ps.uni-sb.de (Andreas Rossberg) Date: Thu, 22 Jun 2006 11:31:19 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: <1150916327.332627.124400@g10g2000cwb.googlegroups.com> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <0%Wlg.3521$MF6.947@tornado.socal.rr.com> <44992e6c$0$664$bed64819@news.gradwell.net> <1150916327.332627.124400@g10g2000cwb.googlegroups.com> Message-ID: Marshall wrote: >Andreas Rossberg wrote: >>Chris Uppal wrote: >> >>>I have never been very happy with relating type to sets of values (objects, >>>whatever). >> >>Indeed, this view is much too narrow. In particular, it cannot explain >>abstract types, which is *the* central aspect of decent type systems. > > What prohibits us from describing an abstract type as a set of values? If you identify an abstract type with the set of underlying values then it is equivalent to the underlying representation type, i.e. there is no abstraction. >>There were papers observing this as early as 1970. > > References? This is 1973, actually, but most relevant: James Morris Types Are Not Sets. Proc. 1st ACM Symposium on Principles of Programming Languages, 1973 >>(There are also theoretic problems with the types-as-sets view, because >>sufficiently rich type systems can no longer be given direct models in >>standard set theory. For example, first-class polymorphism would run >>afoul the axiom of foundation.) > > There is no reason why we must limit ourselves to "standard set theory" > any more than we have to limit ourselves to standard type theory. > Both are progressing, and set theory seems to me to be a good > choice for a foundation. What else would you use? I'm no expert here, but Category Theory is a preferred choice in many areas of PLT. - Andreas From maxerickson at gmail.com Fri Jun 23 08:43:38 2006 From: maxerickson at gmail.com (Max Erickson) Date: Fri, 23 Jun 2006 12:43:38 +0000 (UTC) Subject: code is data References: <44965f53$0$12743$636a55ce@news.free.fr> <4496b29f$0$27412$626a54ce@news.free.fr> <4496e9c9$0$14868$626a54ce@news.free.fr> <4fokj4F1ihat3U1@uni-berlin.de> <4497c20e$0$29656$636a55ce@news.free.fr> <4fpuh5F1i9bl1U1@uni-berlin.de> <4497d72d$0$30964$636a55ce@news.free.fr> <4fq5fkF1k346bU1@uni-berlin.de> <44982637$0$29812$626a54ce@news.free.fr> <1151013151.902103.32800@g10g2000cwb.googlegroups.com> Message-ID: Anton Vredegoor wrote: > > However, I knew of the existence of such languages but I am > mostly interested in standardized code interchange, like for > example with JSONP which fetches some external javascriptcode > from another server using JSON and places the translated > javascript into a webpage at the request of the clients browser > or so it seems. Maybe a Python webserver could also emit pieces > of javascript code by getting them from a *Python* code library > after translating Python code on the fly? > > Anton I have no idea how close it is to what you are talking about, but pypy does have some sort of python->javascript support: http://codespeak.net/pypy/dist/pypy/doc/getting- started.html#translating-the-flow-graph-to-javascript-code About two thirds down, if the above link is broken: http://codespeak.net/pypy/dist/pypy/doc/getting-started.html max From rzantow at gmail.com Fri Jun 9 14:24:44 2006 From: rzantow at gmail.com (Rick Zantow) Date: Fri, 09 Jun 2006 14:24:44 -0400 Subject: Pychecker References: Message-ID: Anthony Greene wrote in news:pan.2006.06.09.18.10.58.746134 at zetafunc.net: > Howdy, I had the impression that pychecker caught and reported such > dynamic syntactical errors. > > #!/usr/bin/env python > > > def add(i): > i += 10 > > status = 3 > > if 1 == 1: > statuss = 15 > > add(status) > > ======================= > > exalted sysfault$ pychecker foo.py > Processing foo... > > Warnings... > > None > > ======================= > > Hence the mispelling of status (statuss), which was done purposely to > test if pychecker will acknowledge and report the error. Do i need to > enable some type of pychecker option in order for it to pick up the > error? I know that it is syntactically correct in python, however it's > likely that 'status' is meant. Am i wishing that pychecker will > replace a statically typed language mechanism? > I think you're asking a lot from pychecker. kop = 1 koi = 2 if True: koo = 3 What would you like pychecker to report? -- rzed From bdesth.quelquechose at free.quelquepart.fr Wed Jun 28 20:20:09 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 29 Jun 2006 02:20:09 +0200 Subject: Generator naming convention? In-Reply-To: <1151520720.749818.131460@i40g2000cwc.googlegroups.com> References: <1151520720.749818.131460@i40g2000cwc.googlegroups.com> Message-ID: <44a2ec68$0$9013$626a54ce@news.free.fr> aurora00 at gmail.com a ?crit : > I use generators a lot. E.g. > > > def gen_words(text) > ... parse text ... > yield each word in text > > for word in gen_words(text): > print word > > > I don't like the name gen_xxx() very much. Nor do I. > Looking for some inspiration > to name generators. Here are some of my ideas: > > enumerate_words > gen_words > generate_words > parse_words > walk_words > > Any idea? D Any of these names have different (somewhat implied) semantic to me. I'd expect enunmerate_words to yield (order, word) pairs, parse_words to yield tokens, walk_words to traverse a tree of words, etc As you see, this is much about what it does than what it is. And FWIW, do you prefix function names s with fun_ ? > you have a naming convention for generators? No. From duncan.booth at invalid.invalid Thu Jun 8 04:34:14 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 8 Jun 2006 08:34:14 GMT Subject: Regular Expression question References: Message-ID: Paul McGuire wrote: >> import re >> r=re.compile('[^"]+)"[^>]*>',re.IGNORECASE) >> for m in r.finditer(html): >> print m.group('image') >> > > Ouch - this fails to match any tag that has some other > attribute, such as "height" or "width", before the "src" attribute. > www.yahoo.com has several such tags. It also fails to match any image tag where the src attribute is quoted using single quotes, or where the src attribute is not enclosed in quotes at all. Handle all of that correctly in the regex and the beautiful soup or pyparsing options look even more attractive. In fact, if anyone can write a regex which matches the source attribute in a single named group, and correctly handles double, single and unquoted attributes, I'll admit to being impressed (and probably also slightly queasy when looking at it). Here's my best attempt at a regex that gets it right, but it still gets confused by other attributes if they contain spaces. >>> ATTR = '''[^\s=>]+(?:=(?:"[^">]*"|'[^'>]*'|[^"'\s>][^\s>]*))?''' >>> NOTSRC = '(?!src=)' + ATTR >>> PAT = '''(?<=")[^">]*|(?<=')[^'>]*|[^ >]*)''' >>> htmlPage = ''' ''' >>> for m in r.finditer(htmlPage): print m.group('image') fred.jpg freda.jpg >>> From marshall.spight at gmail.com Mon Jun 26 22:18:24 2006 From: marshall.spight at gmail.com (Marshall) Date: 26 Jun 2006 19:18:24 -0700 Subject: What is a type error? In-Reply-To: <4gakhiF1m698cU1@individual.net> References: <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <7i3mg.204167$8W1.155367@fe1.news.blueyonder.co.uk> <44992e6c$2$664$bed64819@news.gradwell.net> <%Igmg.464974$xt.353729@fe3.news.blueyonder.co.uk> <4fv0v3F1kipa6U1@individual.net> <4gakhiF1m698cU1@individual.net> Message-ID: <1151374704.304776.60630@u72g2000cwu.googlegroups.com> Pascal Costanza wrote: > > Consider division by zero: appropriate arguments for division are > numbers, including the zero. A bold assertion! The general question is, what do we do about partial functions? > The dynamic type check will typically not > check whether the second argument is zero, but will count on the fact > that the processor will raise an exception one level deeper. This is an implementation artifact, and hence not relevant to our understanding of the issue. Marshall From spam.noam at gmail.com Thu Jun 8 17:10:40 2006 From: spam.noam at gmail.com (spam.noam at gmail.com) Date: 8 Jun 2006 14:10:40 -0700 Subject: Allowing zero-dimensional subscripts Message-ID: <1149801040.936452.26270@i40g2000cwc.googlegroups.com> Hello, I discovered that I needed a small change to the Python grammar. I would like to hear what you think about it. In two lines: Currently, the expression "x[]" is a syntax error. I suggest that it will be evaluated like "x[()]", just as "x[a, b]" is evaluated like "x[(a, b)]" right now. In a few more words: Currently, an object can be subscripted by a few elements, separated by commas. It is evaluated as if the object was subscripted by a tuple containing those elements. I suggest that an object will also be subscriptable with no elements at all, and it will be evaluated as if the object was subscripted by an empty tuple. It involves no backwards incompatibilities, since we are dealing with the legalization of a currently illegal syntax. It is consistent with the current syntax. Consider that these identities currently hold: x[i, j, k] <--> x[(i, j, k)] x[i, j] <--> x[(i, j)] x[i, ] <--> x[(i, )] x[i] <--> x[(i)] I suggest that the next identity will hold too: x[] <--> x[()] I need this in order to be able to refer to zero-dimensional arrays nicely. In NumPy, you can have arrays with a different number of dimensions. In order to refer to a value in a two-dimensional array, you write a[i, j]. In order to refer to a value in a one-dimensional array, you write a[i]. You can also have a zero-dimensional array, which holds a single value (a scalar). To refer to its value, you currently need to write a[()], which is unexpected - the user may not even know that when he writes a[i, j] he constructs a tuple, so he won't guess the a[()] syntax. If my suggestion is accepted, he will be able to write a[] in order to refer to the value, as expected. It will even work without changing the NumPy package at all! In the normal use of NumPy, you usually don't encounter zero-dimensional arrays. However, I'm designing another library for managing multi-dimensional arrays of data. Its purpose is similiar to that of a spreadsheet - analyze data and preserve the relations between a source of a calculation and its destination. In such an environment you may have a lot of multi-dimensional arrays - for example, the sales of several products over several time periods. But you may also have a lot of zero-dimensional arrays, that is, single values - for example, the income tax. I want the access to the zero-dimensional arrays to be consistent with the access to the multi-dimensional arrays. Just using the name of the zero-dimensional array to obtain its value isn't going to work - the array and the value it contains have to be distinguished. I have tried to change CPython to support it, and it was fairly easy. You can see the diff against the current SVN here: http://python.pastebin.com/768317 The test suite passes without changes, as expected. I didn't include diffs of autogenerated files. I know almost nothing about the AST, so I would appreciate it if someone who is familiar with the AST will check to see if I did it right. It does seem to work, though. Well, what do you think about this? Have a good day, Noam Raphael From sjmachin at lexicon.net Fri Jun 16 20:47:39 2006 From: sjmachin at lexicon.net (John Machin) Date: Sat, 17 Jun 2006 10:47:39 +1000 Subject: [Python-Dev] The baby and the bathwater (Re: Scoping, augmented assignment, 'fast locals' - conclusion) In-Reply-To: <449329F0.2000703@gmail.com> References: <20060614093042.F2D7.JCARLSON@uci.edu> <449329F0.2000703@gmail.com> Message-ID: <4493512B.3010300@lexicon.net> On 17/06/2006 8:00 AM, Boris Borcic wrote: > Josiah Carlson wrote: Please consider abandoning this "conversation". Plan B: Please consider conducting it using private e-mail. Plan C: Please consider conducting it in alt.you.said.I.said.you.said.I.said From luismgz at gmail.com Mon Jun 12 22:41:14 2006 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 12 Jun 2006 19:41:14 -0700 Subject: Combining The Best Of Python, Ruby, & Java?????? In-Reply-To: <1150157085.887359.318760@f14g2000cwb.googlegroups.com> References: <1150157085.887359.318760@f14g2000cwb.googlegroups.com> Message-ID: <1150166474.168065.220110@i40g2000cwc.googlegroups.com> bearophileHUGS at lycos.com wrote: > Scala seems terse and fast enough, few examples: > > http://shootout.alioth.debian.org/gp4sandbox/benchmark.php?test=all&lang=psyco&lang2=scala > > Bye, > bearophile Static typing, type inference, "sequence comprehensions"... Looks that there's a new crop of programming languages on top of the main .NET and JAVA with these characteristics. This one seems to be following the trend initiated by Nemerle and Boo. The good thing about these languages is that they offer the performance of static languages, with the feel of dynamic ones. Thanks to their local type inference, you don't have to declare types or return types so often, and with generics, type castings are also reduced to a minimum. Anyway, I think that from a python programmer perspective, those looking for a static language for .NET or Mono would find Boo more appealing. For example, I use it for writing extenssions for Ironpython when I need more performance. From serge.orlov at gmail.com Tue Jun 27 16:47:21 2006 From: serge.orlov at gmail.com (Serge Orlov) Date: Tue, 27 Jun 2006 13:47:21 -0700 Subject: to py or not to py ? In-Reply-To: References: Message-ID: On 6/27/06, Chandrashekhar kaushik wrote: > HI all > I have the following prob. > I am to write a parallel vis application . > I wud have by default used C++ for the same but somehow > thought if py cud help me .. > It does as in many things that i would otherwise have written down > already exists ... ( like built in classes for sockets , threading etc ) > > I would be doin the following type of tasks .. > > 1. sending data across the network > the data is going to be huge > > 2. once data has been sent i will run some vis > algos parallely on them and get the results > > now one thing that i wud req. is serializing my data structures so that > they can be sent across the net. > > pyton does allow this using cPickle , but it bloats the data like anythin > !!! > for example a class containing 2 integers which i expect will be 8 bytes > long .. > cPickle.dumps returns a string thats 86 bytes wide !!!! ( this is the binary > version protocol 1 ) > > anyway to improve serialization ?? Do it yourself using struct module. > also is it actually a good idea to write high perf applications in python ? Take a look at Mercurial sources. It's a high performance python application. Or watch Bryan O'Sullivan's Mercurial presentation he talks briefly how they made it work fast. But writing high performance application in python requires self-discipline and attention to details, looking at the way you spell I think it will be a challenge ;) From rpdooling at gmail.com Thu Jun 1 15:30:42 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 1 Jun 2006 12:30:42 -0700 Subject: How to format datetime values In-Reply-To: References: Message-ID: <1149190242.446952.52180@j55g2000cwa.googlegroups.com> Are you trying to get banned, or what? It's the equivalent of me asking you: Hey, does Ruby have anything like dictionaries and will you teach me about strings? Oh, and what's an object? Go read the bleeping tutorial. rd From david.nospam.hopwood at blueyonder.co.uk Wed Jun 21 00:19:10 2006 From: david.nospam.hopwood at blueyonder.co.uk (David Hopwood) Date: Wed, 21 Jun 2006 04:19:10 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: <4fqt33F1kfd1jU1@individual.net> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <4fpvbvF1keed1U1@individual.net> <4fqonoF1kfkapU1@individual.net> <1150824752.799997.206210@p79g2000cwp.googlegroups.com> <4fqt33F1kfd1jU1@individual.net> Message-ID: <2N3mg.462963$xt.331923@fe3.news.blueyonder.co.uk> Pascal Costanza wrote: > Rob Thorpe wrote: >> Pascal Costanza wrote: >>> Matthias Blume wrote: >>>> Pascal Costanza writes: >>>> >>>>> (slot-value p 'address) is an attempt to access the field 'address in >>>>> the object p. In many languages, the notation for this is p.address. >>>>> >>>>> Although the class definition for person doesn't mention the field >>>>> address, the call to (eval (read)) allows the user to change the >>>>> definition of the class person and update its existing >>>>> instances. Therefore at runtime, the call to (slot-value p 'adress) >>>>> has a chance to succeed. >>>> >>>> I am quite comfortable with the thought that this sort of evil would >>>> get rejected by a statically typed language. :-) >>> >>> This sort of feature is clearly not meant for you. ;-P >> >> To be fair though that kind of thing would only really be used while >> debugging a program. >> Its no different than adding a new member to a class while in the >> debugger. >> >> There are other places where you might add a slot to an object at >> runtime, but they would be done in tidier ways. > > Yes, but the question remains how a static type system can deal with > this kind of updates. It's not difficult in principle: - for each class [*], define a function which converts an 'old' value of that class to a 'new' value (the ability to do this is necessary anyway to support some kinds of upgrade). A default conversion function may be autogenerated if the class definition has changed only in minor ways. - typecheck the new program and the conversion functions, using the old type definitions for the argument of each conversion function, and the new type definitions for its result. - have the debugger apply the conversions to all values, and then resume the program. [*] or nearest equivalent in a non-OO language. -- David Hopwood From buzzard at urubu.freeserve.co.uk Fri Jun 2 09:11:28 2006 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Fri, 02 Jun 2006 14:11:28 +0100 Subject: after del list , when I use it again, prompt 'not defined'.how could i delete its element,but not itself? In-Reply-To: <1149235087.256704.309360@g10g2000cwb.googlegroups.com> References: <1149235087.256704.309360@g10g2000cwb.googlegroups.com> Message-ID: <44803b20.0@entanet> python wrote: [snip] > > How could I keep the list1 not to change when remove list2's elements? > You can't when the names list1 and list2 refer to the same list. Try making list2 a copy of list1, list2 = list(list1) Duncan From harry.g.george at boeing.com Fri Jun 9 02:52:04 2006 From: harry.g.george at boeing.com (Harry George) Date: Fri, 9 Jun 2006 06:52:04 GMT Subject: How to link foreign keys & primary keys using python? References: <1149856668.055162.209650@u72g2000cwu.googlegroups.com> Message-ID: "sonal" writes: > Hi all, > I hv started with python just recently... and have been assigned to > make an utility which would be used for data validations... ,snip] > plz help me... till get my hands on python... :) > 1. This sure looks like a school assignment. 2. "till get my..." Do you actually not have python installed yet? It is hopeless to tackle this problem if you haven't done a few simple "hello, world" tasks. 3. Do you have a data model? In this case, you need to think carefully about what a RDBMS, PK, and FK are. In otherwords, a metamodel. Generally, once you understand the data structures you should implement them pretty much verbatim in a "model" module. Then do reader/writer modules so you can load that model from your data sources and dump out to your data sinks. 4. Do you have a testsuite and test harness? Put together your test harness, then develop for the simplest case, then add complexity. E.g., no FK, FK with 1 attr, FK with multiple attrs, FKs with shared attrs. -- Harry George PLM Engineering Architecture From jonathan.wright at gmail.com Fri Jun 2 06:38:28 2006 From: jonathan.wright at gmail.com (Jon) Date: 2 Jun 2006 03:38:28 -0700 Subject: import confused by contents of working directory Message-ID: <1149244708.049852.153980@i39g2000cwa.googlegroups.com> It appears that (windows) python searches in the current working directory before looking in the local site-packages directory, or that '.' comes first in sys.path? The problem arises when I made the mistake of running a test program from the same directory where I built and installed my package. Python uses the package from the current directory, which misses the pyd files, instead of the site-packages package which has them installed. Would somebody please explain how to know what is going on when an import statement is ambiguous? If the interpreter has several choices about what to import then which one is chosen? I apologise if this is FAQ, but it seems that if I say "import mymodule" and the interpreter finds more than one option for mymodule it could raise an Exception asking "which one do you want??" instead of silently picking up the first thing it finds? This would be perhaps a major change - but I expect "import" to go look in the python installation and would look for a command like "load" to go looking for specific filenames or find things that are hanging around in the current working directory. Is there any plan for a statement like: "from future import PleaseDontJustGuessWhatToImport" ? Thanks in advance for any useful advice, perhaps I am just missing the out on the "right way to do it"? It is normal to remove '.' from sys.path at the start of a script? Jon ------------------------------------- Some examples of my confusion are outlined below. I use Numeric only because I assume they are doing a proper installation. I had thought for a long time that I had this problem because I was screwing up with distutils or .pth files etc etc. c:\> mkdir import c:\> cd import c:\import> python -c "import Numeric; print 'OK!'" OK! c:\import> echo raise Exception("Not OK! Local py file") > Numeric.py c:\import> python -c "import Numeric;print 'OK!'" Traceback (most recent call last): File "", line 1, in ? File "Numeric.py", line 1, in ? raise Exception("Not OK! Local py file") Exception: Not OK! Local py file c:\import> del Numeric.py c:\import> mkdir Numeric c:\import> python -c "import Numeric; print 'OK!'" OK! c:\import> echo raise Exception("Not OK! Local version") > Numeric\__init__.py c:\import> python -c "import Numeric;print 'OK!'" Traceback (most recent call last): File "", line 1, in ? File "Numeric\__init__.py", line 1, in ? raise Exception("Not OK! Local version") Exception: Not OK! Local version c:\import> del Numeric\__init__.py c:\import>python -c "import Numeric;print 'OK!'" Traceback (most recent call last): File "", line 1, in ? File "c:\python24\lib\site-packages\PIL\__init__.py", line 1, in ? # Exception: Not OK! Local version [authors note] What??? This was imported from Numeric\__init__.pyc c:\import> del Numeric\__init__.pyc c:\import> python -c "import Numeric;print 'OK!'" OK! The the actual example is more like this: c:\ImageD11> python setup.py build --compiler=mingw32 install ... c:\ImageD11>c:\python24\scripts\ImageD11_gui.py ... ImportError: can't import name closest c:\ImageD11> cd .. c:\> c:\python24\scripts\ImageD11_gui.py ...and the gui runs!! ... Given that the script resides in $python\scripts I sort of expect it to avoid tripping over some local and irrelevant file. From gregory.petrosyan at gmail.com Wed Jun 14 17:07:59 2006 From: gregory.petrosyan at gmail.com (Gregory Petrosyan) Date: 14 Jun 2006 14:07:59 -0700 Subject: nested functions Message-ID: <1150319279.865335.323530@u72g2000cwu.googlegroups.com> I often make helper functions nested, like this: def f(): def helper(): ... ... is it a good practice or not? What about performance of such constructs? -- Regards, Gregory. From kent at kentsjohnson.com Thu Jun 1 14:58:15 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Thu, 01 Jun 2006 14:58:15 -0400 Subject: Python for Visual Basic or C# programmers In-Reply-To: References: Message-ID: <447f37ce$1_1@newspeer2.tds.net> A.M wrote: > I am trying to find the equivalent functions such as vb's str or asc in > Python. Is there any resource that help me to find these kinds of functions > in Python faster? The Library Reference has a section on built-in functions: http://docs.python.org/lib/built-in-funcs.html Also take a look at the section on string methods: http://docs.python.org/lib/string-methods.html Kent From fredrik at pythonware.com Thu Jun 15 17:00:50 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 15 Jun 2006 23:00:50 +0200 Subject: Which compiler will Python 2.5 / Windows (Intel) be built with? In-Reply-To: References: <1150367139.495114.148550@g10g2000cwb.googlegroups.com> <44917535$1@nntp0.pdx.net> <1150391891.130185.4640@f6g2000cwb.googlegroups.com> <4491b9e1$1@nntp0.pdx.net> Message-ID: Jarek Zgoda wrote: > Sorry, gals and guys, but if you force us to buy something irrelevant > like VC2003, you will not get our sympathy. How should I explain my boss > that we need to buy one Pro license more, just to be able to build our > Python app? Please, don't left us with pants down. huh? 2.5 isn't released yet. if you *have* a Python app, you can continue to use the same compiler when you upgrade from 2.4 and 2.5. it's not like anyone is forcing you to uninstall the compiler just because you upgrade Python... From fabiofz at gmail.com Mon Jun 19 12:50:18 2006 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Mon, 19 Jun 2006 13:50:18 -0300 Subject: Pydev 1.2.0 Released Message-ID: Hi All, Pydev and Pydev Extensions 1.2.0 have been released Details on Pydev Extensions: http://www.fabioz.com/pydev Details on Pydev: http://pydev.sf.net Details on its development: http://pydev.blogspot.com Release Highlights in Pydev Extensions: ----------------------------------------------------------------- - This is the first version supporting Eclipse 3.2. - Interactive console: content is now changed so that blocks are closed with the interactive interpreter 'rules' (so that you don't have invalid syntax errors when passing code-blocks to the interactive console). - An action was added to the menu so that you can use the Open Declaration Quick-outline without needing focus on the pydev editor. Release Highlights in Pydev: ---------------------------------------------- - Eclipse 3.2 supported (and 3.1 support is now discontinued) - Lot's of optimizations to make pydev faster - Ctrl+Click now works with the find definition engine - Comments that start with #--- are shown in the outline - Attributes are shown in the outline - Parse errors are now shown (again) in the editor - Many other bugs fixed What is PyDev? --------------------------- PyDev is a plugin that enables users to use Eclipse for Python and Jython development -- making Eclipse a first class Python IDE -- It comes with many goodies such as code completion, syntax highlighting, syntax analysis, refactor, debug and many others. Cheers, -- Fabio Zadrozny ------------------------------------------------------ Software Developer ESSS - Engineering Simulation and Scientific Software http://www.esss.com.br Pydev Extensions http://www.fabioz.com/pydev Pydev - Python Development Enviroment for Eclipse http://pydev.sf.net http://pydev.blogspot.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Thu Jun 15 08:38:51 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 15 Jun 2006 14:38:51 +0200 Subject: distutils `requires' tag In-Reply-To: <1150366092.188588.57940@g10g2000cwb.googlegroups.com> References: <1150366092.188588.57940@g10g2000cwb.googlegroups.com> Message-ID: <4fd2mpF1hnhinU1@uni-berlin.de> jimburton schrieb: > Hi, I'm using python 2.3.5 and want to use distutils to distribute a > module that depends on another - is there any way to specify that? Use setuptools. It can do such a thing. Diez From tenente.navalhada at gmail.com Tue Jun 27 16:28:08 2006 From: tenente.navalhada at gmail.com (navalha) Date: 27 Jun 2006 13:28:08 -0700 Subject: Parallel Port and FreeBSD Message-ID: <1151440088.495444.239790@i40g2000cwc.googlegroups.com> I'm trying to run pyparallel to control de parallel port in python but i cant, because it doesnt find pyparallelioctl.py, and i cant find it anywhere in the internet does anyone have any ideas or another option to control de parallel port int freebsd? thanks From bayazee at gmail.com Wed Jun 28 18:19:21 2006 From: bayazee at gmail.com (Bayazee) Date: 28 Jun 2006 15:19:21 -0700 Subject: for and while loops In-Reply-To: <1151531527.496772.65130@i40g2000cwc.googlegroups.com> References: <1151531527.496772.65130@i40g2000cwc.googlegroups.com> Message-ID: <1151533161.267631.260520@p79g2000cwp.googlegroups.com> hi #Exercise 1 : s=0 while 1: s+=input("Enter a num : ") if s>=100: print "The sum is greater than 100 : ",s break #Exercise 2 : s=0 for i in range(5): s+=input("Enter num #%d > "%(i+1)) print "The Sum is : " , s From gherron at islandtraining.com Tue Jun 13 18:06:11 2006 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 13 Jun 2006 15:06:11 -0700 Subject: "groupby" is brilliant! In-Reply-To: <448F351A.7000201@lexicon.net> References: <1150180151.643245.148210@y43g2000cwc.googlegroups.com> <448F351A.7000201@lexicon.net> Message-ID: <448F36D3.1070003@islandtraining.com> John Machin wrote: > On 13/06/2006 6:28 PM, Paul McGuire wrote: > > >> (Oh, and I like groupby too! Combine it with sort to quickly create >> histograms.) >> >> # tally a histogram of a list of values from 1-10 >> dataValueRange = range(1,11) >> data = [random.choice(dataValueRange) for i in xrange(10000)] >> >> hist = [ (k,len(list(g))) for k,g in itertools.groupby(sorted(data)) ] >> > > That len(list(g)) looks like it uses O(N) memory just to find out what N > is :-( > Not at all! A python list *knows* its length at all times. len() is a constant time lookup of an internal attribute. Gary Herron > The best I could come up with is sum(itertools.imap(lambda x: 1, g)) -- > but that does look a bit ugly ... > > From tim.peters at gmail.com Mon Jun 26 16:27:51 2006 From: tim.peters at gmail.com (Tim Peters) Date: Mon, 26 Jun 2006 16:27:51 -0400 Subject: Questions on Threading In-Reply-To: <54adf1910606260725x4315c85fscdff24bb11a8ab77@mail.gmail.com> References: <54adf1910606260725x4315c85fscdff24bb11a8ab77@mail.gmail.com> Message-ID: <1f7befae0606261327s470e839i68daccc11d62e88e@mail.gmail.com> [j.c.sackett] > I'm using the threading module to accomplish some distributed processing on > a project, and have a basic (I hope) question that I can't find an answer to > elsewhere. > > I've noted that there's a lot of documentation saying that there is no > external way to stop a thread, True. > and yet when creating a thread through the threading module I can see > that it has a method called _Thread__stop, which does indeed stop it. You're misreading the code then. __stop() is used internally by a thread T to record when T itself knows it's _about_ to stop. Other threads may be blocked in T.join() calls, and the purpose of T calling T.__stop() is to notify such threads they can proceed. > Is this in any way dangerous ( i.e. doesn't actually stop the thread, That's right. > or causes other thread timing issues down the road?) If you call T.__stop(), T will keep running (exactly as if you hadn't called it), but threads waiting on T.join() will think T has stopped. > Or is there some other reason that there is officially no stop method? Python never offered it primarily for the same reasons Java regretted offering it (so much so that Java eventually deprecated it): http://java.sun.com/j2se/1.3/docs/guide/misc/threadPrimitiveDeprecation.html From vbgunz at gmail.com Sun Jun 11 02:13:31 2006 From: vbgunz at gmail.com (vbgunz) Date: 10 Jun 2006 23:13:31 -0700 Subject: learning python idioms References: <1149998884.261678.299860@u72g2000cwu.googlegroups.com> Message-ID: <1150006411.269862.117680@j55g2000cwa.googlegroups.com> > After several years developing in Java, I've begun to switch to Python > for several of my new projects as I have found the language quite > interesting. I've read several tutorials and implemented a few sample > programs and I've found that Python enables one to program in a variety > of different styles (I'm not sure if this was the original intention or > not). Thus, I find myself occaisionally slipping into the "Java" > mindset when writing Python code and I wonder if this is not optimal. > Python is not Java and there must be more "correct" ways of doing this > in Python that simply writing Java code with different syntax. Is > there a good reference on the internet about Python-specific idioms and > just good Python style in general. Which language constructs are > efficient and which aren't? I completely agree with this. I wish some people would gather and create a site dedicated to efficient Python idioms. This would be truly awesome! I hope you get good news on this! http://vbgunz.blogspot.com From alisonken1 at gmail.com Thu Jun 8 18:54:48 2006 From: alisonken1 at gmail.com (alisonken1) Date: 8 Jun 2006 15:54:48 -0700 Subject: ValueError: too many values to unpack In-Reply-To: <1149803076.552465.137150@j55g2000cwa.googlegroups.com> References: <1149803076.552465.137150@j55g2000cwa.googlegroups.com> Message-ID: <1149807288.129274.269000@i39g2000cwa.googlegroups.com> k.retheesh at gmail.com wrote: > 56 records were different > Type, FileType, > Item, > Hash, > > Path, Size, CullCd, Ext, DtCr, > DtLMd, DtLAc > Traceback (most recent call last): > File > "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", > line 310, in RunScript > exec codeObject in __main__.__dict__ > File "Q:\PythonScripts\InventoryCompareCase.py", line 234, in ? > main() > File "Q:\PythonScripts\InventoryCompareCase.py", line 117, in main > for (Type,FileType,Item,Hash,Path,Size,CullCd,Ext,DtCr,DtLMd,DtLAc) > in infoDiffs : > ValueError: too many values to unpack > > Thanks > Retheesh The "too many values to unpack" indicates you don't have enough variables in the [for (...) in infoDiffs: ] construct. You also may want to change some of the names; although "Type" (variable name) and "type" (python function) should be different, it's good practice to not use names that are similar to functions. From nospam at see.signature Wed Jun 14 18:35:49 2006 From: nospam at see.signature (Richard E Maine) Date: Wed, 14 Jun 2006 15:35:49 -0700 Subject: Earthquake and Tornado Forecasting Programs June 13, 2006 References: <448eef76$0$30713$ec3e2dad@news.usenetmonster.com> <448EFE0D.3B2D968B@yahoo.com> Message-ID: <1hgxhlv.11k6ev6ncp43jN%nospam@see.signature> edgrsprj wrote: > > Oh for a newsreader that can eliminate all such ugly excessively > > cross-posted articles lacking follow-ups. PLONK thread is the only > > remaining answer. > > > > Posted by E.D.G. June 14, 2006 > > In my opinion, even moderated Internet Newsgroups cannot provide the > necessary control for adequately protected scientific communications. I > have in mind the development of a sophisticated Web site based Internet > Bulletin Board which past experiences indicate to me should work. The Web > site running that bulletin board should be of interest to computer > programmers around the globe regardless of what programming language they > are using. Wow. That is an impressive display of.... ummm.... understanding. :-) Yes, I guess plonk thread will have to do. (My news server wouldn't even accept this as a followup until I trimmed a few of the groups.) -- Richard Maine | Good judgment comes from experience; email: my first.last at org.domain| experience comes from bad judgment. org: nasa, domain: gov | -- Mark Twain From UrsusMaximus at gmail.com Thu Jun 15 17:39:59 2006 From: UrsusMaximus at gmail.com (UrsusMaximus at gmail.com) Date: 15 Jun 2006 14:39:59 -0700 Subject: GUI in Python using wxGlade References: <1150380251.279150.73620@u72g2000cwu.googlegroups.com> <1150386216.365531.157690@g10g2000cwb.googlegroups.com> <1150403353.755218.292100@c74g2000cwc.googlegroups.com> Message-ID: <1150407599.899549.108310@y41g2000cwy.googlegroups.com> Ther is a short online tutorial on using wxGlade here wxGlade Tutorial From dpickles at pacbell.net Mon Jun 26 23:23:34 2006 From: dpickles at pacbell.net (dylpkls91) Date: 26 Jun 2006 20:23:34 -0700 Subject: Execute Commands on Remote Computers over Network Message-ID: <1151378614.481850.271340@c74g2000cwc.googlegroups.com> I have been researching this topic and come up with some code to make it work. It uses SSL and requires the 3rd party package Paramiko (which requires PyCrypto). However, at this moment I have no network to test the code on! Trying to connect to localhost (127.0.0.1) fails. Before I buy network components, I want to be sure that this code will work. Will someone with two networked computers try it out for me? Thanks! Code: def remotely_execute_command(ipaddr, port, user, passwd=None, cmd): import paramiko transport = paramiko.Transport(ipaddr + ":" + port) transport.connect(username=user, password=passwd) channel = transport.open_session() channel.exec_command(cmd) print "Command " + cmd + " executed by user " + user + " with password " + passwd + " at " + host + ":" + port From owong at castortech.com Mon Jun 26 10:29:53 2006 From: owong at castortech.com (Oliver Wong) Date: Mon, 26 Jun 2006 14:29:53 GMT Subject: languages with full unicode support References: <1151251736.590910.36050@u72g2000cwu.googlegroups.com> <1151276031.641318@elch.in-berlin.de> Message-ID: "Oliver Bandel" wrote in message news:1151276031.641318 at elch.in-berlin.de... > > Xah Lee wrote: > >> >> As far as i know, Java and JavaScript are languages with full, complete >> unicode support. That is, they allow names to be defined using unicode. > > Can you explain what you mena with the names here? As in variable names, function names, class names, etc. - Oliver From fredrik at pythonware.com Fri Jun 30 11:10:42 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 30 Jun 2006 17:10:42 +0200 Subject: Way for see if dict has a key In-Reply-To: References: <6V6pg.21624$_J1.271925@twister2.libero.it> <44a5041f$0$29637$636a55ce@news.free.fr> <4F7pg.21676$_J1.272665@twister2.libero.it> <1151666867.604260.116320@h44g2000cwa.googlegroups.com> Message-ID: Paul McGuire wrote: > Another factor to consider is if "default" is not something simple like 0 or > None, but is an object constructed and initialized with some expensive > initialization code (like access to a database). In this case: > > dict.get(key, ExpensiveObjectToCreate()) > > always creates the default value, and if the key does not exist, then > promptly drops it on the floor. > > In such a case you'd be better off with one of the "check for existence" > patterns, which only creates the default value if you *know* you're going to > need it. unless you're targeting 2.5 or later, in which case you can use the defaultdict class: >>> import collections >>> def ExpensiveObjectToCreate(): ... print "creating an expensive object" ... return "expensive object" ... >>> d = collections.defaultdict(ExpensiveObjectToCreate) >>> d["key"] creating an expensive object 'expensive object' >>> d["key"] 'expensive object' or, if you prefer, the new __missing__ hook: >>> class mydict(dict): ... def __missing__(self, key): ... print "add new object base on", key ... value = "new object" ... self[key] = value ... return value ... >>> d = mydict() >>> d["key"] add new object base on key 'new object' >>> d["key"] 'new object' From wahab at chemie.uni-halle.de Sun Jun 25 08:17:33 2006 From: wahab at chemie.uni-halle.de (Mirco Wahab) Date: Sun, 25 Jun 2006 14:17:33 +0200 Subject: Python taught in schools? In-Reply-To: References: <1151220913.406987.162420@u72g2000cwu.googlegroups.com> Message-ID: Thus spoke Cameron Laird (on 2006-06-25 13:08): > I'll gratuitously add that, even though I'm personally fond of > C++, I think teaching it as is done in colleges and high schools > (!) amounts to child abuse. It's wildly inappropriate. C++ programming requires you to massively invest your thinking first into the setup of your build environment (can only be beaten by Java here). This is where the real abuse starts. Plain C++-baby-style (with some structs and cin/cout) is just fun, despite the required 'variable prototyping' (which is not that bad for a beginner). Regards Mirco From mslists at 256bit.org Sun Jun 4 02:26:17 2006 From: mslists at 256bit.org (Marc Schoechlin) Date: 4 Jun 2006 06:26:17 GMT Subject: Hostmask matching References: Message-ID: Hi ! Nexu schrieb: > I'm trying to write a def to match a string that is an irc hostmask. eg: > *one!~*name at a??-??-101-101.someisp.com > But using re.search(). I get an error when the string starts with '*'. > What is the best way to solve this? I suppose the problem occurs because you expression is not a valid regular expression. A correct regular expression should look like this: ".*one!~.*name at a..-..-101-101.someisp.com" Best regards Marc Schoechlin -- I prefer non-proprietary document-exchange. http://sector7g.wurzel6.de/pdfcreator/ http://www.prooo-box.org/ Contact me via jabber: ms at 256bit.org From scott.daniels at acm.org Wed Jun 14 11:58:28 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Wed, 14 Jun 2006 08:58:28 -0700 Subject: Bundling an application with third-party modules In-Reply-To: <1150285229.237626.36440@y41g2000cwy.googlegroups.com> References: <1150285229.237626.36440@y41g2000cwy.googlegroups.com> Message-ID: <44902d60$1@nntp0.pdx.net> utabintarbo wrote: > A couple of alternatives: > 1. py2exe/csFreeze-type thing. This would even relieve the customer of > installing python > 2. An Installshield-type installer can place files (essentially) > wherever you want them > > HTH > Also, remember to credit those third-party packages; they likely aren't getting money for their contribution. --Scott David Daniels scott.daniels at acm.org From aum at spam.me.please Mon Jun 19 18:46:19 2006 From: aum at spam.me.please (aum) Date: Tue, 20 Jun 2006 10:46:19 +1200 Subject: ANN: pyfcp (URL correction) References: Message-ID: On Mon, 19 Jun 2006 16:24:41 +1200, aum wrote: > http://www.python.org/pyfcp Sorry, that should have been: http://www.freenet.org.nz/pyfcp -- Cheers aum From jzgoda at o2.usun.pl Fri Jun 2 17:32:57 2006 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Fri, 02 Jun 2006 23:32:57 +0200 Subject: New to Python: Do we have the concept of Hash in Python? In-Reply-To: References: Message-ID: Fredrik Lundh napisa?(a): >>I am new to Python, with C#/Java background > > that's not really much of an excuse for not reading *any* Python tutorial before > you jump in... That's a great idea, anytime I had a problem with Java I would write c.l.j with heading "I am new to Java, but have solid background in Python, REXX and CL" and then I'll ask "do you have an implementation for tuple in Java?" or "how do I change an object generation routine for class?". At least, the are profis, they should know that. -- Jarek Zgoda http://jpa.berlios.de/ From steven.bethard at gmail.com Mon Jun 5 01:24:49 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 04 Jun 2006 23:24:49 -0600 Subject: Max function question: How do I return the index of the maximum value of a list? In-Reply-To: References: <1149459320.802652.186930@i40g2000cwc.googlegroups.com> <38adnTLbg47fFh7ZnZ2dnUVZ_qednZ2d@comcast.com> Message-ID: <1d2dnWAQWYiDXR7ZnZ2dnUVZ_oOdnZ2d@comcast.com> Robert Kern wrote: > Steven Bethard wrote: >> Can you do something like:: >> >> max_val, max_index = max((x, i) for i, x in enumerate(my_list)) >> >> ? If any two "x" values are equal, this will return the one with the >> lower index. Don't know if that matters to you. > > Wouldn't it return the one with the highest index? Yes sorry. Mentally switched my min and max calls. Thanks for the catch. Steve From fredrik at pythonware.com Sun Jun 11 15:10:02 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 11 Jun 2006 21:10:02 +0200 Subject: direct initialization of class attributes vs. declarations w/in __init__ In-Reply-To: <1150047314.025241.260750@c74g2000cwc.googlegroups.com> References: <1150041510.139609.171120@f6g2000cwb.googlegroups.com> <4f2thrF1fd4r4U1@uni-berlin.de> <1150043792.136250.99770@u72g2000cwu.googlegroups.com> <1150047314.025241.260750@c74g2000cwc.googlegroups.com> Message-ID: digitalorganics at gmail.com wrote: > At first, I thought that self.jerk was resolving to the class attribute > instead of creating a new variable (w/ a differing scope). When you access an instance attribute, Python first looks in the instance object, and then in the class object. When you assign to an instance attribute, it's *always* assigned to the instance object, whether there's a class attribute with the same name or not. If there's already a class attribute with the same name, that attribute will be shadowed (but can still be accessed via the class object, of course). > It doesn't work this way on my laptop... Python's always worked that way, so I find that a bit hard to believe. From __peter__ at web.de Fri Jun 2 07:50:46 2006 From: __peter__ at web.de (Peter Otten) Date: Fri, 02 Jun 2006 13:50:46 +0200 Subject: shuffling elements of a list References: <1149045499.212967.13120@f6g2000cwb.googlegroups.com> <1149051212.139046.155340@c74g2000cwc.googlegroups.com> <1149247855.487864.124540@i39g2000cwa.googlegroups.com> Message-ID: Iain King wrote: > or shorter but possible less readable (and only in 2.4+): > > def shuffle(data): > return [y[1] for y in sorted([(random(), x) for x in data])] sorted() and list.sort() will happily accept a key function argument and then do the decorating/undecorating for you: >>> from random import random >>> def key(item): return random() ... >>> def shuffled(items): ... return sorted(items, key=key) ... >>> shuffled(range(10)) [6, 5, 3, 4, 8, 9, 0, 7, 1, 2] > or in nicer python, but still when you're mysitified by map and lambda > (like me): Turning the key() function into a lambda is left as an exercise :-) Peter From wahab at chemie.uni-halle.de Thu Jun 22 17:48:09 2006 From: wahab at chemie.uni-halle.de (Mirco Wahab) Date: Thu, 22 Jun 2006 23:48:09 +0200 Subject: map() return of flat tuple list Message-ID: Hi, I have a 2D array, maybe irregular, like arr = [[2,2,2,2], [2,2,2,2], [2,2,2,2]] if tried to pull an index list (tuples or array elements) of all positions - via the map funtion, but failed. I tried to get sth. like [ [0,0], [0,1], [0,2], ... ] for each element which really exists in the 2D array above. What I really got, was another in- direction for each row of arr [ [(0, 0), (0, 1), (0, 2), (0, 3)], [(1, 0), (1, 1), (1, 2), (1, 3)], ... ] How can I flatten the list in place by map(), so that the outer map hull would collect [i,j] flat? This is what I tried: id = map(lambda i: map(lambda j: (i,j), range(len(arr[i]))), range(len(arr))) print id I tried the map solution because I'd make a shot at another posting (find min of 2D array), what I intended to solve by decorate/undecorate sort. But I didn't manage to create the flat coordinate list in one map(map)-stroke ;-) Regards Mirco From jstroud at ucla.edu Thu Jun 15 19:19:07 2006 From: jstroud at ucla.edu (James Stroud) Date: Thu, 15 Jun 2006 16:19:07 -0700 Subject: Looking for examples related to advanced python string, list and map operations In-Reply-To: References: Message-ID: A.M wrote: > Hi, > > > > Is there any online resource that gives examples about advanced python > string, list and map operations? > > > > Today I saw this and I found that I have to work more on mentioned topics: > > > > numbers = [72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33] > > print filter(lambda n: n % 2 == 0, numbers) > > > > numbers = [72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33] > > print reduce(lambda x, y: x+y, numbers) > > > > Thank you, > > Alan > > First Chapter of Text Processing in Python by David Mertz. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From chris.uppal at metagnostic.REMOVE-THIS.org Fri Jun 23 17:23:33 2006 From: chris.uppal at metagnostic.REMOVE-THIS.org (Chris Uppal) Date: Fri, 23 Jun 2006 22:23:33 +0100 Subject: Saying "latently-typed language" is making a category mistake References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> Message-ID: <449c5b85$0$656$bed64819@news.gradwell.net> Chris Smith wrote: > Perhaps, if you wanted to be quite careful about your distinctions, you > may want to choose different words for the two. However, then you run > into that same pesky "you can't choose other people's terminology" block > again. There may be more flexibility in this area than you'd think. I get the impression that (after only a few years hard work) the terms "weak typing" and "strong typing", used as synonyms for what we are here calling "dynamic typing" and "static typing", are starting to die out. So be of good hope ! I may yet be persuaded to talk of "static type checks" vs "dynamc checks" (with a slight, veilled, sneer on the word "type" -- oh, so very limiting ;-) > I'd be more careful in the analogy, there. Since type theory (as > applied to programming languages, anyway) is really just a set of > methods of proving arbitrary statements about program behaviors, Not "arbitrary" -- there is only a specific class of statements that any given type system can address. And, even if a given statement can be proved, then it might not be something that most people would want to call a statement of type (e.g. x > y). It seems to me that most (all ? by definition ??) kinds of reasoning where we want to invoke the word "type" tend to have a form where we reduce values (and other things we want to reason about) to equivalence classes[*] w.r.t the judgements we wish to make, and (usually) enrich that structure with more-or-less stereotypical rules about which classes are substitutable for which other ones. So that once we know what "type" something is, we can short-circuit a load of reasoning based on the language semantics, by translating into type-land where we already have a much simpler calculus to guide us to the same answer. (Or representative symbols, or... The point is just that we throw away the details which don't affect the judgements.) > a > corresponding "informal type theory" would just be the entire set of > informal reasoning by programmers about their programs. I think that, just as for static theorem proving, there is informal reasoning that fits the "type" label, and informal reasoning that doesn't. I would say that if informal reasoning (or explanations) takes a form more-or-less like "X can [not] do Y because it is [not] a Z", then that's taking advantage of exactly the short-cuts mentioned above, and I would want to call that informal type-based reasoning. But I certainly wouldn't call most of the reasoning I do type-based. -- chris From rossberg at ps.uni-sb.de Wed Jun 21 08:51:05 2006 From: rossberg at ps.uni-sb.de (Andreas Rossberg) Date: Wed, 21 Jun 2006 14:51:05 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: <44992e6c$0$664$bed64819@news.gradwell.net> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <0%Wlg.3521$MF6.947@tornado.socal.rr.com> <44992e6c$0$664$bed64819@news.gradwell.net> Message-ID: Chris Uppal wrote: > > I have never been very happy with relating type to sets of values (objects, > whatever). Indeed, this view is much too narrow. In particular, it cannot explain abstract types, which is *the* central aspect of decent type systems. There were papers observing this as early as 1970. A type system should rather be seen as a logic, stating invariants about a program. This can include operations supported by values of certain types, as well as more advanced properties, e.g. whether something can cause a side-effect, can diverge, can have a deadlock, etc. (There are also theoretic problems with the types-as-sets view, because sufficiently rich type systems can no longer be given direct models in standard set theory. For example, first-class polymorphism would run afoul the axiom of foundation.) > It's worth noting, too, that (in some sense) the type of an object can change > over time[*]. No. Since a type expresses invariants, this is precisely what may *not* happen. If certain properties of an object may change then the type of the object has to reflect that possibility. Otherwise you cannot legitimately call it a type. Taking your example of an uninitialised reference, its type is neither "reference to nil" nor "reference to object that understands message X", it is in fact the union of both (at least). And indeed, languages with slightly more advanced type systems make things like this very explicit (in ML for example you have the option type for that purpose). - Andreas From bdesth.quelquechose at free.quelquepart.fr Tue Jun 27 00:21:56 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 27 Jun 2006 06:21:56 +0200 Subject: replace a method in class: how? In-Reply-To: References: <44A06A6B.6010200@bryant.edu> Message-ID: <44a08221$0$19040$636a55ce@news.free.fr> Maric Michaud a ?crit : (snip) > In OOP Methods are defined in *classes* not in any arbitrary object Chapter and verse, please ? AFAIK, the first O in OOP stands for "object", not for "class" !-) Classes are just an implementation convenience, and the fact that the class-based model is the most usual one doesn't imply it's the only valid one. So there's no reason one shouldn't override (or add) a method on a per-object basis. As a matter of fact, it's perfectly legal (and can be very convenient) to do so in Python. From duncan.booth at invalid.invalid Thu Jun 8 09:26:00 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 8 Jun 2006 13:26:00 GMT Subject: Extended zip() for lists References: Message-ID: Florian Reiser wrote: > Hello, > > I have 4 lists: a, b, c and d > Out of this 4 lists I want to build a table (e.g. list of lists): > > a|b|c|d > --------------------------- > a1|b1|c1|d1 > a1|b2| |d2 > > You see: the lists are not equally sized. > Is there a command which fills up the shorter lists with blanks? > Like an enhanced zip() command, maybe? > > Regards > Florian Reiser > I posted a function to do this back in January. See: http://groups.google.co.uk/group/comp.lang.python/browse_frm/thread/f424f63bfdb77c4/88d1541e632adfdd?lnk=st&rnum=1#88d1541e632adfdd From bayerj at in.tum.de Sun Jun 11 04:56:12 2006 From: bayerj at in.tum.de (bayerj) Date: 11 Jun 2006 01:56:12 -0700 Subject: learning python idioms In-Reply-To: <1150006411.269862.117680@j55g2000cwa.googlegroups.com> References: <1149998884.261678.299860@u72g2000cwu.googlegroups.com> <1150006411.269862.117680@j55g2000cwa.googlegroups.com> Message-ID: <1150016172.064188.264790@m38g2000cwc.googlegroups.com> Hi, If you switched from java to python the best point to start is http://dirtsimple.org/2004/12/python-is-not-java.html. Greets, -Justin From SeaFuncSpam at gmail.com Sat Jun 10 23:59:03 2006 From: SeaFuncSpam at gmail.com (Mallor) Date: 10 Jun 2006 20:59:03 -0700 Subject: Xah Lee network abuse In-Reply-To: <1148495974.975395.12920@i40g2000cwc.googlegroups.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148495974.975395.12920@i40g2000cwc.googlegroups.com> Message-ID: <1149998343.493200.144990@h76g2000cwa.googlegroups.com> PofN wrote: > > Liar. You were never sorry when you troubled us with your posting > excrements in the past, you are not sorry now. > > Liar. You are a net abuser, a kook and a troll. It has nothing to do > with your writings and style. It has everything to do with your > vialoation of netiquette, with you x-posting of off-topic messages, > with your trolling and kookery. > > Liear. John asked people do do their duty as net citizens and to report > a serial net abuser. > > Liar. Your whole usenet "career" is build around the posting of > off-topic messages. > > Liar. You were getting out of hand for some time now. > > People know very well about you, Xah Lee, the serial newsgroup abuser, > troll, liar, and kook. > > More lies. > > I appreciate the courage of John and friends to stand up against > someone who is out of control. You are not even affraid off accusing > John of a crime (harrasment) and starting a smear campaing on your web > site. You have sunken so low that you are fast approaching the earth's > metal core. I know I'm coming late to the barbeque. In passing, I ask: do you have an objective, impartial perspective on the subject of committing crimes? Because libel is a crime. It all depends on whether what you state about Xah is provably true or not. I haven't followed his posts, but when I hear someone chanting "abuser, troll, liar, kook!" I really wonder about the accuser. Anyways, I suppose it's all "sport" until one of you gets the lawyers involved. Cheers, Brandon Van Every From robert.thorpe at antenova.com Tue Jun 20 09:11:58 2006 From: robert.thorpe at antenova.com (Rob Thorpe) Date: 20 Jun 2006 06:11:58 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> Message-ID: <1150809118.677124.142230@u72g2000cwu.googlegroups.com> Andreas Rossberg wrote: > Rob Thorpe wrote: > > > > No, that isn't what I said. What I said was: > > "A language is latently typed if a value has a property - called it's > > type - attached to it, and given it's type it can only represent values > > defined by a certain class." > > "it [= a value] [...] can [...] represent values"? ??? > > Easy, any statically typed language is not latently typed. Values have > > no type associated with them, instead variables have types. > > A (static) type system assigns types to (all) *expressions*. That's right most of the time yes, I probably should have said expressions. Though I can think of static typed languages where the resulting type of an expression depends on the type of the variable it is being assigned to. > This includes values as well as variables. Well I haven't programmed in any statically typed language where values have types themselves. Normally the language only knows that variable Z is of type Q because it's in a variable of type Q, or as you mention an expression of type Q. There are many things that could be considered more than one type. The integer 45 could be unsigned 45 or signed 45 or even float 45 depending on the variable it's in, but without context it doesn't have a precise type. It does imply the type to some extent though, you could imagine a language where every value has a precise type. So, you've found a hole in my definition. Maybe a better definition would be:- if (variables have types || expressions have types) else if (values have types) else That seems to fit usage, quite well. Even then there are problems. Perl has static types for arrays, hashs and scalars. But scalars themselves can be integers, strings, etc. > Don't confuse type assignment with type annotation (which many > mainstream languages enforce for, but also only allow for, variable > declarations). Point taken. From tchur at optushome.com.au Fri Jun 2 17:59:18 2006 From: tchur at optushome.com.au (Tim Churches) Date: Sat, 03 Jun 2006 07:59:18 +1000 Subject: Open Source Charting Tool In-Reply-To: References: <1L0gg.1841$Su3.159041@news20.bellglobal.com> Message-ID: <4480B4B6.4050905@optushome.com.au> A.M wrote: > I can't browse to www.reporlab.org, but I found http://www.reportlab.com/ > which has a commercial charting product. Is that what you referring to? Typo in the URL. Try http://www.reportlab.org You should also have a look at http://matplotlib.sourceforge.net/ Tim C From max at alcyone.com Sun Jun 4 18:42:51 2006 From: max at alcyone.com (Erik Max Francis) Date: Sun, 04 Jun 2006 15:42:51 -0700 Subject: Where is the ucs-32 codec? In-Reply-To: <1149459785.331497.203920@c74g2000cwc.googlegroups.com> References: <1149459785.331497.203920@c74g2000cwc.googlegroups.com> Message-ID: beni.cherniavsky at gmail.com wrote: > Python seems to be missing a UCS-32 codec, even in wide builds (not > that it the build should matter). > Is there some deep reason or should I just contribute a patch? > > If it's just a bug, should I call the codec 'ucs-32' or 'utf-32'? Or > both (aliased)? > There should be '-le' and '-be' variats, I suppose. Should there be a > variant without explicit endianity, using a BOM to decide (like > 'utf-16')? > And it should combine surrogates into valid characters (on all builds), > like the 'utf-8' codec does, right? Note that UTF-32 is UCS-4. UCS-32 ("Universial Character Set in 32 octets") wouldn't make much sense. Not that Python has a UCS-4 encoding available either. I'm really not sure why. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Could it be / That we need loving to survive -- Neneh Cherry From grahn+nntp at snipabacken.dyndns.org Thu Jun 29 03:27:00 2006 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 29 Jun 2006 07:27:00 GMT Subject: Linux info References: <448ec675_1@news.tm.net.my> Message-ID: On Tue, 13 Jun 2006 22:06:42 +0800, TheSaint wrote: > Hello there, > > I still learning, but I couldn't find anything which tells me where a > symlink is pointing to. os.readlink() os.lstat() And they are /not/ Linux-specific; expect them to work on most or all Unix-like OSes. > A part of os.system('ls -l ' + path) and cutting down to the need, I haven't > got any specialized function. Both functions mentioned above are documented as part of module os, section "Files and Directories". /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From kirklin.mcdonald at gmail.com Thu Jun 15 19:51:07 2006 From: kirklin.mcdonald at gmail.com (Kirk McDonald) Date: Thu, 15 Jun 2006 16:51:07 -0700 Subject: API functions not working as expected Message-ID: <4491edc3$1@nntp0.pdx.net> ... for reasons that are obvious in retrospect. Specifically, I am talking about the PyNumber_InPlace* family of functions. For example, the docs for InPlaceAdd say: PyObject* PyNumber_InPlaceAdd(PyObject *o1, PyObject *o2) Return value: New reference. Returns the result of adding o1 and o2, or NULL on failure. The operation is done in-place when o1 supports it. This is the equivalent of the Python statement "o1 += o2". But, of course, numbers are immutable. None of them support in-place addition. This is not the same as o1 += o2, as o1 is not actually changed when using this function. Am I missing something here? Is there, in fact, no point to these InPlace* functions? -Kirk McDonald From justin.mailinglists at gmail.com Mon Jun 5 21:47:12 2006 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: 5 Jun 2006 18:47:12 -0700 Subject: Get EXE (made with py2exe) path directory name References: <1149557188.392915.287220@i39g2000cwa.googlegroups.com> Message-ID: <1149558432.944605.249050@y43g2000cwc.googlegroups.com> try, if hasattr(sys, 'frozen'): me = sys.executable else: me = sys.argv[0] From mhellwig at xs4all.nl Thu Jun 8 10:28:22 2006 From: mhellwig at xs4all.nl (Martin P. Hellwig) Date: Thu, 08 Jun 2006 16:28:22 +0200 Subject: Is there a python wrapper for OpenPAM? Message-ID: <4488340a$0$31646$e4fe514c@news.xs4all.nl> Hi all, I'm busy with a personal project that does password synchronization between NT and BSD. By using a password hook/filter/notifier when password is changed (on NT PasswdHk and on BSD a modified version of pam_exec*) I can retrieve a changed password, however when I want to check the validation of the password or change it, I run into my limitations. On NT I can use the win32 extension to check and change the password. On BSD this is a bit of a problem, the PyPAM (a Linux package) is not compatible to OpenPAM (as used for example used in FreeBSD). At this moment I change the password by calling the passwd program and check the password by using my imaps service but I rather like to do it by accessing the pam libs itself. I checked out the dl function and I understand the syntax but I have no clue how I could implement a password change or check module with it (due to my limited knowledge of OpenPAM and the C programming language). Is there perhaps somebody who already created a wrapping for OpenPAM or has some pointers for me how I should proceed on this matter? On a side note, wouldn't it be a great module for python to have a platform independent authentication module that wraps these types of operations (password fetching, checking and changing) of the local system? -- mph * Yes I am well aware of the huge security risks on that matter ;-) From nuffnough at gmail.com Mon Jun 12 13:15:35 2006 From: nuffnough at gmail.com (nuffnough at gmail.com) Date: 12 Jun 2006 10:15:35 -0700 Subject: [newbie]apache authentication questions Message-ID: <1150132535.766644.99870@g10g2000cwb.googlegroups.com> I have an apache 1.3.29 server that is running my website. I have written a bunch of scripts to generate the pages from csv files which work great. My next thing to learn is how to get user authentication functioning the way I need it. I understand the steps required to make .htpaccess files work, but this won't be enough for my purposes. I want the site to remember that a visitor has logged in or not, and also to read a bunch of personal info from a csv file dedicated to the userbase. (A later project will be to convert my csv files into databases, but I am into baby steps at the moment, so just focussing on python webiste authentication) Ideally I would like this authentication to not be in the form of a popup, but rather via a username/password pair of fields at some place on the page. After authentication, this should be reaplced by some generic "have a nice day" kinda message, or perhaps simply removed altogether. Additionally, they will be able to alter their personal information and doing stuff like filling in the feedback form should mean that they don't have to enter any personal info, just fill in the details and click the send buttopn. My experience with .htaccess files is that they make an authentication popup, which is not what I am aiming at. How can I incorporate this sort of user info in the apache authentication stuff using python? TIA! Nuffnnough. From micklee74 at hotmail.com Wed Jun 28 02:06:08 2006 From: micklee74 at hotmail.com (micklee74 at hotmail.com) Date: 27 Jun 2006 23:06:08 -0700 Subject: a class variable question Message-ID: <1151474768.546012.254380@p79g2000cwp.googlegroups.com> hi i have define a class like this class A: _var1 = 0 def __init__(self): ## some initialization self.func1() def func1(): ..... _var1 = 1 .... def getvarValue(self): return _var1 I wanted var1 to be "global" inside Class A. when i do AnInstance = A() AnInstance.getvarValue() it gives me 0. It should be 1. What am i doing wrong here..thanks From fredrik at pythonware.com Wed Jun 7 17:27:52 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 07 Jun 2006 23:27:52 +0200 Subject: Regular Expression question In-Reply-To: <1149714949.542234.148800@y43g2000cwc.googlegroups.com> References: <1149714949.542234.148800@y43g2000cwc.googlegroups.com> Message-ID: ken.carlino at gmail.com wrote: > I am new to python regular expression, I would like to use it to get an > attribute of an html element from an html file? if you want to parse HTML, use an HTML parser. if you want to parse sloppy HTML, use a tolerant HTML parser: http://www.crummy.com/software/BeautifulSoup/ From onurb at xiludom.gro Thu Jun 15 08:14:13 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 15 Jun 2006 14:14:13 +0200 Subject: how you get Python files on websites? In-Reply-To: <1150373046.038502.307850@i40g2000cwc.googlegroups.com> References: <1150373046.038502.307850@i40g2000cwc.googlegroups.com> Message-ID: <44914f16$0$22866$626a54ce@news.free.fr> azadi232 at gmail.com wrote: (snip) > i have a few questions about Python > > 1. Can Python work with databases like MySql,Oracle? (i think it sounds > silly) http://www.google.com/search?q=%2Bpython+%2Bdb > 2.the Python files have .py extension and i used Windows Command > Prompt(DOS) to execute the file,how can i use the programs written in > Python on the web? (for large-scale search engines) http://www.google.com/search?q=%2Bpython+%2Bweb In both cases, the second entry should be a good starting point and answer most of these 2 questions. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From bblais at bryant.edu Wed Jun 28 07:02:39 2006 From: bblais at bryant.edu (Brian Blais) Date: Wed, 28 Jun 2006 07:02:39 -0400 Subject: [Pyrex] pyrex functions to replace a method (Re: replace a method in class: how?) In-Reply-To: <44A1C5C7.4090007@canterbury.ac.nz> References: <44A06A6B.6010200@bryant.edu> <44A11564.9030009@bryant.edu> <44A1C5C7.4090007@canterbury.ac.nz> Message-ID: <44A261CF.4000309@bryant.edu> Greg Ewing wrote: > Brian Blais wrote: >> I have found a very similar problem trying to replace a method using a >> function defined in pyrex. > > > What *should* work is to define the method inside a > class in Pyrex (plain class, not extension type) and > extract it out of the class's __dict__. That's because > Pyrex pre-wraps a function defined in a class in an > unbound method object before putting it in the class. > So I tried: #--------------------------------------------------------------------------------- #module_pyrex.pyx class update_funcs: def pyrex_update_within_class(self,val): print "pyrex module within class",val #--------------------------------------------------------------------------------- #(adding to test_replace_method.py) This.update4=module_pyrex.update_funcs.__dict__['pyrex_update_within_class'] t.update4('pyrex within class') # doesn't work #--------------------------------------------------------------------------------- and get: TypeError: unbound method pyrex_update_within_class() must be called with update_funcs instance as first argument (got str instance instead) did I do this wrong? thanks, bb -- ----------------- bblais at bryant.edu http://web.bryant.edu/~bblais From aleax at mac.com Sat Jun 3 20:03:00 2006 From: aleax at mac.com (Alex Martelli) Date: Sat, 3 Jun 2006 17:03:00 -0700 Subject: An oddity in list comparison and element assignment References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> <1hg9nl6.xivwcd7n0j5N%aleax@mac.com> <1149277242.199765.213600@g10g2000cwb.googlegroups.com> <1hgbjx1.1gn7haipx7x5N%aleax@mac.com> Message-ID: <1hgd7ry.1lrs9rqnn77ayN%aleax@mac.com> Terry Reedy wrote: > > it's EXACTLY the > > concatenation of three copies of that string -- no more, no less. > > Depends what one means by 'copy'. See below for your alternate wording. Please give me a reasonable definition of the unadorned word "copy" which would make this statement false. (And, just to forestall one possible attempt: no, I cannot agree that a ``deepcopy'' is a reasonable definition of the _unadorned_ word "copy"). > >> Or one could say that the result *is the same as* (not *is*) the > > > > I find this distinction, in this context, to be empty padding, with zero > > added value on ANY plane -- including the plane of "pedantry";-). > > Perhaps you should tone down the overwrought emotionalism and take a look > in a mirror. In *your* response to Michael you made the *same* > distinction: I did not *DRAW* any distinction (as you did with your parenthetical note "(not *is*)", emphasis and all) -- rather, I used one of many reasonably interchangeable ways to word a concept. ((In the Nutshell, I always deliberately try to pick the shortest and most concise way; in my more spontaneous writing, I strongly tend to wilder exhuberance). So, having deeply delved into the mirror, I still fail to find any validity in your criticism: the phrases "S*n is the same as the concatenation of" and "S*n the concatenation of", taken as definitions of what S*n means, are such that your emphatic distinction has no added value whatsoever -- I stand by this assertion and fail to see in it any emotionalism, overwrought or otherwise. Care to _defend_ your criticism, with some _objective_ explanation of why that parenthetical was warranted (particularly the emphasis within it)? Or would you rather continue the personal attacks against me and the unproven accusations of "overwrought emotionalism" in particular? Alex From cfc at shell01.TheWorld.com Thu Jun 22 15:12:56 2006 From: cfc at shell01.TheWorld.com (Chris F Clark) Date: 22 Jun 2006 15:12:56 -0400 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150902275.129780.50260@p79g2000cwp.googlegroups.com> <1150918629.818145.143220@y41g2000cwy.googlegroups.com> <4fv081F1jh4ifU1@individual.net> <1150967543.947096.72840@g10g2000cwb.googlegroups.com> <4fv84rF1kp06kU1@individual.net> <1150988625.527780.148710@c74g2000cwc.googlegroups.com> <1150995359.404878.316920@m73g2000cwd.googlegroups.com> Message-ID: Pascal Costanza wrote: > Consider a simple expression like 'a + b': In a dynamically typed > language, all I need to have in mind is that the program will attempt to > add two numbers. In a statically typed language, I additionally need to > know that there must a guarantee that a and b will always hold numbers. "Marshall" replied: > I would not expect that the dynamic programmer will be > thinking that this code will have two numbers most of the > time but sometimes not, and fail. I would expect that in both > static and dynamic, the thought is that that code is adding > two numbers, with the difference being the static context > gives one a proof that this is so. I don't think the the problem is down at the atom level. It's really at the structure (tuple) level. If we view 'a + b' as applying the function + to some non-atomic objects a and b. The question is how well do we specify what a and b are. From my limited exposure to programs that use dynamic typing, I would surmise that developers who use dynamic typing have very broad and open definitions of the "types" of a and b, and they don't want the type system complaining that they have nailed the definitions down quite yet. And, if you read some of the arguments in this topic, one assumes that they want to even be able to correct the "types" of a and b at run-time, when they find out that they have made a mistake without taking the system down. So, for a concrete example, let b be a "file" type (either text file or directory) and we get a whole system up and running with those two types. But, we discover a need for "symbolic links". So, we want to change the file type to have 3 sub-types. In a dynamic type system, because the file "type" is loose (it's operationally defined by what function one applies to b), this isn't an issue. As each function is recoded to deal with the 3rd sub-type, the program becomes more functional. If we need to demo the program before we have worked out how symbolic links work for some operation, it is not a problem. Run the application, but don't exercise that combination of type and operation. In many ways, this can also be done in languages with type inference. I don't understand the process by which one does it, so I can't explain it. Perhaps someone else will--please.... Back to the example, the file type is not an atomic type, but generally some structure/tuple/list/record/class with members or fields. A function which renames files by looking at only the name field may work perfectly adequately with the new symbolic link subtype without change because the new subtype has the same name field and uses it the same way. A spell-check function which works on text files using the "contents" field might need to be recoded for symbolic links if the contents field for that subtype is "different" (e.g. the name of the target). The naive spell check function might appear to work, but really do the wrong thing, (i.e. checking if the target file name is made of legal words). Thus, the type problems are not at the atomic level (where contents is a string), but at the structure level, where one needs to know which fields have which meanings for which subtypes. -Chris From mumia.w.18.spam+nospam.usenet at earthlink.net Sun Jun 25 15:27:35 2006 From: mumia.w.18.spam+nospam.usenet at earthlink.net (Mumia W.) Date: Sun, 25 Jun 2006 19:27:35 GMT Subject: languages with full unicode support In-Reply-To: <1151251736.590910.36050@u72g2000cwu.googlegroups.com> References: <1151251736.590910.36050@u72g2000cwu.googlegroups.com> Message-ID: Xah Lee wrote: > Languages with Full Unicode Support > > As far as i know, Java and JavaScript are languages with full, complete > unicode support. That is, they allow names to be defined using unicode. > (the JavaScript engine used by FireFox support this) > > As far as i know, here's few other lang's status: > > C ? No. > Python ? No. > Perl ? No. Perl supports unicode in its core, and that include identifier names using exotic characters. > Haskell ? Yes by the spec, but no on existing compilers. Erm, isn't this an effective "No"? > JavaScript ? No in general. Firefox's engine do support it. > Lisps ? No. > unix shells (bash) ? No. (this probably applies to all unix shells) > Java ? Yes and probably beats all. However, there may be a bug in 1.5 > compiler. > > Also, there appears to be a bug with Java 1.5's unicode support. The > following code compiles fine in 1.4, but under 1.5 the compiler > complains about the name x1.str?. > > class ? { > String str? = > "?????,??????\n?????,??????\n?????????\n??????"; > String str?="?????????? ????????? > ?????? ??????? ???? ?? ??? > ??????? ??"; > > } > > class UnicodeTest { > public static void main(String[] arg) { > ? x1 = new ?(); > System.out.println( x1.str? ); > System.out.println( x1.str? ); > } > } > > If you know a lang that does full unicode support, please let me know. > Thanks. > > Xah > xah at xahlee.org > ? http://xahlee.org/ Perl is coming close to having full unicode support. '?' is not an alphabetic or numeric character and has no place in an identifier. That is why both Perl and Java reject it. Let's see what Perl can do: #!/usr/bin/perl use strict; use warnings; use utf8; package ?; our $str?="?????,??????\n?????,??????" . "\n?????????\n??????"; our $str? = "?????????? ????????? ?????? ??????? ???? ?? ??? ??????? ??"; sub new { my $class = shift; my $self = { str? => \$str?, 'str?' , \$str?, }; bless ($self, $class); } sub str? { ${ (shift)->{str?} }; } sub str? { ${ (shift)->{str?} }; }; package Test?; sub do { binmode STDOUT, 'utf8'; my $obj? = ?->new(); $\ = "\n"; print $obj?->str?(); print '----------------'; print $obj?->str?(); } Test?->do(); From boris.lorbeer at science-computing.de Sun Jun 11 09:20:58 2006 From: boris.lorbeer at science-computing.de (boris) Date: 11 Jun 2006 06:20:58 -0700 Subject: package search In-Reply-To: References: <1150009850.738535.155550@m38g2000cwc.googlegroups.com> Message-ID: <1150032058.923953.134550@u72g2000cwu.googlegroups.com> imho wrote: > > You just have to put in "__init__.py" in "lib2" (the package directory > you are "extending"), the following lines: > > from pkgutil import extend_path > __path__ = extend_path(__path__, __name__) > > "__path__", in each __init__ module, is a list initialized with the > module's path, but you can extend it by appending paths where you want > the interpreter to look for further modules. > pkgutil.extend_path automatically appends to __path__ all subdirectories > of directories on sys.path named after the package. > > HTH :-) > > Diego. COOL! You just saved me an awful lot of work. Thanks, Diego! Boris From ilias at lazaridis.com Wed Jun 7 10:24:21 2006 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Wed, 07 Jun 2006 17:24:21 +0300 Subject: Django Quick Start with Schema Evolution Support In-Reply-To: References: <1149446706.085692.174980@h76g2000cwa.googlegroups.com> <1149505316.406428.242450@c74g2000cwc.googlegroups.com> <448429E1.90305@kered.org> <35081.132.60.240.80.1149530454.squirrel@kered.org> <4486D6F2.7000407@lazaridis.com> Message-ID: Steve Holden wrote: > Ilias Lazaridis wrote: >> [Replying to comp.lang.python, due to censorship on Django User] >> [additional notification of poster via email, as medium is changed] >> > And yet you still don't see why people call you a troll? Missing liberal qualities? http://dev.lazaridis.com/base/wiki/LiberalProjectDefinition > This is completely inappropriate for comp.lang.python. Please take it > elsewhere. This is perfectly appropriate for comp.lang.python, as it is the closest usenet group for django. > This newsgroup is not a proxy for any other group who may have tired of > your postings, and is not an arbitration forum for disputes. no. It's a place to discuss python. And it's a place to continue discussions which were censored within other media of the python domain. - sidenote: I forgot to post the link to the original article: http://groups.google.com/group/django-users/msg/710f456a3c1f1ee5 > regards > Steve -- http://lazaridis.com From alikakakhel at yahoo.com Sat Jun 3 23:01:15 2006 From: alikakakhel at yahoo.com (greenflame) Date: 3 Jun 2006 20:01:15 -0700 Subject: reordering elements of a list In-Reply-To: <1149382009.640607.217470@y43g2000cwc.googlegroups.com> References: <1149382009.640607.217470@y43g2000cwc.googlegroups.com> Message-ID: <1149390075.653265.193370@j55g2000cwa.googlegroups.com> Thank you all for your replies. The only thing is I do not understand how the code is working. The following are more particular questions. Travis: Iam sorry, but I do not know what list comprehension is. Roberto: I do not understand the first half of the last line of your code. Also thank you for also teaching me to use '+' to append one list to another. This will be very useful for me. Christoph: I do not undertand the map method. Thanks again for all the help. :) From onurb at xiludom.gro Fri Jun 16 10:27:22 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 16 Jun 2006 16:27:22 +0200 Subject: Python is fun (useless social thread) ;-) In-Reply-To: <1150381872.958342.180420@p79g2000cwp.googlegroups.com> References: <1150381872.958342.180420@p79g2000cwp.googlegroups.com> Message-ID: <4492bfcc$0$9271$636a55ce@news.free.fr> BartlebyScrivener wrote: (snip) > Also, it seems to be a minimalist > language. *seems* minimalist, but is really not - have a look at the object model (metaclasses, descriptors etc), at closures and HOFs and decorators, at list-comp and generators and (coming in 2.5) coroutines... Definitively not minimalist in fact !-) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From michele.petrazzo at TOGLIunipex.it Thu Jun 1 10:27:11 2006 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Thu, 01 Jun 2006 14:27:11 GMT Subject: Trying to get FreeImagePy to work. In-Reply-To: <1149166096.176405.22780@i40g2000cwc.googlegroups.com> References: <1148651668.578852.3160@i40g2000cwc.googlegroups.com> <7fEdg.13375$cX1.201311@twister2.libero.it> <1148655611.990937.322350@j73g2000cwa.googlegroups.com> <1149166096.176405.22780@i40g2000cwc.googlegroups.com> Message-ID: <3PCfg.20835$cX1.315781@twister2.libero.it> Iain King wrote: > Michele Petrazzo wrote: >> Iain King wrote: >>> Michele Petrazzo wrote: >>> >>> I downloaded and installed 0.9.9.3, and it now works. Thanks! >>> >> I advice you to don't use that ctypes version... Better is to use >> the newest one and update freeimagepy! >> >>> Iain >>> >> Michele > > OK, Ive installed the latest versions I can find, which are > FreeImagePy 1.2.4 and ctypes 0.9.9.6, and I'm back to the error I had > earlier. Do you know what's wrong? > > Iain > Can you download the last svn version from sf.net? Otherwise I'll send you the last sources privately. Bye, Michele From ldo at geek-central.gen.new_zealand Thu Jun 29 05:42:50 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 29 Jun 2006 21:42:50 +1200 Subject: Passing a Cookie with httplib References: Message-ID: In article , scott at bogusaddress.com wrote: >I would like to >hard code the cookie in the code so it works every time: > >i.e. cookie = 'auth=buster%3A12345678901234567890exZ9rzMqgtxa5A'. > > conn=httplib.HTTPConnection(WP_SERVER) > conn.request('GET',WP_PATH % uservalue) According to , you can pass additional "body" and "headers" args to HTTPConnection.request. How about trying something like this in place of the last line above: Headers = {"Cookie" : "auth=buster%3A12345678901234567890exZ9rzMqgtxa5A"} conn.request('GET',WP_PATH % uservalue, None, Headers) From richard at pyweek.org Sun Jun 25 20:53:50 2006 From: richard at pyweek.org (richard at pyweek.org) Date: Mon, 26 Jun 2006 10:53:50 +1000 Subject: Pygame.draw challenge is over! Message-ID: <200606261053.50740.richard@pyweek.org> It was quite successful too! Download the submissions from the pyweek.org site: http://media.pyweek.org/static/pgd-200606.zip Congratulations to all who participated! Richard -- Visit the PyWeek website: http://www.pyweek.org/ From michele.petrazzo at TOGLIunipex.it Fri Jun 30 06:19:46 2006 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Fri, 30 Jun 2006 10:19:46 GMT Subject: Way for see if dict has a key Message-ID: <6V6pg.21624$_J1.271925@twister2.libero.it> Hi ng, what the preferred way for see if the dict has a key? We have a lot of solutions: key in dict key in dict.keys() dict.has_key(key) ... but what the better or the more "pythonic"? Thanks, Michele From ldo at geek-central.gen.new_zealand Mon Jun 26 03:19:48 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 26 Jun 2006 19:19:48 +1200 Subject: Python taught in schools? References: <1151220913.406987.162420@u72g2000cwu.googlegroups.com> <1hhhbmb.qcvbcn14uox59N%aleax@mac.com> Message-ID: In article <1hhhbmb.qcvbcn14uox59N%aleax at mac.com>, aleax at mac.com (Alex Martelli) wrote: >... let's try some google searches and see the number of million hits...: But how reliable are those estimates of numbers of hits, anyway? More than once I've got a page showing something like "Results 1 - 10 of about 36 hits", only to find that there were no more pages after the second one. If it could get estimates so wrong with such small numbers, how can you trust the large ones? From bborcic at gmail.com Fri Jun 9 04:11:36 2006 From: bborcic at gmail.com (Boris Borcic) Date: Fri, 09 Jun 2006 10:11:36 +0200 Subject: How to generate k+1 length strings from a list of k length strings? In-Reply-To: <1149800459.244528.220790@u72g2000cwu.googlegroups.com> References: <44883789$1_4@news.bluewin.ch> <1149785331.109164.208340@i39g2000cwa.googlegroups.com> <4488658e$1_5@news.bluewin.ch> <1149800459.244528.220790@u72g2000cwu.googlegroups.com> Message-ID: <44892d49$1_2@news.bluewin.ch> bearophileHUGS at lycos.com wrote: > Boris Borcic: > >> I challenge you to write simpler code to do the equivalent. context ? > > I don't do challenges. Pfff... and you don't do real debates either. > I too have written the code to solve that > problem, Why ? When ? From klaus at seistrup.dk Tue Jun 27 10:53:12 2006 From: klaus at seistrup.dk (Klaus Alexander Seistrup) Date: Tue, 27 Jun 2006 14:53:12 +0000 (UTC) Subject: How do you use this list? References: <12a2foromcuj30b@corp.supernews.com> Message-ID: Grant Edwards wrote: > Find an NNTP server and read it as a newsgroup. Or Google Groups: http://groups.google.com/group/comp.lang.python Cheers, -- Klaus Alexander Seistrup Dysseg?rd, Denmark http://surdej.dk/ From icebear at northpole.gov Sat Jun 24 08:51:19 2006 From: icebear at northpole.gov (icebear) Date: Sat, 24 Jun 2006 12:51:19 GMT Subject: dragging with Boa Constructor Message-ID: There's some non-obvious trick to being able to drag widgets around on a frame screen using Boa Constructor. I'd appreciate hearing from anybody who knows what it is. From digitalorganics at gmail.com Mon Jun 26 15:49:01 2006 From: digitalorganics at gmail.com (digitalorganics at gmail.com) Date: 26 Jun 2006 12:49:01 -0700 Subject: TypeError: Cannot create a consistent method resolution order (MRO) for bases object In-Reply-To: <1151350365.357634.221780@u72g2000cwu.googlegroups.com> References: <1151345197.691600.200060@y41g2000cwy.googlegroups.com> <1151350365.357634.221780@u72g2000cwu.googlegroups.com> Message-ID: <1151351341.426409.225480@c74g2000cwc.googlegroups.com> Hint: If I change Dog and Bat to old-style classes, there's no problem, everything works fine. Okay, here's the code dump from my playground:: ------------------------------------------ #!/usr/bin/env python class Mixin: def mixin(object, *classes): NewClass = type('Mixin', (object.__class__,) + classes, {}) newobj = NewClass() newobj.__dict__.update(object.__dict__) return newobj class Cat(object): def __init__(self): self.love = 0 def meow(self): print "meow" class Dog(object): def bark(self): print "bark" class Bat(object): def scream(self): print "scream" mycat = Cat() mycat.love = 4 mycat.__class__.__bases__ += (Mixin,) mycat.mixin(Dog, Bat) print mycat.love def isClass(object): if isinstance(object, type): return True elif isinstance(object, types.ClassType): return True else: return False def listClasses(): classes = [] for eachobj in globals().keys(): if isClass(globals()[eachobj]): classes.append(globals()[eachobj]) print eachobj return classes def applyMixinGlobal(*Mixins): for eachclass in listClasses(): MixInto(eachclass, Mixins) #applyMixinGlobal(Mixin) def MixInto(Class, *Mixins): for eachMixin in Mixins: if eachMixin not in Class.__bases__: Class.__bases__ += (eachMixin,) MixInto(Bat, Mixin) Bat.__bases__ += (Dog,) dargo = Bat() dargo = dargo.mixin(Cat) dargo.meow() Simon Forman wrote: > digitalorganics at gmail.com wrote: > > What are the reason one would get this error: TypeError: Cannot create > > a consistent method resolution order (MRO) for bases object ?? > > > > I can provide the code if needed.... > > Yes, do that. > > That's an amazing error. > > ~Simon From maric at aristote.info Tue Jun 20 07:28:01 2006 From: maric at aristote.info (Maric Michaud) Date: Tue, 20 Jun 2006 13:28:01 +0200 Subject: Specifing arguments type for a function In-Reply-To: References: <4fq09iF1k0h0eU1@uni-berlin.de> Message-ID: <200606201328.02784.maric@aristote.info> Le Mardi 20 Juin 2006 12:29, Rony Steelandt a ?crit?: > What about > def f(arg): > ? ? if type(arg)=='list': > ? ? ? ? #do something And if arg's type is subclass of list ? The problem with isinstance is : and if arg is not of type list but is a sequence (a instance of UserList for example) ? The general case in python is duck typing, that means you define apis that accept file-like object, iterables, dict-like (mapping) objects, string like objects... The problem with iterables is that they don't all implement the __iter__ attribute, for compatibility purpose the right test should be : if not getattr(arg, '__iter__') and not getattr(arg, '__getitem__') : raise ValueError('Function accepts only iterables') # or error handling code -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From fredrik at pythonware.com Wed Jun 21 15:03:13 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 21 Jun 2006 21:03:13 +0200 Subject: Update on Memory problem with NumPy arrays In-Reply-To: <1150907922.908497.120310@u72g2000cwu.googlegroups.com> References: <1150907922.908497.120310@u72g2000cwu.googlegroups.com> Message-ID: sonjaa wrote: > Also, are there other python methods/extensions that can create > multi-deminsional arrays? if this example is typical for the code you're writing, you might as well use nested Python lists: def make_array(width, height, value): out = [] for y in range(height): out.append([value] * width) return y = make_array(501, 501, 1) z = make_array(501, 501, 0) y[ee][ff] = 4 etc From nmm1 at cus.cam.ac.uk Wed Jun 28 11:20:23 2006 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 28 Jun 2006 15:20:23 GMT Subject: Immutability References: <4Qj*cEjkr@news.chiark.greenend.org.uk> Message-ID: In article <4Qj*cEjkr at news.chiark.greenend.org.uk>, Sion Arrowsmith writes: |> |> Actually, there's an almost throw-away mention in |> http://docs.python.org/ref/descriptor-invocation.html |> which gives you what you need (although not, I have to say, in an |> easily digestible form). Thanks very much. |> What I've not seen documented anywhere is the: |> @property |> def fset(self, value): |> ... |> idiom. It's not obvious from the documentation of the property |> function that it can be used as a decorator like this. (cf. |> classmethod and staticmethod.) Most especially since it isn't working very well for me, and I am trying to track down why. When I run: class alf : def pete (self) : print "Inside pete\n" b = alf() b.pete() class fred : @property def joe (self) : print "Inside /joe\n" a = fred() a.joe() I get: Inside pete Inside joe Traceback (most recent call last): File "crap.py", line 14, in a.joe() TypeError: 'NoneType' object is not callable VERY weird - I could understand it if I got the error and DIDN'T succeed in the call .... Regards, Nick Maclaren. From David.Squire at no.spam.from.here.au Tue Jun 20 10:29:36 2006 From: David.Squire at no.spam.from.here.au (David Squire) Date: Tue, 20 Jun 2006 15:29:36 +0100 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <1150809118.677124.142230@u72g2000cwu.googlegroups.com> Message-ID: Andreas Rossberg wrote: > Rob Thorpe wrote: >>> >>>> No, that isn't what I said. What I said was: >>>> "A language is latently typed if a value has a property - called it's >>>> type - attached to it, and given it's type it can only represent values >>>> defined by a certain class." >>> >>> "it [= a value] [...] can [...] represent values"? >> >> ??? > > I just quoted, in condensed form, what you said above: namely, that a > value represents values - which I find a strange and circular definition. > But you left out the most significant part: "given it's type it can only represent values *defined by a certain class*" (my emphasis). In C-ish notation: unsigned int x; means that x can only represent elements that are integers elements of the set (class) of values [0, MAX_INT]. Negative numbers and non-integer numbers are excluded, as are all sorts of other things. You over-condensed. DS NB. This is not a comment on static, latent, derived or other typing, merely on summarization. From riteshsarraf at gmail.com Fri Jun 30 05:01:32 2006 From: riteshsarraf at gmail.com (Ritesh Raj Sarraf) Date: 30 Jun 2006 02:01:32 -0700 Subject: FIXED: Re: optparse multiple arguments In-Reply-To: <1151657634.348133.291340@x69g2000cwx.googlegroups.com> References: <1151657119.837675.213700@p79g2000cwp.googlegroups.com> <1151657634.348133.291340@x69g2000cwx.googlegroups.com> Message-ID: <1151658092.273456.32260@75g2000cwc.googlegroups.com> Ritesh Raj Sarraf wrote: > I just noticed that the args variable is holding values b and c. > the args variables comes from: > (options, args) = parser.parse_args() > > I guess I only need to figure out now is why args isn't storing > argument "a" also... > > Ritesh I fixed it, I guess. parser.add_option("", "--my-option", dest="my_option", action="store_true") sets my_option to True and the arguments are all stored in the list "args". :-) Ritesh From mensanator at aol.com Fri Jun 30 14:00:14 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 30 Jun 2006 11:00:14 -0700 Subject: list comprehension References: <1151600332.552024.119990@y41g2000cwy.googlegroups.com> <1151602493.629010.269360@i40g2000cwc.googlegroups.com> <1151671605.957887.158150@m73g2000cwd.googlegroups.com> Message-ID: <1151690413.955323.254690@d30g2000cwa.googlegroups.com> Andy Dingley wrote: > Simon Forman wrote: > > > There's more to it, but that's the basic idea. > > This much I knew, but _why_ and _when_ would I choose to use list > comprehension (for good Python style), rather than using a simple > "traditional" loop ? To make dynamically nested for loops. def ooloop6(a, n, perm=True, repl=True): if (not repl) and (n>len(a)): return r0 = range(n) r1 = r0[1:] if perm and repl: # ok v = ','.join(['c%s' % i for i in r0]) f = ' '.join(['for c%s in a' % i for i in r0]) e = ''.join(["p = [''.join((",v,")) ",f,"]"]) print 'Permutations with Replacement' print e exec e return p if (not perm) and repl: # ok v = ','.join(['c%s' % i for i in r0]) f = ' '.join(['for c%s in a' % i for i in r0]) i = ' and '.join(['(c%s>=c%s)' % (j,j-1) for j in r1]) e = ''.join(["p = [''.join((",v,")) ",f," if ",i,"]"]) print 'Combinations with Replacement' print e exec e return p if perm and (not repl): # ok v = ','.join(['c%s' % i for i in r0]) f = ' '.join(['for c%s in a' % i for i in r0]) i = ' and '.join([' and '.join(['(c%s!=c%s)' % (j,k) for k in range(j)]) for j in r1]) e = ''.join(["p = [''.join((",v,")) ",f," if ",i,"]"]) print 'Permutations without Replacement' print e exec e return p if (not perm) and (not repl): # ok v = ','.join(['c%s' % i for i in r0]) f = ' '.join(['for c%s in a' % i for i in r0]) i = ' and '.join(['(c%s>c%s)' % (j,j-1) for j in r1]) e = ''.join(["p = [''.join((",v,")) ",f," if ",i,"]"]) print 'Combinations without Replacement' print e exec e return p s = 'abcde' p = ooloop6(s,2,True,True) print p = ooloop6(s,2,False,True) print p = ooloop6(s,2,True,False) print p = ooloop6(s,2,False,False) print p = ooloop6(s,4,True,True) print p = ooloop6(s,4,False,True) print p = ooloop6(s,4,True,False) print p = ooloop6(s,4,False,False) print """ Permutations with Replacement p = [''.join((c0,c1)) for c0 in a for c1 in a] Combinations with Replacement p = [''.join((c0,c1)) for c0 in a for c1 in a if (c1>=c0)] Permutations without Replacement p = [''.join((c0,c1)) for c0 in a for c1 in a if (c1!=c0)] Combinations without Replacement p = [''.join((c0,c1)) for c0 in a for c1 in a if (c1>c0)] Permutations with Replacement p = [''.join((c0,c1,c2,c3)) for c0 in a for c1 in a for c2 in a for c3 in a] Combinations with Replacement p = [''.join((c0,c1,c2,c3)) for c0 in a for c1 in a for c2 in a for c3 in a if (c1>=c0) and (c2>=c1) and (c3>=c2)] Permutations without Replacement p = [''.join((c0,c1,c2,c3)) for c0 in a for c1 in a for c2 in a for c3 in a if (c1!=c0) and (c2!=c0) and (c2!=c1) and (c3!=c0) and (c3!=c1) and (c3!=c2)] Combinations without Replacement p = [''.join((c0,c1,c2,c3)) for c0 in a for c1 in a for c2 in a for c3 in a if (c1>c0) and (c2>c1) and (c3>c2)] """ > > If I want to generate something that's simply ( [1] + [2] + [3]+... ) > then list comprehension is obviously the tool of choice. I suspect > though that there's more to it than this. Is list comprehension also > treatable as a sneaky concise formulation for nested lists, where > they're as much about selection of individual elements, so much as > concatenation of the sequence? > > What happens if a comprehension has side effects, such as from calling > a function within it? Is this regarded as good or bad coding style? Is > it evil (as structured programming would claim) or is it a concise > formulation for an iterator or visitor pattern ? From paul at boddie.org.uk Thu Jun 22 17:52:31 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 22 Jun 2006 14:52:31 -0700 Subject: code is data References: <44965f53$0$12743$636a55ce@news.free.fr> <4496b29f$0$27412$626a54ce@news.free.fr> <4496e9c9$0$14868$626a54ce@news.free.fr> <4fokj4F1ihat3U1@uni-berlin.de> <4497c20e$0$29656$636a55ce@news.free.fr> <4fpuh5F1i9bl1U1@uni-berlin.de> <4497d72d$0$30964$636a55ce@news.free.fr> <4fq5fkF1k346bU1@uni-berlin.de> <44982637$0$29812$626a54ce@news.free.fr> Message-ID: <1151013151.902103.32800@g10g2000cwb.googlegroups.com> Anton Vredegoor wrote: > Bruno Desthuilliers wrote: > > > You mean like 'converting' javascript to python or python to ruby (or > > converting any home-grown DSL to Python, etc) ? > > Yes, but also what some other posters mentioned, making Pythons internal > parsing tree available to other programs (and to Python itself) by using > a widely used standard like XML as its datatype. http://pysch.sourceforge.net/ast.html I was going to write a long reply to one of your previous messages, but the above link references a project which may intersect with some of your expectations. Meanwhile, it should be noted that the availability of Python AST processing tools is not a recent thing: the compiler module has been around for a long time, and it is possible to modify the AST and to generate bytecode from it; my own experiments have centred on producing other representations from the AST, and other more successful projects (eg. ShedSkin) produce other languages (eg. C++) from the AST. Paul From scott.daniels at acm.org Sat Jun 17 14:17:13 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Sat, 17 Jun 2006 11:17:13 -0700 Subject: Which compiler will Python 2.5 / Windows (Intel) be built with? In-Reply-To: References: <1150367139.495114.148550@g10g2000cwb.googlegroups.com> <44917535$1@nntp0.pdx.net> <1150391891.130185.4640@f6g2000cwb.googlegroups.com> <4492414C.10505@v.loewis.de> <1150444191.618761.22810@c74g2000cwc.googlegroups.com> Message-ID: <4494424f$1@nntp0.pdx.net> Roel Schroeven wrote: > Isn't Python for other platforms built with GCC? Seems to me that if it > GCC is good enough for other platforms, it's good enough for Windows. You clearly misunderstand the interface to the Windows OS & GUI system. Microsoft provides that interface through its language systems, and has used that edge to knock off other compilers (such as WatCom) by providing header files that are not standard C compatible. --Scott David Daniels scott.daniels at acm.org From pink at odahoda.de Mon Jun 12 06:24:54 2006 From: pink at odahoda.de (Benjamin Niemann) Date: Mon, 12 Jun 2006 12:24:54 +0200 Subject: urllib behaves strangely References: Message-ID: Benjamin Niemann wrote: > Gabriel Zachmann wrote: > >> Here is a very simple Python script utilizing urllib: >> >> import urllib >> url = >> "http://commons.wikimedia.org/wiki/Commons:Featured_pictures/chronological" >> print url >> print >> file = urllib.urlopen( url ) >> mime = file.info() >> print mime >> print file.read() >> print file.geturl() >> >> >> However, when i ecexute it, i get an html error ("access denied"). >> >> On the one hand, the funny thing though is that i can view the page fine >> in my browser, and i can download it fine using curl. >> >> On the other hand, it must have something to do with the URL because >> urllib works fine with any other URL i have tried ... >> >> Any ideas? >> I would appreciate very much any hints or suggestions. > > The ':' in '..Commons:Feat..' is not a legal character in this part of the > URI and has to be %-quoted as '%3a'. Oops, I was wrong... ':' *is* allowed in path segments. I should eat something, my vision starts to get blurry... > Try the URI > 'http://commons.wikimedia.org/wiki/Commons%3aFeatured_pictures/chronological', You may try this anyway... -- Benjamin Niemann Email: pink at odahoda dot de WWW: http://pink.odahoda.de/ From jzgoda at o2.usun.pl Thu Jun 15 14:36:21 2006 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Thu, 15 Jun 2006 20:36:21 +0200 Subject: Which compiler will Python 2.5 / Windows (Intel) be built with? In-Reply-To: References: <1150367139.495114.148550@g10g2000cwb.googlegroups.com> <44917535$1@nntp0.pdx.net> <1150391891.130185.4640@f6g2000cwb.googlegroups.com> Message-ID: Fredrik Lundh napisa?(a): > hint: most people who provide third-party extensions to Python support > more than just the latest Python version... We're happy with your support for us, Windows users, but you are an exception to the general rule of providing only sources. That's the reason we are fragile on compiler. If the core will be buid with "non-generally-available" compiler, we would end up with searching for person willing to compile a library for us, if the MinGW way won't succeed. I'd like to see core compiled with latest available "free" toolkit compiler available, as previous versions can not be downloaded from provider's home. -- Jarek Zgoda http://jpa.berlios.de/ From sjmachin at lexicon.net Fri Jun 2 23:44:11 2006 From: sjmachin at lexicon.net (John Machin) Date: 2 Jun 2006 20:44:11 -0700 Subject: how to erase a variable In-Reply-To: <1149306000.615590.30020@c74g2000cwc.googlegroups.com> References: <1149306000.615590.30020@c74g2000cwc.googlegroups.com> Message-ID: <1149306251.073558.274980@i39g2000cwa.googlegroups.com> greenflame wrote: > Is there a way to get rid of a variable as though it never existed? I > know this sounds very basic but I have not come across any such > methods. Also is the fact that I will have a bunch of extra variables > just haning around because my use for them is over a bad thing? I will > likely have on the order of 10 to 50 or so of these for the particular > program I an working on at the moment. del rubbish, garbage, junk, unwanted_stuff From bignose+hates-spam at benfinney.id.au Wed Jun 14 19:51:59 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 15 Jun 2006 09:51:59 +1000 Subject: Writing PNG with pure Python References: <1149853401.521169.112530@i39g2000cwa.googlegroups.com> <1149889778.182865.181600@f6g2000cwb.googlegroups.com> <1149910872.025017.60160@i40g2000cwc.googlegroups.com> <1150152913.315502.16840@u72g2000cwu.googlegroups.com> <1150215317.349097.326970@p79g2000cwp.googlegroups.com> <1150300541.971664.153000@g10g2000cwb.googlegroups.com> Message-ID: <87zmgfmh28.fsf@benfinney.id.au> "Johann C. Rocholl" writes: > Ben Finney schrieb: > > Simplify. Please don't attempt to write yet another set of license > > terms without expert legal assistance. You've already chosen the > > Expat license as being acceptable; use that, and you grant all the > > rest without even mentioning it. > > Sorry for my stubborn ignorance, and thank you for your patient > explanations. No problems; if license proliferation can be reduced, it's worth spending some time to do so. > I think I finally got it: I'll put the bulk of my browsershots > project under the GNU GPL again, and the independent library parts > like png.py under the Expat License. Sounds quite workable. This has the effect that the work as a whole can be redistributed under the GNU GPL (since the Expat license allows this), and the library parts can be redistributed independently under just about any license. -- \ "As we enjoy great advantages from the inventions of others, we | `\ should be glad to serve others by any invention of ours." -- | _o__) Benjamin Franklin | Ben Finney From marv at mailcity.com Thu Jun 1 21:35:24 2006 From: marv at mailcity.com (Marvin) Date: 02 Jun 2006 01:35:24 GMT Subject: Inheritance structure less important in dynamic languages? Message-ID: <447f95dc$0$1167$ba620e4c@news.skynet.be> Hi, It's been claimed that inheritance structures are less important in dynamic languages like Python. Why is that and where can i read more about that? /Marv From onurb at xiludom.gro Fri Jun 9 04:27:27 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 09 Jun 2006 10:27:27 +0200 Subject: Error in Chain of Function calls In-Reply-To: References: Message-ID: <448930f1$0$10302$636a55ce@news.free.fr> Girish Sahani wrote: > Hi, > > There is a code in my main function which is something like: > > while prunedFinal != []: > prunedNew = genColocations(prunedK) *** > tableInstancesNew = genTableInstances(prunedNew,tableInstancesK) > tiCountDict = tiCount(tableInstancesNew) > tiDict = findPI(tableInstancesNew) > prunedFinal = pruneTI(tiDict,pi) > rulesDict = genRules(prunedFinal) > cpDict = findCP(rulesDict) > prunedRulesList = pruneCP(cpDict,cp) > prunedK = prunedFinal > tableInstancesK = tableInstancesNew > else: > return prunedRulesList > > prunedK and tableInstancesK are defined in the main function. defined as what ? functions, strings, lists, classes, ... ? > Before the > main function, i have defined the other functions such as > genColocations,genTableInstances,etc. Output of genColocations is to be > given to the next function genTableInstances,output of this function to > tiCount and findPI, and so on. > However i am getting an error at the line marked with ***. Which error ? How do you hope us to be of any help here if you don't *at least* provide the full traceback ? FWIW, the canonical way to do things is to: - provide minimal *runnable* code exposing the problem - explain what you hoped to get - explain what you got instead (including full traceback) As a matter of fact, it's often the case that one solves the problem when working on the first point !-) (snip) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From jcrocholl at googlemail.com Mon Jun 12 12:34:04 2006 From: jcrocholl at googlemail.com (Johann C. Rocholl) Date: 12 Jun 2006 09:34:04 -0700 Subject: Writing PNG with pure Python References: <1149853401.521169.112530@i39g2000cwa.googlegroups.com> Message-ID: <1150130044.566109.222100@f6g2000cwb.googlegroups.com> > Just in case anybody has the same problem, here's my first attempt at > implementing a subset of the PNG spec in pure Python. I license it to > you under the terms of the GNU GPL. Update: the code is now licensed under the Apache License 2.0. > http://trac.browsershots.org/browser/trunk/shotfactory/lib/image/png.py Update: the module has moved to its own package, with its own setup.py: http://trac.browsershots.org/browser/trunk/pypng http://svn.browsershots.org/trunk/pypng/ Cheers, Johann From thirsteh at gmail.com Tue Jun 27 11:44:22 2006 From: thirsteh at gmail.com (Patrick M. Nielsen) Date: Tue, 27 Jun 2006 17:44:22 +0200 Subject: [Stackless] Suggestion for a Solution ? Re: Blocking Problem with Stackless Python and Twisted In-Reply-To: <20060626181123.67620.qmail@web34208.mail.mud.yahoo.com> References: <20060626181123.67620.qmail@web34208.mail.mud.yahoo.com> Message-ID: <28dc07920606270844n33f158bbv77116d69907462cf@mail.gmail.com> I had a similar problem, and Radix's threadless Twisted snippet proved to be a very viable solution Have a look at: http://twistedmatrix.com/trac/browser/sandbox/radix/threadless.py?rev=17407 On 6/26/06, Andrew Francis wrote: > > Hello Jas, Bob, et al: > > > Twisted isn't designed for Stackless integration, > > and the approach you're taking simply will not > work. > > Twisted does block on reactor.run(), and during > > each runloop iteration it blocks waiting for a > >timeout or network activity (via select or poll > >usually). > > ~ > > > What's the deal with this error from > > stackless.run(): > > ... > > >have some reasons to need to be able to run a > >scheduler on another thread... Did someone discover > >some problem? Or is this check just overly > >conservative? (A few simple scheduling experiments > >seem to run without problem...) > > >From what I can tell, the only time I really care > about blocking that cuts down overall concurrency is > when I have tasklets running in parallel, and one or > more of those tasklets, at some low level will be > doing an IO operation that can block for an > indeterminate amount of time (i.e., an accept()). > > That said, I beleive the the easiest way to get around > this problem is to bite the bullet and run Twisted (or > the programme with blocking IO) in another process. > > In turn, I : > > 1. create a simple protocol. > 2. and have my Stackless process establish a > connection with the process doing the actual IO (some > other IPC could also be used). > 3. Mark the socket as non-blocking (or use MSG_PEEK?) > 4. Have tasklets with a network event loop. > > > #requests > while (some_condition): > request = requestChannel.receive() > serverSocket.send(request) > stackless.schedule() > > > #responses > while (some_condition): > if (there is data): > reply = serverSocket.receive() > replyChannel.send(reply) > stackless.schedule() > > > you get the idea. Comments? Suggestions? > > Cheers, > Andrew > > > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > http://mail.yahoo.com > > _______________________________________________ > Stackless mailing list > Stackless at stackless.com > http://www.stackless.com/mailman/listinfo/stackless > -------------- next part -------------- An HTML attachment was scrubbed... URL: From warpcat at sbcglobal.net Thu Jun 8 19:40:48 2006 From: warpcat at sbcglobal.net (warpcat) Date: 8 Jun 2006 16:40:48 -0700 Subject: better Python IDE? Mimics Maya's script editor? Message-ID: <1149810048.765664.107820@i40g2000cwc.googlegroups.com> I've been scripting in Maya, via mel for years now. Recently learning to Python, love it. Thing that's driving me nuts it the IDE. I'm using PythonWin right now and trying to find something better, mainly with this functionality: In Maya's mel script editor window, it's split into two sections. Bottom window you can enter commands (where your script lives), top window gives results. The thing I'm really used to is highlighting X# of lines in the bottom window (little snippits from my script), and executing that selection, with instant feedback of the results on top. This really speeds my workflow. It seems completely missing (so far) in Python's IDE. I have to copy and paste from a script to the ide window to execute and see the results, or I have to make a bunch of "buffer scripts" with just the code snippetsI want to test in. Seems *really* clunky. Does anyone know of a scripting enviroment for Python that mimics what Maya's script editor has? Much appreciated. From tjreedy at udel.edu Sat Jun 3 22:02:55 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 3 Jun 2006 22:02:55 -0400 Subject: Proposed new PEP: print to expand generators References: <4482390E.7060809@cascade-sys.com> Message-ID: "James J. Besemer" wrote in message news:4482390E.7060809 at cascade-sys.com... > I propose that we extend the semantics of "print" such that if the object > to > be printed is a generator then print would iterate over the resulting > sequence of sub-objects and recursively print each of the items in order. A generator is an iterator produced by a generator function rather than a class. What treat them differently? Iterating over an iterator is usually destructive. So you would be printing what it was but no longer is. This is why iterators are printed differently from sequences. Terry Jan Reedy From bjourne at gmail.com Sun Jun 18 17:28:22 2006 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Sun, 18 Jun 2006 23:28:22 +0200 Subject: code is data In-Reply-To: <1150606118.456390.262620@y41g2000cwy.googlegroups.com> References: <1150574111.415068.255900@p79g2000cwp.googlegroups.com> <1150606118.456390.262620@y41g2000cwy.googlegroups.com> Message-ID: <740c3aec0606181428r4d693e3qfbeb3924b606729@mail.gmail.com> > > > community has no interest in it. When I absolutely need macros, I will > > > go elsewhere. > I *like* 1..5 (ada, ruby) instead of range(5). If I had macros, I would > have done it myself for *my* code. I think this example more is a symptom of a childish need to get things your way than of a deficiency in Python. BTW, range(5) = 0..4 in Ada and Ruby. You said "when I absolutely need macros" but none of your examples demonstrate any "absolute need." I can't see your point. -- mvh Bj?rn From paul at eval.ca Fri Jun 9 16:04:53 2006 From: paul at eval.ca (Paul Osman) Date: Fri, 9 Jun 2006 16:04:53 -0400 Subject: Python or Ajax? In-Reply-To: References: Message-ID: <2A3C1C1F-842E-456F-B645-F7A8ED855FB7@eval.ca> On 9-Jun-06, at 4:00 PM, Redefined Horizons wrote: > I've been hearing a ot about AJAX lately. I may have to build a web > application in the near future, and I was curoius: > > How does a web application that uses Python compare with one that > uses AJAX? > > I've done some basic web page design with HTML and CSS, but never any > web applications. I don't want to learn a new language if I can use > Python. Would AJAX offer me any significant advantages? > > Thanks, > > Scott Huey Apples and Oranges my friend :) You may want to browse through the following: http://en.wikipedia.org/wiki/AJAX A nice toolkit for such things: http://mochikit.com/ Which is conveniently used in a Python framework called Turbogears: http://www.turbogears.org/ Hope that helps clear things up. Cheers, -- Paul Osman http://www.eval.ca From peace.is.our.profession at gmx.de Mon Jun 26 05:49:14 2006 From: peace.is.our.profession at gmx.de (Mirco Wahab) Date: Mon, 26 Jun 2006 11:49:14 +0200 Subject: Python taught in schools? In-Reply-To: References: <1151220913.406987.162420@u72g2000cwu.googlegroups.com> Message-ID: Thus spoke Lawrence D'Oliveiro (on 2006-06-26 09:21): > In article , > Mirco Wahab wrote: > >>C++ programming requires you to massively invest your thinking >>first into the setup of your build environment ... > > I don't understand why. It's easy enough to build small programs with a > single g++ command. Think about beeing a young guy with a windows pc at home. To make sense of your 45 min C++ class, you need to practice the stuff at home for sure, I'd guess. Now go ahead! What would you do? Download "The C++" from the Internet, click on setup and start? Right ;-) Regards Mirco From gene.tani at gmail.com Sun Jun 11 04:57:54 2006 From: gene.tani at gmail.com (gene tani) Date: 11 Jun 2006 01:57:54 -0700 Subject: learning python idioms In-Reply-To: <1149998884.261678.299860@u72g2000cwu.googlegroups.com> References: <1149998884.261678.299860@u72g2000cwu.googlegroups.com> Message-ID: <1150016274.233220.270980@u72g2000cwu.googlegroups.com> conkerll at gmail.com wrote: > After several years developing in Java, I've begun to switch to Python > for several of my new projects as I have found the language quite > interesting. I've read several tutorials and implemented a few sample > programs and I've found that Python enables one to program in a variety > of different styles (I'm not sure if this was the original intention or > not). Thus, I find myself occaisionally slipping into the "Java" i googled "Python idioms": http://www.gungfu.de/facts/wiki/Main/PythonIdioms also look at the OReilly Python cookbook and the online repository it's based on http://aspn.activestate.com/ASPN/Cookbook/Python From durumdara at gmail.com Wed Jun 14 05:49:17 2006 From: durumdara at gmail.com (Dara Durum) Date: Wed, 14 Jun 2006 11:49:17 +0200 Subject: About Threading - implementation Message-ID: <9e384ef60606140249m7e548f0r@mail.gmail.com> Hi ! I don't understand something. Under Python the threads are simulated by Python Interpreter as when prev. setted pieces (interval) of the interpreted tokens are executed, it is change to another "virtual" thread ? Or it was really create real threads, and they are figth for the priority, and for the execution time ? And can I create REAL threads under Python (just like in Delphi), or better if I use processes, not threads ? Please help me: dd From chris.uppal at metagnostic.REMOVE-THIS.org Fri Jun 23 13:09:29 2006 From: chris.uppal at metagnostic.REMOVE-THIS.org (Chris Uppal) Date: Fri, 23 Jun 2006 18:09:29 +0100 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <0%Wlg.3521$MF6.947@tornado.socal.rr.com> <44992e6c$0$664$bed64819@news.gradwell.net> <449aaea0$0$656$bed64819@news.gradwell.net> <449bde5e$1$663$bed64819@news.gradwell.net> Message-ID: <449c1f4d$0$662$bed64819@news.gradwell.net> Andreas Rossberg wrote: > So what you are suggesting may be an interesting notion, but it's not > what is called "type" in a technical sense. Overloading the same term > for something different is not a good idea if you want to avoid > confusion and misinterpretations. Frivolous response: the word "type" has been in use in the general sense in which I wish to use it for longer than that. If theorists didn't want ordinary people to abuse their technical terms they should invent their own words not borrow other people's ;-) Just for interest, here's one item from the OED's entry on "type" (noun): The general form, structure, or character distinguishing a particular kind, group, or class of beings or objects; hence transf. a pattern or model after which something is made. And it has supporting quotes, here are the first and last: 1843 Mill Logic iv. ii. ?3 (1856) II. 192 When we see a creature resembling an animal, we compare it with our general conception of an animal; and if it agrees with that general conception, we include it in the class. The conception becomes the type of comparison. 1880 Mem. J. Legge vi. 76 Every creature has a type, a peculiar character of its own. Interestingly the first one is from: John Stuart Mill A System of Logic (but it's not mathematical logic ;-). OK, I admitted I was being frivolous. But I really don't see why a type system (as understood by type theorists) /must/ have no runtime element. Just as I wouldn't stop calling a type system a "type system" if it were designed to work on incomplete information (only part of the program text is available for analysis) and so could only make judgements of the form "if X then Y". [JVM dynamic class loading] > Incidentally, I know this scenario very well, because that's what I'm > looking at in my thesis :-). > All of this can easily be handled > coherently with well-established type machinery and terminology. I'd be interested to know more, but I suspect I wouldn't understand it :-( > A type system states > propositions about a program, a type assignment *is* a proposition. A > proposition is either true or false (or undecidable), but it is so > persistently, considered under the same context. So if you want a type > system to capture temporal elements, then these must be part of a type > itself. You can introduce types with implications like "in context A, > this is T, in context B this is U". But the whole quoted part then is > the type, and it is itself invariant over time. But since the evolving type-attribution that I'm thinking of also includes time as a static element (at each specific time there is a specific attribution of types), the dynamic logic can also be viewed as invarient in time, since each judgement is tagged with the moment(s) to which it applies. But there we go. I don't expect you to agree, and though I'll read any reply with interest, I think I've now said all I have to say in this particular subthread. Cheers. -- chris From onurb at xiludom.gro Tue Jun 13 10:28:24 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 13 Jun 2006 16:28:24 +0200 Subject: What's wrong in this HTML Source file of a Bank In-Reply-To: <1150206298.560467.18420@g10g2000cwb.googlegroups.com> References: <1150196896.819711.154640@c74g2000cwc.googlegroups.com> <1150204559.415713.288600@h76g2000cwa.googlegroups.com> <1150205478.055121.60300@u72g2000cwu.googlegroups.com> <4f7t7dF1f0g44U1@uni-berlin.de> <1150206298.560467.18420@g10g2000cwb.googlegroups.com> Message-ID: <448ecb88$0$25347$636a55ce@news.free.fr> Thaqalainnaqvi at gmail.com wrote: > I have posted the same question in alt.html but no one yet replied. You should ask your butcher. Now please stop posting off-topic. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From hdante at gmail.com Sun Jun 18 17:27:18 2006 From: hdante at gmail.com (hdante) Date: 18 Jun 2006 14:27:18 -0700 Subject: Passing data to system command References: Message-ID: <1150666037.974563.25610@i40g2000cwc.googlegroups.com> Should be like this: from subprocess import Popen, PIPE my_output = file('output1.ps', 'w') p1 = Popen(["psxy"], stdin = PIPE, stdout=my_output) p1.stdin.write(my_format(array)) p1.communicate() my_output.close() I've never used that, though, please tell us if it worked. Chris Hieronymus wrote: > Hi, > > I have a bunch of x-y data contained in an array. I would like to > plot the data using an > external program (psxy in GMT). The plotting program takes x-y > couples as standard > input. How do I get the data into the system call? I used to do > things in csh and awk, > i.e., something like > > awk '{; print $1, $2}' filename | psxy options> >! output.ps > > The reason I'm trying to use python is because the manipulations are > getting too cumbersome > in awk. Now I have all the manipulations done in python, but I'm > missing that last step. > > I've tried various things with os.system, popen, and subprocess, but > so far without success. > Does anyone know how to do this? > > chris > > > ------------------------------------------------------------------------ > ------------------------------------------- > Christoph > Hieronymus > christoph.hieronymus at geo.uu.se > Associate > Professor > phone: (+46) 18-471 2383 > Uppsala > University > fax: (+46) 18-501 110 > Dept. of Earth Sciences (Geophysics) > Villav?gen 16 > SE-752 36 Uppsala, Sweden From marc.t.davies at gmail.com Fri Jun 16 05:40:21 2006 From: marc.t.davies at gmail.com (MTD) Date: 16 Jun 2006 02:40:21 -0700 Subject: Extracting values from text file In-Reply-To: <1150449483.216515.308440@h76g2000cwa.googlegroups.com> References: <1150449483.216515.308440@h76g2000cwa.googlegroups.com> Message-ID: <1150450821.709882.223840@c74g2000cwc.googlegroups.com> P.S. >>> file.close() MTD wrote: > list.txt is a file that contains the following lines: > Apples 34 > Bananas 10 > Oranges 56 > > >>> file = open("list.txt","r") > >>> mystring = file.read() > >>> mystring > 'Apples 34 \nBananas 10\nOranges 56 ' > >>> mylist = mystring.split('\n') > >>> mylist > ['Apples 34 ', 'Bananas 10', 'Oranges 56 '] > >>> mydict = {} > >>> for el in mylist: > ... l = el.split() > ... mydict[l[0]] = l[1] > ... > >>> mydict > {'Apples': '34', 'Oranges': '56', 'Bananas': '10'} > >>> mydict["Apples"] > '34' > >>> mydict["Oranges"] > '56' From rbann11 at hotmail.com Sat Jun 3 23:58:04 2006 From: rbann11 at hotmail.com (rbann11 at hotmail.com) Date: 3 Jun 2006 20:58:04 -0700 Subject: wxpython wxgrid question In-Reply-To: References: <1149366330.999234.299880@u72g2000cwu.googlegroups.com> Message-ID: <1149393484.553463.286220@i39g2000cwa.googlegroups.com> Tim Roberts wrote: > rbann11 at hotmail.com wrote: > > > > I am looking for example code that consists of just a frame and a > >grid(10x2). The grid must fill the its parent even if the frame is > >resized. > > Have you gone through the wxPython demo application? It contains examples > of every standard control and almost every behavior you might want. > -- > - Tim Roberts, timr at probo.com > Providenza & Boekelheide, Inc. Yes, and i have even checked out "wxpython in action". All of the examples tend to leave white space on the right of the frame. I tried basic a example with sizers and it didnt work. That why I was wondering if someone had got it to work. Roger From davidh at ilm.com Mon Jun 12 14:00:33 2006 From: davidh at ilm.com (David Hirschfield) Date: Mon, 12 Jun 2006 11:00:33 -0700 Subject: Advanced lockfiles Message-ID: <448DABC1.9030801@ilm.com> I'm not sure it's even possible to do what I'm trying to here...just because the logistics may not really allow it, but I thought I'd ask around... I want some kind of lockfile implementation that will allow one process to lock a file (or create an appropriately named lockfile that other processes will find and understand the meaning of), but there are some important requirements: 1. Multiple processes will be attempting to grab a lock on the file, and they must not freeze up if they can't get a lock 2. The processes can be on different hosts on a network, attempting to grab a lock on a file somewhere in network storage 3. All processes involved will know about the locking system, so no need to worry about rogue processes that don't care about whatever setup we have 4. The locking process has to be "crash safe" such that if the process that locked a file dies, the lock is released quickly, or other processes can find out if the lock is held by a dead process and force a release I've tried a bunch of ideas, looked online, and still don't have a good way to make a system that meets all the requirements above, but I'm not too well-read on this kind of synchronicity problem. Any good ideas? Thanks in advance, -David -- Presenting: mediocre nebula. From mail at microcorp.co.za Mon Jun 12 03:05:02 2006 From: mail at microcorp.co.za (H J van Rooyen) Date: Mon, 12 Jun 2006 09:05:02 +0200 Subject: Intermittent Failure on Serial Port References: <1149934488.780566.265600@j55g2000cwa.googlegroups.com> <1150033060.839717.87860@y43g2000cwc.googlegroups.com> Message-ID: <000201c68df9$a248f020$03000080@hendrik> Serge Orlof wrote: | H J van Rooyen wrote: | > Serge Orloff wrote: | > | > | H J van Rooyen wrote: | > | > Traceback (most recent call last): | > | > File "portofile.py", line 232, in ? | > | > ret_val = main_routine(port, pollstruct, pfifo) | > | > File "portofile.py", line 108, in main_routine | > | > send_nak(port, timeout) # so bad luck - comms error | > | > File "/home/hvr/Polling/lib/readerpoll.py", line 125, in send_nak | > | > port.flush() | > | > IOError: [Errno 29] Illegal seek | > | > close failed: [Errno 29] Illegal seek | > | > | > | | > | | > | > Where can I find out what the Errno 29 really means? | > | > Is this Python, the OS or maybe hardware? | > | | > | It is from kernel: grep -w 29 `locate errno` | > | /usr/include/asm-generic/errno-base.h: #define ESPIPE 29 | > | /* Illegal seek */ | > | | > | man lseek: | > | | > | ERRORS: | > | ESPIPE fildes is associated with a pipe, socket, or FIFO. | > | | > | RESTRICTIONS: | > | Linux specific restrictions: using lseek on a tty device | > | returns ESPIPE. | > | > | > Thanks for the info - so the Kernel sometimes bombs me out - does anybody know | > why the python flush sometimes calls lseek? | | I thought it was your own flush method. If it is file.flush method that | makes the issue more complicated, since stdlib file.flush doesn't call | lseek method. I suggest you run your program using strace to log system | calls, without such log it's pretty hard to say what's going on. The | most interesting part is the end, but make sure you have enough space | for the whole log, it's going to be big. Thanks - I will research and use the strace - havent used it before - I have about 30 gig disk space left... Trouble is that the silly thing works for anything from some hours to some days before it falls over - ugly... Will bleat again when I have some more results... In the meantime I have a datascope attached to the line, and it appears as if it was on the point of sending a nak in response to a perfectly well formed message - almost as if either an interrupt was missed - unlikely at 9600 baud and a pentium 3 at some 2 GHz - or there is a weird hardware error - also unlikely - hardware normally just breaks, does not work for millions for chars and miss one... - I dont like the implication... I also dont really understand the second reference - to a close that failed - anyway we have to wait for the trace... - Hendrik From anton at appsolutions.com Sun Jun 25 04:10:34 2006 From: anton at appsolutions.com (Anton van Straaten) Date: Sun, 25 Jun 2006 08:10:34 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: <1151199196.870389.81960@p79g2000cwp.googlegroups.com> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <1151199196.870389.81960@p79g2000cwp.googlegroups.com> Message-ID: <_xrng.108673$H71.2451@newssvr13.news.prodigy.com> Marshall wrote: > Chris F Clark wrote: > >>I'm particularly interested if something unsound (and perhaps >>ambiguous) could be called a type system. I definitely consider such >>things type systems. > > > I don't understand. You are saying you prefer to investigate the > unsound over the sound? The problem is that there are no useful sound definitions for the type systems (in the static sense) of dynamically-typed languages. Yet, we work with type-like static properties in those languages all the time, as I've been describing. If you want to talk about those properties as though they were types, one of the options is what Chris Clark described when he wrote "I reason about my program using types which I can (at least partially) formalize, but for which there is no sound axiomatic system." >>However, I like my definitions very general and >>vague. Your writing suggests the opposite preference. > > > Again, I cannot understand this. In a technical realm, vagueness > is the opposite of understanding. To me, it sounds like you are > saying that you prefer not to understand the field you work in. The issue as I see it is simply that if we're going to work with dynamically-typed programs at all, our choices are limited at present, when it comes to formal models that capture our informal static reasoning about those programs. In statically-typed languages, this reasoning is mostly captured by the type system, but it has no formal description for dynamically-typed languages. >>To me if >>something works in an analogous way to how a known type system, I tend >>to consider it a "type system". That probably isn't going to be at >>all satisfactory to someone wanting a more rigorous definition. > > > Analogies are one thing; definitions are another. A formal definition is problematic, precisely because we're dealing with something that to a large extent is deliberately unformalized. But as Chris Clark pointed out, "these types are locally sound, i.e. I can prove properties that hold for regions of my programs." We don't have to rely entirely on analogies, and this isn't something that's entirely fuzzy. There are ways to relate it to formal type theory. >>Of >>course, to my mind, the rigorous definitions are just an attempt to >>capture something that is already known informally and put it on a >>more rational foundation. > > > If something is informal and non-rational, it cannot be said to > be "known." As much as I love the view down into that abyss, we're nowhere near being in such bad shape. We know that we can easily take dynamically-typed program fragments and assign them type schemes, and we can make sure that the type schemes that we use in all our program fragments use the same type system. We know that we can assign type schemes to entire dynamically-typed programs, and we can even automate this process, although not without some practical disadvantages. So we actually have quite a bit of evidence about the presence of static types in dynamically-typed programs. Besides, we should be careful not to forget that our formal methods are incredibly weak compared to the power of our intelligence. If that were not the case, there would be no advantage to possessing intelligence, or implementing AIs. We are capable of reasoning outside of fully formal frameworks. The only way in which we are able to develop formal systems is by starting with the informal. We're currently discussing something that so far has only been captured fairly informally. If we restrict ourselves to only what we can say about it formally, then the conversation was over before it began. Anton From onurb at xiludom.gro Fri Jun 16 10:20:39 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 16 Jun 2006 16:20:39 +0200 Subject: a good programming text editor (not IDE) In-Reply-To: <1150411969.535331.43840@g10g2000cwb.googlegroups.com> References: <_xgkg.2317$No6.48542@news.tufts.edu> <1150411969.535331.43840@g10g2000cwb.googlegroups.com> Message-ID: <4492be39$0$9939$636a55ce@news.free.fr> BartlebyScrivener wrote: >>>Most IDEs are rather weak as text editors compared to emacsen. > > > That's true, but even emacs and xemacs don't offer simple automatic > word wrap (i.e. wrap a line without splitting words or putting an eol > or hard carriage return at the end of every line). I don't know if vim > allows this. line-wrapping in an IDE ??? > It's something writers just take for granted in non-Unix > text editors. Ah, ok. It's about vim/emacs as a general text editor. Emacs provides word-wrapping, but true, it split words. I maybe wrong, but I don't think it would be that hard to make it more word-friendly. Now I wonder: what the use for line-wrapping at first ? Both emacs and vim are text *editors*, not text *formatters*. Might be a unix-vs-others cultural difference, but the general use on unix is to use some markup (tex/LaTex, html, ReST or any 'structured-text' variant etc) and the appropriate formater/renderer for presentation stuff. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From fredrik at pythonware.com Tue Jun 27 02:17:34 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 27 Jun 2006 08:17:34 +0200 Subject: Select in Python In-Reply-To: <1151388082.261840.306260@75g2000cwc.googlegroups.com> References: <1151388082.261840.306260@75g2000cwc.googlegroups.com> Message-ID: Dio wrote: > from sys import stdin > from select import select > > while 1: > (rr, wr, er) = select([stdin], [], []) > for fd in rr: > print fd > > program block in the first select(), after I type something and "enter > ", it never block in select() again,why? if there's data waiting to be read from the stream, select() will tell you so every time you ask. From fredrik at pythonware.com Thu Jun 8 05:48:24 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 08 Jun 2006 11:48:24 +0200 Subject: language-x-isms In-Reply-To: <1149759486.695563.110640@g10g2000cwb.googlegroups.com> References: <1149753206.451066.120960@h76g2000cwa.googlegroups.com> <1149759486.695563.110640@g10g2000cwb.googlegroups.com> Message-ID: Alan Kennedy wrote: > On jython 2.1, I use something like this > > #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= > try: > enumerate > except NameError: > def enumerate(iterable): > results = [] ; ix = 0 > for item in iterable: > results.append( (ix, item) ) > ix = ix+1 > return results at least in CPython, using a user-defined enumerate function is a bit slower than using the built-in version. in fact, if performance is important, the following can sometimes be the most efficient way to loop over things: ix = 0 for fibo in my_list: do something with ix and my_list[ix] ix += 1 From esmond.not.pitt at not.bigpond.com Sun Jun 11 02:51:29 2006 From: esmond.not.pitt at not.bigpond.com (EJP) Date: Sun, 11 Jun 2006 06:51:29 GMT Subject: Xah Lee network abuse In-Reply-To: References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148495974.975395.12920@i40g2000cwc.googlegroups.com> <1149998343.493200.144990@h76g2000cwa.googlegroups.com> Message-ID: Philippa Cowderoy wrote: > I'm not aware of a current legal system where it's the case, but I don't > know the details of many of them. Many states have criminal as well as civil libel. http://en.wikipedia.org/wiki/Slander_and_libel From sleepingsquirrel at yahoo.com Wed Jun 21 18:04:23 2006 From: sleepingsquirrel at yahoo.com (Greg Buchholz) Date: 21 Jun 2006 15:04:23 -0700 Subject: What is Expressiveness in a Computer Language References: <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <34aj92h0g7tqi9amhh7k3ieq5n568t0e6f@4ax.com> Message-ID: <1150927463.340542.65690@g10g2000cwb.googlegroups.com> George Neuner wrote: > You can't totally prevent it ... if the index computation involves > types having a wider range, frequently the solution is to compute a > wide index value and then narrow it. But if the wider value is out of > range for the narrow type you have a problem. > ...snip... > > The point is really that the checks that prevent these things must be > performed at runtime and can't be prevented by any practical type > analysis performed at compile time. I'm not a type theorist but my > opinion is that a static type system that could, a priori, prevent the > problem is impossible. I haven't been following this thread too closely, but I thought the following article might be of interest... Eliminating Array Bound Checking through Non-dependent types. http://okmij.org/ftp/Haskell/types.html#branding "There is a view that in order to gain static assurances such as an array index being always in range or tail being applied to a non-empty list, we must give up on something significant: on data structures such as arrays (to be replaced with nested tuples), on general recursion, on annotation-free programming, on clarity of code, on well-supported programming languages. That does not have to be the case. The present messages show non-trivial examples involving native Haskell arrays, index computations, and general recursion. All arrays indexing operations are statically guaranteed to be safe -- and so we can safely use an efficient unsafeAt provided by GHC seemingly for that purpose. The code is efficient; the static assurances cost us no run-time overhead. The example uses only Haskell98 + higher-ranked types. No new type classes are introduced. The safety is based on: Haskell type system, quantified type variables, and a compact general-purpose trusted kernel." From grante at visi.com Fri Jun 30 15:47:55 2006 From: grante at visi.com (Grant Edwards) Date: Fri, 30 Jun 2006 19:47:55 -0000 Subject: How to control permission of file? Message-ID: <12aavvb7vc58b48@corp.supernews.com> When one open()s a file (that doesn't exist) for writing , how does one control that file's permissions (it's "mode" in Unix terms). -- Grant Edwards grante Yow! We just joined the at civil hair patrol! visi.com From george.sakkis at gmail.com Tue Jun 20 07:57:25 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 20 Jun 2006 04:57:25 -0700 Subject: Specifing arguments type for a function References: <200606201328.02784.maric@aristote.info> Message-ID: <1150804645.542646.38570@g10g2000cwb.googlegroups.com> Maric Michaud wrote: > Le Mardi 20 Juin 2006 13:28, Maric Michaud a ?crit : > > if not getattr(arg, '__iter__') and not getattr(arg, '__getitem__') : > > raise ValueError('Function accepts only iterables') # or error handling > > code > > oops, hasattr of course : > > if not hasattr(arg, '__iter__') and not hasattr(arg, '__getitem__') : > raise ValueError('Function accepts only iterables') # or error handling This is ok - in theory. In practice I've found that e.g. strings are more often than not handled as scalars although they are typically iterables. Also tuples may or may not be considered as iterables, depending on what they are used for. The definition of scalar is application-dependent, that's why there is not an isscalar() builtin. George From webraviteja at gmail.com Sun Jun 18 15:23:17 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 18 Jun 2006 12:23:17 -0700 Subject: code is data In-Reply-To: References: <1150574111.415068.255900@p79g2000cwp.googlegroups.com> <1150606118.456390.262620@y41g2000cwy.googlegroups.com> <1150626424.563673.175060@c74g2000cwc.googlegroups.com> <1150650852.275956.249340@p79g2000cwp.googlegroups.com> Message-ID: <1150658597.272001.171840@r2g2000cwb.googlegroups.com> Fredrik Lundh wrote: > Ravi Teja wrote: > > > Web frameworks, which seem to be the rage now in Python community could > > have benefited tremendously from Macro capabilities since they have a > > lot of boiler plate. > > they do? methinks you haven't done much web programming lately... > > You blogged on Django. Let's use that. Don't you think model creation in Django can be represented better, given that it is done often enough? Let's take an example from the official tutorial from http://www.djangoproject.com/documentation/tutorial1/#creating-models class Poll(models.Model): question = models.CharField(maxlength=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): poll = models.ForeignKey(Poll) choice = models.CharField(maxlength=200) votes = models.IntegerField() I don't use Django and I made this up quickly, so please don't pick on subtleties. @Poll: question: char length 200 pub_date('date published'): date @Choice: poll -> Poll choice: char length 200 votes: int The following is my rationale. Annoted variables, symbols and code layout visually cue more efficiently to the object nature than do explicit text definitions. Of course, this is only sensible when there aren't too many of any of those. In that case, the cognitive cost of notation outweighs the representational cost of text. Representational minimalism is troublesome in general code (ala Perl), but not so in a DSL where the context is constrained. I would also like to symbolize field types since they occur so commonly in a definition file and only a few of them are commonly used. I admit though that I find the code below a bit visually jarring and I might use something else. But it serves to illustrate the point. I chose the respective symbols based on their colloquial use and association with the field types. @Poll: $question: length 200 %pub_date('date published') @Choice: poll -> Poll $choice: length 200 #votes Since you are on thread and are a prominent and involved member of the Python community, I would like it if you (or any such other) can provide feedback on the rest of my previous post rather than be dismissive by just a small portion of it. Perhaps, that will give me some insight how these language design decisions are rationally made (I am not strictly a programmer by profession, much less a language designer). From sonja.coussell at gmail.com Wed Jun 14 16:35:25 2006 From: sonja.coussell at gmail.com (sonjaa) Date: 14 Jun 2006 13:35:25 -0700 Subject: memory leak problem with arrays Message-ID: <1150317325.614389.14770@i40g2000cwc.googlegroups.com> Hi I'm new to programming in python and I hope that this is the problem. I've created a cellular automata program in python with the numpy array extensions. After each cycle/iteration the memory used to examine and change the array as determined by the transition rules is never freed. I've tried using "del" on every variable possible, but that hasn't worked. I've read all the forums for helpful hints on what to do, but nothing has worked so far. I've even tried the "python memory verification" (beta) program, which did point to numpy.dtype and numpy.ndarray as increasing objects, before the whole computer crashed. I can supply the code if needed. I'm desperate because this is part of my thesis, and if I can't get this fixed, I'll try another programming language. thanks in advance Sonja From riteshsarraf at gmail.com Wed Jun 14 05:22:15 2006 From: riteshsarraf at gmail.com (Ritesh Raj Sarraf) Date: 14 Jun 2006 02:22:15 -0700 Subject: determining file type Message-ID: <1150276935.270798.5550@i40g2000cwc.googlegroups.com> Hi, I have a funtion named unzipper() which does the work of unzipping the files. Is there a way I can identify what is the type of the file which'll be passed to unzipper(). If yes, I'll be able to make out if it's a zip file or a tar or a bz2 file. Thanks, Ritesh From onurb at xiludom.gro Fri Jun 23 10:50:01 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Fri, 23 Jun 2006 16:50:01 +0200 Subject: * in Python In-Reply-To: <1151072320.621378.218520@r2g2000cwb.googlegroups.com> References: <1151061836.557835.295820@p79g2000cwp.googlegroups.com> <1151065046.668902.23010@g10g2000cwb.googlegroups.com> <449beca5$0$13891$626a54ce@news.free.fr> <1151072320.621378.218520@r2g2000cwb.googlegroups.com> Message-ID: <449bff99$0$19544$636a55ce@news.free.fr> placid wrote: > Bruno Desthuilliers wrote: > (snip) >>Why don't you try by yourself in the Python shell ? One of the nice >>things with Python is that it's quite easy to explore and experiment. > > > i did try it in a Python shell after i learnt what it was. Like i said > *args will be a list, but when i try **args with the following code it > doesnt work "doesn't work" is the most useless description of a problem. > def test(**args): > keys = args.keys() > for key in keys: > print key+"="+args(key) you want args[key], not args(key) And you forget to tell how you called this code and what you got. FWIW: Python 2.4.3 (#1, Jun 3 2006, 17:26:11) [GCC 3.4.6 (Gentoo 3.4.6-r1, ssp-3.4.5-1.0, pie-8.7.9)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> def test(**kw): ... for item in kw.items(): ... print "%s : %s" % item ... >>> test() >>> test(parrot="dead", walk="silly", nose="big") nose : big parrot : dead walk : silly >>> test(**{'answer':42}) answer : 42 >>> -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From esj at harvee.org Thu Jun 22 22:17:49 2006 From: esj at harvee.org (Eric S. Johansson) Date: Thu, 22 Jun 2006 22:17:49 -0400 Subject: need all python dialog equivalent In-Reply-To: <129l40ffu3fsn8a@corp.supernews.com> References: <1150872252.418400.13070@i40g2000cwc.googlegroups.com> <129l40ffu3fsn8a@corp.supernews.com> Message-ID: <449B4F4D.9030609@harvee.org> Thomas Dickey wrote: > Eric S. Johansson wrote: >> hdante at gmail.com wrote: >>> dialog binary is 110 KB. Won't it fit ? > >> missing library. I have ncurses and newt and dialog seems to require >> something called ncursesw. I've been trying to find the Python newt > > "seems to require" if you're installing some package. > dialog builds/works against either ncurses/ncursesw ncursews was what the binary image of dialogue was complaining about. But that's all behind me now because I'm using http://excess.org/urwid/ as was suggested by someone else. So far, it works pretty well. There are errors reported that aren't obvious in terms of what they indicate but like others software packages, once you acquire the scar tissue, it becomes something you tolerate. ---eric From 63q2o4i02 at sneakemail.com Sat Jun 17 17:10:03 2006 From: 63q2o4i02 at sneakemail.com (63q2o4i02 at sneakemail.com) Date: 17 Jun 2006 14:10:03 -0700 Subject: a good programming text editor (not IDE) In-Reply-To: <1150563080.448650.38090@g10g2000cwb.googlegroups.com> References: <_xgkg.2317$No6.48542@news.tufts.edu> <1150406662.900552.46650@u72g2000cwu.googlegroups.com> <1150533881.540254.270400@i40g2000cwc.googlegroups.com> <1150563080.448650.38090@g10g2000cwb.googlegroups.com> Message-ID: <1150578603.338286.282360@f6g2000cwb.googlegroups.com> > > Cream is a package built on top of vim that presents a more "Windows > friendly" face to the vim/gvim editor. Cool thanks, I'll check it out. From spohle at gmail.com Sat Jun 24 01:06:50 2006 From: spohle at gmail.com (spohle) Date: 23 Jun 2006 22:06:50 -0700 Subject: tkinter modifying multiple widgets with one scrollbar Message-ID: <1151125610.608131.35510@r2g2000cwb.googlegroups.com> hi how can i modify multiple widgets with one scrollbar ? thanks in advance sven From sdcook55 at sbcglobal.net Sun Jun 11 16:10:22 2006 From: sdcook55 at sbcglobal.net (Stan Cook) Date: Sun, 11 Jun 2006 20:10:22 GMT Subject: how to get the length of a number Message-ID: Can anyone tell me how to get the length of a number. I know len(string) will get the length of a string, but it doesn't like len(int). I seem to remember something like %s string. I tried to set a variable = to %s int, but that doesn't work. Is there a function I've forgotten about to convert an integer to a string? Regards Stan From simon at brunningonline.net Sun Jun 11 07:52:08 2006 From: simon at brunningonline.net (Simon Brunning) Date: Sun, 11 Jun 2006 12:52:08 +0100 Subject: regexp questoin In-Reply-To: <1149900282.616379.216200@h76g2000cwa.googlegroups.com> References: <1149868825.331142.280180@f6g2000cwb.googlegroups.com> <1149900282.616379.216200@h76g2000cwa.googlegroups.com> Message-ID: <8c7f10c60606110452w1da17402lbcb28f0d3ed1409c@mail.gmail.com> On 9 Jun 2006 17:44:42 -0700, micklee74 at hotmail.com wrote: > actually, i am doing an application that allows user to delete files by > entering an input pattern. If you are looking to match filenames, you might want to have a look at the fnmatch and glob modules. The patterns that they support are less powerful and flexible than regex patters, but much simpler, and specifically designed with filename matching in mind. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From cdsmith at twu.net Tue Jun 20 10:19:53 2006 From: cdsmith at twu.net (Chris Smith) Date: Tue, 20 Jun 2006 08:19:53 -0600 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> Message-ID: Rob Thorpe wrote: > I'm not talking about correctness, I'm talking about typing. > Since you wrote that, I've come to understand that you meant something specific by "property" which I didn't understand at first. From my earlier perspective, it was obvious that correctness was a property of a value. I now realize that you meant a property that's explicitly associated with the value and plays a role in determining the behavior of the language. Sorry for the confusion. > No, that isn't what I said. What I said was: > "A language is latently typed if a value has a property - called it's > type - attached to it, and given it's type it can only represent values > defined by a certain class." No, to answer Andreas' concern, you would only need to say: ... if a value has a property - called it's type - attached to it, and the language semantics guarantees that only values defined by a certain class may have that same property attached. > Easy, any statically typed language is not latently typed. I'm actually not sure I agree with this at all. I believe that reference values in Java may be said to be latently typed. This is the case because each reference value (except null, which may be tested separately) has an explicit property (called its "class", but surely the word doesn't make any difference), such that the language semantics guarantees that only a certain class of values may have that same property, and the property is used to determine behavior of the language in many cases (for example, in the case of type-based polymorphism, or use of Java's instanceof operator). Practically all class-based OO languages are subject to similar consideration, as it turns out. I'm unsure whether to consider explicitly stored array lengths, which are present in most statically typed languages, to be part of a "type" in this sense or not. -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation From iant at the-wire.com Wed Jun 14 11:20:06 2006 From: iant at the-wire.com (moonman) Date: 14 Jun 2006 08:20:06 -0700 Subject: cos: "Integer Required"?!?!?!? In-Reply-To: <1149782419.886876.145060@c74g2000cwc.googlegroups.com> References: <1149777499.262577.318070@u72g2000cwu.googlegroups.com> <2aqdnQ8uYZLpoxXZnZ2dnUVZ_qadnZ2d@comcast.com> <1149780685.768525.276850@h76g2000cwa.googlegroups.com> <1149782419.886876.145060@c74g2000cwc.googlegroups.com> Message-ID: <1150298406.865551.285370@f6g2000cwb.googlegroups.com> It appears that the cause of this problem was indirect. I input something incorrect as an argument to an xplane sdk function and the cos/integer type error followed. Thanks for the help. The diagnostic functions I learned in this thread will be very helpful in the future. moonman wrote: > I'm using ActiveState PythonV2.4.1 > > I'm certainly not affecting 'math'. I wonder if the XPlane SDK Python > binding is touching anything. > > I'll download the latest ActiveState Python and keep on plugging. > > Thanks! > > > Mikael Olofsson wrote: > > moonman wrote: > > > print self.ACphi, type(self.ACphi) yields: > > > 19412557 > > > > > > value = XPLMGetDataf(self.ACphi); print value type(value ) yields: > > > -0.674469709396 > > > > > > print math.radians(XPLMGetDataf(self.ACphi)), > > > type(math.radians(XPLMGetDataf(self.ACphi))) yields: > > > > > > TypeError > > > : > > > an integer is required > > > > > > Am I totally missing something about 'math'. Does it really expect an > > > int? > > > > Not my Python: > > > > >>> math.radians(-0.674469709396) > > -0.011771717133929535 > > > > This all seems very confusing. Have you tried exactly the above? > > > > Do you perhaps have a module of your own called math, that Python might > > be importing? Or is your math not a module, but some other object that > > happens to have a method called radians, that expects an int? Or have > > you accidentally redefined math.radians? > > > > /MiO From micklee74 at hotmail.com Fri Jun 9 12:00:25 2006 From: micklee74 at hotmail.com (micklee74 at hotmail.com) Date: 9 Jun 2006 09:00:25 -0700 Subject: regexp questoin Message-ID: <1149868825.331142.280180@f6g2000cwb.googlegroups.com> hi i created a script to ask user for an input that can be a pattern right now, i use re to compile that pattern pat = re.compile(r"%s" %(userinput) ) #userinput is passed from command line argument if the user key in a pattern , eg [-] , and my script will search some lines that contains [-] pat.findall(lines) but the script produce some error: sre_constants.error: unexpected end of regular expression how can i successful catch patterns such as "[-]" in my regexp compilation where input is unknown...? thanks From pjb at informatimago.com Thu Jun 22 08:33:57 2006 From: pjb at informatimago.com (Pascal Bourguignon) Date: Thu, 22 Jun 2006 14:33:57 +0200 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150902275.129780.50260@p79g2000cwp.googlegroups.com> <1150918629.818145.143220@y41g2000cwy.googlegroups.com> <4fv081F1jh4ifU1@individual.net> <1150967543.947096.72840@g10g2000cwb.googlegroups.com> <4fv84rF1kp06kU1@individual.net> <4fvfuiF1kncqtU1@individual.net> Message-ID: <87ejxh9xoq.fsf@thalassa.informatimago.com> Pascal Costanza writes: > Andreas Rossberg wrote: >> Pascal Costanza wrote: >>> >>> Consider a simple expression like 'a + b': In a dynamically typed >>> language, all I need to have in mind is that the program will >>> attempt to add two numbers. In a statically typed language, I >>> additionally need to know that there must a guarantee that a and b >>> will always hold numbers. >> I'm confused. Are you telling that you just write a+b in your >> programs without trying to ensure that a and b are in fact numbers?? > > Basically, yes. > > Note that this is a simplistic example. Consider, instead, sending a > message to an object, or calling a generic function, without ensuring > that there will be applicable methods for all possible cases. When I > get a "message not understood" exception, I can then decide whether > that kind of object shouldn't be a receiver in the first place, or > else whether I should define an appropriate method. I don't want to be > forced to decide this upfront, because either I don't want to be > bothered, or maybe I simply can't because I don't understand the > domain well enough yet, or maybe I want to keep a hook to be able to > update the program appropriately while it is running. Moreover, a good proportion of the program and a good number of algorithms don't even need to know the type of the objects they manipulate. For example, sort doesn't need to know what type the objects it sorts are. It only needs to be given a function that is able to compare the objects. Only a few "primitive" functions need specific types. So basically, you've got a big black box of applicaition code in the middle that doesn't care what type of value they get, and you've got a few input values of a specific type, a few processing functions needing a specific type and returning a specific type, and a few output values that are expected to be of a specific type. At anytime, you may change the type of the input values, and ensure that the needed processing functions will be able to handle this new input type, and the output gets mapped to the expected type. Why should adding a few functions or methods, and providing input values of a new type be rejected from a statically checked point of view by a compiled program that would be mostly bit-for-bit the same with or without this new type? Of course, in the process of so modifying the program, we may get some dynamically detected type errors that we would correct as Pascal indicated. -- __Pascal Bourguignon__ http://www.informatimago.com/ "Specifications are for the weak and timid!" From deo at corpit.ru Thu Jun 29 09:46:01 2006 From: deo at corpit.ru (Egor Duda) Date: Thu, 29 Jun 2006 17:46:01 +0400 Subject: problems with mimify.mime_encode_header Message-ID: <44A3D999.4020605@corpit.ru> I'm trying to use mimify module and have a problem with mime_encode_header function. Below is the testcase #!/usr/bin/python # -*- coding: utf-8 -*- import mimify mimify.CHARSET = 'utf-8' print mimify.mime_encode_header('Subject: ???? ?.\n'); ?he output is: Subject: =?utf-8?Q?=D1=82=D0=B5=D1=81=D1=82?= ?. Please note that the last character (before dot) is not quoted, and resulting string is not 8bit clean. Is it incorrect behavior, or i'm calling mime_encode_header in a way it's not supposed to be called? egor From onurb at xiludom.gro Wed Jun 28 06:44:31 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Wed, 28 Jun 2006 12:44:31 +0200 Subject: Immutability In-Reply-To: References: Message-ID: <44a25d90$0$9287$636a55ce@news.free.fr> Nick Maclaren wrote: > The way that I read it, Python allows only values (and hence types) > to be immutable, I don't understand this sentence. Some types are immutable, some are not. This has nothing to do with "values" (FWIW, everything in Python is an object, there's no 'primitive type' vs 'object type' distinction) > and not class members. If an attribute is of an immutable type, it will still be immutable. If what you want is 'read-only' attributes, then use properties: class MyClass(object): def __init__(self, name): self._name = name name = property(fget=lambda self : self._name) >>> m = MyClass('parrot') >>> m.name 'parrot' >>> m.name = "toto" Traceback (most recent call last): File "", line 1, in ? AttributeError: can't set attribute >>> > The nearest approach to the > latter is to use the name hiding conventions. naming conventions are used to denote what's API and what's implementation. But this won't make an attribute read-only. If you want an attribute to be part of the API *but* read-only, use the solution above. HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From invalidemail at aerojockey.com Fri Jun 9 19:31:18 2006 From: invalidemail at aerojockey.com (Carl Banks) Date: 9 Jun 2006 16:31:18 -0700 Subject: Allowing zero-dimensional subscripts In-Reply-To: References: <1149801040.936452.26270@i40g2000cwc.googlegroups.com> <1149807149.516004.48590@f6g2000cwb.googlegroups.com> <1149832139.948242.64160@f6g2000cwb.googlegroups.com> <1149844947.822478.128580@g10g2000cwb.googlegroups.com> Message-ID: <1149895878.694150.215960@j55g2000cwa.googlegroups.com> Steve Holden wrote: > Carl Banks wrote: > > Steve Holden wrote: > > > >>Hey, I have an idea, why don't we look at the language reference manual > >>instead of imagining how we think it might work! > > > > > > I don't know. Sounds risky. > > > > > > > >>In section 3.2 we find: > >> > >> > >>""" > >>Tuples > >>The items of a tuple are arbitrary Python objects. Tuples of two or more > >>items are formed by comma-separated lists of expressions. A tuple of one > >>item (a `singleton') can be formed by affixing a comma to an expression > >>(an expression by itself does not create a tuple, since parentheses must > >>be usable for grouping of expressions). An empty tuple can be formed by > >>an empty pair of parentheses. > >>""" > >> > >>So it seems that your speculation is false. Section 2.6 specifically > >>defines "[" and "]" as delimiters. Section 5.3.2 defines a subscription > >>(a term I've not really grown to love, but what the heck) as > >> > >>subscription ::= primary "[" expression_list "]" > >> > >>and section 5.12, which defines expression_list, explicitly says > >> > >>"""An expression list containing at least one comma yields a tuple.""". > >> > >>So it would appear that while your change might be very convenient to > >>allow you to refer to scalar values as zero-dimensional arrays, it > >>doesn't really fit into Python's conceptual framework. Sorry. > > > > > > Yes, that would appear to be so. You would have a point... if the > > documentation were correct. Only it's not. > > > > According to the reference manual, the rule for an expression_list is: > > > > expression_list ::= expression ( "," expression )* [","] > > > > But take the following legal Python subscripted array: > > > > a[1:2,...,3:4] > > > But the element inside the brackets there isn't an expression-list, > it's a slicing (see section 5.3.2). Section 5.3.2 says an expression-list is what's inside the brackets (you quoted this rule yourself). Section 5.12 says an expression-list consissts of comma-separated expressions. But 1:2 and ... aren't expressions. I only brought this up to point out that the docs were not exactly correct, and in particular it swept an important distinction (for this nit-picky discussion) under the rug. [snip] > > trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME > > subscriptlist: subscript (',' subscript)* [','] > > sliceop: ':' [test] > > subscript: '.' '.' '.' | test | [test] ':' [test] [sliceop] > > testlist: test (',' test)* [','] > > > The simplification of the grammar is explicitly documented: [snip] Nice to know. > > Clearly, the grammar rule used for list subscript is different from the > > one used for list of expressions (for some reason, what an ordinary > > person would call an expression is called a "test" in the grammar, > > whereas "expr" is a non-short-circuiting expression). > > > > So there's a regular way to create non-empty tuples, and a subscript > > way. > > > > And there's a regular way to create an empty tuple... but not a > > subscript way. > > > > So I'd say this change fits the conceptual framework of the tuple quite > > well; in fact, it makes subscript tuples more parallel to their regular > > counterparts. > > Although this debate is beginning to make me sound like one, I am really > not a language lawyer. However, I should point out that what you are > describing as a "tuple" should more correctly be described as a > "slice-list" once you include slices or an ellipsis as elements. > Slicings are described, as I am fairly sure you know, in section 5.3.3. No, I don't think I am. I was careful to distinguish between grammar rules and tuples. subscriptlist and testlist are grammar rules. "Evaluation" of both of these guys can create a tuple. The two grammar rules have exactly the same relationship to the tuple: an testlist with a comma creates a tuple, a subscriptlist with a comma creates a tuple. But note neither testlist nor subscriptlist can create an empty tuple. You need a special case for that--only there's no special special case for subscripts. (The visual effect, as OP noted, is that you need parentheses for the empty tuple, but never need them for any other subscript.) > >>One further point: if you really do conceptualize scalars as > >>zero-dimensional arrays, where is the value conceptually stored? > > > > Think of it this way: an array with n-dimensions of length 3 would have > > 3**n total entries. How many entries would a 0-dimensional array have? > > 3**0 == 1. > > > > Numeric has had zero-dimensional arrays for a long time, and has had no > > problem storing them. Think of the rule for accessing an element of an > > array: it's a base pointer + sum (indices*stride) for all indices. Now > > generalize it down to zero: there are no indices, so the scalar is > > stored at the base pointer. > > I can see that, and it doesn't seem unreasonable. Fortunately your > persistence has goaded me into determining the point that *did* seem > unreasonable to me: you were falsely trying to equate slicings and tuples. The OP might have been; I wasn't. But that's fair enough; everyone should be clear on what's happening behind the scenes. > Having said all of which, there probably *is* a case for proposing that > an empty slicing become syntactically acceptable, so why not write the > PEP and go for it? Well, I'm only +0 on it, so I'll leave it to the OP. I was mainly concerned with how the language reference was obscuring what I felt were important distinctions. Carl Banks From faulkner612 at comcast.net Mon Jun 26 02:12:46 2006 From: faulkner612 at comcast.net (faulkner) Date: 25 Jun 2006 23:12:46 -0700 Subject: Python "sub-interpreter," security In-Reply-To: <1151298465.155786.317310@u72g2000cwu.googlegroups.com> References: <1151298465.155786.317310@u72g2000cwu.googlegroups.com> Message-ID: <1151302366.426298.202590@i40g2000cwc.googlegroups.com> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496746 jvvhie at gmail.com wrote: > Hello, I am writing a pure-Python game engine that interprets the code > of game objects within the same process with the exec statement. My > main goal is to make as much power available as possible and exec seems > like the best way to do that. > > This is my "proof-of-concept" code(only 18 lines and some whitespace, > including the test): > > http://people.ucsc.edu/~jhofmann/programmables.py > > I showed this to the Pygame list and recieved some interest and a > completely different, more sophisticated implementation: > > http://codereactor.net/~shang/interpret/ > > As-is, both versions are wide-open security holes. I think that I can > patch them up if I run checks on the statements and eliminate all > language features that pose risks. Then, features that are useful but > not needed at their full capacity can be accessed through functions > designed to be secure. Forcing a crash is not considered an exploit for > this purpose(since it's a game engine - if it crashes, the user can > recover and lose no data) > > What I'd like to know is, is it possible to meet this level of > security, and if so, which features have to be eliminated? > > The two that I'm sure should go are module imports and self-modifying > code. But in the latter case, I don't know all the ways that might be > done. It seems like a very complicated problem, and if I can't solve it > I might leave the whole thing unsecured. From vincenzo_yahoo_addressguard-gmane at yahoo.it Mon Jun 5 05:15:46 2006 From: vincenzo_yahoo_addressguard-gmane at yahoo.it (Vincenzo Ciancia) Date: Mon, 05 Jun 2006 11:15:46 +0200 Subject: HOST - dreamhost.com / Liberality (Hosting, Basic Requirement) References: <4482CDDA.9060905@lazaridis.com> Message-ID: <4483f641$0$29729$4fafbaef@reader2.news.tin.it> Joachim Durchholz wrote: >> People can then decide if they still wish to send the abuse complain >> (e.g. can follow a link within the autoresponder). > > Nope. Finding out the provider is enough of a barrier. Additional > barriers are not really necessary. > Xah Lee has been irritating people for months. Come on! What does it cost to ignore a thread compared to what it costs to allow arbitrary censorship? Also, what would it cost to this guy to get another account and irritate people again for many years until termination of the new account? The only difference here is that someone legally decided that he could not express himself for a while. This will not prevent him coming back. There are lots of people that irritate me in italian politics for example, telling bullshit all the time :) but I do not hope they will be censored :) Again, in kmail I press the "i" key when I see Xah Lee and I live happier. Bye Vincenzo -- Please note that I do not read the e-mail address used in the from field but I read vincenzo_ml at yahoo dot it Attenzione: non leggo l'indirizzo di posta usato nel campo from, ma leggo vincenzo_ml at yahoo dot it From alsmeirelles at gmail.com Wed Jun 7 23:27:14 2006 From: alsmeirelles at gmail.com (alsmeirelles at gmail.com) Date: 7 Jun 2006 20:27:14 -0700 Subject: Select hangs after some reads Message-ID: <1149737234.816833.177710@j55g2000cwa.googlegroups.com> Hi, I'm building a multithreaded application and I encountered a tiny and annoying problem. I use a select to wait for data to be read from a socket, after some reads, the select simply blocks and stays that way until I close the connection on the other side of the socket. When the socket is closed on the writer end the select releases and then I get only empty strings from the socket. My question is this: Why did it block? The reading has never ended, every test I make I write 50 requests (wich are strings) to the socket and I have read the maximum of 34 requests. I'm using winPdb to take a closer look on what's happening and I see the threads blocked on this same select. If I send anything more through the socket, the select releases for a thread, despite the other data that is still unread. This is the select: rd,w,e = select.select([self.rfd],[],[]) self.rfd is the fileno of the file object returned by the makefile method from the socket object. I know that's some buffer behavior that I'm missing but I don't know what it is. anything is helpfull, If I'm beeing stupid you can say it. thanks From bdesth.quelquechose at free.quelquepart.fr Sun Jun 4 20:39:37 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 05 Jun 2006 02:39:37 +0200 Subject: re beginner In-Reply-To: <1149454925.752919.276020@y43g2000cwc.googlegroups.com> References: <1149454071.232909.197270@y43g2000cwc.googlegroups.com> <1149454925.752919.276020@y43g2000cwc.googlegroups.com> Message-ID: <44834dad$0$6192$626a54ce@news.free.fr> bearophileHUGS at lycos.com a ?crit : >>strings = islice(data2, 0, len(data), 2) >>numbers = islice(data2, 1, len(data), 2) > > > This probably has to be: > > strings = islice(data2, 0, len(data2), 2) > numbers = islice(data2, 1, len(data2), 2) try with islice(data2, 0, None, 2) From rschroev_nospam_ml at fastmail.fm Thu Jun 15 18:08:38 2006 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Thu, 15 Jun 2006 22:08:38 GMT Subject: Python in Windows ng In-Reply-To: <449131ab$0$10456$afc38c87@news.optusnet.com.au> References: <449131ab$0$10456$afc38c87@news.optusnet.com.au> Message-ID: veritas schreef: > Can anyone tell me of a good newsgroup for running/programming Python on > Windows OS ? There is the python-win32 at python.org mailing list which you can read as a newsgroup (gmane.comp.python.windows) via gmane.org. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From cdsmith at twu.net Wed Jun 21 22:22:06 2006 From: cdsmith at twu.net (Chris Smith) Date: Wed, 21 Jun 2006 20:22:06 -0600 Subject: What is a type error? References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <7i3mg.204167$8W1.155367@fe1.news.blueyonder.co.uk> <44992e6c$2$664$bed64819@news.gradwell.net> <%Igmg.464974$xt.353729@fe3.news.blueyonder.co.uk> Message-ID: David Hopwood wrote: > Typical programming languages have many kinds of semantic error that can occur > at run-time: null references, array index out of bounds, assertion failures, > failed casts, "message not understood", ArrayStoreExceptions in Java, > arithmetic overflow, divide by zero, etc. > > Conventionally, some of these errors are called "type errors" and some are > not. But there seems to be little rhyme or reason to this categorization, as > far as I can see. If in a particular language, both array index bounds errors > and "message not understood" can occur at run-time, then there's no objective > reason to call one a type error and the other not. Both *could* potentially > be caught by a type-based analysis in some cases, and both *are not* caught > by such an analysis in that language. Incidentally, yes! Filtering out the terminology stuff [as hard as this may be to believe on USENET where half the world seems to be trolls, I really was not so aware when I originally posted of how some communities use terminology and where the motivations come from], this was my original point. In the static sense, there is no such thing as a type error; only an error that's caught by a type system. I don't know if the same can be said of dynamic types. Some people here seem to be saying that there is a universal concept of "type error" in dynamic typing, but I've still yet to see a good precise definition (nor a good precise definition of dynamic typing at all). In either case it doesn't make sense, then, to compare how static type systems handle type errors versus how dynamic systems handle type errors. That's akin to asking how comparing how much many courses are offered at a five star restaurant versus how many courses are offered by the local university. (Yes, that's an exaggeration, of course. The word "type" in the static/dynamic typing world at least has a closer to common root.) > A more consistent terminology would reserve "type error" for errors that > occur when a typechecking/inference algorithm fails, or when an explicit > type coercion or typecheck fails. I am concerned as to whether that actually would turn out to have any meaning. If we are considering array length bounds checking by type systems (and just to confuse ourselves, by both static and dynamic type systems), then is the error condition that gets raised by the dynamic system a type error? Certainly, if the system keeps track of the fact that this is an array of length 5, and uses that information to complain when someone tries to treat the array as a different type (such as an array of length >= 7, for example), certainly that's a type error, right? Does the reference to the seventh index constitute an "explicit" type coercion? I don't know. It seems pretty explicit to me, but I suspect some may not agree. The same thing would certainly be a type error in a static system, if indeed the static system solved the array bounds problem at all. While this effort to salvage the term "type error" in dynamic languages is interesting, I fear it will fail. Either we'll all have to admit that "type" in the dynamic sense is a psychological concept with no precise technical definition (as was at least hinted by Anton's post earlier, whether intentionally or not) or someone is going to have to propose a technical meaning that makes sense, independently of what is meant by "type" in a static system. > In the terminology I'm suggesting, the object has no type in this language > (assuming we're talking about a Smalltalk-like language without any type system > extensions). I suspect you'll see the Smalltalk version of the objections raised in response to my post earlier. In other words, whatever terminology you think is consistent, you'll probably have a tough time convincing Smalltalkers to stop saying "type" if they did before. If you exclude "message not understood" as a type error, then I think you're excluding type errors from Smalltalk entirely, which contradicts the psychological understanding again. -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation From sybrenUSE at YOURthirdtower.com.imagination Sun Jun 4 18:21:21 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Mon, 5 Jun 2006 00:21:21 +0200 Subject: Max function question: How do I return the index of the maximum value of a list? References: <1149459320.802652.186930@i40g2000cwc.googlegroups.com> Message-ID: jj_frap enlightened us with: > When I try to print the "winner" (I've not coded for kicker strength > and ties yet) via the max function, it returns the maximum value in > the list rather than the index associated with that value. > > How do I return the index? You can't even be sure it exists - there might be multiple maximum values. What would you expect in such a case? Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From cito at online.de Mon Jun 5 07:04:58 2006 From: cito at online.de (Christoph Zwerschke) Date: Mon, 05 Jun 2006 13:04:58 +0200 Subject: How to search for substrings of a string in a list? In-Reply-To: References: Message-ID: Girish Sahani schrieb: > Given a length k string,i want to search for 2 substrings (overlap > possible) in a list consisting of length k-1 strings. These 2 substrings > when 'united' give the original string. > e.g given 'abc' i want to search in the list of 2-length strings > ['ab',ac','cd','bc','bd'] to extract either > 1) 'ab and 'ac' OR ('a' common) > 2) 'ab' and 'bc' OR ('b' common) > 3) 'ac' and 'bc' ('c' common) Here is a simple brute force solution that also works for different lengths of your strings: complete = 'abc' partial = ['ab','ac','cd','bc','bd'] for i1, s1 in enumerate(partial): for s2 in partial[i1+1:]: if set(s1).union(set(s2)) == set(complete): print s1, s2 -- Christoph From camillo at rockit.it Mon Jun 19 04:40:23 2006 From: camillo at rockit.it (camillo at rockit.it) Date: 19 Jun 2006 01:40:23 -0700 Subject: Check if a file is closed Message-ID: <1150706423.217609.164870@y41g2000cwy.googlegroups.com> How to check if a file is closed? On Win32 you can call CreateFile with write and share write and if it raises an error, the file is closed. How to do it in Python??? Thanks, Camillo From jo at durchholz.org Wed Jun 14 15:04:34 2006 From: jo at durchholz.org (Joachim Durchholz) Date: Wed, 14 Jun 2006 21:04:34 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: <2006061410510511272-raffaelcavallaro@pasdespamsilvousplaitmaccom> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <2006061410510511272-raffaelcavallaro@pasdespamsilvousplaitmaccom> Message-ID: Raffael Cavallaro schrieb: > On 2006-06-14 09:42:25 -0400, torbenm at app-1.diku.dk (Torben ?gidius > Mogensen) said: > >> It takes longer for the average >> programmer to get the program working in the dynamically typed >> language. > > Though I agree with much of your post I would say that many here find > the opposite to be true - it takes us longer to get a program working in > a statically typed language because we have to keep adding/changing > things to get the compiler to stop complaining and actually compile and > run I think Torben was assuming a language with type inference. You write only those type annotations that really carry meaning (and some people let the compiler infer even these). > a program which would be perfectly permissible in a dynamically > typed language such as common lisp - for example - heterogeneous lists > and forward references to as yet non-existent functions. Um... heterogenous lists are not necessarily a sign of expressiveness. The vast majority of cases can be transformed to homogenous lists (though these might then contain closures or OO objects). As to references to nonexistent functions - heck, I never missed these, not even in languages without type inference :-) I don't hold that they are a sign of *in*expressiveness either. They are just typical of highly dynamic programming environments such as Lisp or Smalltalk. Regards, Jo From news00 at wilec.net Thu Jun 29 05:28:28 2006 From: news00 at wilec.net (Al) Date: Thu, 29 Jun 2006 11:28:28 +0200 Subject: Exchanging data with a C program using shared memory (sysV IPC) References: <1151445486.353407.32930@75g2000cwc.googlegroups.com> Message-ID: "slacker" writes: Hello slacker, > Al wrote: > >> I want my python application to communicate with an legacy C program which >> read/write data in a shared memory (Unix Sys V IPC). > > Have you looked at the dl module? Types and portability aside, it > might provide you with what you need. > > Cheers, > > - slacker Thank you very much for your advice. I didn't use the dl module, but searching information on dl, led me to the 'new' ctype one which is perfect for my use. -- Al From jim.lewis at miclog.com Sun Jun 4 09:07:01 2006 From: jim.lewis at miclog.com (Jim Lewis) Date: 4 Jun 2006 06:07:01 -0700 Subject: Pyrex list/array In-Reply-To: <4482CF65.1070506@lexicon.net> References: <1149360983.373137.200740@i39g2000cwa.googlegroups.com> <448239EB.6010706@lexicon.net> <1149415140.458073.65310@c74g2000cwc.googlegroups.com> <4482CF65.1070506@lexicon.net> Message-ID: <1149426421.864274.319290@c74g2000cwc.googlegroups.com> > cunningly concealed in the last place one would think of finding it: under the heading "Mailing List" on the Pyrex home page :-) Hmmm - maybe I should try the scroll bar occassionally ;-) > Do you mean alist[x:x+n] == alist[y:y+n] ? OK, probably you an Skip are right - let's see if I missed something at the Python level. There are essentially two differences from your snip above. I am trying to compute n and there are multiple (under 10) lists. Size of lists are typically under 100 ints. > ...See what psyco makes of that. I'm doing a similar straightforward loop approach but it's too slow. Jim From aum at spam.me.please Thu Jun 29 06:49:21 2006 From: aum at spam.me.please (aum) Date: Thu, 29 Jun 2006 22:49:21 +1200 Subject: ftplib.FTP.retrbinary() hangs on completion Message-ID: Hi, I've been having some headaches with FTP.retrbinary() hanging on completion. I'm only seeing the symptom when downloading a 700k .bmp file in passive mode. What happens is that after all the data comes in over the data connection, .retrbinary() does 'return self.voidresp()'. This has a call chain ending with 'self.file.readline()'. To investigate, I overrode the .getline() method with one which replaces the self.file.readline() with a self.sock.recv(1) loop, and determined from this that after the last byte of binary data comes in on the data connection, not a single byte comes in on the control connection. Not sure if this is a deeper underlying socket issue - I'm running python2.3 on debian unstable linux. For a workaround, I've overridden retrbinary, so that it sets a socket timeout on the control connection prior to doing the last .voidresp() call, and in the event of timeout, it closes the control connection, reconnects and logs in again - very ugly. Can anyone share some light, or offer a better workaround? -- Cheers aum From sjmachin at lexicon.net Fri Jun 2 22:12:20 2006 From: sjmachin at lexicon.net (John Machin) Date: Sat, 03 Jun 2006 12:12:20 +1000 Subject: Seg fault in python extension module In-Reply-To: References: Message-ID: <4480F004.7000602@lexicon.net> On 3/06/2006 9:51 AM, Luke Miller wrote: > Hello, > > I am working on my first python module based on a c program. The > module builds and installs OK using dist-utils, and imports fine into > python. However, when I try and use the one wrapper > ("modgl.glVertex4f(1, 2, 3, 1)") in the module, it seg faults. > > Can anyone spot why this isn't working, or recommend a way to debug > these things. > > Thanks, > Luke > > #include > > static PyObject *_wrap_glVertex4f(PyObject *self, PyObject *args) { > PyObject *resultobj = NULL; > float arg1 ; > float arg2 ; > float arg3 ; > float arg4 ; > PyObject * obj0 = 0 ; > PyObject * obj1 = 0 ; > PyObject * obj2 = 0 ; > PyObject * obj3 = 0 ; > > if(!PyArg_ParseTuple(args,(char > *)"OOOO:glVertex4f",&obj0,&obj1,&obj2,&obj3)) goto fail; > { > arg1 = (float)(PyFloat_AsDouble(obj0)); Not testing for an error after an API call is just asking for trouble. > } > { > arg2 = (float)(PyFloat_AsDouble(obj1)); > } > { > arg3 = (float)(PyFloat_AsDouble(obj2)); > } > { > arg4 = (float)(PyFloat_AsDouble(obj3)); > } You are making it really hard for yourself. Try this: if(!PyArg_ParseTuple(args,"ffff:glVertex4f",&arg1,&arg2 etc etc The batteries are already included. Using the code for the precise type that you want gives you checking for type mismatches, a with sensible error message. > glVertex4f(arg1,arg2,arg3,arg4); You don't declare this function before calling it. That's dangerous. > > Py_INCREF(Py_None); resultobj = Py_None; > return resultobj; > fail: > return NULL; > }; > > > static PyMethodDef modglMethods[] = { > { (char *)"glVertex4f", _wrap_glVertex4f, METH_VARARGS, NULL}, > { NULL, NULL, 0, NULL } > }; > > > PyMODINIT_FUNC modgl(void) I can't see how you were able to import the module. For "import modgl" to work, your initialisation function should be called "initmodgl". > { > (void) Py_InitModule("modgl", modglMethods); > }; > > You are writing an extension, not embedding Python. You don't need a main(). Lose it. > int > main(int argc, char *argv[]) > { > /* Pass argv[0] to the Python interpreter */ > Py_SetProgramName(argv[0]); > > /* Initialize the Python interpreter. Required. */ > Py_Initialize(); > > /* Add a static module */ > initmodgl(); > return 0; > }; Below is a cutdown version of your module, that returns a value so that you can see that it is working. You might like to use that as a base. Here it is working: |>>> import modgl |>>> modgl.glVertex4f(1, 2, 3, 4) 10.0 |>>> modgl.glVertex4f(1, 2, "three", 4) Traceback (most recent call last): File "", line 1, in ? TypeError: a float is required |>>> HTH, John 8<--- #include static PyObject * _wrap_glVertex4f(PyObject *self, PyObject *args) { PyObject *resultobj = NULL; float arg1, arg2, arg3, arg4; if(!PyArg_ParseTuple(args,"ffff:glVertex4f",&arg1,&arg2,&arg3,&arg4)) goto fail; /* glVertex4f(arg1,arg2,arg3,arg4); */ /* Py_INCREF(Py_None); resultobj = Py_None; */ resultobj = Py_BuildValue("d", (double)(arg1 + arg2 + arg3 + arg4)); return resultobj; fail: return NULL; }; static PyMethodDef modglMethods[] = { { (char *)"glVertex4f", _wrap_glVertex4f, METH_VARARGS, NULL}, { NULL, NULL, 0, NULL } }; PyMODINIT_FUNC initmodgl(void) { (void) Py_InitModule("modgl", modglMethods); }; 8<--- From sjmachin at lexicon.net Fri Jun 23 22:14:16 2006 From: sjmachin at lexicon.net (John Machin) Date: Sat, 24 Jun 2006 12:14:16 +1000 Subject: Trouble including Python.h In-Reply-To: <1151099498.381282.64590@b68g2000cwa.googlegroups.com> References: <1151099498.381282.64590@b68g2000cwa.googlegroups.com> Message-ID: <449c9ff6$1@news.eftel.com> On 24/06/2006 7:51 AM, Marcelo Gosling wrote: > Hi, everyone. > > This is on WinXP SP2, with Python 2.4.3 and DJGPP gcc 4.1.0. > > I'm having trouble including Python.h in a C file. The following C > code: > > #include "Python.h" > > int main() > { > return 0; > } > > when compiled with "gcc -I..\Python2.4\include\", gives more than 1000 > lines of errors, beginning with: > > c:/documents and settings/marcelo.gosling/my > documents/djgpp/bin/as.exe: BFD 2.16.1 assertion fail > ../../bfd/coff-i386.c:576 Hmmmm.... the *assembler* appears to be grumbling about its input. I'd suspect that you have a mangled DJGPP installation. You may be better asking on the DJGPP mailing list. Aside: Wouldn't it have been better to install DJGPP in c:\djgpp???? > c:/documents and settings/marcelo.gosling/my > documents/djgpp/tmp/ccACtxBR.s: Assembler messages: > c:/documents and settings/marcelo.gosling/my > documents/djgpp/tmp/ccACtxBR.s:28: Error: cannot represent relocation > type BFD_RELOC_386_PLT32 > In file included from ../../Python2.4/include/Python.h:74, > from example_wrap.c:112: 1. You allegedly have a 6-line test program. What is this example_wrap.c that has 112 lines (or more) in it? 2. What was the full compiler command line? 3. What are you doing with DJGPP? Are you attempting to make an MS-DOS port of Python? 4. Have you successfully compiled linked and executed anything with this installation of DJGPP? Does the standard "Hello, world!" program work? 5. Have you tried compiling (not linking) this: #include "Python.h" void dummy() {} HTH, John From PPNTWIMBXFFC at spammotel.com Wed Jun 14 09:27:58 2006 From: PPNTWIMBXFFC at spammotel.com (Marco Aschwanden) Date: Wed, 14 Jun 2006 15:27:58 +0200 Subject: Using "external" vars on module load time References: Message-ID: Marvelous that was the solution I was looking for. > I think you should consider a class instead of a module, though. What I don't get: Why should I consider using a class? Greetings from sunny Switzerland, Marco From evenprimes at gmail.com Tue Jun 6 13:45:26 2006 From: evenprimes at gmail.com (Chris Cioffi) Date: Tue, 6 Jun 2006 13:45:26 -0400 Subject: what are you using python language for? In-Reply-To: References: Message-ID: I tend to do a significant amount of EDI related work: -statistical analysis -X12->HTML formatting I've do a ton of customer DB reporting. I find it easier to use Python that Crystal reports for a lot of the stuff I do so I extract data and spit out CSV files for Excel to make it look pretty. And I'm getting ready to do a fun/work project using TurboGears for a web-based migration tracking utility we need. Chris On 6/4/06, hacker1017 wrote: > > im just asking out of curiosity. > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- "A little government and a little luck are necessary in life, but only a fool trusts either of them." -- P. J. O'Rourke -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Wed Jun 28 13:04:19 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 28 Jun 2006 19:04:19 +0200 Subject: Problem with sets and Unicode strings References: <44a17d05$1@news.uni-ulm.de> <44a19d55$2@news.uni-ulm.de> <44a2b2cc$2@news.uni-ulm.de> Message-ID: <4gfr58F1mijo5U2@uni-berlin.de> > But I'd say that it's not intuitive that for sets x in y can be false > (without raising an exception!) while the doing the same with a tuple > raises an exception. Where is this difference documented? 2.3.7 Set Types -- set, frozenset ... Set elements are like dictionary keys; they need to define both __hash__ and __eq__ methods. ... And it has to hold that a == b => hash(a) == hash(b) but NOT hash(a) == hash(b) => a == b Thus if the hashes vary, the set doesn't bother to actually compare the values. Diez From sreeram at tachyontech.net Mon Jun 19 15:32:15 2006 From: sreeram at tachyontech.net (K.S.Sreeram) Date: Tue, 20 Jun 2006 01:02:15 +0530 Subject: Overriding a function... In-Reply-To: References: <1150742558.198061.239660@p79g2000cwp.googlegroups.com> Message-ID: <4496FBBF.7050303@tachyontech.net> Marc 'BlackJack' Rintsch wrote: >> 2) Once I assign mymodule.test with override, will modules that >> imported my module *PRIOR* to the assignment get override, or will they >> keep the original function test()? > > They see the `override()` function. That depends on how the import was done. If you do 'import mymodule' and then use 'mymodule.test' to access the function, then they'll see the new 'override' function. Alternatively, If you do 'from mymodule import test', and use 'test', then they'll see the original 'test' function. Regards Sreeram -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 260 bytes Desc: OpenPGP digital signature URL: From aleax at mac.com Mon Jun 19 11:18:13 2006 From: aleax at mac.com (Alex Martelli) Date: Mon, 19 Jun 2006 08:18:13 -0700 Subject: Just out of curiosity: Which languages are they using at Google and what for? References: <1150710705.482745.230070@r2g2000cwb.googlegroups.com> Message-ID: <1hh66f4.tku89zt9ts2xN%aleax@mac.com> wrote: > I know Google are using Python for testing purposes. ...and many more besides, as per the other response. > But for the rest ? > is it PHP or Java or .NET? > Which technology is rendering the google main page? I think you can get a reasonable idea by perusing the 800+ job offers we currently have open;-), and eyeballing the several papers published by Googlers -- between one and the other, it becomes pretty clear that we use mostly Python, C++ and Java, plus of course a host of others for special purposes (Javascript for AJAX purposes, C and Assembly for kernel-hacking of various sort, SQL for relational databases, etc, etc), including some highly specialized ones invented within Google for highly specialized purposes (e.g., Rob Pike's "sawzall" for log-processing). > And of course th obvious question, why not Python? You can read Pike et al's paper on sawzall to see why we would want a special-purpose language for that specialized, very-high-volume task, for example; I hope the reason for the other specialized ones, from Javascript to Assembly to SQL, is pretty obvious in each case;-). As among the "three big ones" -- Python, C++, Java -- there are good reasons why the overall job is best done by a mix of them. I won't address Java (we don't use any in my group, nor any of the groups we interact with intensely), but the tradeoffs between Python and C++ should, again, be pretty clear. For example, C++ allows (and demands) close control of where all your memory is going -- much harder to achieve in garbage collected languages such as Python or Java (managing memory IS a chore, but, under potentially heavy load, an important one). Also, a consideration I also made at SDForum: at Google's volumes of traffic, we need load-balancing among many machines, of course, but we _also_ are unwilling to let user experience suffer from high latencies. Now, you can scale the "bandwidth" of a cluster by throwing more servers at the problem -- but latency does not work the same way: you can't make a baby in 1 month by load-balancing among 9 mothers, as the saying goes. So, having as few machine-instructions as feasible on the critical paths that determine the user-perceived latency is important; even the very first paper by Page and Brin describing what would later become Google made the point indirectly -- they describe the "crawling" (where latency is no big deal) as being implemented in Python, but the processing of queries (where latency is crucial) in C++. Alex From __peter__ at web.de Thu Jun 1 07:34:53 2006 From: __peter__ at web.de (Peter Otten) Date: Thu, 01 Jun 2006 13:34:53 +0200 Subject: Function mistaken for a method References: Message-ID: Eric Brunel wrote: > My actual question is: why does it work in one case and not in the other? > As I see it, int is just a function with one parameter, and the lambda is > just another one. So why does the first work, and not the second? What > 'black magic' takes place so that int is not mistaken for a method in the > first case? A python-coded function has a __get__ attribute, a C-function doesn't. Therefore C1.f performs just the normal attribute lookup while C2.f also triggers the f.__get__(C2(), C2) call via the descriptor protocol which happens to return a bound method. Peter From aleax at mac.com Sat Jun 24 02:12:05 2006 From: aleax at mac.com (Alex Martelli) Date: Fri, 23 Jun 2006 23:12:05 -0700 Subject: Python on intel osx References: Message-ID: <1hheqsf.1urca49t7abnsN%aleax@mac.com> John Lockwood wrote: > Can someone please suggest the most suitable python for mac osx 10.4.6 > Finding the right installs doesn't seem quite as cut and dried as it is for > linux or windows. -- a link found at under the heading "MacOS X". > I'm also looking for numeric and pyopengl. I am not aware of precompiled versions of these packages for this latest version of MacOSX. However, Apple's XCode can be downloaded for free (you can probably also get a copy, w/o the bother of downloading, from the Installers folder on your MacOSX DVD -- but it won't be the latest and greatest;-), and it includes a gcc which lets you build and install most normal Python extensions from source distributions by just typing "python setup.py install" at the Terminal (you may need to use sudo to request installation privileges, and/or set your $PATH appropriately to ensure you're using the version of Python you want to build and install for, e.g. the above-mentioned 2.4.3 rather than the 2.3.5 that comes with MacOSX itself). Alex From shejo284 at gmail.com Thu Jun 15 14:19:32 2006 From: shejo284 at gmail.com (Sheldon) Date: 15 Jun 2006 11:19:32 -0700 Subject: python and HDF In-Reply-To: References: <1150376026.665920.50860@h76g2000cwa.googlegroups.com> Message-ID: <1150395572.077974.18590@r2g2000cwb.googlegroups.com> Marc 'BlackJack' Rintsch skrev: > In <1150376026.665920.50860 at h76g2000cwa.googlegroups.com>, Sheldon wrote: > > > I am using a HLHDF C wrapper to extract data from HDF (version 5) > > files. > > I can view the contents with IDL, for example, and read the attributes > > in the HDF file. There is one attribute that I extracted and only of > > part of the string was returned. In the HDF file, the attribute data is > > a name which is called "baseline" but when python reads it, it returns > > "baselin" instead. > > Does anyone have any idea why this is happening? > > Not from this description. How do you read the data with Python? Which C > library/wrapper do you use? > > Ciao, > Marc 'BlackJack' Rintsch Hi I an using HLHDF developed locally. I found someone who said that if the string was written to the HDF file with being NULL+1 terminated then this would happen. Sounds good to me. Thanks for your help. /Sheldon From sreeram at tachyontech.net Sat Jun 17 15:08:45 2006 From: sreeram at tachyontech.net (K.S.Sreeram) Date: Sun, 18 Jun 2006 00:38:45 +0530 Subject: PyObject_SetItem(..) *always* requires a Py_INCREF or not? In-Reply-To: <1150569854.734805.278760@r2g2000cwb.googlegroups.com> References: <1150569854.734805.278760@r2g2000cwb.googlegroups.com> Message-ID: <4494533D.9020002@tachyontech.net> seberino at spawar.navy.mil wrote: > int > set_all(PyObject *target, PyObject *item) > { > int i, n; > > n = PyObject_Length(target); > if (n < 0) > return -1; > for (i = 0; i < n; i++) { > if (PyObject_SetItem(target, i, item) < 0) > return -1; > } > return 0; > } > > *WHY* don't you need a Py_INCREF(item); in the for loop!?!?!? Thats because PyObject_SetItem automatically increases the refcount of the 'item' that you pass. Whereas, PyTuple_SetItem and PyList_SetItem *DONT* automatically increment the refcount. Sreeram -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 260 bytes Desc: OpenPGP digital signature URL: From mscottschilling at hotmail.com Sun Jun 11 02:05:22 2006 From: mscottschilling at hotmail.com (Mike Schilling) Date: Sun, 11 Jun 2006 06:05:22 GMT Subject: Xah Lee network abuse References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148495974.975395.12920@i40g2000cwc.googlegroups.com> <1149998343.493200.144990@h76g2000cwa.googlegroups.com> Message-ID: "Philippa Cowderoy" wrote in message news:Pine.WNT.4.61.0606110548540.1652 at SLINKY... > On Sun, 11 Jun 2006, Mike Schilling wrote: > >> I'm not aware of any definition of libel that includes "making statements >> that are not provably true". >> > > I believe UK law uses one that's close to it. If I were to write, say, that Tony Blair's tax policy will lead to higher deficits, I could be convicted of libel? Even if that's true, it's not a priori provable. From danmcleran at yahoo.com Fri Jun 9 11:15:18 2006 From: danmcleran at yahoo.com (danmcleran at yahoo.com) Date: 9 Jun 2006 08:15:18 -0700 Subject: References and copying In-Reply-To: References: Message-ID: <1149866118.229243.53290@g10g2000cwb.googlegroups.com> > Where can I find a good explanation when does an interpreter copy the > value, and when does it create the reference. Any good Python book. I have Learning Python and Programming Python 2nd edition and they are very good IMO. > I thought I understand > it, but I have just typed in following commands: > > >>> a=[[1,2],[3,4]] > >>> b=a[1] > >>> b=[5,6] > >>> a > [[1, 2], [3, 4]] > >>> b > [5, 6] > > And I don't understand it. I thought, that b will be a reference to a, > so changing b should change a as well. No, you've set the name b to reference a slice of a. Slicing a list always returns a new list. To change a via b, do this: a = [[1,2],[3,4]] b = a print a print b b[1] = [5,6] print a print b From sjmachin at lexicon.net Tue Jun 27 20:25:30 2006 From: sjmachin at lexicon.net (John Machin) Date: Wed, 28 Jun 2006 10:25:30 +1000 Subject: Ascii Encoding Error with UTF-8 encoder In-Reply-To: References: <44a1bbcb$1@news.eftel.com> Message-ID: <44a1cc79$1@news.eftel.com> On 28/06/2006 9:44 AM, Mike Currie wrote: > > What I am doing is converting data for processing that will be tab (for > columns) and newline (for row) delimited. Some of the data contains tabs > and newlines so, I have to convert them to something else so the file > integrity is good. > > Not my idea, I've been left with the implementation however. > Do you *need* UTF-8? Or is that only there to hide away the \x88 and \x83? Apart from tab and linefeed, what (if any) other characters are there in the data that are not printable ASCII characters? In any case, if you have 8-bit string data, the CSV file format would appear to meet the requirement: it preserves your data by "quoting" delimiters and newlines that appear in the actual data. The Python csv module is included in every Python distribution since 2.3. Cheers, John From george.sakkis at gmail.com Fri Jun 9 22:56:37 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 9 Jun 2006 19:56:37 -0700 Subject: Allowing zero-dimensional subscripts References: <1149801040.936452.26270@i40g2000cwc.googlegroups.com> Message-ID: <1149908197.118535.199910@j55g2000cwa.googlegroups.com> spam.noam at gmail.com wrote: > However, I'm designing another library for > managing multi-dimensional arrays of data. Its purpose is similiar to > that of a spreadsheet - analyze data and preserve the relations between > a source of a calculation and its destination. Sounds interesting. Will it be related at all to OLAP or the Multi-Dimensional eXpressions language (http://msdn2.microsoft.com/en-us/library/ms145506.aspx) ? George From dimitri.pater at gmail.com Fri Jun 16 16:37:08 2006 From: dimitri.pater at gmail.com (dimitri pater) Date: Fri, 16 Jun 2006 22:37:08 +0200 Subject: GUI in Python using wxGlade In-Reply-To: <1150463313.588433.248560@h76g2000cwa.googlegroups.com> References: <1150380251.279150.73620@u72g2000cwu.googlegroups.com> <1150386216.365531.157690@g10g2000cwb.googlegroups.com> <1150403353.755218.292100@c74g2000cwc.googlegroups.com> <1150463313.588433.248560@h76g2000cwa.googlegroups.com> Message-ID: the link should be: www.serpia.org/wxglade thanks for finding it, UrsusMaximus ;-) Dimitri On 16 Jun 2006 06:08:33 -0700, diffuser78 at gmail.com wrote: > > Did you paste any code ? > > Also the link for the next message is not working ..... > > > John Salerno wrote: > > diffuser78 at gmail.com wrote: > > > I am a newbie. I was looking for some code where I could a list of > > > different items from a file and display it in a list box. Then give a > > > user the capability to select some. > > > > > > Basically, reading and writing to a file and displaying them in > > > different widgets...thats something I am looking for. If anybody can > > > point me to some good example tutorials...I will be greatly helped. > > > > > > Thanks, > > > > > > Every help is appreciated > > > > > > > Have you tried looking at the code in the wxPython demo? In the ListBox > > control demo, it populates a ListBox with items from a list, but you > > could easily translate that into reading from a file, I think. Here's > > the full code in case you don't have the demo: > > > > > > > > > > import wx > > > > > > > #--------------------------------------------------------------------------- > > > > > > # This listbox subclass lets you type the starting letters of what you > want to > > > # select, and scrolls the list to the match if it is found. > > > class FindPrefixListBox(wx.ListBox): > > > def __init__(self, parent, id, pos=wx.DefaultPosition, size= > wx.DefaultSize, > > > choices=[], style=0, validator=wx.DefaultValidator): > > > wx.ListBox.__init__(self, parent, id, pos, size, choices, > style, validator) > > > self.typedText = '' > > > self.log = parent.log > > > self.Bind(wx.EVT_KEY_DOWN, self.OnKey) > > > > > > > > > def FindPrefix(self, prefix): > > > self.log.WriteText('Looking for prefix: %s\n' % prefix) > > > > > > if prefix: > > > prefix = prefix.lower() > > > length = len(prefix) > > > > > > # Changed in 2.5 because ListBox.Number() is no longer > supported. > > > # ListBox.GetCount() is now the appropriate way to go. > > > for x in range(self.GetCount()): > > > text = self.GetString(x) > > > text = text.lower() > > > > > > if text[:length] == prefix: > > > self.log.WriteText('Prefix %s is found.\n' % > prefix) > > > return x > > > > > > self.log.WriteText('Prefix %s is not found.\n' % prefix) > > > return -1 > > > > > > > > > def OnKey(self, evt): > > > key = evt.GetKeyCode() > > > > > > if key >= 32 and key <= 127: > > > self.typedText = self.typedText + chr(key) > > > item = self.FindPrefix(self.typedText) > > > > > > if item != -1: > > > self.SetSelection(item) > > > > > > elif key == wx.WXK_BACK: # backspace removes one character > and backs up > > > self.typedText = self.typedText[:-1] > > > > > > if not self.typedText: > > > self.SetSelection(0) > > > else: > > > item = self.FindPrefix(self.typedText) > > > > > > if item != -1: > > > self.SetSelection(item) > > > else: > > > self.typedText = '' > > > evt.Skip() > > > > > > def OnKeyDown(self, evt): > > > pass > > > > > > > > > > #--------------------------------------------------------------------------- > > > > > > class TestListBox(wx.Panel): > > > def __init__(self, parent, log): > > > self.log = log > > > wx.Panel.__init__(self, parent, -1) > > > > > > sampleList = ['zero', 'one', 'two', 'three', 'four', 'five', > > > 'six', 'seven', 'eight', 'nine', 'ten', > 'eleven', > > > 'twelve', 'thirteen', 'fourteen'] > > > > > > wx.StaticText(self, -1, "This example uses the wx.ListBoxcontrol.", (45, 10)) > > > wx.StaticText(self, -1, "Select one:", (15, 50)) > > > self.lb1 = wx.ListBox(self, 60, (100, 50), (90, 120), > sampleList, wx.LB_SINGLE) > > > self.Bind(wx.EVT_LISTBOX, self.EvtListBox, self.lb1) > > > self.Bind(wx.EVT_LISTBOX_DCLICK, self.EvtListBoxDClick, > self.lb1) > > > self.lb1.Bind(wx.EVT_RIGHT_UP, self.EvtRightButton) > > > self.lb1.SetSelection(3) > > > self.lb1.Append("with data", "This one has data"); > > > self.lb1.SetClientData(2, "This one has data"); > > > > > > > > > wx.StaticText(self, -1, "Select many:", (220, 50)) > > > self.lb2 = wx.ListBox(self, 70, (320, 50), (90, 120), > sampleList, wx.LB_EXTENDED) > > > self.Bind(wx.EVT_LISTBOX, self.EvtMultiListBox, self.lb2) > > > self.lb2.Bind(wx.EVT_RIGHT_UP, self.EvtRightButton) > > > self.lb2.SetSelection(0) > > > > > > sampleList = sampleList + ['test a', 'test aa', 'test aab', > > > 'test ab', 'test abc', 'test abcc', > > > 'test abcd' ] > > > sampleList.sort() > > > wx.StaticText(self, -1, "Find Prefix:", (15, 250)) > > > fp = FindPrefixListBox(self, -1, (100, 250), (90, 120), > sampleList, wx.LB_SINGLE) > > > fp.SetSelection(0) > > > > > > > > > def EvtListBox(self, event): > > > self.log.WriteText('EvtListBox: %s, %s, %s, %s\n' % > > > (event.GetString(), > > > event.IsSelection(), > > > event.GetSelection(), > > > event.GetClientData())) > > > > > > lb = event.GetEventObject() > > > data = lb.GetClientData(lb.GetSelection()) > > > > > > if data is not None: > > > self.log.WriteText('\tdata: %s\n' % data) > > > > > > > > > def EvtListBoxDClick(self, event): > > > self.log.WriteText('EvtListBoxDClick: %s\n' % > self.lb1.GetSelection()) > > > self.lb1.Delete(self.lb1.GetSelection()) > > > > > > def EvtMultiListBox(self, event): > > > self.log.WriteText('EvtMultiListBox: %s\n' % str( > self.lb2.GetSelections())) > > > > > > def EvtRightButton(self, event): > > > self.log.WriteText('EvtRightButton: %s\n' % event.GetPosition > ()) > > > > > > if event.GetEventObject().GetId() == 70: > > > selections = list(self.lb2.GetSelections()) > > > selections.reverse() > > > > > > for index in selections: > > > self.lb2.Delete(index) > > > > > > > > > > #--------------------------------------------------------------------------- > > > > > > def runTest(frame, nb, log): > > > win = TestListBox(nb, log) > > > return win > > > > > > > #--------------------------------------------------------------------------- > > > > > > > > > > > > > > > overview = """ > > > A listbox is used to select one or more of a list of > > > strings. The strings are displayed in a scrolling box, with the > > > selected string(s) marked in reverse video. A listbox can be single > > > selection (if an item is selected, the previous selection is removed) > > > or multiple selection (clicking an item toggles the item on or off > > > independently of other selections). > > > > > > """ > > > > > > > > > if __name__ == '__main__': > > > import sys,os > > > import run > > > run.main(['', os.path.basename(sys.argv[0])] + sys.argv[1:]) > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- ---- I'd really like to help you man I'd really like to help you man..... Nervous messed up marionette Floating around on a prison ship --- Radiohead - Optimistic ---- Please visit dimitri's website: www.serpia.org -------------- next part -------------- An HTML attachment was scrubbed... URL: From esj at harvee.org Tue Jun 20 23:27:39 2006 From: esj at harvee.org (Eric S. Johansson) Date: Tue, 20 Jun 2006 23:27:39 -0400 Subject: need all python dialog equivalent Message-ID: I'm creating a dialogue style interface for an application on a dedicated system. All I have is basic Python 2.3. Is there anything like an all Python dialog equivalent floating around? I'm currently hacking away in curses but it's taking me a long way down what I fear to be a wrong path. I've looked at the Python dialog web site but it clearly states that it is a wrapper around dialogue/Xdialog. suggestions would be most welcome. ---eric From cito at online.de Sun Jun 4 17:14:22 2006 From: cito at online.de (Christoph Zwerschke) Date: Sun, 04 Jun 2006 23:14:22 +0200 Subject: Python less error-prone than Java In-Reply-To: <1149453000.162259.105090@y43g2000cwc.googlegroups.com> References: <1149424883.529756.13700@j55g2000cwa.googlegroups.com> <1149453000.162259.105090@y43g2000cwc.googlegroups.com> Message-ID: nikie wrote: > Hm, then I probably didn't get your original point: I thought your > argument was that a dynamically typed language was "safer" because it > would choose the "right" type (in your example, an arbitrary-pecision > integer) automatically. No, my point was not to make a general statement. It just stumbled over that example and said to myself "that wouldn't have happend with Python." And I thought it might be interesting for people on c.l.p as well. That was all. > As you can see from the above sample, it > sometimes picks the "wrong" type, too. Now you tell me that this > doesn't count, because I should have told Python what type to use. Yes. Python did not "pick" that type - you explicitely said that x should an int by setting x = 10001. > I mean, you could have told Java to used a 64-bit or arbitrary-length > integer type instead of a 32-bit integer (which would actually be > equivalent to the Python code), so it would do the same thing > as the Python binary search implementation. Right, but then Java would do all index operations in that type, even for very small arrays when it's not necessary. That's why people probably don't do it. > The is OT, but what makes you think a C# decimal can't store 0.01? A C# data type summary gave me the impression that it was just a more accurate but still binary floating point type. But you're right, the name "decimal" should have given me a clue that it uses base 10 ;-) So sorry for the confusion. Forget what I wrote about float. I should have corretly written that the equivalent to the C# statement decimal x = 10001; is the following Python statement x = Decimal(10001) If you do the equivalent thing, Python will give the same result as C#. > All I wanted to point out is that bounded integers do have their > advantages, because some people in this thread apparently have > never stumbled over them. Sure, I did not want to deny that. The main advantages are speed, and dealing with hardware related issues. Your Distance function in C is of course much faster than my Python implementation. Surely I wouldn't want to write a device driver in Python. -- Christoph From faulkner612 at comcast.net Fri Jun 2 20:09:24 2006 From: faulkner612 at comcast.net (faulkner) Date: 2 Jun 2006 17:09:24 -0700 Subject: do you have a local copy of Lython? Message-ID: <1149293364.597445.302600@y43g2000cwc.googlegroups.com> # Lython = Miles Egan's Lisp->Python compiler. The usual place throws a 404, and when I tried the email address in whois the server threw an error. I've asked around on a few forums, and somebody on irc.efnet.org/python suggested posting here. If you have a saved copy, please email it to me or link me to a working download. Thanks for your time, faulkner From robert.kern at gmail.com Tue Jun 27 18:27:41 2006 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 27 Jun 2006 17:27:41 -0500 Subject: Ascii Encoding Error with UTF-8 encoder In-Reply-To: References: Message-ID: Mike Currie wrote: > Can anyone explain why I'm getting an ascii encoding error when I'm trying > to write out using a UTF-8 encoder? Please read the Python Unicode HOWTO. http://www.amk.ca/python/howto/unicode -- 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 From marshall.spight at gmail.com Fri Jun 23 12:32:13 2006 From: marshall.spight at gmail.com (Marshall) Date: 23 Jun 2006 09:32:13 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <1150809118.677124.142230@u72g2000cwu.googlegroups.com> <1150815461.210286.53120@r2g2000cwb.googlegroups.com> <1150823297.816352.75370@u72g2000cwu.googlegroups.com> <7zzmg6amm1.fsf@app-3.diku.dk> <1150904475.363283.234730@y41g2000cwy.googlegroups.com> <1151027800.460188.116860@i40g2000cwc.googlegroups.com> Message-ID: <1151080333.467194.286050@m73g2000cwd.googlegroups.com> Andreas Rossberg wrote: > Marshall wrote: > > > > What we generally (in programming) call variables are locals > > and globals. If the languages supports an update operation > > on those variables, then calling them variables makes sense. > > But "variable" has become such a catch-all term that we call > > > > public static final int FOO = 7; > > > > a variable, even though it can never, ever vary. > > > > That doesn't make any sense. > > It does, because it is only a degenerate case. In general, you can have > something like > > void f(int x) > { > const int foo = x+1; > //... > } > > Now, foo is still immutable, it is a local, but it clearly also varies. So what then is to be the definition of "variable" if it includes things that can never vary, because they are only a degenerate case? Shall it be simply a named value? Marshall From riquito at gmail.com Wed Jun 14 20:40:45 2006 From: riquito at gmail.com (riquito at gmail.com) Date: 14 Jun 2006 17:40:45 -0700 Subject: prog1 | prog2 . How not to make prog2 block if not piped? In-Reply-To: References: <1150297984.798904.229730@h76g2000cwa.googlegroups.com> <1150306815.394154.130250@h76g2000cwa.googlegroups.com> Message-ID: <1150332045.405495.75020@u72g2000cwu.googlegroups.com> Steve Holden ha scritto: > When you run it "standalone" you should give it some input - type some > text then enter ^D (on Unix-like systems) or ^Z (on Windows). How else > do you expect read() to return anything? It *has* to read to the end fo > the file before it returns a value. > > regards > Steve you've got reason. I must read my command line options, if then there is still text I use that, otherwise I read from stdin. If nothing was piped, the user must complete the work. Thank you all, Riccardo From a.cavallo at mailsnare.com Thu Jun 22 05:10:29 2006 From: a.cavallo at mailsnare.com (cavallo71) Date: 22 Jun 2006 02:10:29 -0700 Subject: 10GB XML Blows out Memory, Suggestions? References: <1149594519.098115.8980@u72g2000cwu.googlegroups.com> <2Qfhg.18186$0v4.787@tornado.texas.rr.com> Message-ID: <1150967429.648508.29520@m73g2000cwd.googlegroups.com> > > I wrote a program that takes an XML file into memory using Minidom. I > > found out that the XML document is 10gb. > > > > I clearly need SAX or something else? If the data is composed by a large number of records, like a database dump of some sort, then probably you could have a look to a stax processor for python like pulldom. In this way you could process each single record one at the time, without loading the entiere document. Regards, Antonio From jorgen.stenarson at bostream.nu Thu Jun 1 15:58:06 2006 From: jorgen.stenarson at bostream.nu (jorgen stenarson) Date: 1 Jun 2006 12:58:06 -0700 Subject: pyreadline 1.3 release (was UNC readline) Message-ID: <1149191886.302736.327180@i40g2000cwc.googlegroups.com> We are happy to announce the release of pyreadline 1.3. Pyreadline is based on UNC readline by Gary Bishop. UNC readline is not being developed further by Gary, and PyReadline can be considered the continuation of that project. This was done in full agreement with Gary, given his current development priorities. Pyreadline is maintained by the ipython project (http://projects.scipy.org/ipython/ipython/wiki/PyReadline/Intro). New features: * Support for international characters (if you have the correct codepage active) * Copy and paste using the clipboard * Smart paste for convenient use with ipython. Converting tab separated data to python list or numpy array. Converting file paths to use / and escaping any spaces using \ . * Pasting of multiline code removing empty lines Get it at: http://ipython.scipy.org/dist/pyreadline-1.3.win32.exe. Installations instructions are available on the pyreadline wiki. Once again we would like to thank Gary for creating this readline package. /pyreadline team From quentel.pierre at wanadoo.fr Wed Jun 28 02:15:22 2006 From: quentel.pierre at wanadoo.fr (Pierre Quentel) Date: 27 Jun 2006 23:15:22 -0700 Subject: a class variable question In-Reply-To: <1151474768.546012.254380@p79g2000cwp.googlegroups.com> References: <1151474768.546012.254380@p79g2000cwp.googlegroups.com> Message-ID: <1151475322.648696.21880@b68g2000cwa.googlegroups.com> In func1, _var1 = 1 creates a local variable _var1 (local to the method), not an attribute of the instance. If you want an instance attribute you must specify the reference to the instance by self._var1 = 1 ; self must be passed as an attribute to func1 def func1(self): self._var1 = 1 Similarly, in getvarValue : def getvarValue(self): return self._var1 Pierre From tactics40 at gmail.com Fri Jun 30 10:40:04 2006 From: tactics40 at gmail.com (tac-tics) Date: 30 Jun 2006 07:40:04 -0700 Subject: print shell output in a file In-Reply-To: <44a52fdb$0$3892$91cee783@newsreader01.highway.telekom.at> References: <44a52fdb$0$3892$91cee783@newsreader01.highway.telekom.at> Message-ID: <1151678404.089542.108160@h44g2000cwa.googlegroups.com> It sounds like you want to use print >> If you have an open object with a "write" property, you can do print >> thefile, mystring and Python will simply redirect the output to "thefile" instead of sys.stdout. From antroy at gmail.com Fri Jun 16 04:09:26 2006 From: antroy at gmail.com (Ant) Date: 16 Jun 2006 01:09:26 -0700 Subject: a good programming text editor (not IDE) In-Reply-To: References: <_xgkg.2317$No6.48542@news.tufts.edu> <1150393919.514359.55580@h76g2000cwa.googlegroups.com> Message-ID: <1150445365.919494.184770@r2g2000cwb.googlegroups.com> > > Vim is great if you have a good memory... Otherwise you end up trawling > > through the help to find out how to do stuff that would in another IDE > > be just a few menu clicks away. > > Mental memory (the painful kind of memory) rapidly turns into muscle > memory (the fun kind of memory) and all of those mind boggling > keystrokes begin to feel like an artistic expression reminiscent of > playing the piano. That's probably true. I still have a long way to go to get the most out of vim though, because it takes a certain amount of mental memory to be able to use the keystrokes often enough to turn them into muscle memory... I tend to use gvim on my PC if I'm also working on my server via ssh - that way it doesn't matter if I type a few ESC :w's or :dd's. Otherwise I tend to use jEdit. From flaus.a at wanadoo.fr Sun Jun 18 05:03:14 2006 From: flaus.a at wanadoo.fr (flaus.a at wanadoo.fr) Date: 18 Jun 2006 02:03:14 -0700 Subject: Standard Yes / No Windows Dialog box creation In-Reply-To: <1150586399.452037.85270@h76g2000cwa.googlegroups.com> References: <1150581640.385143.83410@y41g2000cwy.googlegroups.com> <1150586399.452037.85270@h76g2000cwa.googlegroups.com> Message-ID: <1150621394.707432.122730@f6g2000cwb.googlegroups.com> Ravi Teja a ?crit : > > Assuming you are on MS Windows. > import win32api, win32con > win32api.MessageBox(0, "Question", "Title", win32con.MB_YESNO) Yes, that's exactly what I was looking for! Thanks!! From padraigkitterick at gmail.com Mon Jun 19 11:30:53 2006 From: padraigkitterick at gmail.com (Padraig) Date: 19 Jun 2006 08:30:53 -0700 Subject: Installing Python on Windows Vista Message-ID: <1150731053.741522.190010@p79g2000cwp.googlegroups.com> Hi all, Just a quick question... when I try to install Python on Windows Vista Beta 2 the installer seems to hang after I select the destination folder, saying that it will "return when it has finished calculating disk space requirements". I just can't seem to get past that step. I've also tried installing both 2.4.3 and 2.4.2 with no luck. Any help would be very much appreciated. Many thanks P From johannes.wollard at gmail.com Thu Jun 29 07:01:29 2006 From: johannes.wollard at gmail.com (notanotheridiot) Date: 29 Jun 2006 04:01:29 -0700 Subject: Running DocTest on Strings Message-ID: <1151578889.243272.167750@y41g2000cwy.googlegroups.com> Hi, I have two strings - a docstring containing doctests and a code string containing code to be tested with those doctests. I've been trying for a day now to run the test without concatenating the two strings, adding: import doctest doctest.testmod to the bottom, writing it all to a file and executing it using popen(). There must be some way of doing this without writing to a temporary file, any ideas? thanks in advance, johannes Woolard From scott.daniels at acm.org Mon Jun 26 14:29:26 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Mon, 26 Jun 2006 11:29:26 -0700 Subject: Formatted string to object In-Reply-To: <1151333706.837501.40170@m73g2000cwd.googlegroups.com> References: <1150731552.799052.47320@r2g2000cwb.googlegroups.com> <4496d806$0$9017$626a54ce@news.free.fr> <1151333706.837501.40170@m73g2000cwd.googlegroups.com> Message-ID: <44a0226b@nntp0.pdx.net> janama wrote: > i can use this: > aaa = 1 > result = eval("self.b%s.SetBitmapDisabled(self.yellow)" % aaa) > > .... How would i to achieve this with getattr() ? result = getattr(self, 'b%s' % aaa).SetBitmapDisabled(self.yellow) --Scott David Daniels scott.daniels at acm.org From anton at appsolutions.com Fri Jun 23 08:37:31 2006 From: anton at appsolutions.com (Anton van Straaten) Date: Fri, 23 Jun 2006 12:37:31 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: <1151056505.908723.162580@u72g2000cwu.googlegroups.com> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150904134.520639.71070@b68g2000cwa.googlegroups.com> <1151056505.908723.162580@u72g2000cwu.googlegroups.com> Message-ID: rossberg at ps.uni-sb.de wrote: > I very much agree with the observation that every programmer performs > "latent typing" in his head Great! > (although Pascal Constanza's seems to have > the opposite opinion). I'll have to catch up on that. > But I also think that "latently typed language" is not a meaningful > characterisation. And for the very same reason! Since any programming > activity involves latent typing - naturally, even in assembler! - it > cannot be attributed to any language in particular, and is hence > useless to distinguish between them. (Even untyped lambda calculus > would not be a counter-example. If you really were to program in it, > you certainly would think along lines like "this function takes two > chuch numerals and produces a third one".) Vesa raised a similar objection in his post 'Saying "latently typed language" is making a category mistake'. I've made some relevant responses to that post. I agree that there's a valid point in the sense that latent types are not a property of the semantics of the languages they're associated with. But to take your example, I've had the pleasure of programming a little in untyped lambda calculus. I can tell you that not having tags is quite problematic. You certainly do perform latent typing in your head, but without tags, the language doesn't provide any built-in support for it. You're on your own. I'd characterize this as being similar to other situations in which a language has explicit support for some programming style (e.g. FP or OO), vs. not having such support, so that you have to take steps to fake it. The style may be possible to some degree in either case, but it's much easier if the language has explicit support for it. Dynamically-typed languages provide support for latent typing. Untyped lambda calculus and assembler don't provide such support, built-in. However, I certainly don't want to add to confusion about things like this. I'm open to other ways to describe these things. Part of where "latently-typed language" comes from is as an alternative to "dynamically-typed language" -- an alternative with connotations that I'm suggesting should be more compatible with type theory. > I hear you when you define latently typed languages as those that > support the programmer's latently typed thinking by providing dynamic > tag checks. But in the very same post (and others) you also explain in > length why these tags are far from being actual types. This seems a bit > contradictory to me. I don't see it as contradictory. Tags are a mechanism. An individual tag is not a type. But together, tags help check types. More below: > As Chris Smith points out, these dynamic checks are basically a > necessaity for a well-defined operational semantics. You need them > whenever you have different syntactic classes of values, but lack a > type system to preclude interference. They are just an encoding for > differentiating these syntactic classes. Their connection to types is > rather coincidential. Oooh, I think I'd want to examine that "coincidence" very closely. For example, *why* do we have different syntactic classes of values in the first place? I'd say that we have them precisely to support type-like reasoning about programs, even in the absence of a formal static type system. If you're going to talk about "syntactic classes of values" in the context of latent types, you need to consider how they relate to latent types. Syntactic classes of values relate to latent types in a very similar way to that in which static types do. One difference is that since latent types are not automatically statically checked, checks have to happen in some other way. That's what checks of tags are for. Chris Smith's observation was made in a kind of deliberate void: one in which the existence of anything like latent types is discounted, on the grounds that they're informal. If you're willing to acknowledge the idea of latent types, then you can reinterpret the meaning of tags in the context of latent types. In that context, tags are part of the mechanism which checks latent types. Anton From msol at o2.pl Fri Jun 30 05:40:34 2006 From: msol at o2.pl (Marek S.) Date: Fri, 30 Jun 2006 11:40:34 +0200 Subject: Entry Widget problem Message-ID: <44A4F192.9010703@o2.pl> Hi, I am new in Python and I have no experience in object-oriented programming. I want to make an easy GUI for my application. What is my problem? I have the data-file like this (file ETab_H1.dan): 16 1 13 10 1 0.9 1.1 1 0 0.0 0.0 0.0 2 14 50 2 0.9 1.1 4 2 0.0 0.0 0.0 3 15 10 2 0.9 1.1 1 0 0.0 0.0 0.0 4 16 10 1 0.9 1.1 1 0 0.0 0.0 0.0 5 17 50 2 0.9 1.1 4 2 0.0 0.0 0.0 6 18 10 2 0.9 1.1 1 0 0.0 0.0 0.0 7 19 10 1 0.4 0.9 1 0 0.0 0.0 0.0 8 20 5 2 0.4 0.8 1 0 0.0 0.0 0.0 9 21 40 2 0.2 1.1 0 0 0.0 0.0 0.0 10 22 40 2 0.4 1.5 0 0 0.0 0.0 0.0 11 23 5 2 3.7 1.1 1 0 0.0 0.0 0.0 12 24 10 2 0.9 1.1 1 0 0.0 0.0 0.0 13 25 10 2 0.9 1.1 1 0 0.0 0.0 0.0 14 26 10 2 0.9 1.1 1 0 0.0 0.0 0.0 15 31 10 2 0.9 1.1 1 0 0.0 0.0 0.0 16 32 10 2 0.9 1.1 1 0 0.0 0.0 0.0 The first number is a number of rows in data-block below. These numbers are the coefficients for my functions in FORTRAN program. Before I run my program I must read this file, change some of these coefficients and write this file again in the same form. In the file ETab.py I wrote: file ETab.py: ----------------------------------------------------------------- from Tkinter import * import tkFont import string class ETab(Frame): def __init__(self): Frame.__init__(self,height="40",width="600",relief=RAISED) self.master.title('Data for grid generation') self.grid() ELista=["nr","Egde","nCell","nFun","P","Q","Metoda","WBTyp","Left","Right","sigma"] for icol in range(len(ELista)): self.Etykieta(icol,irow=0,EText=ELista[icol]) f=open('ETab_H1.dan', 'r'); self.c=f.readline() c1=int(self.c) self.FieldList=[] self.FieldList.append(c1) k=1 for i in range(c1): c=f.readline() s=c.split() dl=len(s) for j in range(dl): self.Pola(k,j,i,DefaultValue=s[j]) k=k+1 f.close() self.applyBotton = Button(self,text="Apply",command=self.addEntry) self.applyBotton.grid(column=dl-2,row=c1+1) self.quitButton = Button(self, text="Quit",command=self.quit) self.quitButton.grid(column=dl-1,row=c1+1) def addEntry(self): nElem=len(self.FieldList) print nElem ff=open('ETab_H1.spr', 'w'); ff.write(self.c) LL=StringVar() for k in range(nElem): LL=self.FieldList[k] print k,LL ff.close() def Etykieta(self,icol,irow,EText): lab=Label(self,text=EText) lab.grid(column=icol,row=irow) return def Pola(self,k,icol,irow,DefaultValue): self.Tab=StringVar() WLista=[5,5,5,5,10,10,10,10,10,10,10] self.pole=Entry(self,highlightcolor="BLUE",textvariable=self.Tab,justify=RIGHT,width=WLista[icol]) self.pole.grid(column=icol,row=irow+1) self.pole.insert(0,DefaultValue) self.FieldList.append(self.Tab) return self.Tab ETab().mainloop() ----------------------------------------------------------------- This script connects all numbers in my data-file with Entry Widget, but the results are: 177 0 16 1 PY_VAR0 2 PY_VAR1 3 PY_VAR2 ... 174 PY_VAR173 175 PY_VAR174 176 PY_VAR175 And when I change LL into LL.get(): 177 Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python2.4/lib-tk/Tkinter.py", line 1345, in __call__ return self.func(*args) File "ETab.py", line 107, in addEntry print k,LL.get() AttributeError: 'int' object has no attribute 'get' What is wrong? And, how can I take the value of self.Tab? Sorry for my English. M.S. From Serge.Orlov at gmail.com Wed Jun 14 20:20:24 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 14 Jun 2006 17:20:24 -0700 Subject: Bundling an application with third-party modules References: <1150285229.237626.36440@y41g2000cwy.googlegroups.com> Message-ID: <1150330824.653252.212300@f6g2000cwb.googlegroups.com> Ben Finney wrote: > > 2. An Installshield-type installer can place files (essentially) > > wherever you want them > > That's a large part of my question. How can I lay out these modules > sensibly during installation so they'll be easily available to, but > specific to, my application? Put them in a directory "lib" next to the main module and start the main module with the following blurb: ------------------------------------------------ import sys, os sys.path.insert(1, os.path.join(sys.path[0],"lib")) ------------------------------------------------ From boris.lorbeer at science-computing.de Sun Jun 11 03:10:50 2006 From: boris.lorbeer at science-computing.de (boris) Date: 11 Jun 2006 00:10:50 -0700 Subject: package search Message-ID: <1150009850.738535.155550@m38g2000cwc.googlegroups.com> I have two directories, lib1 and lib2, that both contain the package foo, one with the submodule mod1 and the other with the submodule mod2: $ ls lib*/foo/ lib1/foo/: __init__.py __init__.pyc mod1.py mod1.pyc lib2/foo/: __init__.py __init__.pyc mod2.py mod2.pyc $ Now this script: import sys sys.path.append("lib1") sys.path.append("lib2") import foo.mod1 will find the module foo.mod1, while the same script with the two append-lines interchanged will not: import sys sys.path.append("lib2") sys.path.append("lib1") import foo.mod1 The error is: import foo.mod1 ImportError: No module named mod1 So I guess that when Python finds the package foo, it will not look for it again using the rest of the search path, even if at that first place the module could not be found. Other languages like e.g. Java would find the module mod1 in the second case too (if Java doesn't find it in the first place, it will also look for it in the second place). This behaviour of Python is very unfortunate, because you always have to merge your package trees. In my cvs I have several packages, each in its own cvs module, all starting with de.science_computing. Now if I need two of them in a new project, I will have two package trees in my cvs sandbox, both starting with de.science_computing. Leaving the sandbox that way, cvs will work but Python imports will fail while if I merge all the package trees, Python will work but cvs won't. My questions: - Have I done anything wrong? - If not, is this behaviour of Python a bug or intentional? - If it it intentional, what is the intent? Thank you for your help Boris From jjlee at reportlab.com Tue Jun 6 16:59:25 2006 From: jjlee at reportlab.com (John J. Lee) Date: Tue, 06 Jun 2006 20:59:25 GMT Subject: Need pixie dust for building Python 2.4 curses module on Solaris 8 References: Message-ID: <87vereq9ua.fsf@reportlab.com> skip at pobox.com writes: > I'm having no success building the curses module on Solaris 8 (yes, I know > it's ancient - advancing the state-of-the-art is not yet an option) for > Python 2.4. Sun provides an apparently ancient version of curses in > /usr/lib, so I downloaded and installed ncurses 5.5, both using default > settings and using --with-shared. When the curses module is linked against > libcurses.so I get some strange error about acs32map being undefined (which > appears to live in a couple termcap-ish files in /usr/lib). When the curses > module is linked against libncurses.a I get bazillions of linker errors like > this: > > Text relocation remains referenced > against symbol offset in file > table.0 0x41 /opt/app/nonc++/ncurses-5.5/lib/libncurses.a(lib_color.o) [...] > The build step and output from distutils are: [...] > Any ideas what's wrong and what I need to do to correct the problem? Was libncurses.a compiled with -fpic (or -fPIC, if necessary)? http://mail.python.org/pipermail/python-dev/2001-March/013510.html John From junkytownMAKNI at gmail.com Mon Jun 26 13:41:05 2006 From: junkytownMAKNI at gmail.com (SuperHik) Date: Mon, 26 Jun 2006 19:41:05 +0200 Subject: Beginner Programmer Question In-Reply-To: <1151342733.742416.180370@r2g2000cwb.googlegroups.com> References: <1151342733.742416.180370@r2g2000cwb.googlegroups.com> Message-ID: kydavis77 at gmail.com wrote: > I am doing alot of reading and trying to teach myself how to program. > I can not figure out how to make "Write a program that continually > reads in numbers from the user and adds them together until the sum > reaches 100." this work. If someone could show me the correct code so i > can learn from that it would be much appreciated. Thanks > summ = 0 while summ < 100: usr = input('Enter a number:') summ += usr #that's same as>>> summ = summ + usr print summ print "now continue with whatever you want..." From nmm1 at cus.cam.ac.uk Tue Jun 20 11:41:11 2006 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 20 Jun 2006 15:41:11 GMT Subject: Iteration over recursion? References: <1150808045.539887.291180@i40g2000cwc.googlegroups.com> <1150816827.826028.114740@h76g2000cwa.googlegroups.com> Message-ID: In article <1150816827.826028.114740 at h76g2000cwa.googlegroups.com>, "Jon Clements" writes: |> MTD wrote: |> |> > I've been told that iteration in python is generally more |> > time-efficient than recursion. Is that true? |> |> AFAIK, in most languages it's a memory thing. Each time a function |> calls itself, the 'state' of that function has to be stored somewhere |> so that it may continue, as was, when the recursive function returns. Well, vaguely. That is probably the case in Python, but it isn't always true, and is not the only issue. Tail recursion removal can often eliminate the memory drain, but the code has to be written so that will work - and I don't know offhand whether Python does it. In compiled "3rd GL" languages, there are a lot of optimisation issues where iteration will often produce better code than recursion, but few (if any) are relevant to Python. Regards, Nick Maclaren. From bborcic at gmail.com Tue Jun 20 08:49:50 2006 From: bborcic at gmail.com (Boris Borcic) Date: Tue, 20 Jun 2006 14:49:50 +0200 Subject: [OT] code is data In-Reply-To: <4496b29f$0$27412$626a54ce@news.free.fr> References: <44965f53$0$12743$636a55ce@news.free.fr> <4496b29f$0$27412$626a54ce@news.free.fr> Message-ID: <4497eee6$1_1@news.bluewin.ch> bruno at modulix wrote: > Anton Vredegoor wrote: >> bruno at modulix wrote: >> >>> I still don't get the point. >> >> Well, I've got to be careful here, lest I'd be associated with the >> terr.., eh, the childp..., eh the macro-enablers. >> >> The idea is to have a way to transform a Python (.py) module into XML >> and then do source code manipulations in XML-space using ElementTree. > > My my my... I'm not against the idea of dynamic source code > transformation, but for heaven's sake, *why* would one put XML in the > mix ??????? If a good transform could "reveal" xml as "python's s-expression syntax", not only would source2source transform using xml t2t transform tools be facilitated, but generally speaking it would be easier for "xml retro-coded" python source to find its way through xml-enabled tools&chains. And incite developpers of such tools to consider python a better candidate (eg than it currently is) whenever the matter of scripting the tool comes up. From scott.mccracken at gmail.com Tue Jun 27 23:53:56 2006 From: scott.mccracken at gmail.com (Scott McCracken) Date: 27 Jun 2006 20:53:56 -0700 Subject: Help Installing smartypants.py Message-ID: <1151466836.227516.40540@d56g2000cwd.googlegroups.com> I just got Python 2.4 setup locally (Mac OS X) and am trying to extend it by installing both the markdown and smartypants plugins. Ultimately I'd like to be able use both in a custom CMS I'm building with Django. Installing markdown was a snap by following the instructions at http://www.freewisdom.org/projects/python-markdown/, but I cannot figure out what to do for smartypants. I have found: http://web.chad.org/projects/smartypants.py/, but cannot make any sense of it. After reading Jeff Croft's wonderful site, I know it's possible - and when I asked him in one of his posts he gave me the following response: > As for SmartyPants -- there is a Python port. I've found it to be not quite as perfect as the original >Perl version, but it basically works. Just Google for it. You'd install it the same way (drop >smartypants.py in your Python path). Does anyone know what port he's talking about? Is it the smartypants.py file referenced above? And if so, any quick tips for a clueless UNIX user on how to drop smartypants.py in my Python path? Many thanks in advance! From flaus.a at wanadoo.fr Sun Jun 18 05:01:29 2006 From: flaus.a at wanadoo.fr (flaus.a at wanadoo.fr) Date: 18 Jun 2006 02:01:29 -0700 Subject: Standard Yes / No Windows Dialog box creation In-Reply-To: References: <1150581640.385143.83410@y41g2000cwy.googlegroups.com> Message-ID: <1150621289.332562.201500@p79g2000cwp.googlegroups.com> SuperHik a ?crit : > I've never seen "easier" way to do it, but my solution for you if you > want to create a GUI application without learning any GUI programming > would be to consider Glade, wxGlade and such... Yes I wanted something easy because it's the first time that I use a Gui into Python and I don't wanted to learn the complete Windows GUI programming just to display a Yes / No dialog box... > >> > > Do it just the same way as you did it with the "Open File" or "Open > > Folder" windows dialog. What is your problem with it? > > > I think what he means by "create" is somethink like > win32ui.CreateFileDialog() because of the "easier" part. Yes I wanted something like win32ui.CreateFileDialog() to create my dialog box. Unfortunately, win32ui.CreateDialog() is not so easy... From onurb at xiludom.gro Thu Jun 1 05:20:22 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 01 Jun 2006 11:20:22 +0200 Subject: Best way to do data source abstraction In-Reply-To: References: Message-ID: <447eb1ca$0$27292$626a54ce@news.free.fr> Arthur Pemberton wrote: > What is the best way to do data source abtraction? For example have > different classes with the same interface, but different > implementations. > > I was thinking of almost having classA as my main class, and have > classA dynamically "absorb" classFood into to based on the extension > of the input file received by classA. But this doesn't seem possible. Could you explain more accurately what you're trying to do ? FWIW, it seems that a plain old factory function would do ? class DatasourceAbstraction(object): """ base class, factoring common stuff """ # implementation here class JpegFile(DatasourceAbstraction): # .... class PdfFile(DatasourceAbstraction): # .... class TxtFile(DatasourceAbstraction): # .... # etc _classes = { 'jpg' : JpegFile, 'txt' : TxtFile, 'pdf' : PdfFile, # etc.. } def Datasource(inputfile): ext = os.path.splitext(inputfile) return _classes.get(ext, )(inputfile) The fact that there's no 'new' keyword in Python, and that classes are callable objects acting as factories means that it's a no-brainer to use a plain function (eventually disguised as a Class - the client code just doesn't care !-) as factory... Now if I missed the point, please give more explanations... -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From suma.37 at gmail.com Mon Jun 5 09:40:29 2006 From: suma.37 at gmail.com (su) Date: 5 Jun 2006 06:40:29 -0700 Subject: is it possible to find which process dumped core Message-ID: <1149514829.032643.193890@h76g2000cwa.googlegroups.com> to find which process dumped core at the promt we give $ file core.28424 core.28424: ELF 32-bit LSB core file of 'soffice.bin' (signal 11), Intel 80386, version 1 (SYSV), from 'soffice.bin' from this command we know 'soffice.bin' process dumped core. Now can i do the same using python i.e. finding which process dumped core? if so how can i do it? From jo at durchholz.org Sun Jun 25 08:52:15 2006 From: jo at durchholz.org (Joachim Durchholz) Date: Sun, 25 Jun 2006 14:52:15 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150904134.520639.71070@b68g2000cwa.googlegroups.com> Message-ID: Anton van Straaten schrieb: > Marshall wrote: >> Can you be more explicit about what "latent types" means? > > Sorry, that was a huge omission. (What I get for posting at 3:30am.) > > The short answer is that I'm most directly referring to "the types in > the programmer's head". Ah, finally that terminology starts to make sense to me. I have been wondering whether there's any useful difference between "latent" and "run-time" typing. (I tend to avoid the term "dynamic typing" because it's overloaded with too many vague ideas.) > there are usually many possible static > type schemes that can be assigned to a given program. This seems to apply to latent types as well. Actually the set of latent types seems to be the set of possible static type schemes. Um, well, a superset of these - static type schemes tend to be slightly less expressive than what the programmer in his head. (Most type schemes cannot really express things like "the range of this index variable is such-and-so", and the boundary to general assertions about the code is quite blurry anyway.) > There's a close connection between latent types in the sense I've > described, and the "tagged values" present at runtime. However, as type > theorists will tell you, the tags used to tag values at runtime, as e.g. > a number or a string or a FooBar object, are not the same thing as the > sort of types which statically-typed languages have. Would that be a profound difference, or is it just that annotating a value with a full type expression would cause just too much runtime overhead? In your terminology: > So, where do tagged values fit into this? Tags help to check types at > runtime, but that doesn't mean that there's a 1:1 correspondence between > tags and types. Would it be possible to establish such a correspondence, would it be common consensus that such a system should be called "tags" anymore, or are there other, even more profound differences? Regards, Jo From michael.f.ellis at gmail.com Thu Jun 1 17:57:49 2006 From: michael.f.ellis at gmail.com (michael.f.ellis at gmail.com) Date: 1 Jun 2006 14:57:49 -0700 Subject: An oddity in list comparison and element assignment In-Reply-To: <6dKdnVnjh5LTz-LZnZ2dnUVZ_qmdnZ2d@speakeasy.net> References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> <6dKdnVnjh5LTz-LZnZ2dnUVZ_qmdnZ2d@speakeasy.net> Message-ID: <1149199069.871245.270330@f6g2000cwb.googlegroups.com> Truthfully, I wouldn't mind it at all. In Python, I frequently write things like i == int(f) or vice versa just to avoid subtle bugs that sometimes creep in when later modifications to code change the original assumptions. When working in C, I always set the compiler for maximum warnings and do my damndest to make them all go away. In the long run, time spent on rigorous coding always repays itself with interest in time saved debugging. Mike Erik Max Francis wrote: > michael.f.ellis at gmail.com wrote: > > > With all due respect to your well-deserved standing in the Python > > community, I'm not convinced that equality shouldn't imply invariance > > under identical operations. > > Doo you really want > > 2 == 2.0 > > to be False? > > -- > Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ > San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis > Without victory there is no survival. > -- Winston Churchill From pjb at informatimago.com Thu Jun 22 13:02:49 2006 From: pjb at informatimago.com (Pascal Bourguignon) Date: Thu, 22 Jun 2006 19:02:49 +0200 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150902275.129780.50260@p79g2000cwp.googlegroups.com> <1150918629.818145.143220@y41g2000cwy.googlegroups.com> <4fv081F1jh4ifU1@individual.net> <1150967543.947096.72840@g10g2000cwb.googlegroups.com> <4fv84rF1kp06kU1@individual.net> <1150988625.527780.148710@c74g2000cwc.googlegroups.com> Message-ID: <873bdx9l8m.fsf@thalassa.informatimago.com> "Marshall" writes: > Pascal Costanza wrote: >> >> Consider a simple expression like 'a + b': In a dynamically typed >> language, all I need to have in mind is that the program will attempt to >> add two numbers. In a statically typed language, I additionally need to >> know that there must a guarantee that a and b will always hold numbers. > > I still don't really see the difference. > > I would not expect that the dynamic programmer will be > thinking that this code will have two numbers most of the > time but sometimes not, and fail. I would expect that in both > static and dynamic, the thought is that that code is adding > two numbers, with the difference being the static context > gives one a proof that this is so. In this simple example, > the static case is better, but this is not free, and the cost > of the static case is evident elsewhere, but maybe not > illuminated by this example. > > This thread's exploration of the mindset of the two kinds > of programmers is difficult. It is actually quite difficult, > (possibly impossible) to reconstruct mental states > though introspection. Nonetheless I don't see any > other way to proceed. Pair programming? Well this is a question of data flow. As I explained, there's a whole body of functions that don't process concretely the data they get. But of course, eventually you must write a function that do some concrete processing on the data it gets. That's when you consider the type of the values. Such functions may be generic functions with methods dispatching on the actual type of the parameters, or you may encounter some TYPECASE or COND inside the function before calling non-abstract "primitives" that work only on some specific type. -- __Pascal Bourguignon__ http://www.informatimago.com/ "I have challenged the entire quality assurance team to a Bat-Leth contest. They will not concern us again." From justin.mailinglists at gmail.com Wed Jun 21 03:20:20 2006 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: 21 Jun 2006 00:20:20 -0700 Subject: Python SHA-1 as a method for unique file identification ? [help!] References: <1150873779.832601.154920@b68g2000cwa.googlegroups.com> Message-ID: <1150874420.935698.314180@y41g2000cwy.googlegroups.com> EP wrote: > This inquiry may either turn out to be about the suitability of the > SHA-1 (160 bit digest) for file identification, the sha function in > Python ... or about some error in my script. > > This is on Windows XP. > > def hashit(pth): > fs=open(pth,'r').read() > sh=sha.new(fs).hexdigest() > return sh > cannot comment on the suitability of SHA for your use-case but shouldn't you be opening the file in binary mode? fs=open(pth,'rb').read() From fredrik at pythonware.com Thu Jun 29 17:21:41 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 29 Jun 2006 23:21:41 +0200 Subject: Is it safe to shre a reg exp object among threads? In-Reply-To: <1151615265.014791.307200@p79g2000cwp.googlegroups.com> References: <1151615265.014791.307200@p79g2000cwp.googlegroups.com> Message-ID: overly.crazy.steve at gmail.com wrote: > Let's say I construct a regular expression object r by: > > r = re.compile("some pattern") > > Is it safe to let multiple threads to use r concurrently (use r.search > on different strings, etc.)? yes. From ketil+news at ii.uib.no Tue Jun 27 03:30:40 2006 From: ketil+news at ii.uib.no (Ketil Malde) Date: Tue, 27 Jun 2006 09:30:40 +0200 Subject: What is Expressiveness in a Computer Language References: <7zy7vt1mz2.fsf@app-3.diku.dk> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <1151384511.223582.305760@m73g2000cwd.googlegroups.com> Message-ID: "Marshall" writes: > There are also what I call "packaging" issues, such as > being able to run partly-wrong programs on purpose so > that one would have the opportunity to do runtime analysis > without having to, say, implement parts of some interface > that one isn't interested in testing yet. These could also > be solved in a statically typed language. (Although > historically it hasn't been done that way.) I keep hearing this, but I guess I fail to understand it. How "partly-wrong" do you require the program to be? During development, I frequently sprinkle my (Haskell) program with 'undefined' and 'error "implement later"' - which then lets me run the implemented parts until execution hits one of the 'undefined's. The "cost" of static typing for running an incomplete program is thus simply that I have to name entities I refer to. I'd argue that this is good practice anyway, since it's easy to see what remains to be done. (Python doesn't seem to, but presumably a serious dynamically typed system would warn about references to entities not in scope?) -k -- If I haven't seen further, it is by standing in the footprints of giants From colincolehour at gmail.com Mon Jun 19 20:46:50 2006 From: colincolehour at gmail.com (colincolehour at gmail.com) Date: 19 Jun 2006 17:46:50 -0700 Subject: Need Help comparing dates In-Reply-To: References: <1150419503.224684.320550@c74g2000cwc.googlegroups.com> <1150741480.160371.234000@g10g2000cwb.googlegroups.com> Message-ID: <1150764410.495033.254520@r2g2000cwb.googlegroups.com> The program works great! It does everything I wanted it to do and now I'm already thinking about ways of making it more useful like emailing me the results of my program. Thanks everyone for the help and advice. Colin Tim Chase wrote: > > I kept getting a Python error for the following line: > > > > month = m[webMonth] > > > > I changed it to month = month_numbers[webMonth] > > > > and that did the trick. > > Sorry for the confusion. Often when I'm testing these things, > I'll be lazy and create an alias to save me the typing. In this > case, I had aliased the month_numbers mapping to "m": > > >>> m = month_numbers > > and it slipped into my pasted answer email. You correctly fixed > the problem. The purpose of the mapping is simply to resolve the > month name to the month number so that the month number can be > used. Depending on how predictable the website's date string > will be, you can use > > month_numbers = dict([(date(2006, m, 1).strftime("%b").upper(), > m) for m in range(1,13)]) > > and then use > > month = month_numbers[webMonth.upper()] > > or > > month = month_numbers[webMonth[0:3].upper()] > > depending on whether the website might return full month names or > not. > > -tkc From anatoli.barski at googlemail.com Thu Jun 1 14:36:29 2006 From: anatoli.barski at googlemail.com (anatoli.barski at googlemail.com) Date: 1 Jun 2006 11:36:29 -0700 Subject: how to print newline in xml? In-Reply-To: References: <1149023930.292203.152540@u72g2000cwu.googlegroups.com> <1149145466.190011.146250@i39g2000cwa.googlegroups.com> Message-ID: <1149186989.073062.230220@f6g2000cwb.googlegroups.com> Thank you! I think description as an attribute is readable. But now I'm thinking about the order of attributes cause I noticed that for instance X="0" Y="0" Z="0" set in this order by my script is printed like X="0" Z="0" Y="0" therefore it could be messy - I wouldn't like the description to be somewhere between the other attributes. But I have to test it. I'll have to consider some better names for the elements Sending my regards, Anatoli From scott.daniels at acm.org Thu Jun 1 19:49:32 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Thu, 01 Jun 2006 16:49:32 -0700 Subject: Recommendations for CD/DVD-based or on-line Python classes? In-Reply-To: <127uturbd73g5ca@corp.supernews.com> References: <127uturbd73g5ca@corp.supernews.com> Message-ID: <447f78a4$1@nntp0.pdx.net> Joel Kolstad wrote: > Just curious... I have plenty of programming background (C++ being the closest > to Python), and I have a copy of Lutz's "Learning Python," but before I dive > head-first into that tome, does anyone know of a web-based or CD/DVD-based > training class that's priced for individuals? > > Example of what I'm looking for: Something like 6 or 7 years ago Ziff-Davis > had a bunch of on-line instructor-lead courses, where you'd read a chapter in > a book, read the instructor's take on the chapter (just a few pages), perform > the programming assignments, and ask the instructor if you had any > difficulties. There was a solid schedule (ch. 1 this week, ch. 2 the next, > etc. -- courses repeated every quarter or somesuch) as well. Ziff-Davis > charged something like $99 or $199/year for this service (all the courses you > wanted to sign up for -- quite reasonable, IMO) and also made money by > requiring the use of their own books (which were often someone else's book > that they'd just put their own name on) -- which were usually cheap enough at > something like $30/ea. > > That whole setup worked quite well for me... anyone know of something similar? > If not I probably will have to force myself to spend an hour a day or > something going through Lutz's book... > > Thanks, > ---Joel Kolstad > > Well, you could read through all the web thingies around (the online tutorial is great), many others listed "getting started" should help, and to really build your muscles, try the "Python challenge." -- --Scott David Daniels scott.daniels at acm.org From martin at v.loewis.de Mon Jun 5 04:22:27 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 05 Jun 2006 10:22:27 +0200 Subject: Python less error-prone than Java In-Reply-To: References: <1149424883.529756.13700@j55g2000cwa.googlegroups.com> Message-ID: <4483E9C3.6090207@v.loewis.de> Christoph Zwerschke wrote: > Anyway, in Python, you would first define: > > def wrap(x, at=1<<31): > if x < -at: > x += at*2 > elif x >= at: > x -= at*2 > return x > > Then, the Python program would be as simple: > > Distance = lambda t1,t0: wrap(t1-t0) In Python 2.4 and later, you could write def Distance(t1, t0, maxint=(1<<32)-1): return (t1-t0) & maxint Like your code, this also extends to 24-bit integers or 64-bit integers. Regards, Martin From fredrik at pythonware.com Wed Jun 28 11:10:26 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 28 Jun 2006 17:10:26 +0200 Subject: handling unicode data References: <1151506510.391856.207460@y41g2000cwy.googlegroups.com> Message-ID: Filipe wrote: > In the console output, for a record where I expected to see "Fran?a" > I'm getting the following: > > "" - When I print the type (print type(row[1])) > "Fran+a" - When I print the "term" variable (print term) > "Fran\xd8a" - When I print all the query results (print results) > > The values in "Term" column in "TestTable" are stored as unicode (the > column's datatype is nvarchar), yet, the python data type of the values > I'm reading is not unicode. > It all seems to be an encoding issue, but I can't see what I'm doing > wrong.. looks like the DB-API driver returns 8-bit ISO-8859-1 strings instead of Unicode strings. there might be some configuration option for this; see in worst case, you could do something like def unicodify(value): if isinstance(value, str): value = unicode(value, "iso-8859-1") return value term = unicodify(row[1]) but it's definitely better if you can get the DB-API driver to do the right thing. From bencvt at gmail.com Thu Jun 1 18:16:33 2006 From: bencvt at gmail.com (Ben Cartwright) Date: 1 Jun 2006 15:16:33 -0700 Subject: grouping a flat list of number by range In-Reply-To: <1149196642.001466.53990@c74g2000cwc.googlegroups.com> References: <1149196642.001466.53990@c74g2000cwc.googlegroups.com> Message-ID: <1149200193.757861.51060@i40g2000cwc.googlegroups.com> joh12005 at yahoo.fr wrote: > i'm looking for a way to have a list of number grouped by consecutive > interval, after a search, for example : > > [3, 6, 7, 8, 12, 13, 15] > > => > > [[3, 4], [6,9], [12, 14], [15, 16]] > > (6, not following 3, so 3 => [3:4] ; 7, 8 following 6 so 6, 7, 8 => > [6:9], and so on) > > i was able to to it without generators/yield but i think it could be > better with them, may be do you an idea? Sure: def group_intervals(it): it = iter(it) val = it.next() run = [val, val+1] for val in it: if val == run[1]: run[1] += 1 else: yield run run = [val, val+1] yield run --Ben From marshall.spight at gmail.com Thu Jun 22 22:35:40 2006 From: marshall.spight at gmail.com (Marshall) Date: 22 Jun 2006 19:35:40 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150904134.520639.71070@b68g2000cwa.googlegroups.com> Message-ID: <1151030140.202720.245140@y41g2000cwy.googlegroups.com> Anton van Straaten wrote: > Marshall wrote: > > Can you be more explicit about what "latent types" means? > > I'm sorry to say it's not at all natural or intuitive to me. > > Are you referring to the types in the programmers head, > > or the ones at runtime, or what? > > Sorry, that was a huge omission. (What I get for posting at 3:30am.) Thanks for the excellent followup. > The short answer is that I'm most directly referring to "the types in > the programmer's head". In the database theory world, we speak of three levels: conceptual, logical, physical. In a dbms, these might roughly be compared to business entities described in a requirements doc, (or in the business owners' heads), the (logical) schema encoded in the dbms, and the b-tree indicies the dbms uses for performance. So when you say "latent types", I think "conceptual types." The thing about this is, both the Lisp and the Haskell programmers are using conceptual types (as best I can tell.) And also, the conceptual/latent types are not actually a property of the program; they are a property of the programmer's mental model of the program. It seems we have languages: with or without static analysis with or without runtime type information (RTTI or "tags") with or without (runtime) safety with or without explicit type annotations with or without type inference Wow. And I don't think that's a complete list, either. I would be happy to abandon "strong/weak" as terminology because I can't pin those terms down. (It's not clear what they would add anyway.) > A more complete informal summary is as follows: > > Languages with latent type systems typically don't include type > declarations in the source code of programs. The "static" type scheme > of a given program in such a language is thus latent, in the English > dictionary sense of the word, of something that is present but > undeveloped. Terms in the program may be considered as having static > types, and it is possible to infer those types, but it isn't necessarily > easy to do so automatically, and there are usually many possible static > type schemes that can be assigned to a given program. > > Programmers infer and reason about these latent types while they're > writing or reading programs. Latent types become manifest when a > programmer reasons about them, or documents them e.g. in comments. Uh, oh, a new term, "manifest." Should I worry about that? > (As has already been noted, this definition may seem at odds with the > definition given in the Scheme report, R5RS, but I'll address that in a > separate post.) > > There's a close connection between latent types in the sense I've > described, and the "tagged values" present at runtime. However, as type > theorists will tell you, the tags used to tag values at runtime, as e.g. > a number or a string or a FooBar object, are not the same thing as the > sort of types which statically-typed languages have. > > A simple example of the distinction can be seen in the type of a > function. Using Javascript as a lingua franca: > > function timestwo(x) { return x * 2 } > > In a statically-typed language, the type of a function like this might > be something like "number -> number", which tells us three things: that > timestwo is a function; that it accepts a number argument; and that it > returns a number result. > > But if we ask Javascript what it thinks the type of timestwo is, by > evaluating "typeof timestwo", it returns "function". That's because the > value bound to timestwo has a tag associated with it which says, in > effect, "this value is a function". Well, darn. It strikes me that that's just a decision the language designers made, *not* to record complete RTTI. (Is it going to be claimed that there is an *advantage* to having only incomplete RTTI? It is a serious question.) > But "function" is not a useful type. Why not? Because if all you know > is that timestwo is a function, then you have no idea what an expression > like "timestwo(foo)" means. You couldn't write working programs, or > read them, if all you knew about functions was that they were functions. > As a type, "function" is incomplete. Yes, function is a parameterized type, and they've left out the parameter values. > By my definition, though, the latent type of timestwo is "number -> > number". Any programmer looking at the function can figure out that > this is its type, and programmers do exactly that when reasoning about a > program. Gotcha. > (Aside: technically, you can pass timestwo something other than a > number, but then you get NaN back, which is usually not much use except > to generate errors. I'll ignore that here; latent typing requires being > less rigourous about some of these issues.) > > So, where do tagged values fit into this? Tags help to check types at > runtime, but that doesn't mean that there's a 1:1 correspondence between > tags and types. For example, when an expression such as "timestwo(5) * > 3" is evaluated, three checks occur that are relevant to the type of > timestwo: > > 1. Before the function call takes place, a check ensures that timestwo > is a function. > > 2. Before the multiplication in "x * 2", a check ensures that x is a number. > > 3. When timestwo returns, before the subsequent multiplication by 3, a > check ensures that the return type of timestwo is a number. > > These three checks correspond to the three pieces of information > contained in the function type signature "number -> number". > > However, these dynamic checks still don't actually tell us the type of a > function. All they do is check that in a particular case, the values > involved are compatible with the type of the function. In many cases, > the checks may infer a signature that's either more or less specific > than the function's type, or they may infer an incomplete signature -- > e.g., the return type doesn't need to be checked when evaluating "arr[i] > = timestwo(5)". > > I used a function just as an example. There are many other cases where > a value's tag doesn't match the static (or latent) type of the terms > through which it flows. A simple example is an expression such as: > > (flag ? 5 : "foo") > > Here, the latent type of this expression could be described as "number | > string". There won't be a runtime tag anywhere which represents that > type, though, since the language implementation never deals with the > actual type of expressions, except in those degenerate cases where the > type is so simple that it happens to be a 1:1 match to the corresponding > tag. It's only the programmer that "knows" that this expression has > that type. Hmmm. Another place where the static type isn't the same thing as the runtime type occurs in languages with subtyping. Question: if a language *does* record complete RTTI, and the languages does *not* have subtyping, could we then say that the runtime type information *is* the same as the static type? Marshall From iddw at hotmail.com Thu Jun 15 18:33:09 2006 From: iddw at hotmail.com (Dave Hansen) Date: Thu, 15 Jun 2006 17:33:09 -0500 Subject: a good programming text editor (not IDE) References: <_xgkg.2317$No6.48542@news.tufts.edu> Message-ID: On Thu, 15 Jun 2006 17:12:26 GMT in comp.lang.python, John Salerno wrote: >I know there's a request for a good IDE at least once a week on the ng, >but hopefully this question is a little different. I'm looking for >suggestions for a good cross-platform text editor (which the features >for coding, such as syntax highlighting, etc.) but not a full IDE with >all the fancy jazz (GUI developer, UML diagrams, etc.). > >Ideally, it would be something I could even put on a flash drive and >move from computer to computer, but this isn't necessary. Just something >I can immediately use in either Windows or Linux (or Mac, if necessary). Very small, very fast, very powerful, and very portable (though I'm not sure about Mac...): Take a look at Jed from www.jedsoft.org. You might not find it pretty, however... Regards, -=Dave -- Change is inevitable, progress is not. From johnjsal at NOSPAMgmail.com Wed Jun 7 13:38:39 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 07 Jun 2006 17:38:39 GMT Subject: GUI Program Error In-Reply-To: <1149700099.634036.88090@f6g2000cwb.googlegroups.com> References: <1149536396.375285.319390@y43g2000cwc.googlegroups.com> <920hg.2238$No6.47697@news.tufts.edu> <1149700099.634036.88090@f6g2000cwb.googlegroups.com> Message-ID: Byte wrote: > Thanks, this works. Now, since the tutorial I was using is clearly > rubbish, any better ones? For a (relative) newbie please. Also, how do > I code a GUI Hello World program? > > -- /usr/bin/byte > Actually, that site is generally considered to be a pretty good place to start for tutorials. I think maybe you didn't go far enough through the "Tour of Some Common Widgets" section before you experienced problems (i.e., you didn't get to pack() or mainloop(), etc.). But I will agree with you that it is confusing when it says, following the top = Tk() line, "Notice that a new blank window has appeared", because as you noticed, nothing appears yet. My only guess is that this is either a mistake, or the tutorial is a little old, because I think Tkinter used to behave differently in the interactive prompt than it does now. Anyhow, I would stick with that site, but you might also try Fredrik's tutorial: http://www.pythonware.com/library/tkinter/introduction/ It's a great little intro, but also a reference to the widgets, methods, etc. I pretty much learned everything so far from that site (admittedly I'm just as new as you are, but it's still a good site!) :) From nmm1 at cus.cam.ac.uk Thu Jun 29 04:26:49 2006 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 29 Jun 2006 08:26:49 GMT Subject: Bug reporting impossible Message-ID: Currently logins are disabled to sourceforge.net, and (despite the comments) it won't let me report a bug anonymously. Does anyone know whether this is short or long term? I have a bug in 2.5 to report - which has been there for a while and isn't overwhelmingly critical and has been there for a while. Create a file called '' in your current directory containing 'print "Oh, yeah?\n"' and then import a module that doesn't exist. Don't include the single quotes. Regards, Nick Maclaren. From ldo at geek-central.gen.new_zealand Thu Jun 8 17:54:47 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 09 Jun 2006 09:54:47 +1200 Subject: Large Dictionaries References: <1147699064.107490@teuthos> <1147772420.405097@teuthos> <1147818548.532882.94180@i39g2000cwa.googlegroups.com> <1147874585.728471@teuthos> <1148514158.790760.205630@i40g2000cwc.googlegroups.com> <447af556$1@nntp0.pdx.net> Message-ID: In article , "Tim Peters" wrote: >For example, the O(N log N) heapsort is unreasonable compared to the >O(N**2) bubblesort by that reasoning (pre-sorted is actually a bad >case for heapsort, but a good case for bubblesort)? O(N log N) >sorting algorithms helped by pre-existing order are uncommon, unless >they do extra work to detect and exploit pre-existing order. Shellsort works well with nearly-sorted data. It's basically a smarter version of bubblesort with much improved efficiency. It's also very compact to implement. From kay.schluehr at gmx.net Mon Jun 19 12:26:14 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 19 Jun 2006 09:26:14 -0700 Subject: code is data References: <1150574111.415068.255900@p79g2000cwp.googlegroups.com> Message-ID: <1150734374.361606.159150@h76g2000cwa.googlegroups.com> Ravi Teja wrote: > People have however written various language interpreters (Scheme, > Forth and yes, even Basic) in Python, just for kicks. Still does not > make it a DSL language anymore than it makes C a DSL language. > > At present, the closest thing to writing a DSL in Python is Logix > http://livelogix.net/logix/ > Too bad though, the project is defunct and there has never been enough > interest in it. You might be interested in EasyExtend: http://www.fiber-space.de/EasyExtend/doc/EE.html Unlike Logix there are no macros defined in application code and there are no runtime macro expansions. So extension language semantics is always fixed at compile time. > Personally, I would like to see macros in Python (actually Logix > succeeding is good enough). But I am no language designer and the > community has no interest in it. When I absolutely need macros, I will > go elsewhere. Although Logix was written in Python and compiled to CPython bytecodes it was a language on its own right: a Python / Lisp hybrid. Opposed to this EasyExtend is a Python framework for language extensions and not itself a language. A quite typical use case may not involve any new grammar rules or terminals, but just generates code. See the coverage fiber as an example. From jes at nl.demon.net Thu Jun 1 13:13:24 2006 From: jes at nl.demon.net (Jim Segrave) Date: Thu, 01 Jun 2006 17:13:24 -0000 Subject: An oddity in list comparison and element assignment References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> Message-ID: <127u81kdf70ch8d@corp.supernews.com> In article <1149177617.985251.74560 at c74g2000cwc.googlegroups.com>, wrote: >Hi Alex, >With all due respect to your well-deserved standing in the Python >community, I'm not convinced that equality shouldn't imply invariance >under identical operations. > >Perhaps the most fundamental notion is mathematics is that the left and >right sides of an equation remain identical after any operation applied >to both sides. Our experience of the physical world is similar. If I >make identical modifications to the engines of two identical >automobiles, I expect the difference in performance to be identical. >If my expectation is met, I would assert that either the two vehicles >were not identical to begin with or that my modifications were not >performed identically. > >As to containers, would you say that envelope containing five $100 >bills is the same as an envelope containing a single $100 bill and 4 >xerox copies of it? If so, I'd like to engage in some envelope >exchanges with you :-) > >As I see it, reference copying is a very useful performance and memory >optimization. But I don't think it should undermine the validity of >assert(a==b) as a predictor of invariance under identical operations. I think you end up with a totally unwieldy definition of '==' for containers, since you have to check for _identical_ aliasing to whatever depth it might occur, and, if you insist on equality modeling the physical world, two lists can only be equal if: for each corresponding element in the two lists, either the element is a reference to the same underlying object or the corresponding elements are references to objects which do not have and never will have other references bound to them. For example: ra = ['a', 'a'] rb = ['b', 'b'] l1 = [ra, rb] l2 = [ra, rb] This will be equal by your definition and will preserve equality over identical operations on l1 and l2 l3 = [ ['a', 'b'], ['a', 'b']] This list will be identical, under your definition, so long as we don't have anyone doing anything to the references ra or rb. Your equality test has to claim that l1 and l3 are not equal, since ra could be changed and that's not an operation on l1 or l3 This also leaves out the complexity of analysiing nested structures - if you have a tuple, containing tuples which contain lists, then are those top level tuples 'equal' if there are aliases in the lists? How many levels deep should an equality test go? Does the more common test, to see if the elements of a sequence are identical at the time of comparision need a new operator or hand coding, since most of the time programmers aren't interested in future equality or not of the structures. -- Jim Segrave (jes at jes-2.demon.nl) From sjmachin at lexicon.net Wed Jun 28 20:00:36 2006 From: sjmachin at lexicon.net (John Machin) Date: Thu, 29 Jun 2006 10:00:36 +1000 Subject: locating strings approximately In-Reply-To: <1151537334.900487.322980@75g2000cwc.googlegroups.com> References: <1151537334.900487.322980@75g2000cwc.googlegroups.com> Message-ID: <44A31824.8000504@lexicon.net> On 29/06/2006 9:28 AM, BBands wrote: > I'd like to see if a string exists, even approximately, in another. For > example if "black" exists in "blakbird" or if "beatles" exists in > "beatlemania". The application is to look though a long list of songs > and return any approximate matches along with a confidence factor. I > have looked at edit distance, but that isn't a good choice for finding > a short string in a longer one. There is a trivial difference between the traditional distance-matrix-based Levenshtein algorithm for edit distance and the corresponding one for approximate string searching. Ditto between finite-state-machine approaches. Ditto between modern bit-bashing approaches. > I have also explored > difflib.SequenceMatcher and .get_close_matches, but what I'd really > like is something like: > > a = FindApprox("beatles", "beatlemania") > print a > 0.857 > > Any ideas? You got no ideas from googling "approximate string search python"??? From ptmcg at austin.rr._bogus_.com Wed Jun 21 11:58:54 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 21 Jun 2006 15:58:54 GMT Subject: returning index of minimum in a list of lists References: <1150901648.832039.165590@b68g2000cwa.googlegroups.com> Message-ID: <21emg.16887$JW5.4797@tornado.texas.rr.com> "Maric Michaud" wrote in message news:mailman.7319.1150903902.27775.python-list at python.org... Le Mercredi 21 Juin 2006 16:54, JJLaRocque at gmail.com a ?crit : > Hi all, > Is there a simple python function to return the list index of the > minimum entry in a list of lists? > ie, for [[3,3,3,3], [3,3,3,1], [3,3,3,3]] to return 2,4. > Or, same question but just for a list of numbers, not a list of lists. > Thanks, > Josh In [7]: min([3, 3, 1, 3]) Out[7]: 1 In [8]: min(min(e) for e in [ [3, 3], [3, 3, 1, 3], [3, 3, 3] ]) Out[8]: 1 regards, Read the original posting again. The OP does not want the minimum *value*, but the *index* of the minimum value. -- Paul data = [[3,3,3,3], [3,3,3,1], [3,3,3,3]] def getMinAndIndex(lst): minval,minidx = lst[0],0 for i,v in enumerate(lst[1:]): if v < minval: minval,minidx = v,i+1 return minval,minidx subMins = [ getMinAndIndex(sub) for sub in data ] subMin,subIdx = getMinAndIndex( [s[0] for s in subMins ] ) print "min = %d at [%d][%d]" % (subMin, subIdx, subMins[subIdx][1]) Gives: min = 1 at [1][3] From girish at cse.iitb.ac.in Mon Jun 12 05:06:18 2006 From: girish at cse.iitb.ac.in (Girish Sahani) Date: Mon, 12 Jun 2006 14:36:18 +0530 (IST) Subject: Function to remove elements from a list not working (corrected) In-Reply-To: <200606121041.01792.maric@aristote.info> References: <49543.10.209.4.1.1150100717.squirrel@10.105.1.3> <200606121041.01792.maric@aristote.info> Message-ID: <36394.10.209.4.1.1150103178.squirrel@10.105.1.3> Thanks!It worked....i wasted a lot of time trying to find a bug in my code...what is wrong in iterating over a list and modifying it? Doesnt python take the modified list every time the loop starts? Also in this case, i want to add a condition that if none of the pairs are in pairList, element = []. How can i do that? > Le Lundi 12 Juin 2006 10:25, Girish Sahani a ?crit : >> Hi, >> I am trying to modify a list of pairs (l4) by removing those >> pairs which are not present in a third list called pairList. >> The following is a simplified part of the routine i have written. >> However >> it does not give the correct output. Please help! >> Its possible i have made a trivial mistke since i am a newbie. >> >> def getl5(): >> l5 = [] >> pairList = [[1,2],[3,4],[3,5],[3,6],[9,7],[8,9],[8,7],[7,9],[11,10]] >> l4 > >> [[4,2],[4,7],[4,10],[4,12],[9,2],[9,7],[9,10],[9,12],[11,2],[11,7]] >> for >> pair in l4: >> if pair not in pairList: >> l4.remove(pair) >> print "l4 is",l4 >> > > You are trying to modify a list while iterating over it, never do that ! > >> The output given is: >> l4 is [[4, 7], [4, 12], [9, 7], [9, 12], [11, 7]] > > Is this work in your case ? > > def getl5(): > pairList = [[1,2],[3,4],[3,5],[3,6],[9,7],[8,9],[8,7],[7,9],[11,10]] > l4 = > [[4,2],[4,7],[4,10],[4,12],[9,2],[9,7],[9,10],[9,12],[11,2],[11,7]] > l4 = [ e for e in l4 if e in pairList ] > print "l5 is", l4 > > > -- > _____________ > > Maric Michaud > _____________ > > Aristote - www.aristote.info > 3 place des tapis > 69004 Lyon > Tel: +33 426 880 097 > -- > http://mail.python.org/mailman/listinfo/python-list > From nomail at nixmail.com Wed Jun 14 20:36:53 2006 From: nomail at nixmail.com (DarkBlue) Date: Thu, 15 Jun 2006 08:36:53 +0800 Subject: wxPython install question Message-ID: <4490ab8d@127.0.0.1> Trying to install wxPython on Suse10.1 64 with gcc4.1.0 and get wxPython-src-2.6.3.2/wxPython # python setup.py install Found wx-config: /usr/local/bin/wx-config Using flags: --toolkit=gtk2 --unicode=no --version=2.6 Preparing CORE... Preparing GLCANVAS... Preparing STC... Preparing GIZMOS... Preparing ANIMATE... running install running build running build_py copying wx/__version__.py -> build-gtk2/lib.linux-x86_64-2.4/wx copying wx/build/build_options.py -> build-gtk2/lib.linux-x86_64-2.4/wx/build running build_ext building '_glcanvas' extension gcc -pthread -fno-strict-aliasing -DNDEBUG -O2 -fmessage-length=0 -Wall -D_FORTIFY_SOURCE=2 -g -fPIC -DSWIG_TYPE_TABLE=_wxPython_table -DHAVE_CONFIG_H -DWXP_USE_THREAD=1 -UNDEBUG -DGTK_NO_CHECK_CASTS -D__WXGTK__ -D_FILE_OFFSET_BITS=64 -D_LARGE_FILES -DNO_GCC_PRAGMA -Iinclude -Isrc -I/usr/local/lib/wx/include/gtk2-ansi-release-2.6 -I/usr/local/include/wx-2.6 -I/usr/include/cairo -I/usr/include/freetype2 -I/usr/X11R6/include -I/usr/include/libpng12 -I/opt/gnome/include/gtk-2.0 -I/opt/gnome/lib64/gtk-2.0/include -I/opt/gnome/include/atk-1.0 -I/opt/gnome/include/pango-1.0 -I/opt/gnome/include/glib-2.0 -I/opt/gnome/lib64/glib-2.0/include -I/usr/include/python2.4 -c contrib/glcanvas/gtk/glcanvas_wrap.cpp -o build-gtk2/temp.linux-x86_64-2.4/contrib/glcanvas/gtk/glcanvas_wrap.o -O3 contrib/glcanvas/gtk/glcanvas_wrap.cpp: In function ?PyObject* _wrap_new_GLContext(PyObject*, PyObject*, PyObject*)?: contrib/glcanvas/gtk/glcanvas_wrap.cpp:1737: error: ?wxGLCanvas? was not declared in this scope contrib/glcanvas/gtk/glcanvas_wrap.cpp:1737: error: ?arg2? was not declared in this scope contrib/glcanvas/gtk/glcanvas_wrap.cpp:1737: error: expected primary-expression before ?)? token contrib/glcanvas/gtk/glcanvas_wrap.cpp:1737: error: expected `;' before numeric constant contrib/glcanvas/gtk/glcanvas_wrap.cpp:1740: error: ?wxGLContext? was not declared in this scope contrib/glcanvas/gtk/glcanvas_wrap.cpp:1740: error: ?arg4? was not declared in this scope then it errors out . What is wrong ? The wxwidgets compiled without a hitch. Thanks From sdcook55 at sbcglobal.net Tue Jun 20 20:31:09 2006 From: sdcook55 at sbcglobal.net (Stan Cook) Date: Wed, 21 Jun 2006 00:31:09 GMT Subject: Another Eclipse Question with Python Message-ID: I followed the help instructions to set a watchpoint for a variable, or at lest I tried. When I hilight the variable and go to the run menu, the "toggle watchpoint" is grayed out and can't be selected as specified. Is this Python related only? Just wondering, I want to use the software with all of the features it allows if possible. Thanks.... S Cook From arvind.mulay at gmail.com Thu Jun 29 05:12:48 2006 From: arvind.mulay at gmail.com (arvind) Date: 29 Jun 2006 02:12:48 -0700 Subject: Database access through python using GUI(Tkinter) Message-ID: <1151572368.885129.38590@p79g2000cwp.googlegroups.com> hi all, i am accessing sql+ database through python 2.4.3. i am using Tkinter to build my screens. how can i pass parameters on the click event of button from one function to the another? how can i run another file from current file? --------arvind From onurb at xiludom.gro Thu Jun 1 08:27:05 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 01 Jun 2006 14:27:05 +0200 Subject: Function mistaken for a method In-Reply-To: References: Message-ID: <447edd8d$0$2135$636a55ce@news.free.fr> Peter Otten wrote: > Eric Brunel wrote: > > >>My actual question is: why does it work in one case and not in the other? >>As I see it, int is just a function with one parameter, and the lambda is >>just another one. So why does the first work, and not the second? What >>'black magic' takes place so that int is not mistaken for a method in the >>first case? > > > A python-coded function has a __get__ attribute, a C-function doesn't. > Therefore C1.f performs just the normal attribute lookup while C2.f also > triggers the f.__get__(C2(), C2) call via the descriptor protocol which > happens to return a bound method. FWIW: class Obj(object): def __new__(cls, val, *args, **kw): print "in Obj.__new__" print "- called with :" print " cls :", cls print " val :", val print " args:", str(args) print " kw :", kw obj = object.__new__(cls, *args, **kw) print "got : %s - %s" % (obj, dir(obj)) return obj class CPlus(C): f = Obj > Peter > > -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From david.nospam.hopwood at blueyonder.co.uk Sat Jun 24 11:13:02 2006 From: david.nospam.hopwood at blueyonder.co.uk (David Hopwood) Date: Sat, 24 Jun 2006 15:13:02 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: <1151083239.829296.33030@i40g2000cwc.googlegroups.com> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150908952.804184.218990@r2g2000cwb.googlegroups.com> <1150991074.705803.211570@m73g2000cwd.googlegroups.com> <1151083239.829296.33030@i40g2000cwc.googlegroups.com> Message-ID: <2Ecng.463176$tc.227775@fe2.news.blueyonder.co.uk> Rob Thorpe wrote: > Andreas Rossberg wrote: >>Rob Thorpe wrote: >> >>>Its easy to create a reasonable framework. >> >>Luca Cardelli has given the most convincing one in his seminal tutorial >>"Type Systems", where he identifies "typed" and "safe" as two orthogonal >>dimensions and gives the following matrix: >> >> | typed | untyped >> -------+-------+---------- >> safe | ML | Lisp >> unsafe | C | Assembler >> >>Now, jargon "dynamically typed" is simply untyped safe, while "weakly >>typed" is typed unsafe. > > Consider a langauge something like BCPL or a fancy assembler, but with > not quite a 1:1 mapping with machine langauge. > > It differs in one key regard: it has a variable declaration command. > This command allows the programmer to allocate a block of memory to a > variable. If the programmer attempts to index a variable outside the > block of memory allocated to it an error will occur. Similarly if the > programmer attempts to copy a larger block into a smaller block an > error would occur. > > Such a language would be truly untyped and "safe", that is safe > according to many peoples use of the word including, I think, yours. > > But it differs from latently typed languages like python, perl or lisp. > In such a language there is no information about the type the variable > stores. The programmer cannot write code to test it, and so can't > write functions that issue errors if given arguments of the wrong type. So the hypothetical language, unlike Python, Perl and Lisp, is not dynamically *tagged*. -- David Hopwood From paul at eval.ca Thu Jun 1 15:38:55 2006 From: paul at eval.ca (Paul Osman) Date: Thu, 1 Jun 2006 15:38:55 -0400 Subject: How to format datetime values In-Reply-To: References: Message-ID: On 1-Jun-06, at 2:55 PM, A.M wrote: > Hi, > > > > I have a datetime value and want to format it to "June 1, 2006" > shape. How > can I do that? > > > > Thank you, > > Alan Why don't you just post the specs to your program and maybe someone will write it *FOR* you in less than a day? This is quicker than waiting for replies: Python Tutorial http://docs.python.org/tut/tut.html Module Index http://docs.python.org/modindex.html Cheers, -- Paul Osman http://www.eval.ca From ilias at lazaridis.com Fri Jun 9 14:06:46 2006 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Fri, 09 Jun 2006 21:06:46 +0300 Subject: CONSTRUCT - Python's way of Ruby's "alias_method" In-Reply-To: References: Message-ID: Duncan Booth wrote: > Ilias Lazaridis wrote: > >>> #patch_service.py >>> from toto import service >>> >>> def my_impl(self, *args) : >>> old_result = self._old_method(*args) >>> # ... >>> return new_result >>> >>> if not hasattr(service, '_old_method') : >>> service._old_method = service.method >>> service.method = my_impl >>> >>> once this file is imported, all future calls to "method" of service >>> instances will use my_impl. >> Ok, just a small problem when a _function_ is to be hooked. >> >> Looking a the code in the debugger shows that the function "syncdb" is >> correctly overridden. But when the code returns, "syncdb" has again >> it's original value. >> >> Can I import "syncdb" by reference instead by value, thus the change >> 'survives'? > > The difference is that Maric imported the module. To make the change affect > the original model you have to access the function as an attribute of its > module, not by importing the function from the module. ok, I understand. the code below works, but has the limitation that I cannot import the syncdb_hook within "django.core.management". There is no way to import/get "syncdb" but mutable? >> #syncdb_hook.py >> >> from django.rework.evolve import evolvedb >> from django.core.management import syncdb > from django.core import management > >> def syncdb_new(*args) : >> evolvedb() >> syncdb_result = syncdb_old(*args) >> return syncdb_result >> >> if syncdb != syncdb_new: >> syncdb_old = syncdb >> syncdb = syncdb_new >> > if management.syncdb != syncdb_new: > syncdb_old = management.syncdb > management.syncdb = syncdb_new works fine. . -- http://lazaridis.com From piet at cs.uu.nl Fri Jun 2 18:58:28 2006 From: piet at cs.uu.nl (Piet van Oostrum) Date: Sat, 03 Jun 2006 00:58:28 +0200 Subject: Open Source Charting Tool References: <1L0gg.1841$Su3.159041@news20.bellglobal.com> Message-ID: >>>>> Felipe Almeida Lessa (FAL) wrote: >FAL> Em Sex, 2006-06-02 ?s 16:56 -0400, A.M escreveu: >>> I can't browse to www.reporlab.org, but I found http://www.reportlab.com/ >>> which has a commercial charting product. Is that what you referring to? >FAL> ReportLab (the commercial bussiness thing on .com) is where the main >FAL> developers of ReportLab (a library freely available on www.reporlab.org) >FAL> work. So what you want really is .org, but apparently it's having >FAL> problems right now. No, but it should really be www.reportlab.org (with the *t*). -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From martin at v.loewis.de Sat Jun 17 07:36:41 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 17 Jun 2006 13:36:41 +0200 Subject: msvcr71.dll necessary? - Re: Which compiler will Python 2.5 / Windows (Intel) be built with? In-Reply-To: References: <1150367139.495114.148550@g10g2000cwb.googlegroups.com> <44934339$0$28177$9b622d9e@news.freenet.de> Message-ID: <4493e94a$0$13403$9b622d9e@news.freenet.de> robert wrote: > hmm, yet msvcrt4 is obviously preinstalled on each Windows - and its in > Windows Update Process. Its tagged: "4.20 - OS use only. DO NOT > DISTRIBUTE") > Think, in principle its possible to compile against that with > VS2003/2005... ? > ( think msvcrt4 is not delivered extra even in the python2.3 installer ) Unfortunately, you also need the header files and an import library to link against this library. Likewise, for applications that bundle MFC, you need the corresponding set of header files and libraries. Microsoft does not provide import libraries for msvcrt4.dll anymore. >> Making more users happy? Certainly not, either. Some users request that >> VS2005 is being used, not that VC6 is being used. Other users request >> that Python 2.5 continues to be built with VS 2003. You can't please >> everybody. > > Yet if the C runtime lib (distribution) problem is solved, the question > of the compiler becomes irrelevant. Everybody could use his compiler > without worry - a soft recommendation could be in the Python2.5 doc's to > link extensions also against the same common basic ctrl in order to keep > the numer of libs small. Unfortunately, that is a real technological challenge. Where do you get the header files and import libraries, and how do you explain to your compiler to use those instead of the ones it comes with? > there is also a "msvcrt.dll" - also updated by the Windows system. maybe > its on each Windows ? On XP it has version 7. What is this? It used to be possible to link with it. See http://msdn2.microsoft.com/en-us/library/abx4dbyh(VS.80).aspx This is now a "known DLL", and meant for use by system-level components only. > Maybe most a most simple cutoff criteria with "costs" does it magically. > Basic proposal: > > cost = (C1 * module-size - C2 * frequency-of-module-usage) Unfortunately, that criterion cannot be determined in an objective manner. It's not possible to determine frequency-of-module-usage in any meaningful way for existing modules, let alone for modules that are contributed and to be included only in the upcoming release. Regards, Martin From pjb at informatimago.com Thu Jun 22 08:15:37 2006 From: pjb at informatimago.com (Pascal Bourguignon) Date: Thu, 22 Jun 2006 14:15:37 +0200 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150902275.129780.50260@p79g2000cwp.googlegroups.com> <1150918629.818145.143220@y41g2000cwy.googlegroups.com> <4fv081F1jh4ifU1@individual.net> <1150967543.947096.72840@g10g2000cwb.googlegroups.com> <4fv84rF1kp06kU1@individual.net> Message-ID: <87irmt9yja.fsf@thalassa.informatimago.com> Andreas Rossberg writes: > Pascal Costanza wrote: >> Consider a simple expression like 'a + b': In a dynamically typed >> language, all I need to have in mind is that the program will >> attempt to add two numbers. In a statically typed language, I >> additionally need to know that there must a guarantee that a and b >> will always hold numbers. > > I'm confused. Are you telling that you just write a+b in your programs > without trying to ensure that a and b are in fact numbers?? Of course. (shadow '(+ *)) (defun + (&rest args) `(+ , at args)) (defun * (&rest args) `(* , at args)) (let ((var 'x) (init 'b) (slop 'a)) (+ init (* slop var))) --> (+ B (* A X)) -- __Pascal Bourguignon__ http://www.informatimago.com/ Nobody can fix the economy. Nobody can be trusted with their finger on the button. Nobody's perfect. VOTE FOR NOBODY. From frank at chagford.com Wed Jun 21 01:37:16 2006 From: frank at chagford.com (Frank Millman) Date: 20 Jun 2006 22:37:16 -0700 Subject: Segmentation fault only on Iinux In-Reply-To: <1150831329.649174.60410@g10g2000cwb.googlegroups.com> References: <1150831329.649174.60410@g10g2000cwb.googlegroups.com> Message-ID: <1150868236.699993.53850@m73g2000cwd.googlegroups.com> Kiran wrote: > Hello All, > In my program, I have a main thread which is the GUI (wxPython) and > then a thread which goes and reads data from a socket. The reason this > is in a different thread is because the data might take some time to > come back, and I want to have the GUI to be responsive during this > wait. > > When I run my program in Linux, a segmentation fault occurs. When I > run it in Windows XP, it works just fine. > Are you doing any xml processing? If so, it may be the same problem as described in this recent post - http://tinyurl.com/l3nr7 Frank Millman From puzzld_me at yahoo.com Tue Jun 6 13:34:29 2006 From: puzzld_me at yahoo.com (puzz) Date: 6 Jun 2006 10:34:29 -0700 Subject: newbie: python application on a web page Message-ID: <1149615269.695229.88820@j55g2000cwa.googlegroups.com> Hi all, I am so new to everything, I don't even know where to post my question... do bear... I made this Python calculator that will take an equation as an input and will display the computed curves on a shiny Tkinter interface Now, I'd like to make this application available on a public web page... and all I could come up with was this post Hints?! I'd also appreciate a link to a beginner forum Thanks Puzzled Me From bdesth.quelquechose at free.quelquepart.fr Wed Jun 28 20:33:28 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 29 Jun 2006 02:33:28 +0200 Subject: Function to prune dictionary keys not working In-Reply-To: References: Message-ID: <44a2ef87$0$1679$626a54ce@news.free.fr> Girish Sahani a ?crit : > hi ppl, > Here is a simple function to remove those keys of a dictionary whose > values are less than some specified value. > > But it isnt working. "is not working" is the worst possible description of a problem. > def prune(d,cp): > l = [] > for rule,value in d.iteritems(): > #print value > if value >= cp: > l.append(rule) > return l This doesn't remove anything from the dict - it returns a list of keys for which values are >= cp value. FWIW, a simple expression is enough to do this: [k for k, v in d.items() if v >= cp] The algorithm for what you described would be: def prune(dic, cmp): for k, v in dic.items(): if v < cmp: del dic[k] >>>>d = {'be=>c': '1.00', 'c=>da': '0.50', 'ea=>b': '0.33', 'be=>d': > > '0.50', 'c=>ba': '0.33', 'bd=>a': '1.00', 'a=>cb': '0.33', 'ea=>c': > '0.67', 'a=>cd': '0.50', 'e=>ac': '0.40', 'e=>ab': '0.20', 'c=>bd': > '0.33', 'e=>cb': '0.40', 'ed=>b': '0.25', 'ed=>c': '0.50'} > >>>>cp = 0.5 You are comparing floats with strings... From walter at livinglogic.de Wed Jun 7 12:04:58 2006 From: walter at livinglogic.de (=?ISO-8859-1?Q?Walter_D=F6rwald?=) Date: Wed, 07 Jun 2006 18:04:58 +0200 Subject: curses event handling In-Reply-To: <8764jdta2g.fsf@peds-pc311.bsd.uchicago.edu> References: <8764jdta2g.fsf@peds-pc311.bsd.uchicago.edu> Message-ID: <4486F92A.9070500@livinglogic.de> John Hunter wrote: > I have a curses app that is displaying real time data. I would like > to bind certain keys to certain functions, but do not want to block > waiting for > > c = screen.getch() > > Is it possible to register callbacks with curses, something like > > screen.register('keypress', myfunc) You could use curses.halfdelay(), so that screen.getch() doesn't block indefinitely. I'm not sure if this will be fast enough for your application. Servus, Walter From junkytownMAKNI at gmail.com Thu Jun 15 14:13:12 2006 From: junkytownMAKNI at gmail.com (SuperHik) Date: Thu, 15 Jun 2006 20:13:12 +0200 Subject: code folding, a unique problem to python? In-Reply-To: <1150390213.599580.183090@f6g2000cwb.googlegroups.com> References: <4fdgh7F1hbtteU1@uni-berlin.de> <1150390213.599580.183090@f6g2000cwb.googlegroups.com> Message-ID: BartlebyScrivener wrote: > Komodo code folds Python, Perl, PHP . . . also the free ActivePython's Pythonwin IDE From fredrik at pythonware.com Wed Jun 21 12:34:51 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 21 Jun 2006 18:34:51 +0200 Subject: memory error with zipfile module In-Reply-To: <44996D90.4000802@gmail.com> References: <446e07ab$0$12795$636a55ce@news.free.fr> <1148072514.207383.26370@j55g2000cwa.googlegroups.com> <446e51e6$0$6831$636a55ce@news.free.fr> <4499689D.1000206@gmail.com> <44996D90.4000802@gmail.com> Message-ID: Hari Sekhon wrote: > I've seen people using everything from zip to touch, either out of > laziness or out of the fact it wouldn't work very well in python, this > zip case is a good example. so based on a limitation in one library, and some random code you've seen on the internet, you're making generalizations about the language ? the zip case is a pretty lousy example, btw; after all, using the existing API, it's not that hard to implement an *incremental* read function if the provided read-into-string version isn't sufficient: import zipfile, zlib ## # Given a 'zip' instance, copy data from the 'name' to the # 'out' stream. def explode(out, zip, name): zinfo = zip.getinfo(name) if zinfo.compress_type == zipfile.ZIP_STORED: decoder = None elif zinfo.compress_type == zipfile.ZIP_DEFLATED: decoder = zlib.decompressobj(-zlib.MAX_WBITS) else: raise zipfile.BadZipFile("unsupported compression method") zip.fp.seek(zinfo.file_offset) size = zinfo.compress_size while 1: data = zip.fp.read(min(size, 8192)) if not data: break size -= len(data) if decoder: data = decoder.decompress(data) out.write(data) if decoder: out.write(decoder.decompress('Z')) out.write(decoder.flush()) From nicogrubert at gmail.com Wed Jun 21 04:28:58 2006 From: nicogrubert at gmail.com (Nico Grubert) Date: Wed, 21 Jun 2006 10:28:58 +0200 Subject: Search substring in a string and get index of all occurances Message-ID: <4499034A.9040306@gmail.com> Hi there, I would like to search for a substring in a string and get the index of all occurances. mystring = 'John has a really nice powerbook.' substr = ' ' # space I would like to get this list: [4, 8, 10, 17, 22] How can I do that without using "for i in mystring" which might be expensive for large strings? Thanks in advance, Nico From rossberg at ps.uni-sb.de Thu Jun 22 17:02:20 2006 From: rossberg at ps.uni-sb.de (rossberg at ps.uni-sb.de) Date: 22 Jun 2006 14:02:20 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <7zpshbsvjy.fsf@app-1.diku.dk><4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <0%Wlg.3521$MF6.947@tornado.socal.rr.com> <44992e6c$0$664$bed64819@news.gradwell.net> Message-ID: <1151010139.960608.122470@b68g2000cwa.googlegroups.com> Joachim Durchholz wrote: > > > A type is the encoding of these properties. A type > > varying over time is an inherent contradiction (or another abuse of the > > term "type"). > > No. It's just a matter of definition, essentially. > E.g. in Smalltalk and Lisp, it does make sense to talk of the "type" of > a name or a value, even if that type may change over time. OK, now we are simply back full circle to Chris Smith's original complaint that started this whole subthread, namely (roughly) that long-established terms like "type" or "typing" should *not* be stretched in ways like this, because that is technically inaccurate and prone to misinterpretation. - Andreas From rr_newsgroup_deleted at gmx.net Thu Jun 22 09:45:25 2006 From: rr_newsgroup_deleted at gmx.net (Roland Rickborn) Date: 22 Jun 2006 06:45:25 -0700 Subject: Feed wxComboBox with dictionary/hash Message-ID: <1150983925.131182.88670@i40g2000cwc.googlegroups.com> Hi folks, I am relatively new to Python. Although I read a lot of howtos, introductions and wikis, I am still having trouble ;-) My querstion: As the subject says, I'd like to feed a wx.ComboBox with a dictionary/hash. According to the posting of Stano Paska ("wxComboBox <> combobox", 20 Jul. 2004), there seems to be a way to do this: > You must use something like > combo.Append('aaa', 'a') > combo.Append('bbb', 'b') > ... My problem is: my data has thousands of entries. Therefore, I'd like to feed the combobox with a dictionary (which itself is fed by a database query). My first question: how can a wx.ComboBox be fed by a dictionary? For further help, Stano says: > read manual for more details... Ok, I'd like to. But which one? I was reading http://www.wxpython.org/docs/api/wx.ComboBox-class.html and didn't even find the above mentioned append method :-( TIA, Roland R. From alexreinhart at satx.rr.com Tue Jun 13 12:58:15 2006 From: alexreinhart at satx.rr.com (Alex Reinhart) Date: Tue, 13 Jun 2006 16:58:15 GMT Subject: [*SPAM*] Python open proxy honeypot In-Reply-To: References: Message-ID: Tim Williams wrote: > On 13/06/06, Alex Reinhart wrote: >> >> Is running Python's built-in smtpd, pretending to accept and forward all >> messages, enough to get me noticed by a spammer, or do I have to do >> something else to "advertise" my script as an open proxy? > > This will get you noticed by crawlers that scan the Internet looking > for SMTP open-relays on port 25, its not an open-proxy :):) > Yeah, I just realized that. What would I do to act as an open proxy as well? > This will work as planned, but you should also have some email > addresses using this server for a full range of spam hits. A single > domain is cheap and you can use it just for incoming spam - seed a few > addresses around the internet and wait > > Things you should be aware of: > > a) You may be breaking your ISP's T&Cs and AUPs I plan on asking them first - it's not actually a proxy/relay, just pretending to be one. > > b) your ISP connection must have port 25 open They use SMTP for their mailservers, so I assume they do. > > c) Be prepared for potentially huge numbers of connections in > intermittent but sustained batches which may make your connection > unusable. I'm hoping to host it on another server, preferably with a firewall to keep things from getting too hairy. Thanks. From JohnRoth1 at jhrothjr.com Sat Jun 17 12:07:42 2006 From: JohnRoth1 at jhrothjr.com (John Roth) Date: 17 Jun 2006 09:07:42 -0700 Subject: code is data References: Message-ID: <1150560461.967123.112300@f6g2000cwb.googlegroups.com> Anton Vredegoor wrote: > With the inclusion of ElementTree (an XML-parser) in Python25 and recent > developments concerning JSON (a very Pythonesque but somewhat limited > XML notation scheme, let's call it statically typed XML) Python seems to > have reached a stage where it now seems to be possible to completely > swallow lesser languages code, modify it, and spit out new source code > targeting the original language the code was written in, or even make a > translation to other languages. When I heard of the new AST based compiler, I thought it would finally be possible to extend things cleanly. Then I learned that they weren't going to allow modification of the AST. There are a lot of things you can't do in source if the language doesn't allow it. Python is pretty good compared to other languages, but it's still not possible to create new control structures with short circuit semantics. And that's one example. I saw the "make" statement as a breath of fresh air. Then it got shot down for what were, to me, totally trivial reasons. That's a second one. Sigh. John Roth > > > Your thoughts please. > > Anton From praveenkumar.117 at gmail.com Fri Jun 2 02:42:16 2006 From: praveenkumar.117 at gmail.com (praveenkumar.117 at gmail.com) Date: 1 Jun 2006 23:42:16 -0700 Subject: Import Issue Message-ID: <1149230536.375190.12150@c74g2000cwc.googlegroups.com> Hi all, I am facing a problem while importing a file in python script. After doing import file i am updating that file. Later i am accessing a dictionary contained in that file. Eventhough changes are reflected in the file... When i access a dictionary those changes are not there. I believe that it is accessing from the object file that is created when i did import at the start of the script. I will be kind enough if somebody suggest solution to this problem. Regards- praveen From jstroud at ucla.edu Fri Jun 9 18:50:06 2006 From: jstroud at ucla.edu (James Stroud) Date: Fri, 09 Jun 2006 15:50:06 -0700 Subject: Most elegant way to generate 3-char sequence In-Reply-To: <1149889784.391965.271570@h76g2000cwa.googlegroups.com> References: <1149889784.391965.271570@h76g2000cwa.googlegroups.com> Message-ID: Rob Cowie wrote: > Hi all, > > I wish to generate a sequence of the form 'aaa', 'aab', aac'.... 'aba', > 'abb', 'abc' etc. all the way to 'zzz'. > > How would you construct a generator to acheive this? > > A simple, working but somewhat inelegant solution is... > > alpha = ['a','b','c','d'] #shortened for brevity > alpha2 = ['a','b','c','d'] > alpha3 = ['a','b','c','d'] > > def generator(): > for char in alpha: > for char2 in alpha2: > for char3 in alpha3: > yield char + char2 + char3 > > x = generate() > x.next() # etc, etc, etc, > Yet a little more efficient. import string alpha = string.lowercase def generator(choices, length): length -= 1 if length: for a in choices: for g in generator(choices, length): yield a + g else: for a in choices: yield a for a in generator(alpha, 3): print a -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From steven.bethard at gmail.com Sat Jun 3 18:21:07 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 03 Jun 2006 16:21:07 -0600 Subject: grouping a flat list of number by range In-Reply-To: <1149362861.558049.172100@j55g2000cwa.googlegroups.com> References: <1149196642.001466.53990@c74g2000cwc.googlegroups.com> <1149362861.558049.172100@j55g2000cwa.googlegroups.com> Message-ID: Gerard Flanagan wrote: > joh12005 at yahoo.fr wrote: >> hello, >> >> i'm looking for a way to have a list of number grouped by consecutive >> interval, after a search, for example : >> >> [3, 6, 7, 8, 12, 13, 15] >> >> => >> >> [[3, 4], [6,9], [12, 14], [15, 16]] >> >> (6, not following 3, so 3 => [3:4] ; 7, 8 following 6 so 6, 7, 8 => >> [6:9], and so on) > > Just another 'itertools.groupby' variation. It considers the whole > range of numbers spanned by the dataset - eg. in your example, > range(3,17) - so possibly not very efficient if the range is large and > the data sparse within the range. > > def get_intervals(data): > intervals = [ [], [] ] > for k,g in groupby(range(data[0],data[-1]+2), lambda x:x in data): > intervals[k].append( list(g)[0] ) #k is 0 or 1 > return zip(intervals[1],intervals[0]) If you're gonna go this route, you should definitely use a set to check containment; ``x in data`` is going to be costly for long lists. Defining your key something like the following would be better:: data_set = set(data) def key(x): return x in data_set STeVe From reply.in.the.newsgroup at my.address.is.invalid Tue Jun 6 08:01:50 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Tue, 06 Jun 2006 14:01:50 +0200 Subject: 10GB XML Blows out Memory, Suggestions? References: <1149594519.098115.8980@u72g2000cwu.googlegroups.com> Message-ID: axwack at gmail.com: >I wrote a program that takes an XML file into memory using Minidom. I >found out that the XML document is 10gb. > >I clearly need SAX or something else? > >Any suggestions on what that something else is? PullDOM. http://www-128.ibm.com/developerworks/xml/library/x-tipulldom.html http://www.prescod.net/python/pulldom.html http://docs.python.org/lib/module-xml.dom.pulldom.html (not much) -- Ren? Pijlman From rossberg at ps.uni-sb.de Sun Jun 25 12:17:06 2006 From: rossberg at ps.uni-sb.de (rossberg at ps.uni-sb.de) Date: 25 Jun 2006 09:17:06 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150908952.804184.218990@r2g2000cwb.googlegroups.com> <1150991074.705803.211570@m73g2000cwd.googlegroups.com> <1151244628.566060.40500@p79g2000cwp.googlegroups.com> Message-ID: <1151252226.104247.62960@b68g2000cwa.googlegroups.com> Gabriel Dos Reis wrote: > | > | (Unfortunately, you can hardly write interesting programs in any safe > | subset of C.) > > Fortunately, some people do, as living job. I don't think so. Maybe the question is what a "safe subset" consists of. In my book, it excludes all features that are potentially unsafe. So in particular, C-style pointers are out, because they can easily dangle, be uninitialisied, whatever. Can you write a realistic C program without using pointers? - Andreas From nmm1 at cus.cam.ac.uk Wed Jun 14 13:54:37 2006 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 14 Jun 2006 17:54:37 GMT Subject: Numerics, NaNs, IEEE 754 and C99 References: <12904mjhl493t49@corp.supernews.com> <1290aik50hmk94a@corp.supernews.com> <4490329e$0$12356$636a55ce@news.free.fr> Message-ID: In article , Gary Herron writes: |> |> The IEEE standard specifies (plus or minus) infinity as the result of |> division by zero. This makes sense since such is the limit of division |> by a quantity that goes to zero. The IEEE standard then goes on to |> define reasonable results for arithmetic between infinities and real |> values. The production of, and arithmetic on, infinities is a choice |> that any application may want allow or not. The mistake you have made (and it IS a mistake) is in assuming that the denominator approaches zero from the direction indicated by its sign. There are many reasons why it is likely to not be, but let's give only two: It may be a true zero - i.e. a count that is genuinely zero, or the result of subtracting a number from itself. It may be a negative zero that has had its sign flipped by an aritfact of the code. For example: lim(x->0 from above) 0.001*b/(a-1.001*a) I fully agree that infinity arithmetic is fairly well-defined for most operations, but it most definitely is not in this case. It should be reserved for when the operations have overflowed. Regards, Nick Maclaren. From conveycj at npt.nuwc.navy.mil Thu Jun 22 11:58:51 2006 From: conveycj at npt.nuwc.navy.mil (Christian Convey) Date: Thu, 22 Jun 2006 11:58:51 -0400 Subject: Status of optional static typing in Python? Message-ID: <449ABE3B.70409@npt.nuwc.navy.mil> Hi guys, I'm looking at developing a somewhat complex system, and I think some static typing will help me keep limit my confusion. I.e.: http://www.artima.com/weblogs/viewpost.jsp?thread=87182 Does anyone know if/when that feature may become part of Python? Thanks very much, Christian -- Christian Convey Computer Scientist, Naval Undersea Warfare Centers Newport, RI (401) 832-6824 conveycj at npt.nuwc.navy.mil From mail at manuzhai.nl Mon Jun 12 15:25:12 2006 From: mail at manuzhai.nl (Manuzhai) Date: Mon, 12 Jun 2006 21:25:12 +0200 Subject: Egg cache problem with mod_python/ez_setup Message-ID: Hello there, I have this weird problem with a mod_python application. Recently I installed ElementTree and cElementTree through ez_setup.py, even though they were already installed normally (this might not be too smart, but I don't think it's related to my actual problem). I have a web application written on top of mod_python that uses cElementTree for several things. After installing cElementTree through ez_setup.py, it turns out that I got this Exception on the site: (most relevant info at the end, obviously, it's quite lengthy) Mod_python error: "PythonHandler equilex" Traceback (most recent call last): File "/usr/lib/python2.4/site-packages/mod_python/apache.py", line 287, in HandlerDispatch log=debug) File "/usr/lib/python2.4/site-packages/mod_python/apache.py", line 464, in import_module module = imp.load_module(mname, f, p, d) File "/var/www/equilex.eu/http/equilex/__init__.py", line 2, in ? from equilex.model import Session File "/var/www/equilex.eu/http/equilex/model/__init__.py", line 4, in ? from page import Page File "/var/www/equilex.eu/http/equilex/model/page.py", line 1, in ? from menu import Menu File "/var/www/equilex.eu/http/equilex/model/menu.py", line 1, in ? import cElementTree as et File "build/bdist.linux-i686/egg/cElementTree.py", line 7, in ? File "build/bdist.linux-i686/egg/cElementTree.py", line 4, in __bootstrap__ File "/usr/lib/python2.4/site-packages/setuptools-0.6b2-py2.4.egg/pkg_resources.py", line 799, in resource_filename return get_provider(package_or_requirement).get_resource_filename( File "/usr/lib/python2.4/site-packages/setuptools-0.6b2-py2.4.egg/pkg_resources.py", line 1228, in get_resource_filename self._extract_resource(manager, self._eager_to_zip(name)) File "/usr/lib/python2.4/site-packages/setuptools-0.6b2-py2.4.egg/pkg_resources.py", line 1249, in _extract_resource real_path = manager.get_cache_path( File "/usr/lib/python2.4/site-packages/setuptools-0.6b2-py2.4.egg/pkg_resources.py", line 880, in get_cache_path self.extraction_error() File "/usr/lib/python2.4/site-packages/setuptools-0.6b2-py2.4.egg/pkg_resources.py", line 846, in extraction_error raise err ExtractionError: Can't extract file(s) to egg cache The following error occurred while trying to extract file(s) to the Python egg cache: [Errno 13] Permission denied: '/var/www/.python-eggs' The Python egg cache directory is currently set to: /var/www/.python-eggs Perhaps your account does not have write access to this directory? You can change the cache directory by setting the PYTHON_EGG_CACHE environment variable to point to an accessible directory. Now, I already had a /tmp/eggs dir for eggs, and I had a SetEnv directive in my vhost config for my Trac vhost (which uses eggs). So I moved the SetEnv directive from the vhost config to my global httpd.conf. Curious enough, after restarting apache2, I still got the same error!! Is there any reason why it may not be picking up the env variable that points it to the other directory? Regards, Manuzhai From tim.peters at gmail.com Thu Jun 15 12:31:51 2006 From: tim.peters at gmail.com (Tim Peters) Date: Thu, 15 Jun 2006 12:31:51 -0400 Subject: Numerics, NaNs, IEEE 754 and C99 In-Reply-To: <12930879vah1k12@corp.supernews.com> References: <12917f6jp7u90f8@corp.supernews.com> <44912058$0$29674$636a55ce@news.free.fr> <1292p7s46ef5off@corp.supernews.com> <1292tvei30ahhd4@corp.supernews.com> <12930879vah1k12@corp.supernews.com> Message-ID: <1f7befae0606150931j41f9634t551fa7dffd868227@mail.gmail.com> [Nick Maclaren] >>>> Firstly, a FAR more common assumption is that integers wrap in twos' >>>> complement - Python does not do that. [Grant Edwards] >>> It used to [Fredrik Lundh] >> for integers ? what version was that ? [Grant] > Am I remebering incorrectly? Mostly but not entirely. > Didn't the old fixed-width integers operate modulo-wordsize? Not in Python. > I distinctly remember having to rewrite a bunch of checksum code when > fixed-width integers went away. Best guess is that you're working on a 32-bit box, and remember this Python <= 2.2 behavior specific to the left shift operator: >>> 1 << 31 -2147483648 >>> 1 << 32 0 On a 64-bit box (except Win64, which didn't exist at the time ;-)), those returned 2**31 and 2**32 instead, while "1 << 64" wrapped to 0 (etc). Python 2.3 starting warning about that: >>> 1 << 31 __main__:1: FutureWarning: x<>> 1 << 31 2147483648L >>> 1 << 32 4294967296L + - * / on short ints always complained about overflow before int-long unification, although IIRC very early Pythons missed the overflow error in (on a 32-bit box) int(-(2L**31))/-1. From fredrik at pythonware.com Sun Jun 11 03:40:30 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 11 Jun 2006 09:40:30 +0200 Subject: Very newbie programming In-Reply-To: <448bb2c7_1@news.tm.net.my> References: <448ae8ce_1@news.tm.net.my> <448bb2c7_1@news.tm.net.my> Message-ID: TheSaint wrote: > A part of this, how python catch variables, the longer the slower, isn't it? nope. From alanmk at hotmail.com Thu Jun 8 05:38:06 2006 From: alanmk at hotmail.com (Alan Kennedy) Date: 8 Jun 2006 02:38:06 -0700 Subject: language-x-isms References: <1149753206.451066.120960@h76g2000cwa.googlegroups.com> Message-ID: <1149759486.695563.110640@g10g2000cwb.googlegroups.com> [Bryan] >>>> for example, i've noticed several java developers i know >>>> write python code like >>>> this: >>>> >>>> foo_list = [...] >>>> for i in range(len(foo_list)): >>>> print '%d %s' % (i, foo_list[i]) [Fredrik Lundh] >>> which is a perfectly valid way of doing things if you're targeting older >>> Python platforms as well (including Jython). [astyonax] >> But it's not the pythonic way. [Terry Reedy] > I don't think you understood what Fredrik said. It was the Python way > before enumerate() builtin was added and remains the Python way if you wish > to write for older versions of Python and Jython. On jython 2.1, I use something like this #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= try: enumerate except NameError: def enumerate(iterable): results = [] ; ix = 0 for item in iterable: results.append( (ix, item) ) ix = ix+1 return results if __name__ == "__main__": my_list = [0, 1, 1, 2, 3, 5, 8, ] for ix, fibo in enumerate(my_list): print "Position %d: %d" % (ix, fibo) #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= Which runs like:- C:\alank>python -V Python 2.4.3 C:\alank>python fibo.py Position 0: 0 Position 1: 1 Position 2: 1 Position 3: 2 Position 4: 3 Position 5: 5 Position 6: 8 C:\alank>jython --version Jython 2.1 on java (JIT: null) C:\alank>jython fibo.py Position 0: 0 Position 1: 1 Position 2: 1 Position 3: 2 Position 4: 3 Position 5: 5 Position 6: 8 Of course, the efficiency is different across cpython vs. jython, but it's nice to have the same pythonic code running across both. And when jython progresses beyond 2.1, (any day now!), it will still work seamlessly. regards, -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From onurb at xiludom.gro Tue Jun 20 05:38:21 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 20 Jun 2006 11:38:21 +0200 Subject: [OT] code is data In-Reply-To: <4fokj4F1ihat3U1@uni-berlin.de> References: <44965f53$0$12743$636a55ce@news.free.fr> <4496b29f$0$27412$626a54ce@news.free.fr> <4496e9c9$0$14868$626a54ce@news.free.fr> <4fokj4F1ihat3U1@uni-berlin.de> Message-ID: <4497c20e$0$29656$636a55ce@news.free.fr> Diez B. Roggisch wrote: >>> because lots of people know how to describe XML transformations, and >>> there are plenty of tools that implement such transformations >>> efficiently ? >> >> >> Efficiently enough for dynamic (runtime) use ? > > > Using XML-transformation for AST manipulation isn't my first choice > either - yet efficiency concerns aren't really the point here - after > all we're talking about generating code, I thought we were talking about *transforming* code - just like one uses metaclasses to transform a class definition, or @decorators to transform a function definition... (snip) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From propheci at gmail.com Wed Jun 21 02:38:28 2006 From: propheci at gmail.com (Xiaolei) Date: 20 Jun 2006 23:38:28 -0700 Subject: Initializing a set from a list References: <1150869540.796459.202330@u72g2000cwu.googlegroups.com> Message-ID: <1150871908.281225.61880@u72g2000cwu.googlegroups.com> Robert Kern wrote: > Xiaolei Li wrote: > > Hi, > > > > I'm trying to initialize a set from a list but am unable to do so. My > > list "c", looks like: > > > > [(1.00909, 0.91969999999999996, -0.13550388182991072, 0), > > (0.87423999999999991, 0.6666700000000001, -0.21230487137222254, 0)] > > > > So basically a list of 2 tuples, each with 4 elements. Since tuples > > are immutable, I think a set should be able to support them. > > > > Anyway, I then do: > > > > set_c = set(c) > > > > And instead of getting a set, I get "None" when I try to print out > > set_c. len(set_c) complains "TypeError: len() of unsized object." > > Help? > > >>> c = [(1.00909, 0.91969999999999996, -0.13550388182991072, 0), > ... (0.87423999999999991, 0.6666700000000001, -0.21230487137222254, 0)] > >>> set_c = set(c) > >>> set_c > set([(1.00909, 0.91969999999999996, -0.13550388182991072, 0), > (0.87423999999999991, 0.6666700000000001, -0.21230487137222254, 0)]) > >>> > > Please copy-and-paste the exact code that you wrote and the exact output. Ok, I've basically found the cause of my problem. I'm including stuff from pylab and that's causing some conflicts? Here's 6 lines of code: from pylab import * c = [1, 2, 3, 3] print c set_c = set(c) print set print set_c When I run that (Python 2.4.2, Pylab 0.80), I get: [1, 2, 3, 3] None If I remove the first line, I correctly get: [1, 2, 3, 3] set([1, 2, 3]) Good news is that I didn't really need pylab in the program. So for now, everything's working just fine. From alanalan at newsgroup.nospam Wed Jun 7 15:08:09 2006 From: alanalan at newsgroup.nospam (A.M) Date: Wed, 7 Jun 2006 15:08:09 -0400 Subject: os.system and command output Message-ID: <8rFhg.1071$Wy.73797@news20.bellglobal.com> Hi, How can I run an OS command and have the command's output (to stdout) in my string variable? For example in windows, this command should return a list of files within directory: os.system("DIR") I am looking for an alternative function that returns the DIR command output in a string Thanks, Alan From jo at durchholz.org Sun Jun 25 08:36:48 2006 From: jo at durchholz.org (Joachim Durchholz) Date: Sun, 25 Jun 2006 14:36:48 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150749670.053433.242210@p79g2000cwp.googlegroups.com> <1150754918.338770.89870@i40g2000cwc.googlegroups.com> Message-ID: Chris F Clark schrieb: > Chris F Clark schrieb: >> In that sense, a static type system is eliminating tags, because the >> information is pre-computed and not explicitly stored as a part of the >> computation. Now, you may not view the tag as being there, but in my >> mind if there exists a way of perfoming the computation that requires >> tags, the tag was there and that tag has been eliminated. > > Joachim Durchholz replied: >> On a semantic level, the tag is always there - it's the type (and >> definitely part of an axiomatic definition of the language). >> Tag elimination is "just" an optimization. > > I agree the tag is always there in the abstract. Well - in the context of a discussion of dynamic and static typing, I'd think that the semantic ("abstract") level is usually the best level of discourse. Of course, this being the Usenet, shifting the level is common (and can even helpful). > In the end, I'm trying to fit things which are "too big" and "too > slow" into much less space and time, using types to help me reliably > make my program smaller and faster is just one trick. [...] > > However, I also know that my way of thinking about it is fringe. Oh, I really agree that's an important application of static typing. Essentially, which aspects of static typing is more important depends on where your problems lie: if it's ressource constraints, static typing tends to be seen as a tool to keep ressource usage down; if it's bug counts, static typing tends to be seen as a tool to express static properties. These aspects are obviously not equally important to everybody. Regards, Jo From redefined.horizons at gmail.com Fri Jun 9 15:58:05 2006 From: redefined.horizons at gmail.com (Redefined Horizons) Date: Fri, 9 Jun 2006 12:58:05 -0700 Subject: Questions about extending Python... Message-ID: I've got a third-part application that exposes a C API. I'd like to wrap it in Python. Is there a specific forum that covers extending and embedding Python, or are those type of questions O.K. on this list? Scott Huey From fredrik at pythonware.com Sat Jun 10 13:45:15 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 10 Jun 2006 19:45:15 +0200 Subject: Getting backtrace on an axception In-Reply-To: <83e8215e0606101024m42748166vf0cf7a2332d7e5bb@mail.gmail.com> References: <83e8215e0606101024m42748166vf0cf7a2332d7e5bb@mail.gmail.com> Message-ID: Paolo Pantaleo wrote: > In the except block I need to print detailed output about the error > occured, and in particular I need to read the backtrace for the line > that raised the exception [then modify and print it]. >>> import traceback >>> help(traceback) From fredrik at pythonware.com Mon Jun 5 12:41:32 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 05 Jun 2006 18:41:32 +0200 Subject: Installation Problem In-Reply-To: <448458CA.E867E532@king-cart.com> References: <44830900.155C7297@king-cart.com> <44831694.A022913A@king-cart.com> <44836E91.7F640B4@king-cart.com> <448458CA.E867E532@king-cart.com> Message-ID: Marshall Dudley wrote: > That is what I did originally, downloaded the latest version from the main > python site. I compiled by the README file instructions, and I compiled by the > instructions on the python url which are different, but both gave identical > results, compiles fine, runs fine from the directory I compiled in, but will > error out when I move the executible code to and run it from the /usr/local/bin > or the /usr/local directory. deep sigh. alright, one more attempt: DO NOT copy any binaries yourself, DO NOT use any bogus FreeBSD source distribution, DO NOT download 2.2.2 if you need Python 2.3 or newer, DO NOT type random commands into the shell when logged in as root. etc. just follow these instructions: 1) go fetch a the latest source code kit from python.org. I recommend getting Python-2.4.3.tgz: $ wget http://www.python.org/ftp/python/2.4.3/Python-2.4.3.tgz 2) unpack the file to a local temporary directory $ tar xvfz Python-2.4.3.tar.gz $ cd Python-2.4.3 3) in that directory, type the following commands: $ ./configure $ make $ ./python 4) verify that the ./python command prints the following: Python 2.4.3 [followed by some number, and today's date] Type "help", "copyright", "credits" or "license" ... >>> 5) press control-D to leave the interpreter 6) login as root, and type # make install (or use sudo, or whatever mechanism you usually do to run a command as root) 7) log out from root. that's it. python is now installed as "/usr/local/bin/python", *and* as "/usr/local/bin/python2.4". support libraries and other files are installed under /usr/local/lib/python2.4 and /usr/local/include/python2.4. From shejo284 at gmail.com Thu Jun 15 08:53:46 2006 From: shejo284 at gmail.com (Sheldon) Date: 15 Jun 2006 05:53:46 -0700 Subject: python and HDF Message-ID: <1150376026.665920.50860@h76g2000cwa.googlegroups.com> Hi, I am using a HLHDF C wrapper to extract data from HDF (version 5) files. I can view the contents with IDL, for example, and read the attributes in the HDF file. There is one attribute that I extracted and only of part of the string was returned. In the HDF file, the attribute data is a name which is called "baseline" but when python reads it, it returns "baselin" instead. Does anyone have any idea why this is happening? Sincerely, Sheldon From fredrik at pythonware.com Mon Jun 5 06:53:39 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 05 Jun 2006 12:53:39 +0200 Subject: Which exceptions are recommended to me handled? In-Reply-To: <2773CAC687FD5F4689F526998C7E4E5FF1E74B@au3010avexu1.global.avaya.com> References: <2773CAC687FD5F4689F526998C7E4E5FF1E74B@au3010avexu1.global.avaya.com> Message-ID: Delaney, Timothy (Tim) wrote: > Note that it's a particularly bad idea to just replace one exception > with another exception (not suggesting that that is what you intended - > just something I've seen a lot ;) > > try: > int(val) > except ValueError: > raise MyValueError('Bad value: ' + val) > > The most important problem here is that you've lost the stack trace from > the original exception. which, in many cases, is a good thing, especially if you replace "int" with a call to some low-level support library. if I call API "foo" to open a data file of some kind, I'm not necessarily interested in an "unsubscriptable error" exception on line 129 in barpath.py, nor is it helping me figure out what's wrong in my program. or do you expose internal implementation details to your end users too, to make sure they don't lose any information? From davecook at nowhere.net Thu Jun 15 20:11:39 2006 From: davecook at nowhere.net (Dave Cook) Date: Fri, 16 Jun 2006 00:11:39 GMT Subject: a good programming text editor (not IDE) References: <_xgkg.2317$No6.48542@news.tufts.edu> Message-ID: <%Gmkg.21787$8q.10336@dukeread08> On 2006-06-15, Dave Hansen wrote: > Very small, very fast, very powerful, and very portable (though I'm > not sure about Mac...): Take a look at Jed from www.jedsoft.org. > > You might not find it pretty, however... But if your distro includes xjed (ubuntu/debian, but not newer fedoras) try xjed -fn mono -fs 16 Dave Cook From sekhon.hari at googlemail.com Wed Jun 21 06:38:23 2006 From: sekhon.hari at googlemail.com (Hari Sekhon) Date: Wed, 21 Jun 2006 11:38:23 +0100 Subject: difference between import from mod.func() and x=mod.func() In-Reply-To: References: <4497ACB9.4020905@gmail.com> Message-ID: I take it that it's not worth listening to that tutorial and just using good old "import from", which I suspect is better anyway since it imports less... "uneducated premature optimisation" - I take it this is insulting a that programmer's progexuality...! "import from" it is then unless anybody has anything else to say on the matter. Thanks Hari On 20/06/06, Fredrik Lundh wrote: > > Hari Sekhon wrote: > > > What is the difference in terms of efficiency and speed between > > > > from os import path > > > > and > > > > import os > > path=os.path > > the only difference is that the former only sets the "path" variable, > while the > latter leaves both "os" and "path" in your namespace. > > > I would think that the import from would be better, just curious since I > > read somewhere on the web, some guy's code tutorial where he did the > > latter and said it was for efficiency/speed. > > sounds like "uneducated premature optimization" to me. > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ywzhan at gmail.com Sat Jun 10 05:14:40 2006 From: ywzhan at gmail.com (ywzhan) Date: 10 Jun 2006 02:14:40 -0700 Subject: Can I set timeout for the sys.stdin.readline() ? Message-ID: <1149930880.741381.230270@i40g2000cwc.googlegroups.com> Hi, I am new here. When I use sys.stdin.readline() to get input string from user, how can I set a timeout value for this operation? thank you. From marc.t.davies at gmail.com Thu Jun 8 06:43:16 2006 From: marc.t.davies at gmail.com (MTD) Date: 8 Jun 2006 03:43:16 -0700 Subject: How to generate k+1 length strings from a list of k length strings? In-Reply-To: <1149762971.803450.69670@j55g2000cwa.googlegroups.com> References: <1149762869.692025.164140@c74g2000cwc.googlegroups.com> <1149762971.803450.69670@j55g2000cwa.googlegroups.com> Message-ID: <1149763396.115578.192490@y43g2000cwc.googlegroups.com> So yeah, just to put it all together, try this. From your two Ks, it either returns K+1 if it can or an empty string. def k2k1(string1, string2): for c in string1: string2 = string2.replace(c,"",1) if len(string2) == 1: string1 += string2 else: string1 = "" return string1 Testing: print k2k1("abcdadd", "abceadd") gives: abcdadde From afa at neuf.fr Tue Jun 20 17:16:16 2006 From: afa at neuf.fr (Amaury Forgeot d'Arc) Date: Tue, 20 Jun 2006 23:16:16 +0200 Subject: Psyco performance In-Reply-To: References: <1150819763.818687.114360@y41g2000cwy.googlegroups.com> <44981e4c$0$29812$626a54ce@news.free.fr> Message-ID: Hello, Gregory Pi?ero a ?crit : > What's the reasoning behind requiring everything to be in functions? > Just curious. You may want to read this: http://psyco.sourceforge.net/introduction.html#differences-with-traditional-jit-compilers Psyco has to run the code at least once to emit code specialized for the actual data. It works by replacing blocks of code by other blocks, optimized for the kind of data seen the previous times. On the contrary, the code outside functions is run only once. You'll never get the chance to run the optimized version again... -- Amaury From __peter__ at web.de Thu Jun 1 12:03:47 2006 From: __peter__ at web.de (Peter Otten) Date: Thu, 01 Jun 2006 18:03:47 +0200 Subject: argmax References: Message-ID: David Isaac wrote: > 2. Is this a good argmax (as long as I know the iterable is finite)? > def argmax(iterable): return max(izip( iterable, count() ))[1] There's a subtle difference to the builtin: argmax() gives you the (index of the) last maximum while max() returns the (value of the) first maximum: >>> from itertools import count, izip >>> def argmax(iterable): ... return max(izip(iterable, count()))[1] ... >>> class Int(int): pass ... >>> type(max([Int(0), 0])) # must be the first item then >>> argmax([Int(0), 0]) 1 If you care, here's the fix building on George's implementation: >>> def argmax2(iterable): ... return -max((v, -i) for i, v in enumerate(iterable))[1] ... >>> argmax2([Int(0), 0]) 0 Peter From john106henry at hotmail.com Fri Jun 30 23:33:45 2006 From: john106henry at hotmail.com (John Henry) Date: 30 Jun 2006 20:33:45 -0700 Subject: Concatenating strings Message-ID: <1151724825.477962.127160@h44g2000cwa.googlegroups.com> Sorry if this is a dumb question. I have a list of strings (some 10,000+) and I need to concatenate them together into one very long string. The obvious method would be, for example: alist=["ab","cd","ef",.....,"zzz"] blist = "" for x in alist: blist += x But is there a cleaner and faster way of doing this? Thanks, From meyer at mesw.de Fri Jun 16 03:49:51 2006 From: meyer at mesw.de (meyer at mesw.de) Date: 16 Jun 2006 00:49:51 -0700 Subject: Which compiler will Python 2.5 / Windows (Intel) be built with? In-Reply-To: <4492414C.10505@v.loewis.de> References: <1150367139.495114.148550@g10g2000cwb.googlegroups.com> <44917535$1@nntp0.pdx.net> <1150391891.130185.4640@f6g2000cwb.googlegroups.com> <4492414C.10505@v.loewis.de> Message-ID: <1150444191.618761.22810@c74g2000cwc.googlegroups.com> Martin, thanks for the tip, I wasn't fully aware of that. OTOH, though GCC might be a theoretical alternative, it isn't a practical one for many situations: * In a professional environment, it opens up another can of potential problems, where one would rather like to stay with one single compiler/build system. * I suppose Python's distutils have to be tweaked to work with GCC * The Makefiles/build system will need to be changed to work with the GCC toolchain * The different semantics of GCC and Microsoft C often need rewriting some of the code * There is no support for MFC/ATL in GCC * The code created by the Windows GCC is not as good as the one created by the Microsoft compiler Markus Martin v. L?wis wrote: > meyer at mesw.de wrote: > > the problem is not the ABI, but the runtime libraries. From what you're > > saying, it looks like we will have to standardize on VS2003. As I said, > > we need to buy VS anyway because of the MFC support. On the other hand, > > I really worry about all those people that want to build open source > > extensions for Python 2.5. It is really possible that there will be no > > legal, free way to do that soon if you don't have an old installation > > of the 2003 toolkit lying around somewhere... > > As others have pointed out already: This is not true. You can build > Python extensions with GCC just fine; gcc provides an import library > for msvcr71.dll. > > It might be possible to integrate an msvcr71.dll import library > with VS 2005, in which case you could use VS 2005 to create Python > extensions as well. > > Regards, > Martin From jmcmonagle at velseis.com.au Tue Jun 6 19:27:37 2006 From: jmcmonagle at velseis.com.au (John McMonagle) Date: Wed, 07 Jun 2006 09:27:37 +1000 Subject: tkinter: making widgets instance or not? In-Reply-To: References: Message-ID: <1149636457.26711.41.camel@kuepper.vels-int.com.au> On Tue, 2006-06-06 at 19:42 +0000, John Salerno wrote: > Fredrik Lundh wrote: > > > however, if you need to access a widget later on, it might be a good > > idea to save a reference to it somewhere... > > To follow up on that point, I have the following code now. I have two > questions about it: > > 1. Can I somehow make the passing of 'master' to the draw_entry method > automatic, so I don't have to type it each time I call the function? > > 2. Related to your comment, the obvious problem here is that it doesn't > save references to the text box names, so I can't access them later. Is > there still a way to automate the process like I've done, but have each > entry field have a separate name? > > Thanks. > > --------------- > > import Tkinter as tk > > > class App: > > def __init__(self, master): > self.draw_entry(master, 'First Name:') > self.draw_entry(master, 'Last Name:') > > def draw_entry(self, master, label_text): > frame = tk.Frame(master, bd=4) > frame.pack() > self.label = tk.Label(frame, text=label_text, width=10) > self.label.pack(side=tk.LEFT) > self.entry = tk.Entry(frame) > self.entry.pack(side=tk.LEFT) > > > root = tk.Tk() > app = App(root) > root.resizable(width=False, height=False) > root.mainloop() > -- Try this: import Tkinter as tk class App: def __init__(self, master): self.parent = master self.entry1 = self.draw_entry('First Name:') self.entry2 = self.draw_entry('Last Name:') def draw_entry(self, label_text): frame = tk.Frame(self,parent, bd=4) frame.pack() label = tk.Label(frame, text=label_text, width=10) label.pack(side=tk.LEFT) entry = tk.Entry(frame) entry.pack(side=tk.LEFT) return entry root = tk.Tk() app = App(root) root.resizable(width=False, height=False) root.mainloop() -- This message has been scanned for viruses and dangerous content by MailScanner, and is believed to be clean. From rbonvall at gmail.com Mon Jun 5 12:35:31 2006 From: rbonvall at gmail.com (Roberto Bonvallet) Date: Mon, 5 Jun 2006 12:35:31 -0400 Subject: Concatenating dictionary values and keys, and further operations In-Reply-To: <55123.10.209.4.1.1149479379.squirrel@10.105.1.3> References: <55123.10.209.4.1.1149479379.squirrel@10.105.1.3> Message-ID: <1908cb6b0606050935n562f6555m17e3fa212e5c92f4@mail.gmail.com> Girish Sahani : > I wrote the following code to concatenate every 2 keys of a dictionary and > their corresponding values. > e.g if i have tiDict1 = tiDict1 = {'a':[1,2],'b':[3,4,5]} i should get > tiDict2={'ab':[1,2][3,4,5]} and similarly for dicts with larger no. of > features. Note that dictionary keys are not ordered, so--if I understand your requirement correctly--it could also result in {'ba': [3, 4, 5, 1, 2]}. > Now i want to check each pair to see if they are connected...element of > this pair will be one from the first list and one from the second....e.g > for 'ab' i want to check if 1 and 3 are connected,then 1 and 4,then 1 and > 5,then 2 and 3,then 2 and 4,then 2 and 5. According to this, I think that you shouldn't concatenate the lists, but keep them apart instead. > The information of this connected thing is in a text file as follows: > 1,'a',2,'b' > 3,'a',5,'a' > 3,'a',6,'a' > 3,'a',7,'b' > 8,'a',7,'b' > . > This means 1(type 'a') and 2(type 'b') are connected,3 and 5 are connected > and so on. > I am not able to figure out how to do this.Any pointers would be helpful I don't understand very well what you want to do. Could you explain it more clearly, with an example? -- Roberto Bonvallet From slawomir.nowaczyk.847 at student.lu.se Fri Jun 9 09:36:54 2006 From: slawomir.nowaczyk.847 at student.lu.se (Slawomir Nowaczyk) Date: Fri, 09 Jun 2006 15:36:54 +0200 Subject: better Python IDE? Mimics Maya's script editor? In-Reply-To: <1149810048.765664.107820@i40g2000cwc.googlegroups.com> References: <1149810048.765664.107820@i40g2000cwc.googlegroups.com> Message-ID: <20060609153319.FC93.SLAWOMIR.NOWACZYK.847@student.lu.se> On Thu, 08 Jun 2006 16:40:48 -0700 warpcat wrote: #> I'm using PythonWin right now and trying to find something better, #> mainly with this functionality: *Assuming* I understood your description correctly, python-mode in Emacs does what you want. Emacs is hardly a substitute for PythonWin, though: the learning curve is quite steep. -- Best wishes, Slawomir Nowaczyk ( Slawomir.Nowaczyk at cs.lth.se ) If you're constantly looking behind you, you may miss the frontal attack. From LittlePython at lost.com Fri Jun 9 17:00:54 2006 From: LittlePython at lost.com (LittlePython) Date: Fri, 09 Jun 2006 21:00:54 GMT Subject: Converting binary sid's to a hex string References: <1149708725_1865@sp6iad.superfeed.net> Message-ID: Thx Roger, I have been off line for a few days. I am sorry not to reply earlier. I will try this, but I am not sure what "buffer" does ( I am a newbie to python). "Roger Upole" wrote in message news:1149708725_1865 at sp6iad.superfeed.net... > You can use the binascii module to convert the raw > bytes of the sid to hex. > > binascii.b2a_hex(buffer(MySid)) > > Roger > > "LittlePython" wrote in message news:Y6Ehg.6441$im3.3067 at trnddc01... > >I am trying to create a hexstring of a NT4 user account sid which I can in > > turn use to query an exchange 55 database. I believe I need to convert a > > binary sid to a hex string. ADsSID com object will do this for me however it > > is a little slow. Can anybody point me in the right direction to converting > > a PySID to a hexstring. > > Thx > > > > import win32netcon > > import win32net > > import win32security > > def report(): > > resume = 0 > > while 1: > > filter = win32netcon.FILTER_NORMAL_ACCOUNT > > data, total, resume = win32net.NetUserEnum('nt4pridc1', 20, filter, > > resume) > > for user in data: > > MySid, string, int = win32security.LookupAccountName('nt4pridc1', > > user['name']) > > sString = win32security.ConvertSidToStringSid(MySid) > > print MySid > > print sString > > if resume ==0: > > break > > > > report() > > ## sString prints = S-1-5-21-357043131-537017027-1947940980-1289 > > ## MySid prints = PySID:S-1-5-21-357043131-537017027-1947940980-1289 > > ## I need this , I believe this is a hex string of the SID > > ## 010500000000000515000000BB0B4815C33A022074381B7409050000 > > > > > > > > > ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==---- > http://www.newsfeeds.com The #1 Newsgroup Service in the World! >100,000 Newsgroups > ---= East/West-Coast Server Farms - Total Privacy via Encryption =--- From sjmachin at lexicon.net Thu Jun 1 18:51:16 2006 From: sjmachin at lexicon.net (John Machin) Date: Fri, 02 Jun 2006 08:51:16 +1000 Subject: struct: type registration? In-Reply-To: <1149185926.636174.48970@y43g2000cwc.googlegroups.com> References: <447e4b98$1@news.eftel.com> <1149185926.636174.48970@y43g2000cwc.googlegroups.com> Message-ID: <447F6F64.400@lexicon.net> On 2/06/2006 4:18 AM, Serge Orlov wrote: > Giovanni Bajo wrote: >> John Machin wrote: >>> I am an idiot, so please be gentle with me: I don't understand why you >>> are using struct.pack at all: >> Because I want to be able to parse largest chunks of binary datas with custom >> formatting. Did you miss the whole point of my message: >> >> struct.unpack("3liiSiiShh", data) > > Did you want to write struct.unpack("Sheesh", data) ? Seriously, the > main problem of struct is that it uses ad-hoc abbreviations for > relatively rarely[1] used functions calls and that makes it hard to > read. Indeed. The first time I saw something like struct.pack('20H', ...) I thought it was a FORTRAN format statement :-) > > If you want to parse binary data use pyconstruct > > Looks promising on the legibility and functionality fronts. Can you make any comment on the speed? Reason for asking is that Microsoft Excel files have this weird "RK" format for expressing common float values in 32 bits (refer http://sc.openoffice.org, see under "Documentation" heading). I wrote and support the xlrd module (see http://cheeseshop.python.org/pypi/xlrd) for reading those files in portable pure Python. Below is a function that would plug straight in as an example of Giovanni's custom unpacker functions. Some of the files can be very large, and reading rather slow. Cheers, John from struct import unpack def unpack_RK(rk_str): # arg is 4 bytes flags = ord(rk_str[0]) if flags & 2: # There's a SIGNED 30-bit integer in there! i, = unpack('>= 2 # div by 4 to drop the 2 flag bits if flags & 1: return i / 100.0 return float(i) else: # It's the most significant 30 bits # of an IEEE 754 64-bit FP number d, = unpack(' Hello, While extracting a tar file, is there a way to give an umask option for creating the non-existing upper directories of the file within the tar archive. The default behaviour is to create the directories with 0777 permission bits. Code taken from tarfile.py of python version 2.4.3: # Create all upper directories. upperdirs = os.path.dirname(targetpath) if upperdirs and not os.path.exists(upperdirs): ti = TarInfo() ti.name = upperdirs ti.type = DIRTYPE ti.mode = 0777 ^^^^^^ ti.mtime = tarinfo.mtime ti.uid = tarinfo.uid ti.gid = tarinfo.gid ti.uname = tarinfo.uname ti.gname = tarinfo.gname try: self._extract_member(ti, ti.name) except: pass Regards, - Faik From johnjsal at NOSPAMgmail.com Thu Jun 15 12:38:00 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 15 Jun 2006 16:38:00 GMT Subject: code folding, a unique problem to python? In-Reply-To: References: Message-ID: Fredrik Lundh wrote: > John Salerno wrote: > >> But my question is more general: is it possible to implement code >> folding with Python given that it has no real block delimiters? Or is >> this still a matter of which particular editor/IDE you use? > > since the Python syntax *has* real block delimiters (look up INDENT and > DEDENT in the language reference), it's an editor issue. > > > Interesting. This might help me then, assuming UE can use characters other than strings to delimit blocks. Thanks! From bignose+hates-spam at benfinney.id.au Wed Jun 14 21:47:45 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 15 Jun 2006 11:47:45 +1000 Subject: Negative hex to int References: <1150326597.327669.222640@r2g2000cwb.googlegroups.com> <4490B347.1050004@lexicon.net> Message-ID: <87pshbkx4u.fsf@benfinney.id.au> John Machin writes: > On 15/06/2006 10:31 AM, Ben Finney wrote: > > If you want a special interpretation of the value, you'll have to > > calculate it. > > > > Example assuming you want a one's-complement interpretation:: > > Given that the OP had to ask the question at all, it is doubtful > that he knows what "one's-complement" means. He may well not be > alone -- see later. You've pointed out something useful: a quick attempt (by me, in this case) to describe the algorithm isn't worth much, less so if it's already well-documented. Hopefully the original poster can consult a more authoritative reference on the topic. Fortunately, that was also one of my points :-) The implementation itself seems to do the job the OP asked. I hope it's useful in some form. -- \ "If society were bound to invent technologies which could only | `\ be used entirely within the law, then we would still be sitting | _o__) in caves sucking our feet." -- Gene Kan, creator of Gnutella | Ben Finney From richie at entrian.com Tue Jun 27 09:57:41 2006 From: richie at entrian.com (Richie Hindle) Date: Tue, 27 Jun 2006 14:57:41 +0100 Subject: Having problems with strings in HTML In-Reply-To: References: Message-ID: [Kiana] > [Lawrence] > By the way, you _do_ realize that your "&" characters should be escaped > as "&", don't you? [Sion] > No they shouldn't. They part of the url, which is (IIRC) a CDATA > attribute of the A element, not PCDATA. The W3C validator at http://validator.w3.org/ disagrees with you. It accepts this: Test

link

but rejects this: Test

link

saying "cannot generate system identifier for general entity "b" [...] The most common cause of this error is unencoded ampersands in URLs". -- Richie Hindle richie at entrian.com From kay.schluehr at gmx.net Thu Jun 29 07:39:17 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 29 Jun 2006 04:39:17 -0700 Subject: Python decompiler In-Reply-To: References: Message-ID: <1151581157.056321.141950@75g2000cwc.googlegroups.com> subramanian2003 wrote: > Hello All, > > I have some compiled python 2.4 scripts. If anyone has python decompiler, pls send me. > > Thanks, > subramanian. http://www.python.org/doc//2.4/lib/module-dis.html From lucaberto at libero.it Mon Jun 26 16:07:22 2006 From: lucaberto at libero.it (luca72) Date: 26 Jun 2006 13:07:22 -0700 Subject: Pycrypto In-Reply-To: References: <1150446904.527285.255170@g10g2000cwb.googlegroups.com> <1150458752.342042.189650@h76g2000cwa.googlegroups.com> <1150462237.224431.213020@c74g2000cwc.googlegroups.com> Message-ID: <1151352442.831855.230710@y41g2000cwy.googlegroups.com> Hello again You know if is possible save all the encryption process in a text file and not only the result? This will be wery helpful for compare the pycrypto step by step operation, with the hand made operation and see where hand made make a mistake From sekhon.hari at googlemail.com Wed Jun 21 06:22:42 2006 From: sekhon.hari at googlemail.com (Hari Sekhon) Date: Wed, 21 Jun 2006 11:22:42 +0100 Subject: What's the best way to wrap a whole script in try..except? Message-ID: <44991DF2.6090403@gmail.com> I want to wrap a whole script in try ... except. What is the best way of doing this? Consider the following: - try: import def notifyme(traceback): code to tell me there is a problem except Exception, traceback: notifyme(traceback) Would this code not work because if any part of encounters an exception then it won't reach the notifyme() function definition and therefore the whole thing won't work and I won't get notified when a traceback occurs, in fact the call to notifyme() under except will itself probably trace back as well! Do I have to instead do: import def notifyme(): code to tell me there is a problem try: except Exception, traceback: notifyme(traceback) How you you handle this? Hari From luismgz at gmail.com Wed Jun 28 20:48:03 2006 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 28 Jun 2006 17:48:03 -0700 Subject: web Develop question In-Reply-To: <1151541085.359563.156990@i40g2000cwc.googlegroups.com> References: <1151514841.490454.284770@i40g2000cwc.googlegroups.com> <1151515979.877494.316720@m73g2000cwd.googlegroups.com> <1151541085.359563.156990@i40g2000cwc.googlegroups.com> Message-ID: <1151542083.518621.93970@x69g2000cwx.googlegroups.com> gerkarcher at gmail.com wrote: > Dear Luis , > > Thanks for your kindly answer , so you say that installing mod_python > and a template like chetaah or dyango I can do like as I do with php > and Apache ? Do not get confussed: Django is a complete web development framework, and "Cheetah" is just a template engine. You don't need any framework to use mod_python (although many frameworks use mod_python as a deployment option, as well as CGI or FastCGI, etc). Mod_python is just the module that lets you use python with Apache. However, it has some built-in capabilities for letting you build web sites. They are called "handlers". You can write your own handlers, or you can use the ones included within mod_python. The main two handlers are: 1) PSP: this stands for Python Server Pages, and it is a way to parse scripts in a PHP-like way. For example, you enclose your python instructions between <% and %> tags, and your can mix them within html. However, it is not very polished and I would recomend it... 2) Publisher: It lets you write scripts where you define functions, that correspond to different pages. For example, if you define a function "index" it will contain the code to display your main page. This way you can create a whole site with only one script. You can include html code within these functions, but it is recommended to use a template system combined with publisher, in order to separate presentation and logic. Cheetah is a very good templating engine. I suggest you start by reading mod_python's documentation, and then, when you are up and running with all your installation, you can check Cheetah... Hope it helps... Luis From steven.bethard at gmail.com Wed Jun 14 01:48:34 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 13 Jun 2006 23:48:34 -0600 Subject: python-dev Summary for 2006-05-01 through 2006-05-15 Message-ID: python-dev Summary for 2006-05-01 through 2006-05-15 ++++++++++++++++++++++++++++++++++++++++++++++++++++ .. contents:: [The HTML version of this Summary is available at http://www.python.org/dev/summary/2006-05-01_2006-05-15] ============= Announcements ============= ------------------- Python 2.5 progress ------------------- Python 2.5 is moving steadily towards its first beta release. See `PEP 356`_ for more details and the full schedule. .. _PEP 356: http://www.python.org/dev/peps/pep-0356/ Contributing threads: - `2.5 open issues `__ - `nag, nag -- 2.5 open issues `__ ---------------------------------------------------------- Experimental wiki for editing the Python library reference ---------------------------------------------------------- Fredrik Lundh introduced his `pyref wiki`_ which allows wiki-style editing of the Python Library Reference. In addition to providing useful links, like unique URLs for all keywords, types and special methods, the project aims to make cleaning up and rewriting parts of the Python documentation as easy as editing a wiki. If you'd like to help out, let `Fredrik`_ know your infogami user name and he can add you to the group. .. _pyref wiki: http://pyref.infogami.com/ .. _Fredrik: fredrik at effbot.org Contributing threads: - `introducing the experimental pyref wiki `__ - `introducing the experimental pyref wiki `__ - `more pyref: continue in finally statements `__ - `more pyref: a better term for "string conversion" `__ - `more pyref: comparison precedence `__ - `context guards, context entry values, context managers, context contexts `__ ----------------------------------------------- Assigning a SourceForge group to a tracker item ----------------------------------------------- When opening a new patch on the SourceForge tracker, you should set "Group" to the earliest still-maintained Python version to which it applies. Currently, that means if it's a candidate for backporting, you should set the "Group" to 2.4. Contributing thread: - `Assigning "Group" on SF tracker? `__ ========= Summaries ========= -------------------------------- PEP 3102: Keyword-only arguments -------------------------------- This fortnight continued discussion from the last on Talin's PEP for keyword-only arguments. Mainly the discussion focused on the second half of his proposal which would allow positional arguments and keyword-only arguments at the same time with syntax like:: def compare(a, b, *, key=None): The arguments for it included: * It allows function APIs to be more strict initially to allow API evolution without breaking existing code. * It provides better documentation for functions that currently would have to take a \*\*kwargs. Still, a lot of people felt uncomfortable with the idea that the writer of a function could force the callee to use keyword arguments even if the callee found positional arguments to be simpler. Contributing thread: - `PEP 3102: Keyword-only arguments `__ ---------------------------------- Alternative to PEP 355 path object ---------------------------------- Noam Raphael suggested an alternative to the path object suggested by `PEP 355`_ which makes paths more like tuples than strings. The ensuing discussion considered a variety of options, which would have allowed code something like:: pth = Path("~/foo/bar/baz.tar.gz"): assert pth.basepath == HOMEDIR assert pth.dirparts == ('foo', 'bar') assert pth.nameparts == ('baz', 'tar', 'gz') assert pth.prefix == str(pth.basepath) assert pth.dir == os.sep.join(pth.dirparts + ('',)) assert pth.name == os.extsep.join(pth.nameparts) Most of the ideas were also posted to the wiki under `AlternativePathClass`_ or `AlternativePathDiscussion`_, and a number of people asked for a PEP, but none was available at the time of this summary. .. _PEP 355: http://www.python.org/dev/peps/pep-0355/ .. _AlternativePathClass: http://wiki.python.org/moin/AlternativePathClass .. _AlternativePathDiscussion: http://wiki.python.org/moin/AlternativePathDiscussion Contributing thread: - `Alternative path suggestion `__ ---------------------------- Mechanics for Python sprints ---------------------------- Tim Peters started a discussion about the best way to handle SVN commits during a sprint. After discussing a number of heavier-handed solutions, like trying to grant commit privileges for a single branch, in the end it seemed easiest to just add all the sprinters as committers, warn them to be careful about their commits, and have folks keep an eye on python-checkins. Contributing thread: - `Python sprint mechanics `__ ------------------------- Methods of the bytes type ------------------------- Josiah Carlson asked about which str/unicode methods would still be available in Python 3000's bytes type. Guido asked for the thread to be moved to the `Python-3000 list`_ but then also suggested that "startswith", "endswith", "index", "rindex", "find", "rfind", "split", "rsplit", "join", "count", "replace", and "translate" might all be candidate methods. Josiah brought up some concerns about the bytes type not being hashable, but then Guido stepped in to ask that the debate be put on hold until the Python 3000 branch is more complete and some of these usability issues can be tested out there. .. _Python-3000 list: http://mail.python.org/mailman/listinfo/python-3000 Contributing threads: - `methods on the bytes object `__ - `methods on the bytes object `__ - `methods on the bytes object (was: Crazy idea for str.join) `__ ------------------------------------ PEP 3101: Advanced String Formatting ------------------------------------ Talin presented an updated `PEP 3101`_, and Edward Loper brought up an issue with the current escaping strategy -- code like ``'Foo\\%s' % x`` could not be written with the new string formatting since ``'Foo\\{0}'.format(x)`` would read the first brace as being escaped. .. _PEP 3101: http://www.python.org/dev/peps/pep-3101/ Contributing threads: - `PEP 3101: Advanced String Formatting `__ - `PEP 3101 Update `__ -------------------------------------------- Additional support for Py_ssize_t formatting -------------------------------------------- Georg Brandl asked about formatting unsigned Py_ssize_t values with PyString_FromFormat. To support this, Tim Peters added %u, %lu, and %zu to PyString_FromFormat, PyErr_Format, and PyString_FromFormatV. Contributing thread: - `Py_ssize_t formatting `__ --------------------------------------------- Supporting long options: --help and --version --------------------------------------------- Heiko Wundram provided a `patch to support long options`_ for the Python interpreter in order to support --version and --help on Unix and -?, /?, /version and /help on Windows. No one seemed opposed to the idea, but at the time of this summary, the patch was still open. .. _patch to support long options: http://bugs.python.org/1481112 Contributing thread: - `Python long command line options `__ ---------------------- Error codes on Windows ---------------------- Martin v. L??wis and Marc-Andre Lemburg discussed how to include both DOS and WIN32 error codes on WindowsError objects. As part of the solution, they discussed making the Win32 error code for a specific exception available as a .winerror attribute and making all the Windows error codes available through a winerror module. Contributing thread: - `[Python-checkins] r45925 - in python/trunk: Lib/tempfile.py Lib/test/test_os.py Misc/NEWS Modules/posixmodule.c `__ ------------------------------- Signature objects for functions ------------------------------- Brett Cannon asked for some discussion of signature objects that would accompany functions and describe what kind of arguments they take. In particular, he wanted to know: * should signature objects be automatically generated, or only created at the request of a user? * should there be a function somewhere that can determine if a particular set of arguments are valid for a function? Some people wanted signature objects to always be available, but with the current C API, that isn't possible because functions declared in C can't be guaranteed to have the information necessary for determining a signature. Others suggested that since the signature object was only useful for introspection, it should only be available through, say, ``inspect.getsignature()``. No PEP was available at the time of this summary. Contributing thread: - `signature object issues (to discuss while I am out of contact) `__ ------------------------- Set complement operations ------------------------- Terry Jones asked about adding efficient set complement operations to Python's builtin sets so that, say, the complement of a 999,999 element set in a 1,000,000 element universe would take up the space of 1 element, not 999,999. Most folks thought it would be better to implement this as a standalone module first before there were any considerations about adding it to the stdlib. Contributing thread: - `Efficient set complement and operation on large/infinite sets. `__ ------------------------------------------------------------------ Getting the weakref objects out of weakref.Weak*Dictionary objects ------------------------------------------------------------------ Fred L. Drake, Jr. presented a `patch to let users get the weakref objects out`_ of weakref.Weak*Dictionary objects. There was a brief discussion about trying to allow iteration over such dictionaries, but it looked like the patch was pretty reasonable and would soon be applied. .. _patch to let users get the weakref objects out: http://bugs.python.org/1479988 Contributing thread: - `New methods for weakref.Weak*Dictionary types `__ ----------------------------- Python support for Windows CE ----------------------------- Luke Dunstan offered to maintain the port of Python to Windows CE. He got some clarifications about a number of issues, in particular that, although #ifdefs are occasionally removed to ease Python's maintenance, if they are accompanied by a record of what system and version needs them, they will not be dropped while there is an appropriate maintainer. Contributing thread: - `Python for Windows CE `__ --------------------------------- Universal binaries for Python 2.4 --------------------------------- Ronald Oussoren asked about backporting to Python 2.4 the universal binary patches he applied to 2.5, mainly in order to avoid Apple picking up a recent copy of Python and shipping with a broken universal build like it did for python 2.3. While 2.4.4 isn't planned until after 2.5.0 (so if Apple picks up the newest version, they won't get the 2.4 line anyway), people seemed happy with the plan, and so there should be universal binary support in both Python 2.4.4 and 2.5.0. Contributing thread: - `python 2.4 and universal binaries `__ ================ Deferred Threads ================ - `pthreads, fork, import, and execvp `__ ================== Previous Summaries ================== - `Adding functools.decorator `__ - `More on contextlib - adding back a contextmanager decorator `__ - `Tkinter lockups. `__ - `Visual studio 2005 express now free `__ =============== Skipped Threads =============== - `unittest argv `__ - `speeding up function calls `__ - `elimination of scope bleeding of iteration variables `__ - `global variable modification in functions [Re: elimination of scope bleeding of iteration variables] `__ - `python syntax additions to support indentation insensitivity/generated code `__ - `socket module recvmsg/sendmsg `__ - `__getslice__ usage in sre_parse `__ - `More Path comments (PEP 355) `__ - `Path.ancestor() `__ - `[Python-checkins] r45850 - in python/trunk: Doc/lib/libfuncs.tex Lib/test/test_subprocess.py Misc/NEWS Objects/fileobject.c Python/bltinmodule.c `__ - `Reminder: call for proposals "Python Language and Libraries Track" for Europython 2006 `__ - `Date for DC-area Python sprint? `__ - `test failures in test_ctypes (HEAD) `__ - `Positional-only Arguments `__ - `Any reason that any()/all() do not take a predicate argument? `__ - `mail to talin is bouncing `__ - `Seeking students for the Summer of Code `__ - `binary trees. Review obmalloc.c `__ - `Shared libs on Linux (Was: test failures in test_ctypes (HEAD)) `__ - `lambda in Python `__ - `Time since the epoch `__ - `[Python-checkins] r45898 - in python/trunk: Lib/test/test_os.py Lib/test/test_shutil.py Misc/NEWS Modules/posixmodule.c `__ - `Confirmed: DC-area sprint on Sat. June 3rd `__ - `A critic of Guido's blog on Python's lambda `__ - `Weekly Python Patch/Bug Summary `__ - `binary trees. `__ - `Yet another type system -- request for comments on a SoC proposal `__ - `possible use of __decorates__ in functools.decorator `__ - `total ordering. `__ - `rest2latex - pydoc writer - tables `__ - `[Python-checkins] Python Regression Test Failures basics (1) `__ - `PyThreadState_SetAsyncExc, PyErr_Clear and native extensions `__ - `[Python-3000] Questions on optional type annotations `__ - `Status: sqlite3 module docs `__ - `cleaned windows icons `__ - `correction of a bug `__ - `Building with VS 2003 .NET `__ - `[Python-checkins] r46005 - in python/trunk: Lib/tarfile.py Lib/test/test_tarfile.py Misc/NEWS `__ ======== Epilogue ======== This is a summary of traffic on the `python-dev mailing list`_ from May 01, 2006 through May 15, 2006. It is intended to inform the wider Python community of on-going developments on the list on a semi-monthly basis. An archive_ of previous summaries is available online. An `RSS feed`_ of the titles of the summaries is available. You can also watch comp.lang.python or comp.lang.python.announce for new summaries (or through their email gateways of python-list or python-announce, respectively, as found at http://mail.python.org). This python-dev summary is the 4th written by the python-dev summary drone, Steve Bethard. (Look ma! No hundred-message threads!) To contact me, please send email: - Steve Bethard (steven.bethard at gmail.com) Do *not* post to comp.lang.python if you wish to reach me. The `Python Software Foundation`_ is the non-profit organization that holds the intellectual property for Python. It also tries to advance the development and use of Python. If you find the python-dev Summary helpful please consider making a donation. You can make a donation at http://python.org/psf/donations.html . Every cent counts so even a small donation with a credit card, check, or by PayPal helps. -------------------- Commenting on Topics -------------------- To comment on anything mentioned here, just post to `comp.lang.python`_ (or email python-list at python.org which is a gateway to the newsgroup) with a subject line mentioning what you are discussing. All python-dev members are interested in seeing ideas discussed by the community, so don't hesitate to take a stance on something. And if all of this really interests you then get involved and join `python-dev`_! ------------------------- How to Read the Summaries ------------------------- That this summary is written using reStructuredText_. Any unfamiliar punctuation is probably markup for reST_ (otherwise it is probably regular expression syntax or a typo :); you can safely ignore it. We do suggest learning reST, though; it's simple and is accepted for `PEP markup`_ and can be turned into many different formats like HTML and LaTeX. Unfortunately, even though reST is standardized, the wonders of programs that like to reformat text do not allow us to guarantee you will be able to run the text version of this summary through Docutils_ as-is unless it is from the `original text file`_. .. _python-dev: http://www.python.org/dev/ .. _SourceForge: http://sourceforge.net/tracker/?group_id=5470 .. _python-dev mailing list: http://mail.python.org/mailman/listinfo/python-dev .. _c.l.py: .. _comp.lang.python: http://groups.google.com/groups?q=comp.lang.python .. _PEP Markup: http://www.python.org/peps/pep-0012.html .. _Docutils: http://docutils.sf.net/ .. _reST: .. _reStructuredText: http://docutils.sf.net/rst.html .. _PSF: .. _Python Software Foundation: http://python.org/psf/ .. _original text file: http://www.python.org/dev/summary/2006-05-01_2006-05-15.rst .. _archive: http://www.python.org/dev/summary/ .. _RSS feed: http://www.python.org/dev/summary/channews.rdf From rodrigostrauss at gmail.com Mon Jun 26 15:38:26 2006 From: rodrigostrauss at gmail.com (rodrigostrauss at gmail.com) Date: 26 Jun 2006 12:38:26 -0700 Subject: PythonWin 207: How to change caret color? Message-ID: <1151350706.858536.184370@i40g2000cwc.googlegroups.com> I already changed some colors hacking registry (prompt color is among them), but I was not able to change the caret color. I've changed the backgroud color to black, now I need to change the caret color from black to something else. I don't mind if the solution includes sending messages to Scintilla (the SCI_SETCARETFORE message should do the job, but I'm not finding which object I should call). Regards, Strauss From cdsmith at twu.net Fri Jun 23 22:40:14 2006 From: cdsmith at twu.net (Chris Smith) Date: Fri, 23 Jun 2006 20:40:14 -0600 Subject: What is Expressiveness in a Computer Language References: <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150908952.804184.218990@r2g2000cwb.googlegroups.com> <1150991074.705803.211570@m73g2000cwd.googlegroups.com> <1151083239.829296.33030@i40g2000cwc.googlegroups.com> <1151083931.162325.268050@g10g2000cwb.googlegroups.com> <1151086320.564736.272500@y41g2000cwy.googlegroups.com> <1151100483.057344.310970@g10g2000cwb.googlegroups.com> <1151115244.951029.56060@g10g2000cwb.googlegroups.com> Message-ID: Marshall wrote: > I stand corrected: if one is using C and writing self-modifying > code, then one *can* zip one's pants. I believe you'd need quite the creative USB-based or similar peripheral device, as well. -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation From jkn_gg at nicorp.f9.co.uk Wed Jun 14 09:27:59 2006 From: jkn_gg at nicorp.f9.co.uk (jkn) Date: 14 Jun 2006 06:27:59 -0700 Subject: Tiddlywiki type project in Python? In-Reply-To: <44900ae9$0$8386$626a54ce@news.free.fr> References: <1150289313.533749.52330@i40g2000cwc.googlegroups.com> <44900ae9$0$8386$626a54ce@news.free.fr> Message-ID: <1150291679.746132.114730@y43g2000cwc.googlegroups.com> Hi Bruno [...] > > > > I don't know Javascript (although it looks moderately simple from a > > brief peruse, > > It's not as simple as it may seem at first look. There are some real > gotchas. But if you want a more pythonic javascript, you should have a > look at mochikit. OK, thanks for the pointer [...] > > > and I know enough languages to know I'll be able to pick > > it up); however I do know and use Python, although not nuch in a > > web-oriented way. Since unlike JS, python is at least pre-compiled, I > > have hopes that this would make things quicker. I do appreciate that JS > > is built into the browser, which might make my Python approach slower. > > I'm not sure of the 'architectural' approach to this; any suggestions, > > and maybe pointers to previous work? > > I don't really understand what you're after here, since TiddlyWikiLikes > can *not* work without javascript. Well, that may be an/the answer, since another form of my question would be 'how can I write a TiddlyWikiLike using Python instead of JS' ;-). I appreciate that it might involve, for instance, a local server. Does the idea of embedding python in a browser instead of Javascript make any sense at all? > > Anyway, there's at least a Zope-based TiddlyWikiLike, so you may want to > have a look here: > http://ziddlywiki.org/ > Thanks again jon N From chris.cavalaria at free.fr Thu Jun 15 04:55:53 2006 From: chris.cavalaria at free.fr (Christophe) Date: Thu, 15 Jun 2006 10:55:53 +0200 Subject: Numerics, NaNs, IEEE 754 and C99 In-Reply-To: References: <12904mjhl493t49@corp.supernews.com> <1290aik50hmk94a@corp.supernews.com> <4490329e$0$12356$636a55ce@news.free.fr> <12917f6jp7u90f8@corp.supernews.com> Message-ID: <44912058$0$29674$636a55ce@news.free.fr> Nick Maclaren a ?crit : > Now, can you explain why 1/0 => -Inf wouldn't work as well? I.e. why > are ALL of your zeroes, INCLUDING those that arise from subtractions, > are known to be positive? I would say that the most common reason people assume 1/0 = Inf is probably because they do not make use of negative numbers or they forgot they exist at all. From ve_sivakumar at yahoo.com Thu Jun 8 18:10:58 2006 From: ve_sivakumar at yahoo.com (V Sivakumar) Date: Thu, 08 Jun 2006 22:10:58 -0000 Subject: TKinter Message-ID: Dear Group!, I am new to Python. I have Eclipse with Python support , is there better IDE for free and with good support for GUI development. I need to develop a nice looking desktop application. Like we could do in VB, C# and Java Swing. Is there a drag drop support GUI toolkit for Python like the above languages do? Thanks Siva From DustanGroups at gmail.com Tue Jun 13 15:25:59 2006 From: DustanGroups at gmail.com (Dustan) Date: 13 Jun 2006 12:25:59 -0700 Subject: Making a Label that looks the same as a button. In-Reply-To: References: Message-ID: <1150226759.327143.53340@u72g2000cwu.googlegroups.com> Cameron Laird wrote: > In article , > Grayson, John wrote: > > > > > > > >Buttons can look like labels without the need to create another object - > >just remove the > >Command binding, set state to DISABLED and disabledforeground='same > >color as NORMAL'... > > > >This demonstrates how to play with button styles: > . > . > . > John, as I read the original poster, Tkinter.DISABLED is *exactly* > what he wants (although he might not realize it yet); I suspect > there's no need at all for other styling. > > Are Button and Label styles truly identical except for > disabledforeground? While I can't make the time now to research > this for myself, it surprises me; I thought there were padding > differences ... > > Your remark about the Command has me curious: why remove it? In > terms of the original poster's description, what does this serve? > I repeat my speculation that Tkinter.DISABLED will "do it all" for > him. Yes, that's what I needed (and I knew about that before), but I didn't know about the disabledforeground option. Thanks for the information; it worked nicely. From 3dbernard at gmail.com Mon Jun 5 11:09:31 2006 From: 3dbernard at gmail.com (Bernard Lebel) Date: Mon, 5 Jun 2006 11:09:31 -0400 Subject: Little question about Tkiner: window focus Message-ID: <61d0e2b40606050809w1bf2ea7ag41fb45939bf26072@mail.gmail.com> Hello, I have this Tkinter window that when you click on a certain button, another instance of Tk is created, and thus a new windows is spawned. That second windows holds a few widgets to browse files and directories. Now, as soon as I start browsing files and directories, the first window comes back in focus. I have to click the second window to put the focus back there. My question is: is there a way to force the focus of a given Tk instance? I'm using the Toplevel widget to create those second windows. I have looked into the "takefocus" option, but doesn't seem to have any effect. I'm using Python 2.4 on Windows XP Pro SP1. Thanks Bernard From m.yanowitz at kearfott.com Tue Jun 13 10:04:34 2006 From: m.yanowitz at kearfott.com (Michael Yanowitz) Date: Tue, 13 Jun 2006 10:04:34 -0400 Subject: .py and running in Windows: In-Reply-To: <1150206503.313636.50130@c74g2000cwc.googlegroups.com> Message-ID: Thanks. XP looks to be the same as 2000. Works as expected now. Thank You. Not sure what this 'thread' issue is. I never specified a thread. I think perhaps though because I did open another message in this mailing list (to get the correct email address to send to), but I deleted all its contents i put it under that other thread, however there is no indication of a thread in Outlook email. I am sorry if it came up in another thread that was not my intention. -----Original Message----- From: python-list-bounces+m.yanowitz=kearfott.com at python.org [mailto:python-list-bounces+m.yanowitz=kearfott.com at python.org]On Behalf Of Iain King Sent: Tuesday, June 13, 2006 9:48 AM To: python-list at python.org Subject: Re: .py and running in Windows: Andrew Gwozdziewycz wrote: > You'll have better results posting this to it's own thread. > He certainly should have, but since I've read it here anyway: > On Jun 13, 2006, at 9:29 AM, Michael Yanowitz wrote: > > > Hello: > > > > Presently in my Windows 2000 system, when I double-click on a > > .py file (open it) it automatically runs it in Python. I would > > like to change that behavour. That is fine for .pyc file, but > > for .py files, I would either like to have it run in Python but > > return to the Python shell prompt when finished rather than > > exit the shell. How do I do that? > > Or would it cause a problem (so that Python no longer works) if > > I change the default .py extension to open in an editor rather > > than execute it if I open it? > > In an explorer window, go to Tools->Folder Options Go to the File Types tab, find the PY extension, then click on Advanced* Select the 'open' action, and click Edit... change the 'Application used to perform action', inserting a '-i' between the exe and the first parameter. For example, I changed mine to: "C:\Python\python.exe" -i "%1" %* The exact line will depend on where your python.exe is. OK all the dialogs you've opened, then double click a .py file to test it. *I'm using WinXP, so the exact name of some of the buttons may be different for you. Iain -- http://mail.python.org/mailman/listinfo/python-list From slawomir.nowaczyk.847 at student.lu.se Fri Jun 16 04:14:51 2006 From: slawomir.nowaczyk.847 at student.lu.se (Slawomir Nowaczyk) Date: Fri, 16 Jun 2006 10:14:51 +0200 Subject: BeautifulSoup error In-Reply-To: <874pylllqn.fsf@benfinney.id.au> References: <871wtpdbas.fsf@www.williamxu.com> <874pylllqn.fsf@benfinney.id.au> Message-ID: <20060616101031.CCD6.SLAWOMIR.NOWACZYK.847@student.lu.se> On Fri, 16 Jun 2006 15:20:48 +1000 Ben Finney wrote: #> > >>> soup = BeautifulSoup() #> > >>> soup.feed(port) #> > Traceback (most recent call last): #> > File "", line 1, in ? #> > File "/usr/lib/python2.3/sgmllib.py", line 94, in feed #> > self.rawdata = self.rawdata + data #> > UnicodeDecodeError: 'ascii' codec can't decode byte 0xb8 in position 565: ordinal not in range(128) #> > >>> #> #> Uses the default Python text encoding, 'ascii', when it needs to #> decode the data in 'port' to Unicode. Some of the data in that #> object makes no sense in the 'ascii' encoding, so it barfs. In other words, this works for me: >>> soup.feed( unicode(port,"iso-8859-1") ) -- Best wishes, Slawomir Nowaczyk ( Slawomir.Nowaczyk at cs.lth.se ) ^[:wq! Crap! Thought I was in vi. From digitalorganics at gmail.com Mon Jun 26 10:42:28 2006 From: digitalorganics at gmail.com (digitalorganics at gmail.com) Date: 26 Jun 2006 07:42:28 -0700 Subject: Search String for Word Message-ID: <1151332947.985001.226510@r2g2000cwb.googlegroups.com> What's the best way to search a string for a particular word and get a booleen value indicating whether it exists in the string or not? Thanks... From faheem at email.unc.edu Sat Jun 24 15:25:29 2006 From: faheem at email.unc.edu (Faheem Mitha) Date: Sat, 24 Jun 2006 19:25:29 GMT Subject: puzzlement about classmethod Message-ID: Hi, Consider the following small script. My understanding of how this works is that, conceptually, class B holds a separate copy of variable x from class A. Nearly everything behaves the way I would expect, except that setting x to 12 in A using class_setx at the beginning also sets the value for x in B. However, the converse (setting x in B using class_setx), does not change the value in A, which I would consider to be the expected behavior. However, after that the two x variables appear to behave independently. Can anyone explain to me why this is so? Regards, Faheem Mitha. ****************************************************************** #!/usr/bin/python class A(object): x = 0 def class_getx(cls): return cls.x class_getx = classmethod(class_getx) def class_setx(cls, _x): cls.x = _x class_setx = classmethod(class_setx) def getx(self): return type(self).x def setx(self, _x): type(self).x = _x class B(A): pass def printx(): print "*** begin printing values of x... ***" print "Fetching from A using class_getx gives %s"%(A.class_getx()) print "Fetching from B using class_getx gives %s"%(B.class_getx()) print "Fetching from A using instance a and getx gives %s"%(a.getx()) print "Fetching from B using instance b and getx gives %s"%(b.getx()) print "*** end printing values of x... ***" a = A() b = B() printx() print "setting x to 12 in A using class_setx"; A.class_setx(12) printx() print "setting x to 15 in B using class_setx"; B.class_setx(15) printx() print "setting x to 10 in A using class_setx" A.class_setx(10) printx() print "setting x to 44 in A using instance a and setx"; a.setx(55) printx() print "setting x to 22 in B using instance b and setx"; b.setx(22) printx() From samschul at pacbell.net Fri Jun 2 16:45:56 2006 From: samschul at pacbell.net (sam) Date: 2 Jun 2006 13:45:56 -0700 Subject: How do you practice Python? In-Reply-To: References: <1149150517.034409.292530@g10g2000cwb.googlegroups.com> <1149271920.917381.112910@u72g2000cwu.googlegroups.com> Message-ID: <1149281156.712919.226210@g10g2000cwb.googlegroups.com> Years ago I developed a Hard Disk Drive diagnostic program "SCSIPython" while working for a disk drive company. When I left that company,and realized that these routines would never be used by the company, I released it as Open Source. Since then I have maintained this code, and enhanced it with the various versions of Python that have been released after V1.5. I find that with each update my code becomes more robust,with added features. Also As I moved from company to company I made certain that they knew that this code was Open Source,and only proprietary methods will be excluded, when I signed the standard intellectual property forms. Sam Schulenburg Jarek Zgoda wrote: > sjdevnull at yahoo.com napisa?(a): > > >>In our field, we don't always get to program in the language we'd like > >>to program. So... how do you practice Python in this case? > > > > Write code. Lots of it. Work on a project at home, contribute to > > something open source, use it to write support scripts at work, > > whatever. Figure out a way to write code. > > I second that. I moved from Python to J2EE in my job, but I didn't stop > writing Python code for my spare-time projects. Now, when tight schedule > made my project's manager to shift paradigm from buzz to productivity, I > am happy I can write programs in Python again. On AS/400, but still > better than Java... :D > > -- > Jarek Zgoda > http://jpa.berlios.de/ From luca.tavoletti at gmail.com Mon Jun 12 13:35:25 2006 From: luca.tavoletti at gmail.com (lux) Date: 12 Jun 2006 10:35:25 -0700 Subject: VC++ types to ctypes In-Reply-To: References: <1150125909.402633.63250@i40g2000cwc.googlegroups.com> Message-ID: <1150133725.259775.216400@f6g2000cwb.googlegroups.com> Thank you now it work!!! Thomas Heller ha scritto: > lux wrote: > > Hi to all, > > i need to traslate this struct in python using ctypes > > > > struct Soptions > > { > > char chVolumeLabel[128]; > > __int32 nSessionToImport; > > BS_BOOL bJolietFileSystem; > > BS_BOOL bBootable; > > TCHAR chBootImage[_MAX_PATH]; > > BS_BOOL bFinalize; > > BS_BOOL bTestBurn; > > BS_BOOL bPerformOPC; > > BS_BOOL bVerifyAfterBurn; > > __int32 nCacheSize; > > BS_BOOL bUnderrunProtection; > > BS_BOOL bEjectAfterBurn; > > __int32 nCopies; > > } > > > > I try to convert: > > > > char xxx[128] -> c_char*128 > > __int32 -> c_int > > BS_BOOL -> c_byte > > > > TCHAR chBootImage[_MAX_PATH]; -> ??? > > > > But not work... > > how to solve it? > > > > Thank's, Luca > > > > _MAX_PATH is 260. > TCHAR is normally a unicode (wide) or a ascii (ansi) character, depending > on if _UNICODE is defined by the compiler. Assuming ascii, > TCHAR chBootImage[_MAX_PATH] -> c_char * 260 > > Thomas From mscottschilling at hotmail.com Sun Jun 11 11:04:58 2006 From: mscottschilling at hotmail.com (Mike Schilling) Date: Sun, 11 Jun 2006 15:04:58 GMT Subject: Xah Lee network abuse References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148495974.975395.12920@i40g2000cwc.googlegroups.com> <1149998343.493200.144990@h76g2000cwa.googlegroups.com> Message-ID: "Erik Max Francis" wrote in message news:qKmdnUvjhOZZKRbZnZ2dnUVZ_r-dnZ2d at speakeasy.net... > Mike Schilling wrote: > >> If I were to write, say, that Tony Blair's tax policy will lead to higher >> deficits, I could be convicted of libel? Even if that's true, it's not a >> priori provable. > > I think what he was getting at is that, unlike many jurisdictions, writing > something factually true is _not_ in and of itself a defense against a > libel suit in the UK. > > As for the reverse side of the issue, in jurisdictions where it _is_ a > defense, if one were to accuse him of being a pedophile but couldn't prove > it, that would certainly be an actionable offense. In the U.S, for instance, you wouldn't have to prove it. It would be sufficent to demonstrate that there's enough evidence supporting it that you weren't reckless in writing it. From aleax at mac.com Thu Jun 29 00:34:24 2006 From: aleax at mac.com (Alex Martelli) Date: Wed, 28 Jun 2006 21:34:24 -0700 Subject: mmap -- memory mapped file References: Message-ID: <1hhnvpr.7n1vvk1ljr6oiN%aleax@mac.com> Carl Mackey wrote: > hi, i'm new to this list and new to python as well. > > i have a question on the memory mapped file ability python has. when i > use a mmap on a file, will it copy the whole thing to ram or just > whatever part of it i'm working on? basically, i'm wondering if it would > be ok for me to have multiple mmap's open on very large files as i read > or write from them. Python relies on the operating system to do the "memory mapping" sensibly; generally, that means the whole file is mapped in the *virtual* memory of the process -- the process's address space -- but only the necessary pages actually get into RAM. This should work fine with any modern Linux, *BSD, MacOSX, or just about any other Unix that is still sold, or, also, on Windows (at least in the NT/2000/XP line, I wouldn't be so sure on some ancient Windows/98 box:-). Still, assuming that my "very large files" you mean several gigabytes, mmap will not work well on them with a 32-bit machine, or a 64-bit machine hobbled by a 32-bit operating system -- the process's address space being limited to no more 4GB, you may be unable to mmap even just one "very large file" (this is totally unrelated to how much RAM you may have: the limitation is with the *address space* of each process). Alex From stormtoad at gmail.com Mon Jun 5 19:21:01 2006 From: stormtoad at gmail.com (Stormcoder) Date: 5 Jun 2006 16:21:01 -0700 Subject: Software Needs Philosophers References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> Message-ID: <1149549661.721778.8200@i40g2000cwc.googlegroups.com> He means Lisp macros. Lisp macros are nothing like the crippled C++ macros that people tend to think of. Roedy Green wrote: > On 21 May 2006 02:15:31 -0700, "Xah Lee" wrote, > quoted or indirectly quoted someone who said : > > > Java has lots of macro languages, including C++'s preprocessor. What > it does not have is a sanctioned one. It has instead on-the-fly code > generation. See http://mindprod.com/jgloss/onthefly.html > > > -- > Canadian Mind Products, Roedy Green. > http://mindprod.com Java custom programming, consulting and coaching. From onurb at xiludom.gro Fri Jun 30 09:11:58 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Fri, 30 Jun 2006 15:11:58 +0200 Subject: list comprehension In-Reply-To: <1151671605.957887.158150@m73g2000cwd.googlegroups.com> References: <1151600332.552024.119990@y41g2000cwy.googlegroups.com> <1151602493.629010.269360@i40g2000cwc.googlegroups.com> <1151671605.957887.158150@m73g2000cwd.googlegroups.com> Message-ID: <44a5231e$0$7224$626a54ce@news.free.fr> Andy Dingley wrote: > Simon Forman wrote: > > >>There's more to it, but that's the basic idea. > > > This much I knew, but _why_ and _when_ would I choose to use list > comprehension (for good Python style), rather than using a simple > "traditional" loop ? Whenever it's more readable. > If I want to generate something that's simply ( [1] + [2] + [3]+... ) > then list comprehension is obviously the tool of choice. I suspect > though that there's more to it than this. Is list comprehension also > treatable as a sneaky concise formulation for nested lists, where > they're as much about selection of individual elements, so much as > concatenation of the sequence? I've read this last sentence three times now and I'm still not sure to grasp it - hopefully it's friday... Care to give an example ? > What happens if a comprehension has side effects, such as from calling > a function within it? Is this regarded as good or bad coding style? Is > it evil (as structured programming would claim) or is it a concise > formulation for an iterator or visitor pattern ? I'd say it's bad style to call a function having side effects from within a list comp. List comps have a very declarative/functional style, while side effects are clearly on the imperative side. I never took time to think about this, but IIRC I've never used list comp that way - I then use a for loop. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From fredrik at pythonware.com Wed Jun 7 17:54:53 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 07 Jun 2006 23:54:53 +0200 Subject: Using C struct in Python** corrected In-Reply-To: <44874755.9030809@netapp.com> References: <448746BE.9080504@netapp.com> <44874755.9030809@netapp.com> Message-ID: Sudheer Gupta wrote: > I am having trouble using C struct in python. Hope anyone can help me > out ... > > Say, I have my C struct as > > typedef struct call > { > struct call *next; > // ..... > > } call_t; > > I have a global variable, namely call_pool, which is of type call_t * > > My python program: > > cp = call_pool # no error doing this, means that call_pool is accessable Without any glue code? That's weird. What Python implementation is this? > while cp: > print cp > cp = cp.next > > This is giving me error: " There is no member or method name c_next" Doesn't look like a Python exception to me. Cannot find any trace of that message in the CPython sources either... > Now, If I just do: > > print cp > print cp.next > > there is no problem. But I am seeing a difference in the way python is > looking at the struct: > > print cp -> (call_t*) 0xb0... > print cp.next -> (struct call *) 0xb0... > > Is python not intelligent enough to diagnose the next pointer ?? I've written more C extensions for Python than most people, but I'm definitely not intelligent enough to decipher your post. What on earth are you talking about ? Are you sure you're posting to the right newsgroup ? From deets at nospam.web.de Mon Jun 12 03:45:11 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 12 Jun 2006 09:45:11 +0200 Subject: Evaluating a Function After X Seconds: Python Equivalent to JavaScript's SetTimeout() Function In-Reply-To: References: <1150081288.699325.105850@j55g2000cwa.googlegroups.com> Message-ID: <4f4kc6F1hfdseU1@uni-berlin.de> Dennis Lee Bieber schrieb: > I don't know? How does "SetTimeout" actually behave? Asynchronously? > Synchronously? That is... would The former. It is the poor-mans threading of JavaScript so to speak. Diez From aisaac0 at verizon.net Mon Jun 19 16:12:21 2006 From: aisaac0 at verizon.net (David Isaac) Date: Mon, 19 Jun 2006 20:12:21 GMT Subject: Legitimate use of the "is" comparison operator? References: <20060617075308.29014.1287982850.divmod.quotient.2368@ohm> <1150533733.252877.238120@c74g2000cwc.googlegroups.com> Message-ID: > > (I was using *small* integers). "Fredrik Lundh" wrote: > "small integers" is what the phrase "small integers" in the "small > integers" and "small integers" parts of my reply referred too, of course. But aren't "*small* integers" likely to be smaller than "small integers"? Alan Isaac From uche.ogbuji at gmail.com Sun Jun 11 11:02:50 2006 From: uche.ogbuji at gmail.com (uche.ogbuji at gmail.com) Date: 11 Jun 2006 08:02:50 -0700 Subject: 10GB XML Blows out Memory, Suggestions? In-Reply-To: References: <1149594519.098115.8980@u72g2000cwu.googlegroups.com> <4eleh3F1eguosU1@uni-berlin.de> <4485C819.2030206@tachyontech.net> Message-ID: <1150038170.168698.306070@m38g2000cwc.googlegroups.com> K.S.Sreeram wrote: > Fredrik Lundh wrote: > > both ElementTree and cElementTree support "sax-style" event generation > > (through XMLTreeBuilder/XMLParser) and incremental parsing (through > > iterparse). the cElementTree versions of these are even faster than > > pyexpat. > > > > the iterparse interface is described here: > > > > http://effbot.org/zone/element-iterparse.htm > > > Thats cool! Thanks for the info! > > For a multi-gigabyte file, I would still recommend C/C++, because the > processing code which sits on top of the XML library needs to be Python, > and that could turn out to be a significant overhead in such extreme cases. > > Of course, the exact strategy to follow would depend on the specifics of > the case, and all this speculation may not really apply! :) Honestly, i think that legitimate use-cases for multi-gigabyte XML are very rare. Many people abuse XML as some sort of DBMS replacement. This abuse is part of the reason why so many developers are hostile to XML. XML is best for documents, and documents can get to the multi-gigabyte range, but rarely do. Usually, when they do, there is a logical way to decompose them, process them, and re-compose them, whereas with XML used as a DBMS replacement, relations and datatyping complicate such natural divide-and-conquer techniques. I always say that if you're dealing with gigabyte XML, it's well worth considering whether you're not using a hammer to screw in a bolt. If monster XML is inevitable, then I extend's Fredrik earlier mention of Amara to say that Pushdom allows you to pre-declare the chunks of XML you're interested in, and then it processes the XML in streaming mode, only instantiating the chunks of interest one at a time. This allows for handling of huge files with a very simple programming idiom. http://uche.ogbuji.net/tech/4suite/amara/ -- Uche Ogbuji Fourthought, Inc. http://uche.ogbuji.net http://fourthought.com http://copia.ogbuji.net http://4Suite.org Articles: http://uche.ogbuji.net/tech/publications/ From g.brandl-nospam at gmx.net Thu Jun 15 02:06:03 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Thu, 15 Jun 2006 08:06:03 +0200 Subject: Question about the Exception class In-Reply-To: References: Message-ID: Carl J. Van Arsdall wrote: > So this is probably a fairly basic question, but help me out because I'm > just not lining things up and I'm somewhat new to the world of exception > handling. > > What's the benefit to inheriting an exception from and of the available > parent exception classes? Does one subclass have benefits over any > other? Most of what I see involves making a new class and inheriting > from Exception so that one can have an exception class with a name of > their choosing. If you didn't care about the name would there be any > benefit to making a subclass versus raising StandardError or something > else equally vanilla? Are there any difference to library provided > exceptions other than their names? Creating your own exception hierarchy and using it consistently can help you debugging when an exception raised by Python itself occurs. Also, you can customize your own exception objects (such as, add new instance attributes). Georg From bellman at lysator.liu.se Thu Jun 8 10:38:32 2006 From: bellman at lysator.liu.se (Thomas Bellman) Date: Thu, 8 Jun 2006 14:38:32 +0000 (UTC) Subject: simplexmlrpcserver and allow_none References: Message-ID: Laszlo Nagy wrote: > I ran in the same problem again. Many others have the same problem. Just > Google for this: "SimpleXMLRPCServer allow_none site:python.org". > Looks like the 'allow_none' patch was commited to trunk on 2005 Dec ( > http://mail.python.org/pipermail/python-checkins/2005-December/048289.html ) > I just upgraded to Python 2.4.3 (it was released on March 29, 2006) and > SimpleXMLRPCServer.py still has the old code. > I can work around this by coping the whole file into a new file and > patch it, but I hate to do that. > I wonder why it has not been commited to the standard library yet. Does > anyone know if it will be in the next bugfix release? Fredrik has already answered your specific question, but while waiting for 2.5, another way to work around it is to do: import xmlrpclib # WARNING: Dirty hack below. # Replace the dumps() function in xmlrpclib with one that by default # handles None, so SimpleXMLRPCServer can return None. class _xmldumps(object): def __init__(self, dumps): self.__dumps = (dumps,) def __call__(self, *args, **kwargs): kwargs.setdefault('allow_none', 1) return self.__dumps[0](*args, **kwargs) xmlrpclib.dumps = _xmldumps(xmlrpclib.dumps) import SimpleXMLRPCServer -- Thomas Bellman, Lysator Computer Club, Link?ping University, Sweden "This isn't right. This isn't even wrong." ! bellman @ lysator.liu.se -- Wolfgang Pauli ! Make Love -- Nicht Wahr! From fredrik at pythonware.com Fri Jun 16 05:48:26 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 16 Jun 2006 11:48:26 +0200 Subject: getting umask without changing it References: <200606161207.56008.faik@pardus.org.tr> Message-ID: Faik Uygur wrote: > Is there a python way of getting the current umask without changing it? > os.umask changes it, and i dont want to use os.system("umask") just call os.umask twice: current_mask = os.umask(0) os.umask(current_mask) From Dennis.Benzinger at gmx.net Sun Jun 4 11:07:18 2006 From: Dennis.Benzinger at gmx.net (Dennis Benzinger) Date: Sun, 04 Jun 2006 17:07:18 +0200 Subject: in python , could I accomplish the purpose that "a=Console.read()" used in C? In-Reply-To: <1149423026.134144.58940@i40g2000cwc.googlegroups.com> References: <1149423026.134144.58940@i40g2000cwc.googlegroups.com> Message-ID: <4482f724$1@news.uni-ulm.de> python wrote: > in python , could I accomplish the purpose that "a=Console.read()" used > in C? > when program is running, I wanna add a statement like > "a=Console.read()" in C language,it will wait for user's input, after > user's typing a character , and click "enter" key, the program will go > on running. > Use raw_input() : age = raw_input("Your age: ") print age Bye, Dennis From python at hope.cz Tue Jun 6 05:56:42 2006 From: python at hope.cz (Lad) Date: 6 Jun 2006 02:56:42 -0700 Subject: How to add few pictures into one In-Reply-To: <1149580572.739202.110940@y43g2000cwc.googlegroups.com> References: <1149511692.796038.155930@c74g2000cwc.googlegroups.com> <1149517433.880564.128350@h76g2000cwa.googlegroups.com> <1149529269.228019.120480@u72g2000cwu.googlegroups.com> <1149573892.526072.6770@i39g2000cwa.googlegroups.com> <1149580572.739202.110940@y43g2000cwc.googlegroups.com> Message-ID: <1149587802.895959.37210@f6g2000cwb.googlegroups.com> bearophileHUGS at lycos.com wrote: > Lad wrote: > > I want to to do that as easy as possible. > > But not even more easy. > > > > I think the easest way could be add( append) an image to another > > into an image file so that I can use an image browser and see all > > pictures in one file. Is that possible? > > Well, you can do it with PIL, creating a very big white image and > putting on it all the images, as tiles. > But probably you want to do something different. > Maybe you can use PyUNO to create a PowerPoint-like (Presentation) file > with an image on each page. > If you are on Win another easy way is to create an Html page that shows > all the pics, open it with Explorer and save it as a single HMT file. > Probably there are other solutions. I was thinking about much less complicated task. I thought about this: Open a picture file( download it from internet) and write it in a result file( being open in binary mode). Then download another file and append to the result file. And so on... But is it possible? Will be the pictures in the result file seen well?? regards, L. From deets at nospam.web.de Thu Jun 29 10:35:57 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 29 Jun 2006 16:35:57 +0200 Subject: python for windows internet filter / firewall References: <1151590961.464723.249360@p79g2000cwp.googlegroups.com> Message-ID: <4gi6qaF1nctcjU1@uni-berlin.de> > 2) Is this even reasonable in python and how might I get started? (e.g. > win32 COM?) Don't know much (not to say nothing) about windows firewalling & the interfaces one needs to talk to them. But _what_ I know is: a firewall needs to be fast. The big guys in networking put a lot of effort into pushing as much package processing as possible into the hardware-layer. And as much as I love python - I do not see it here, beyond a proof-of-concept. Diez From sjmachin at lexicon.net Thu Jun 8 20:47:37 2006 From: sjmachin at lexicon.net (John Machin) Date: Fri, 09 Jun 2006 10:47:37 +1000 Subject: Win XP: Problem with shell scripting in Python In-Reply-To: References: Message-ID: <4488c529$1@news.eftel.com> On 9/06/2006 8:58 AM, A.M wrote: > Hi, > I am having difficulty with shell scripting in Python. > I use the following command to run a DOS command and put the return value in > a Python variable: > print os.popen('DIR').read() > It works very fine with DIR command, but for commands like "MD :" it doesn't > return the error message into the string: > print os.popen('MD :').read() > # No error message > When I use Ruby, it works perfect: > `md :` > Irrelevant; different "it". > The filename, directory name, or volume label syntax is incorrect. > > I have never had occasion to use os.popen_anything before. Perhaps we can aid each other on the path to enlightenment. I got the following idea from looking at the manual. |>>> handles = os.popen3('MD :') |>>> [f.read() for f in handles[1:]] ['', 'The filename, directory name, or volume label syntax is incorrect.\n'] |>>> [f.close() for f in handles] [None, None, 1] |>>> handles = os.popen3('dir *.py') |>>> [f.read() for f in handles[1:]] [' Volume in drive C has no label.\n Volume Serial Number is **BIG SNIP** bytes free\n', ''] |>>> [f.close() for f in handles] [None, None, None] Windows does occasionally adhere to *x conventions like "data to stdout, error messages to stderr" :-) Now it's *your* turn to do something for the cause. It appears to me that popen4 has exactly the same documentation as popen3, as recently as 2.5a2. I see no fourth gizmoid here. Whoooaaah! "4" is not a gizmoid count: |>>> handles = os.popen4('MD :') |>>> handles (, ) You might like to suss this out, and raise a request to have the docs fixed. Cheers, John From jeethu at tachyontech.net Wed Jun 7 09:23:05 2006 From: jeethu at tachyontech.net (Jeethu Rao) Date: Wed, 07 Jun 2006 18:53:05 +0530 Subject: python socket proxy In-Reply-To: <1149685669.978416.235630@u72g2000cwu.googlegroups.com> References: <1149577919.811693.178730@f6g2000cwb.googlegroups.com> <1149587437.299147.314670@h76g2000cwa.googlegroups.com> <1149685669.978416.235630@u72g2000cwu.googlegroups.com> Message-ID: <4486D339.6000306@tachyontech.net> Simplest way would be to rename your python file with a .pyw extension instead of a .py extension. If you're looking for windows services, checkout win32serviceutil.ServiceFramework in pywin32. Jeethu Rao jstobbs at gmail.com wrote: > Hi > > Thanks for the reply. > > I found a proxy that works for me. Now I would like to know if its > possible to run a python script, so its not visible in the cmd window > (windows, i know, its bad :-) ) Maybe run it as a windows service? > > > > Filip Wasilewski wrote: > >> jstobbs at gmail.com wrote: >> >>> Hi all >>> >>> I am trying to create a lighweight tcp proxy server. >>> >> [...] >> >> There is a bunch of nice recipies in the Python Cookbook on port >> forwarding. In the [1] and [2] case it should be fairly simple to add >> an extra authentication step with pyOpenSSL. >> >> [1] http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/483730 >> [2] http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/114642 >> [3] http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/483732 >> >> best, >> fw >> > > From anton.vredegoor at gmail.com Sat Jun 17 08:46:08 2006 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Sat, 17 Jun 2006 14:46:08 +0200 Subject: [OT] code is data Message-ID: With the inclusion of ElementTree (an XML-parser) in Python25 and recent developments concerning JSON (a very Pythonesque but somewhat limited XML notation scheme, let's call it statically typed XML) Python seems to have reached a stage where it now seems to be possible to completely swallow lesser languages code, modify it, and spit out new source code targeting the original language the code was written in, or even make a translation to other languages. The idea is that we now have a fast parser (ElementTree) with a reasonable 'API' and a data type (XML or JSON) that can be used as an intermediate form to store parsing trees. Especially statically typed little languages seem to be very swallow-able. Maybe I will be able to reimplement GFABasic (my first love computer language, although not my first relationship) someday, just for fun. Then there are things like cTypes (calling functions from native DLL's) and PyPy (implementing Python in Python). All this taken together, to me it starts looking like we're now entering a territory that traditionally was exclusively in the Lisp domain. Yes, Python had eval and exec for a long time already, and metatypes and generators are having some strange unexplored possibilities too, but the day will come soon (and at last when PyPy is reaching execution speeds close to cPython) where Python will be able to swallow smaller languages, and finally it will be able to swallow its own tail, like Lisp but then more powerful (because of the widely used standard data types and the code exchange between languages that that makes possible). Your thoughts please. Anton From davefowler at gmail.com Wed Jun 14 12:03:32 2006 From: davefowler at gmail.com (godavemon) Date: 14 Jun 2006 09:03:32 -0700 Subject: convert floats to their 4 byte representation In-Reply-To: <44902b7c$1@nntp0.pdx.net> References: <1150297093.191223.152330@c74g2000cwc.googlegroups.com> <44902b7c$1@nntp0.pdx.net> Message-ID: <1150301012.403651.198440@g10g2000cwb.googlegroups.com> I've been a member for a while but I had no idea how helpful this form is. I had a one hour meeting and when I came back there were 4 replies. Thanks for your help! Scott David Daniels wrote: > godavemon wrote: > > I need to take floats and dump out their 4 byte hex representation. > > This is easy with ints with the built in hex function or even better > > for my purpose > > > > def hex( number, size ): > > s = "%"+str(size) + "X" > > return (s % number).replace(' ', '0') > > This should be a trifle nicer: > def hexx(number, size): # don't shadow the "hex" builtin > s = "%0s" + str(size) + "X" > return s % number > > > but I haven't been able to find anything for floats. Any help would be > > great. > > Getting to float bytes is tougher. > First, python Floats are C Doubles, so you probably mean 8=byte hex. > > import array > > def eights(number, swap=False): > data = array.array('d', [number]) > if swap: > data.byteswap() > return ' '.join(hexx(ord(char), 2) for char in data.tostring()) > > def fours(number, swap=False): > data = array.array('f', [number]) > if swap: > data.byteswap() > return ' '.join(hexx(ord(char), 2) for char in data.tostring()) > > --Scott David Daniels > scott.daniels at acm.org From daniel.dittmar at sap.corp Fri Jun 16 10:33:01 2006 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Fri, 16 Jun 2006 16:33:01 +0200 Subject: Duplex communication with pipes - is possible ? In-Reply-To: References: Message-ID: Dara Durum wrote: > Hi ! > > I want to create a Process Pool Object. > I can hold started processes, and can communicate with them. > > I tryed with many ipc methods, but every of them have bug or other problem. > Sockets are unavailabe (because Windows Firewall hold them). > > I think I will use pipe. > > The object's pseudocode: > while not Quit: > CheckProcessOutputs; > ProcessReceivedData; > SendDataToSubProcesses; > if NoMoreData: Quit=1 > > If I used pipes and subprocess module in Windows, I got big freezes, > and deadlocks. > > Main proc: > subprocpipe.write('aaaa\n') > subprocpipe.readlines() > > Sub proc: > input=sys.stdin.readlines().strip() > print input+'!!!' > > It is working. But when I move this client code to cycle, I got deadlock. > while not Quit: > input=sys.stdin.readlines().strip() > print input+'!!!' > Quit=input=='q' > > Why ? Why I cannot create cyclic communication with client ? > Subprocess must "staying alive" (don't die), and need to stay in > reuseable state ? > > Simply: subprocess pool needed !!! > > Thanks for help: > dd readlines () will try to read until the stream/socket is closed. Try to read only one line. This of course means that you cannot sent \n as part of the data, you have to escape them somehow. I'm not sure how the pipe code is searching for the \n. Trying to read too much could lead to deadlocks as well. (Although I'm sure that the code is written to return fewerbytes than requested if there isn't enough data pending in the pipe). A safer variant might be to transfer a fixed number of bytes containing the length n of the following data, and then n bytes containing the actual data. Daniel From max at alcyone.com Wed Jun 28 18:10:05 2006 From: max at alcyone.com (Erik Max Francis) Date: Wed, 28 Jun 2006 15:10:05 -0700 Subject: how do i make an array global In-Reply-To: References: <1151472238.400461.42350@p79g2000cwp.googlegroups.com> Message-ID: Georg Brandl wrote: > No need for "global" here. Yes, that's true. I was just following the original poster's lead, but I tend to use a `global` statement whenever I'm mutating a global in a local block. That works as self-documentation and means you don't have to be concerned about the precise case in which it's required, reducing bugs when you change a block so that it would have been required if you hadn't included it. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Seriousness is the only refuge of the shallow. -- Oscar Wilde From bencvt at gmail.com Wed Jun 21 18:42:17 2006 From: bencvt at gmail.com (Ben Cartwright) Date: 21 Jun 2006 15:42:17 -0700 Subject: random.jumpahead: How to jump ahead exactly N steps? In-Reply-To: References: Message-ID: <1150929734.625667.106340@p79g2000cwp.googlegroups.com> Matthew Wilson wrote: > The random.jumpahead documentation says this: > > Changed in version 2.3: Instead of jumping to a specific state, n steps > ahead, jumpahead(n) jumps to another state likely to be separated by > many steps.. This change was necessary because the random module got a new default generator in 2.3. The new generator uses the Mersenne Twister algorithm. Pre 2.3, Wichmann-Hill was used. (For more details, search for "jumpahead" in http://www.python.org/download/releases/2.3/NEWS.txt) Unlike WH, there isn't a way to directly compute the Nth number in the sequence using MT. If you're curious as to why, textbooks/journals/Google are your friends. :-) > I really want a way to get to the Nth value in a random series started > with a particular seed. Is there any way to quickly do what jumpahead > apparently used to do? You can always use the old WH generator. It's still available: >>> import random >>> wh = random.WichmannHill() >>> N, SEED = 100, 0 >>> wh.seed(SEED) >>> for i in range(N): dummy = wh.random() >>> wh.random() 0.68591619673484816 >>> wh.seed(SEED) >>> wh.jumpahead(N) >>> wh.random() 0.68591619673484816 > I devised this function, but I suspect it runs really slowly: Don't just suspect. Experiment, too. :-) > def trudgeforward(n): > '''Advance the random generator's state by n calls.''' > for _ in xrange(n): random.random() > > So any speed tips would be very appreciated. Python's random generator is implemented in C and is quite fast. In my tests, your trudgeforward performs acceptably with n<~100000. "import psyco" usually worth a try when improving execution speed, but it won't help you here. All the real work is being done in C; the overhead of the Python interpreter is neglible. Hope that helps, --Ben From ptmcg at austin.rr._bogus_.com Mon Jun 12 11:13:54 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Mon, 12 Jun 2006 15:13:54 GMT Subject: Function to remove elements from a list not working (corrected) References: Message-ID: "Girish Sahani" wrote in message news:mailman.6916.1150100741.27775.python-list at python.org... > Hi, > I am trying to modify a list of pairs (l4) by removing those > pairs which are not present in a third list called pairList. > The following is a simplified part of the routine i have written. However > it does not give the correct output. Please help! > Its possible i have made a trivial mistke since i am a newbie. > You've fallen victim to one of the Classic Blunders! The First is "Never start a land war in Asia!", but the second, only slightly lesser known is "Never modify a list that you are iterating over!" -- Paul From anthony at python.org Wed Jun 21 11:45:18 2006 From: anthony at python.org (Anthony Baxter) Date: Thu, 22 Jun 2006 01:45:18 +1000 Subject: RELEASED Python 2.5 (beta 1) Message-ID: <200606220145.37444.anthony@python.org> On behalf of the Python development team and the Python community, I'm happy to announce the first BETA release of Python 2.5. This is an *beta* release of Python 2.5. As such, it is not suitable for a production environment. It is being released to solicit feedback and hopefully discover bugs, as well as allowing you to determine how changes in 2.5 might impact you. If you find things broken or incorrect, please log a bug on Sourceforge. I'd like to really encourage you to try out this version and check that your code still works - if not, and you think it's a bug, please log a bug. Hopefully this will make it easier for you to upgrade once the final release of Python 2.5 is done. Please note that changes to improve Python's support for 64 bit systems might require authors of C extensions to change their code. See the website for more, including a link to a posting discussing this issue in particular. More information on the release (as well as source distributions and Windows and Mac OSX installers) are available from the 2.5 website: http://www.python.org/2.5/ Since the alpha releases, a slew of bug fixes and smaller new features have been added. See the release notes (available from the 2.5 webpage) for more. The first beta also includes the results of the Iceland NeedForSpeed sprint, resulting in some significant speedups. As of this release, Python 2.5 is now in *feature freeze*. No new features are planned - only bugfixes for the code already in the codebase. The plan from here is for one more beta release followed by one or more release candidates as needed, leading to a 2.5 final release early August. PEP 356 includes the schedule and will be updated as the schedule evolves. The new features in Python 2.5 are described in Andrew Kuchling's What's New In Python 2.5. It's available from the 2.5 web page. Amongst the language features added include conditional expressions, the with statement, the merge of try/except and try/finally into try/except/finally, enhancements to generators to produce a coroutine kind of functionality, and a brand new AST-based compiler implementation. New modules added include hashlib, ElementTree, sqlite3, wsgiref and ctypes. We also have a new profiling module "cProfile". Enjoy this new release (another step on the path to Python 2.5 final) Anthony -- Anthony Baxter anthony at python.org Python Release Manager (on behalf of the entire python-dev team) -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 198 bytes Desc: not available URL: From sigzero at gmail.com Sun Jun 25 15:38:26 2006 From: sigzero at gmail.com (Robert Hicks) Date: 25 Jun 2006 12:38:26 -0700 Subject: Python taught in schools? In-Reply-To: <1151235945.569325.68430@r2g2000cwb.googlegroups.com> References: <1151220913.406987.162420@u72g2000cwu.googlegroups.com> <1151235945.569325.68430@r2g2000cwb.googlegroups.com> Message-ID: <1151264306.296648.135330@y41g2000cwy.googlegroups.com> BartlebyScrivener wrote: > dan>> but out of curiousity does > dan>> anyone know of a school that teaches Python? > > http://www.python.org/about/quotes/ > > University of Maryland > > "I have the students learn Python in our undergraduate and graduate > Semantic Web courses. Why? Because basically there's nothing else with > the flexibility and as many web libraries," said Prof. James A. > Hendler. > > rd Well that Professor has shown his ignorance to the world but not for choosing Python. : ) Robert From randhol at bacchus.pvv.ntnu.no Fri Jun 16 04:36:32 2006 From: randhol at bacchus.pvv.ntnu.no (Preben Randhol) Date: Fri, 16 Jun 2006 08:36:32 +0000 (UTC) Subject: Extracting values from text file Message-ID: Hi A short newbie question. I would like to extract some values from a given text file directly into python variables. Can this be done simply by either standard library or other libraries? Some pointers where to get started would be much appreciated. An example text file: ----------- Some text that can span some lines. Apples 34 56 Ducks Some more text. 0.5 g butter ----------------- What I first though was if there was possible to make a filter such as: Apples (apples) (ducks) Ducks (butter) g butter The data can be put in a hash table. Or maybe there are better ways? I generally want something that is flexible so one can easily make a filter settings if the text file format changes. Thanks in advance From fredrik at pythonware.com Thu Jun 15 14:09:22 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 15 Jun 2006 20:09:22 +0200 Subject: urllib2 problem with ports. In-Reply-To: <1150394282.406329.177960@c74g2000cwc.googlegroups.com> References: <1150394282.406329.177960@c74g2000cwc.googlegroups.com> Message-ID: Ant wrote: > This gives the output (Stack trace snipped - can post if required): > > urllib2.HTTPError: HTTP Error 502: Proxy Error ( The Uniform Resource > Locator (URL) does not use a recognized protocol. Either the protocol > This I believe is a problem with the addition of a non-default port. > Replace the url with "http://google.com" for example, and all is well. > > Any ideas for workarounds? Or do I roll back to 2.4.2? that's not a Python error, so that won't help. check your proxy configuration. most likely, your new machine is set up to route all requests via a remote proxy. (on windows, you'll find the proxy configuration under "Internet Options" - "Connections" - "LAN Settings". before you do anything else, make sure "Bypass proxy server for local addresses" is checked) From tjreedy at udel.edu Tue Jun 13 12:17:23 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 13 Jun 2006 12:17:23 -0400 Subject: Python 411. References: <1150152755.474292.39010@j55g2000cwa.googlegroups.com><1150188399.809316.172840@f14g2000cwb.googlegroups.com> <448E8E53.90200@cc.umanitoba.ca> Message-ID: "Brian van den Broek" wrote in message news:448E8E53.90200 at cc.umanitoba.ca... > meaning something like information. Introductory university course in > a field are often numbered 101 (i.e. Computer Science 101). So, that > number has acquired a slang meaning of basic and introductory > information. > > Where I did my undergrad studies, a few Departments had 001 classes. > Somehow that felt more honest ;-) This is OT, but... Course numbering varies by college/university, but I think typically 1xx, 2xx, 3xx, and 4xx are aimed at students in years 1, 2, 3, and 4 majoring in that subject. Pre-100 courses would be remedial or aimed or even limited to non-major students. So a Math department might have 023 Business Math that would not count toward the math units needed to get a BS in math. tjr From marshall.spight at gmail.com Wed Jun 21 15:19:23 2006 From: marshall.spight at gmail.com (Marshall) Date: 21 Jun 2006 12:19:23 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <1150809118.677124.142230@u72g2000cwu.googlegroups.com> <1150815461.210286.53120@r2g2000cwb.googlegroups.com> <1150823297.816352.75370@u72g2000cwu.googlegroups.com> <7zzmg6amm1.fsf@app-3.diku.dk> <1150904475.363283.234730@y41g2000cwy.googlegroups.com> Message-ID: <1150917563.369958.250980@m73g2000cwd.googlegroups.com> Matthias Blume wrote: > "Marshall" writes: > > > Torben ?gidius Mogensen wrote: > >> > >> That's not true. ML has variables in the mathematical sense of > >> variables -- symbols that can be associated with different values at > >> different times. What it doesn't have is mutable variables (though it > >> can get the effect of those by having variables be immutable > >> references to mutable memory locations). > > > > While we're on the topic of terminology, here's a pet peeve of > > mine: "immutable variable." > > > > immutable = can't change > > vary-able = can change > > > > Clearly a contradiction in terms. > > No, it is not a contradiction. See the mathematical usage of the word > "variable". I am not saying that this kind of terminology isn't common; what I'm saying is that it isn't good. And I think I gave a pretty clear and solid definition of the two words, and those definitions are decidedly contradictory. > Immutable variables can stand for different values at > different times, even without mutation involved, usually because they > are bound by some construct such as lambda. Well, that's a good point actually. Parameters are variable no matter how you look at it. I was speaking more in terms of locals. > > If you have a named value that cannot be updated, it makes > > no sense to call it "variable" since it isn't *able* to *vary.* > > Mutation is not the only way for an expression to evaluate to > different values over time. I suppose the difficulty arises from the difference between the connotation of "mutate" in a PLT context, which is support for destructive assignment, and the meaning of the word in the larger context. Anyway, I don't see how your sentence above contradicts my sentence. We do not use the term "update" to describe the process of binding values to parameters upon function invocation. (Am I wrong?) Marshall From jnair at ensim.com Wed Jun 7 23:56:28 2006 From: jnair at ensim.com (jnair at ensim.com) Date: 7 Jun 2006 20:56:28 -0700 Subject: Test tool for python code. Message-ID: <1149738987.990132.142610@c74g2000cwc.googlegroups.com> Is there any tool available that will tell me what are the different test paths for any python code? thnaks regards Jitu From johnjsal at NOSPAMgmail.com Tue Jun 6 11:19:41 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 06 Jun 2006 15:19:41 GMT Subject: retaining newline characters when writing to file In-Reply-To: References: Message-ID: Fredrik Lundh wrote: > John Salerno wrote: > >> If I read a string that contains a newline character(s) into a >> variable, then write that variable to a file, how can I retain those >> newline characters so that the string remains on one line rather than >> spans multiple lines? > > you cannot: the whole point of a newline character is to start a new line. > > however, some file formats let you "escape" the newline. for example, > in Python source code, you can use end a line with a backslash. in CSV, > you can put the string with newlines inside quotes, and Python's "csv" > module knows how to do that: > > import csv, sys > > row = ("One\nTwo\nThree", 1, 2, 3) > > writer = csv.writer(sys.stdout) > writer.writerow(row) > > prints > > "One > Two > Three",1,2,3 > > (not all CSV readers can handle multiline rows, though) > > > Thanks. I should give the csv module a look too, while I'm at it. From rupole at hotmail.com Fri Jun 23 00:34:28 2006 From: rupole at hotmail.com (Roger Upole) Date: Fri, 23 Jun 2006 00:34:28 -0400 Subject: occasional win32com error References: <1150394663.125760.231580@f6g2000cwb.googlegroups.com> Message-ID: <1151036917_11125@sp6iad.superfeed.net> You could try using DispatchEx to make sure you always get a new instance of Excel. Roger "Ransom" wrote in message news:1150394663.125760.231580 at f6g2000cwb.googlegroups.com... > Hey folks... > > Newbie here. I'm working with win32com launching, closing and > re-launching Excel grabbing output and doing stuff. > > Well, on some occasions, I get the following error: > > > Traceback (most recent call last): > File "checkrates.py", line 95, in ? > newdata = getNewData(testcases1) > File "checkrates.py", line 62, in getNewData > excel.Workbooks.Open(docdir + 'TOSrat2006_09.xls') > File "C:\Python24\lib\site-packages\win32com\client\dynamic.py", line > 496, in __getattr__ > raise AttributeError, "%s.%s" % (self._username_, attr) > AttributeError: Excel.Application.Workbooks > > Sometimes the code runs fine. Sometimes I get this error. The code in > question is: > > import string > from win32com.client import Dispatch > docdir = 'E:\\scripts\\Python\\RSAutomation\\' > > > def getOldData(testcases): > #open excel > excel = Dispatch("Excel.Application") > excel.Workbooks.Open(docdir + 'TOSrat2006_07.xls') > > oldoutputlist = [] > for rsinput in testcases.xreadlines(): > > inputlist = string.split(rsinput, ',') > > # iterate through and update spreadheet input > cellx = range(3,51) > values = range(0,48) > for i,r in zip(cellx, values): > > excel.ActiveSheet.Cells(i,2).Value = inputlist[r] > > #read spreadsheet output and cat to outputlist > premium = excel.ActiveSheet.Cells(32,6).Value > oldoutputlist.append(premium) > # close up excel > excel.ActiveWorkbook.Close(SaveChanges=0) > excel.Quit() > del excel > return oldoutputlist > > def getNewData(testcases): > # open excel > excel = Dispatch("Excel.Application") > excel.Workbooks.Open(docdir + 'TOSrat2006_09.xls') > newoutputlist = [] > for rsinput in testcases.xreadlines(): > > inputlist = string.split(rsinput, ',') > > # iterate through and update spreadsheet input > cellx = range(3,51) > values = range(0,48) > for i,r in zip(cellx, values): > > excel.ActiveSheet.Cells(i,2).Value = inputlist[r] > > # read ratesheet output and cat to outputlist > premium = excel.ActiveSheet.Cells(32,6).Value > newoutputlist.append(premium) > excel.ActiveWorkbook.Close(SaveChanges=0) > excel.Quit() > del excel > return newoutputlist > > if __name__ == "__main__": > testcases = open('arse_testcases.csv','r') > testcases1 = open('arse_testcases.csv','r') > olddata = getOldData(testcases) > newdata = getNewData(testcases1) > > print olddata > print newdata > > > It seems like Python or COM is having a hard time freeing up (or > closing down) excel prior to the "getNewData" function running and it > is stepping on itself. I thought the stuff I'm doing at the end of > getOldData should successfully shut down excel. > > Any advice, criticism, flames are appreciated. > > Cheers! > ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= East/West-Coast Server Farms - Total Privacy via Encryption =--- From no-spam at no-spam-no-spam.com Fri Jun 16 11:59:57 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Fri, 16 Jun 2006 17:59:57 +0200 Subject: msvcr71.dll necessary? - Re: Which compiler will Python 2.5 / Windows (Intel) be built with? In-Reply-To: <1150367139.495114.148550@g10g2000cwb.googlegroups.com> References: <1150367139.495114.148550@g10g2000cwb.googlegroups.com> Message-ID: meyer at mesw.de wrote: > Hi everyone, > > which compiler will Python 2.5 on Windows (Intel) be built with? I > notice that Python 2.4 apparently has been built with the VS2003 > toolkit compiler, and I read a post from Scott David Daniels [1] where > he said that probably the VS2003 toolkit will be used for Python 2.5 > again. However, even before the release of Python 2.5, I cannot seem to > find many retailers around here that still carry Visual Studio 2003 ... For me the great great problem with Python2.4's lib geometry was that the size of distributable app installers swelled suddenly by many megs with msvcr71.dll and mfc71 and codecs in core and all. Typically installer sizes went from 1.5MB to over 4MB for basic non-trivial apps. Thats a show stopper still in many situations today - at least for my requirements. See e.g. for an example of magnitudes: http://groups.google.de/group/comp.lang.python/msg/edf469a1b3dc3802 Updating to a new expensive compiler problem for extensions was secondary. Thus I decided so far to stay at Python2.3 for longer time for most projects, while I'm using Python2.4+ only for local/web scripts and single-installation projects. The little improvements in Python2.4/2.5 mostly don't justify their monster footprint in memory and installers. Some questions: * Is there a fundamental reason that the C-RTL of VC6 (which is pre-installed on on all Windows today) is not sufficient for current Python and extensions? instable? In case not: As the short living VS 2003 compiler is now more rare than the good old VC6, wouldn't it be better to switch back to VC6 for Py2.5 or at least to VC6 libs (which are maybe "free" of dev-license as they sit on each Windows). Maybe a suitable policy: the default crtl for Python should better be the default library of the OS and not that of a random compiler which is currently hip? * can't the Mingw/gcc be used together with Windows default crt/mfc libs for Python2.5 ? - Python getting away the from this MS studio (lib) harassment? ( Personally I'd give no cent for that little runtime speed advantage by the VS2005 compiler when comparing to a slimness + stable standard + freedom ) Together with a clear decision to clean the Python core libs from recent habits to "statically" preload OS-kind-of-packages (e.g. codecs, the licentious pre-imports in urllib and friends ), I'd have hope to get out of my deadlock on Python2.3. * how many (serious) python users require to build distributable installers (which have carry the python-rtls and non-default crtl's)? I guess, almost all GUI apps have this requirement? And GUI apps probably count more (also in line numbers) than web apps today as more and more Delphi, BCPPB, Java, C++/MFC developers switch to Python? -robert From john.hsu at sovereign.co.nz Wed Jun 14 18:41:56 2006 From: john.hsu at sovereign.co.nz (JH) Date: 14 Jun 2006 15:41:56 -0700 Subject: __cmp__ method Message-ID: <1150324916.775821.142390@u72g2000cwu.googlegroups.com> Hi Can anyone explain to me why the following codes do not work? I want to try out using __cmp__ method to change the sorting order. I subclass the str and override the __cmp__ method so the strings can be sorted by the lengh. I expect the shortest string should be in the front. Thanks >>> class myStr(str): def __init__(self, s): str.__init__(self, s) # Ensure super class is initialized def __cmp__(self, other): return cmp(len(self), len(other)) >>> a = myStr('abc') >>> b = myStr('Personal') >>> c = myStr('Personal firewall') >>> sorted([c, b, a]) ['Personal', 'Personal firewall', 'abc'] >>> From gandalf at designaproduct.biz Thu Jun 22 03:11:36 2006 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Thu, 22 Jun 2006 09:11:36 +0200 Subject: python + postgres psql + os.popen In-Reply-To: <1150946077.931411.170930@u72g2000cwu.googlegroups.com> References: <1150946077.931411.170930@u72g2000cwu.googlegroups.com> Message-ID: <449A42A8.1080809@designaproduct.biz> damacy ?rta: > hello, everyone. > > i am trying to write a program which executes SQL commands stored in > .sql files. > > i wrote a function called psql() whose contents look like the > following. > > ... > os.popen(command) > file = os.popen(command, 'w') > file.write(password) > file.close() > ... > > where command looks like > psql -h [host] -d [dbname] -U [username] -W -f "[filename]" > > this works well. however, it does not show me any warning nor error > messages if there is one. for example, i am trying to create a table > which already exists in the database, it should show me a warning/error > message saying there already is one present in the database, or > something like that. > > can anyone help me? > You can put this in the beginning of your SQL file: \set ON_ERROR_STOP If you also want to know what command caused the error: \set ECHO all You can also use a library written for Python. For example, psycopg http://initd.org/projects/psycopg1 Best, Laszlo From alex.nanou at gmail.com Wed Jun 21 20:40:44 2006 From: alex.nanou at gmail.com (Alex A. Naanou) Date: 21 Jun 2006 17:40:44 -0700 Subject: The code that could not be... Message-ID: <1150936844.874347.163060@r2g2000cwb.googlegroups.com> Though Python is the language I use the most, there are several things that I still hate, mostly about the implementation (CPython)... The good thing is that some of these warts are now resolved, like the exec dict issue. Here is another one: The object's __dict__ can only be a dict derivative and at that none of the Python's mapping API will be used (the dict is accessed directly). Here is a simple example example that this problem makes impossible... ---cut--- class AttrDict(dict): '''This implements JavaScript-like object attribute/mapping interface.''' def __new__(cls, *p, **n): o = dict.__new__(cls, *p, **n) o.__dict__ = o return o # this works fine in current CPython... o = AttrDict() o.attr = 'val' o['other'] = 123 print o.other # -> 123 print o # -> {'attr': 'val', 'other': 123} # now if you modify this to add some logging... def _getitem(self, name): print 'getting "%s".' % name return super(AttrDict, self).__getitem__(name) AttrDict.__getitem__ = _getitem # this will work as expected... o['attr'] # -> getting "attr". # and the following will not! o.attr # will print nothing... --uncut-- Thus, no user defined dict-like will work correctly as the objects namespace... To mention several tasks that can be made trivial using this technique are, for instance zope-like acquisitions, various ACLs, interfaces and other namespace manipulation patterns. I wrote a patch some time back, it appears rather stable and is being production tested. you can download it here: http://pli.sourceforge.net/object_dict_interface_use_fix.patch So, to the purpose of this post... if there is any interest for a patch like this, anyone who would be willing to test it and/or add feedback to the topic would be very welcome! :) P.S. I'm not proposing this patch to the python-dev until it is extensively tested (and not just on my usecases :) ) From maric at aristote.info Tue Jun 20 06:57:33 2006 From: maric at aristote.info (Maric Michaud) Date: Tue, 20 Jun 2006 12:57:33 +0200 Subject: comparing two arrays In-Reply-To: <4fpvr0F1k8dauU1@uni-berlin.de> References: <1150721380.948808.231760@h76g2000cwa.googlegroups.com> <1150795424.752973.303420@g10g2000cwb.googlegroups.com> <4fpvr0F1k8dauU1@uni-berlin.de> Message-ID: <200606201257.34220.maric@aristote.info> Le Mardi 20 Juin 2006 12:09, Diez B. Roggisch a ?crit?: > [i for i, equals in enumerate((x == y for x, y in zip(a, b))) if equals] No needs to nest comprehensions, should be : [ i for i, v in enumerate(zip(a, b)) if v[0] == v[1] ] -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From ilias at lazaridis.com Wed Jun 7 09:38:58 2006 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Wed, 07 Jun 2006 16:38:58 +0300 Subject: Django Quick Start with Schema Evolution Support In-Reply-To: <35081.132.60.240.80.1149530454.squirrel@kered.org> References: <1149446706.085692.174980@h76g2000cwa.googlegroups.com> <1149505316.406428.242450@c74g2000cwc.googlegroups.com> <448429E1.90305@kered.org> <35081.132.60.240.80.1149530454.squirrel@kered.org> Message-ID: <4486D6F2.7000407@lazaridis.com> [Replying to comp.lang.python, due to censorship on Django User] [additional notification of poster via email, as medium is changed] public at kered.org wrote: > yep. i feel particularly hosed for trying to work with you offline to > synchronize our efforts. I don't think that telling me when your project starts and stops can be called "working with me offline". > and even more retarded for the time i spent and > help i offered regarding your web site design, resume and general "how to > better present yourself" as a consulting business. You suggestion subjecting the term "failure" was a positive one and I have reacted. But again, I think you exaggerate about the amount of time invested. (overall conversation: 7 messages of yours, 20 lines, ~3 lines/message) > (considering i've been > a fulltime programmer/consultant for many years now and you were claiming > to just be starting out) I've just (Jan 2006) re-started with the _new_ services. > however i am far from your largest detractor here. and i don't wish to > be, so i won't contribute any more to this discussion. this will be my > last post here regarding you. I've not asked you to post about me, but about the SoC Schema Evolution Project. See further below: > -- derek > > p.s. for the record i'm not totally convinced you're an intentional troll. > i suspect you're just socially and professionally inept. but with your > history on other listservs, it seems that you are incapable of learning > how to better interact with others. so "a rose by any other name..." the > effect is the same. => {"i suspect you're just socially and professinally inept"} I better don't take you as an example how to "better interact with others". And btw: why speculating, instead of just reading the explanations?: http://lazaridis.com/core/eval/index.html > i recommend to all ignoring ilias here. Possibly to avoid the basic question? My question to you was basically: "May I ask you to point my to a resource which shows your current plans, results etc.?" Mine is here: http://case.lazaridis.com/wiki/DjangoSchemaEvolution And with a little support of the team, it could be now a stable working temporary solution, and a reference/foundation for your SoC project. >> Derek Anderson wrote: >>> i believe it's time for... >> Mr. Anderson, >> >> we had some private conversation at the start of my work with Django, >> where I had answered all of your questions. >> >> Based on this, you should have a better rating about me, especially when >> knowing my private situation (or at least some indicators). >> >> - >> >> You are the Student which will execute the "Google Summer of Code" >> Project, which will implement the "Schema Evolution Support for Django", >> >> http://code.djangoproject.com/wiki/SchemaEvolution >> >> May I ask you to point my to a resource which shows your current plans, >> results etc.? >> >> As you have seen, I have provided within a few days something what the >> django project and its community has not provided since a _very_ long >> time. >> >> A working draft version of a Schema Evolution Support for Django: >> >> http://case.lazaridis.com/multi/wiki/DjangoSchemaEvolution >> >> - >> >> You should understand that it looks really somehow, that especially you >> talk so loud about a 'troll'. >> >> Finally, you should be aware of something: all of your writings were >> publically archived. >> >>> ___________________________ >>> /| /| | | >>> ||__|| | Please don't | >>> / O O\__ feed | >>> / \ the trolls | >>> / \ \ | >>> / _ \ \ ---------------------- >>> / |\____\ \ || >>> / | | | |\____/ || >>> / \|_|_|/ | __|| >>> / / \ |____| || >>> / | | /| | --| >>> | | |// |____ --| >>> * _ | |_|_|_| | \-/ >>> *-- _--\ _ \ // | >>> / _ \\ _ // | / >>> * / \_ /- | - | | >>> * ___ c_c_c_C/ \C_c_c_c____________ >>> >>> -- derek :) >> . >> >> -- >> http://lazaridis.com >> >> > > > --~--~---------~--~----~------------~-------~--~----~ > You received this message because you are subscribed to the Google Groups "Django users" group. > To post to this group, send email to django-users at googlegroups.com > To unsubscribe from this group, send email to django-users-unsubscribe at googlegroups.com > For more options, visit this group at http://groups.google.com/group/django-users > -~----------~----~----~----~------~----~------~--~--- > > -- http://lazaridis.com From jake.emerson at onerain.com Mon Jun 26 19:56:22 2006 From: jake.emerson at onerain.com (Jake Emerson) Date: 26 Jun 2006 16:56:22 -0700 Subject: nested dictionary assignment goes too far Message-ID: <1151366182.359999.312270@m73g2000cwd.googlegroups.com> I'm attempting to build a process that helps me to evaluate the performance of weather stations. The script below operates on an MS Access database, brings back some data, and then loops through to pull out statistics. One such stat is the frequency of reports from the stations ('char_freq'). I have a collection of methods that operate on the data to return the 'char_freq' and this works great. However, when the process goes to insert the unique 'char_freq' into a nested dictionary the value gets put into ALL of the sub-keys for all of the weather stations. I have isolated (I think) the problem to the compound key assignment in the next-to-last line before the print statements. The result is that the last 'freq' to run throught the for loops gets posted to all of the sensor_numbers. Eventually the process will put in stats for the other keys in the nested dictionary, so that's why I have set up the dictionary this way. Thanks in advance! run_flag=1 if run_flag > 0: distinctID = runSQL(Unique_IDs) distinctID = map(firstpart,distinctID) # converts the list of tuples that is returned to a list of numbers rain_raw_dict = dict.fromkeys(distinctID,{'N':-6999,'char_freq':-6999,'tip1':-6999,'tip2':-6999,'tip3':-6999,'tip4':-6999,'tip5':-6999,'tip6':-6999,'lost_rain':-6999}) rawList = runSQL(Rain_Raw_Count) temp_list = [110,140,650,1440] for sensor_count, sensor_number in enumerate(temp_list): # get the frequency of timer reports for each rain gauge # note that when a for loop is of the form "for X, x in enumerate(xList)", # X is an index value, and x is the value itself. timerList = [] for icount, i in enumerate(rawList): if i[0]==sensor_number: for jcount in range(icount+1,len(rawList)): # look ahead to the next values for comparison if rawList[jcount][0]==sensor_number: if rawList[icount][2]==rawList[jcount][2]: temp = rawList[jcount][1]-rawList[icount][1] timerList.append(temp) icount = jcount-1 break # now build a histogram of the time differences stored in "timerList" h = Histogram() timer = h.histo(timerList) sorted_timer = h.sorted_histo(timer) freq = h.characteristic_freq(sorted_timer) rain_raw_dict[sensor_number]['char_freq'] = sensor_number # <<<< here's the problem!! freq = -6999 print "ID = 110:",rain_raw_dict[110] print "ID = 140:",rain_raw_dict[140] print "ID = 650:",rain_raw_dict[650] print "ID = 1440:",rain_raw_dict[1440] From find at my.address.elsewhere Mon Jun 19 14:09:28 2006 From: find at my.address.elsewhere (Matthias Blume) Date: Mon, 19 Jun 2006 13:09:28 -0500 Subject: What is Expressiveness in a Computer Language References: <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <2006061410510511272-raffaelcavallaro@pasdespamsilvousplaitmaccom> <2006061501423327544-raffaelcavallaro@pasdespamsilvousplaitmaccom> <2006061611492350073-raffaelcavallaro@pasdespamsilvousplaitmaccom> <2006061618250975249-raffaelcavallaro@pasdespamsilvousplaitmaccom> <7zhd2himme.fsf@app-3.diku.dk> Message-ID: George Neuner writes: > I am, however, going to ask what > information you think type inference can provide that substitutes for > algorithm or data structure exploration. Nobody wants to do such a substitution, of course. In /my/ experience, however, I find that doing algorithm and data structure exploration is greatly aided by a language with static types and type inference. YMMV. From brian at sweetapp.com Wed Jun 21 14:20:35 2006 From: brian at sweetapp.com (Brian Quinlan) Date: Wed, 21 Jun 2006 20:20:35 +0200 Subject: Vancouver Python Conference: T-Shirt design contest Message-ID: <44998DF3.4040409@sweetapp.com> The Vancouver Python Workshop organizers are having problems coming up with text for our T-Shirts (don't worry: we already have the graphics figured out). We want something that matches Python's simplicity and elegance. So we're asking for your help. If you submit the text that we end up using, I'll send you 3 T-Shirts (1 seems too cheap, and there is always wear-and-tear, one for your cat, etc.). If we have extra T-Shirts, we might also send them to other people who had good (but not winning) ideas. So please go here and make a suggestion: http://www.vanpyz.org/conference/tshirt_contest.html BTW, you don't have to attend the conference to participate in the T-Shirt design. But you should attend the conference anyway, because it is going to be great. For information on the workshop, see: http://www.vanpyz.org/conference/ Cheers, Brian From ken at kenw.us Sat Jun 10 00:53:12 2006 From: ken at kenw.us (Ken) Date: Fri, 9 Jun 2006 21:53:12 -0700 Subject: Get my airlines boarding pass Message-ID: <20060610045952.F38D01E400C@bag.python.org> rh0dium wrote: > Hi all, > > Has any of you fine geniuses figured out a nice python script to go to > the Southwest airlines website and check in, and retrieve your boarding > pass - automatically 24 hours in advance > I just wrote such a script in python and tested it successfully. Where should I post it? Ken From ldo at geek-central.gen.new_zealand Tue Jun 27 01:14:38 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 27 Jun 2006 17:14:38 +1200 Subject: Execute Commands on Remote Computers over Network References: <1151378614.481850.271340@c74g2000cwc.googlegroups.com> Message-ID: In article <1151378614.481850.271340 at c74g2000cwc.googlegroups.com>, "dylpkls91" wrote: >I have been researching this topic and come up with some code to make >it work. It uses SSL and requires the 3rd party package Paramiko (which >requires PyCrypto). Why not just spawn an invocation of SSH? From bayazee at gmail.com Tue Jun 20 08:33:08 2006 From: bayazee at gmail.com (Bayazee) Date: 20 Jun 2006 05:33:08 -0700 Subject: =?iso-8859-1?q?comparing_of_python_GUI=B4s?= Message-ID: <1150806788.026172.140150@h76g2000cwa.googlegroups.com> Hi i want some info ... plz tell me the benefit (or any data) of each gui (pyqt , pyqtk , wxpython , tkinter ..) in the other hand wich one you offer (and why ?) ? From george.sakkis at gmail.com Thu Jun 15 00:12:28 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 14 Jun 2006 21:12:28 -0700 Subject: nested functions References: <1150319279.865335.323530@u72g2000cwu.googlegroups.com> Message-ID: <1150344748.652441.316680@g10g2000cwb.googlegroups.com> Ben Finney wrote: > "Gregory Petrosyan" writes: > > > I often make helper functions nested, like this: > > > > def f(): > > def helper(): > > ... > > ... > > > > is it a good practice or not? > > You have my blessing. Used well, it makes for more readable code. I'm not sure it's in general more readable; I typically use nested functions for closures only, not helper functions, so I'd read the code twice to check if it's a closure and if not why might have been defined locally. I prefer to define helpers at the module level, often making them 'private' by prepending their name with a single underscore. > > What about performance of such constructs? > > What about it? Set up some examples maningful for your situation, with > and without such constructs, and use the profiler to find out. It shouldn't come as a surprise if it turns out to be slower, since the nested function is redefined every time the outer is called. If you actually call the outer function a lot, you'd better profile it. George From usenet.rpdillon at xoxy.net Thu Jun 15 11:52:59 2006 From: usenet.rpdillon at xoxy.net (R. P. Dillon) Date: Thu, 15 Jun 2006 08:52:59 -0700 Subject: Tiddlywiki type project in Python? In-Reply-To: <1150291679.746132.114730@y43g2000cwc.googlegroups.com> References: <1150289313.533749.52330@i40g2000cwc.googlegroups.com> <44900ae9$0$8386$626a54ce@news.free.fr> <1150291679.746132.114730@y43g2000cwc.googlegroups.com> Message-ID: <1150386336_12135@sp6iad.superfeed.net> I've been doing some work on a didiwiki-like program written in Python. Since Python is embedded in browsers, the didwiki approach make sense: write the server in your language of choice (didwiki uses C), and lay the necessary (simple) wiki code on top of the server. Roll the entire thing into a single executable, and you have a personal wiki. The catch is that you must run the executable before you can access your wiki, but it is a small price to pay IMHO. Anyway, I'll either GPL or public-domain my code when I'm finished with it and I'll post it here. My hope is it will be as fast on a reasonably modern computer as didiwiki is. Rick jkn wrote: > Hi Bruno > > [...] >>> I don't know Javascript (although it looks moderately simple from a >>> brief peruse, >> It's not as simple as it may seem at first look. There are some real >> gotchas. But if you want a more pythonic javascript, you should have a >> look at mochikit. > > OK, thanks for the pointer > > [...] > >>> and I know enough languages to know I'll be able to pick >>> it up); however I do know and use Python, although not nuch in a >>> web-oriented way. Since unlike JS, python is at least pre-compiled, I >>> have hopes that this would make things quicker. I do appreciate that JS >>> is built into the browser, which might make my Python approach slower. >>> I'm not sure of the 'architectural' approach to this; any suggestions, >>> and maybe pointers to previous work? >> I don't really understand what you're after here, since TiddlyWikiLikes >> can *not* work without javascript. > > Well, that may be an/the answer, since another form of my question > would be 'how can I write a TiddlyWikiLike using Python instead of JS' > ;-). I appreciate that it might involve, for instance, a local server. > Does the idea of embedding python in a browser instead of Javascript > make any sense at all? > >> Anyway, there's at least a Zope-based TiddlyWikiLike, so you may want to >> have a look here: >> http://ziddlywiki.org/ >> > > Thanks again > > jon N > ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups ----= East and West-Coast Server Farms - Total Privacy via Encryption =---- From irmen.NOSPAM at xs4all.nl Tue Jun 20 17:19:50 2006 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Tue, 20 Jun 2006 23:19:50 +0200 Subject: socket programming question In-Reply-To: <1150837683.338093.8960@y41g2000cwy.googlegroups.com> References: <1150837683.338093.8960@y41g2000cwy.googlegroups.com> Message-ID: <44986676$0$31647$e4fe514c@news.xs4all.nl> Kiran wrote: > Hello All, > My question is, is it possible to make python do some other > processing while it is waiting for a socket to timeout? sure, you have to use threads and/or use asynchronous socket programming. Google is your friend. --Irmen From fredrik at pythonware.com Thu Jun 22 15:12:03 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 22 Jun 2006 21:12:03 +0200 Subject: Network Programming in Python In-Reply-To: <1151002934.586359.174540@m73g2000cwd.googlegroups.com> References: <1151002934.586359.174540@m73g2000cwd.googlegroups.com> Message-ID: diffuser78 at gmail.com wrote: > I am a newbie in python. I want to learn and implement a small > networking concept. Please help me. Every help is appreciated. > > I have one Linux Box and one Windows PC. I want to have a daemon > running on Windows PC which listens on some specicif port number. I > want to send a TCP/IP or UDP/IP packet from Linux box to Windows PC to > start some application. As Windows PC recieves such a packet from Linux > Box it executes a certain .exe file. I want to implement this concept. > > In short I want to remotely send command from Linux to Windows PC to > start a particular application. server: http://docs.python.org/lib/module-SimpleXMLRPCServer.html client: http://docs.python.org/lib/module-xmlrpclib.html From fredrik at pythonware.com Thu Jun 8 11:12:24 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 08 Jun 2006 17:12:24 +0200 Subject: Select hangs after some reads In-Reply-To: <1149779056.498540.46620@f6g2000cwb.googlegroups.com> References: <1149737234.816833.177710@j55g2000cwa.googlegroups.com> <1149764138.868847.326250@i39g2000cwa.googlegroups.com> <128g8uvi6aj4240@corp.supernews.com> <1149779056.498540.46620@f6g2000cwb.googlegroups.com> Message-ID: alsmeirelles at gmail.com wrote: > Yes, as I expected, its the buffers. In my opinion the problem is that > the socket module doesn't provide a way of reading all its internal buffer. umm. that's what recv() does, of course, of you pass in a large enough buffersize. for your use case, I suggest looking at asyncore/asynchat instead of trying to write your own asynchronous socket layer... From scott.daniels at acm.org Wed Jun 14 12:15:30 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Wed, 14 Jun 2006 09:15:30 -0700 Subject: Numerics, NaNs, IEEE 754 and C99 In-Reply-To: <12904mjhl493t49@corp.supernews.com> References: <12904mjhl493t49@corp.supernews.com> Message-ID: <4490315e$1@nntp0.pdx.net> Grant Edwards wrote: > While you're at it, the pickle modules need to be fixed so they > support NaN and Inf. ;) The NaN problem is portability -- NaN values are not standard, and pretending they are won't help. There are many possible NaNs, several of which have desirable behaviors, and different processors (and Floating Point settings) choose different bit representations for those NaNs. There are at least: Inf, -Inf, NaN, Ind (Indeterminant). Being able to pickle some of these will produce values that "don't behave right" on a different machine. Up until now, I think you can send a pickle of a data structure and unpickle it on a different processor to get equivalent data. --Scott David Daniels scott.daniels at acm.org From simon at brunningonline.net Wed Jun 14 13:58:16 2006 From: simon at brunningonline.net (Simon Brunning) Date: Wed, 14 Jun 2006 18:58:16 +0100 Subject: Numerics, NaNs, IEEE 754 and C99 In-Reply-To: <1150306401.423825.39490@g10g2000cwb.googlegroups.com> References: <12904mjhl493t49@corp.supernews.com> <4490315e$1@nntp0.pdx.net> <1150306401.423825.39490@g10g2000cwb.googlegroups.com> Message-ID: <8c7f10c60606141058w37d1454biff3bc90fd24931b6@mail.gmail.com> On 14 Jun 2006 10:33:21 -0700, S?bastien Boisg?rault wrote: > Jeez, 12 posts in this IEEE 754 thread, and still > no message from uncle timmy ? ;) Somebody reboot the timbot, please. Seems to have hung. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From ogahejini at yahoo.com Wed Jun 7 10:11:22 2006 From: ogahejini at yahoo.com (gen_tricomi) Date: 7 Jun 2006 07:11:22 -0700 Subject: THE IMPORTANCE OF MAKING THE GOOGLE INDEX DOWNLOADABLE Message-ID: <1149689482.372450.13210@i39g2000cwa.googlegroups.com> THE IMPORTANCE OF MAKING THE GOOGLE INDEX DOWNLOADABLE I write here to make a request on behalf of all the programmers on earth who have been or are intending to use the Google web search API for either research purposes or for the development of real world applications, that Google make their indexes downloadable. Currently application programmers using the Google web search API are limited to 1000 queries a day. This on the one hand is a reasonable decision by Google because; limiting the queries will prevent harm on the Google system by unnecessary automated queries; but it is also limiting us programmers severely. The query limit limits the usefulness of whatever applications we decide to craft out and even limits our imagination on what is possible with a handful of indexes. Firstly, I will commend the Google Corporation for opening their preciously crawled indexes. This is a great service to humanity and especially to the band of programmers who are interested in epistemology and are using the Google web search API to enable them achieve their goals. Google would be doing another great service for us if they would make their indexes downloadable to programmers with a good interface for programmatically accessing the indexes. The advantages of the above approach would be: 1. Decentralizing the Google system. 2. Reducing the overhead of queries on Google from programmers. 3. Enabling programmers to craft out applications that run on their local systems (only requiring internet connection when a web page is needed since the links return on a query are the most important in the result set) thus enabling them have unlimited number of queries should these applications go public. 4. Give Google the competing edge in search engine technology and user satisfaction by gaining programmer loyalty. 5. Encouraging the global adoption and use of the API + INDEXES provided by Google. 6. Another good thing may be here for Google if they create mechanisms in the downloaded INDEXES + API that enable programmers update the indexes from the web. An agreement can now be made that Google will have unlimited access to the indexes whenever the user's computer is online and IDLE. So Google update its own indexes from the ones on various programmers' local machines. Thereby building a truly distributed global crawler. This can be achieved using grid technologies thereby possibly cutting down the 300year range for crawling the world's crawlable information. Google may still enforce their terms of service by enforcing some kind of authentication for the use of index already residing on the programmer's local machine. Though it may not require that the programmer be on the internet every time he/she wishes to access the system; since the programmer may wish to tinker with the API and indexes locally without requiring an internet connection. Online authentication may be required anytime the user gets online. The non-commerciability of the indexes must be emphasized through several schemes. The Google API can be a tool for epistemological engineers to craft future Infowares (Information Applications). The most important thing in the indexes is the links to resources that are returned on queries. 2 versions of the API + INDEXES can be made available. 1. The one without cached pages attached. So that on querying the API on the local machine with the locally stored indexes, the results are like those on the regular internet API result set. 2. The one with the cached pages. This one is optional as it will be large in size. If you people were good enough to release your API's publicly then you would also consider this request. It would be good if the API + INDEX download is accessible by programmers who program in the following languages: (a) Python (b) Java (c) Perl (d) Ruby Or some language independent mechanism can be formulated so programmers in various languages can access the API + INDEX download. Page Rank may or may not be included in the package depending on decisions at Google. It may also be closed source / open source / or partial source (part open part closed). This will be a great service to humanity and to programmers especially. Thanks, Ogah Ejini, Nigeria, West Africa. Mobile: +234 802 601 5061 From bdesth.quelquechose at free.quelquepart.fr Mon Jun 26 23:05:30 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 27 Jun 2006 05:05:30 +0200 Subject: replace a method in class: how? In-Reply-To: References: Message-ID: <44a07037$0$1020$626a54ce@news.free.fr> Brian Blais a ?crit : > Hello, > > I want to replace a method in a class during run-time with another > function. I tried the obvious, but it didn't work: > > class This(object): > def update(self,val): > print val > > def another_update(obj,val): > print "another",val > > t=This() > t.update(5) > t.update=another_update This is not "replacing a method in a class", but replacing it in an instance. > t.update(5) # this one doesn't work, gives > # TypeError: another_update() takes exactly 2 arguments (1 given) > > clearly it isn't seeing it as a method, just an attribute which happens > to be a function. Is there a preferred way to do this? import types t.update = types.MethodType(another_update) From fredrik at pythonware.com Thu Jun 8 15:52:51 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 08 Jun 2006 21:52:51 +0200 Subject: Win XP Error: There is not enough space on the disk In-Reply-To: References: Message-ID: A.M wrote: > Is there any way that I can fix this problem? unlikely, unless you work for the OS development team at Microsoft: http://python.org/sf/1463104 (see the comments for more details, including workarounds) From bj_666 at gmx.net Thu Jun 29 14:53:02 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Thu, 29 Jun 2006 20:53:02 +0200 Subject: problems with mimify.mime_encode_header References: Message-ID: In , Egor Duda wrote: > #!/usr/bin/python > # -*- coding: utf-8 -*- > > import mimify > > mimify.CHARSET = 'utf-8' > > print mimify.mime_encode_header('Subject: ???? ?.\n'); > > ?he output is: > Subject: =?utf-8?Q?=D1=82=D0=B5=D1=81=D1=82?= ?. > > Please note that the last character (before dot) is not quoted, and > resulting string is not 8bit clean. Why should a simple ASCII 'a' be quoted? And what do you mean by "not 8bit clean"? The string is even 7-bit clean! Ciao, Marc 'BlackJack' Rintsch From jjlee at reportlab.com Sat Jun 24 19:20:33 2006 From: jjlee at reportlab.com (John J. Lee) Date: Sat, 24 Jun 2006 23:20:33 GMT Subject: Python to PHP Login System (HTTP Post) References: <1151018390.792574.102920@b68g2000cwa.googlegroups.com> <87mzc3fikh.fsf@reportlab.com> Message-ID: <87r71eqgxq.fsf@reportlab.com> jjlee at reportlab.com (John J. Lee) writes: [...] > #------------------------------- > import mechanize > > SHOW_COOKIES = True > > br = mechanize.Browser() > if SHOW_COOKIES: > cj = mechanize.CookieJar() > br.set_cookiejar(cj) > br.open("http://www.magnetshare.com/main.php") > br.select_form(nr=0) > br["user"] = "joe" > br["pass"] = "password" > r = br.submit() > assert "Logged In" in r.get_data() > if SHOW_COOKIES: > for cookie in cj: > print cj > #------------------------------- That last line should of course have been: print cookie and not: print cj John From steve at holdenweb.com Sat Jun 10 08:48:37 2006 From: steve at holdenweb.com (Steve Holden) Date: Sat, 10 Jun 2006 13:48:37 +0100 Subject: Most elegant way to generate 3-char sequence In-Reply-To: References: <1149889784.391965.271570@h76g2000cwa.googlegroups.com> Message-ID: James Stroud wrote: > SuperHik wrote: > >>and the winner is... :D >>David Isaac wrote: >> >> >>>alpha = string.lowercase >>>x=(a+b+c for a in alpha for b in alpha for c in alpha) >> >> >> > > Not necessarily vying for winner, but David's solution is highly > specific as it doesn't do so well for something like > > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab > . > . > . > zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzy > zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz > > You can't justify your solution by requirements gold-plating ... see the subject line :-) regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From micklee74 at hotmail.com Tue Jun 13 10:02:37 2006 From: micklee74 at hotmail.com (micklee74 at hotmail.com) Date: 13 Jun 2006 07:02:37 -0700 Subject: a string problem In-Reply-To: References: <1150206140.912224.113420@p79g2000cwp.googlegroups.com> Message-ID: <1150207357.433854.153930@f6g2000cwb.googlegroups.com> John Salerno wrote: > micklee74 at hotmail.com wrote: > > hi > > > > if i have a some lines like this > > a ) "here is first string" > > b ) "here is string2" > > c ) "here is string3" > > > > When i specify i only want to print the lines that contains "string" ie > > the first line and not the others. If i use re module, how to compile > > the expression to do this? I tried the re module and using simple > > search() and everytime it gives me all the 3 lines that have "string" > > in it, whereas i only need line 1. > > If re module is not needed, how can i use string manipulation to do > > this? thanks > > > > As far as re goes, you can search for the pattern '\bstring\b', which > will find just the word 'string' itself. Not sure if there's a better > way to do it with REs. > > And I'm actually ashamed to admit that I know the RE way, but not the > regular string manipulation way, if there is one! This seems like > something easy enough to do without REs though. thanks ! From Uri.Nix at gmail.com Sun Jun 25 02:57:15 2006 From: Uri.Nix at gmail.com (Uri Nix) Date: 24 Jun 2006 23:57:15 -0700 Subject: subprocess.Popen on Windows References: <1151094433.181414.164410@g10g2000cwb.googlegroups.com> Message-ID: <1151218635.157581.315230@u72g2000cwu.googlegroups.com> Hi, Been there - try looking at: http://groups.google.com/group/comp.lang.python/browse_frm/thread/f2cb83e948326ff5/d69feabbfc940b01?q=uri.nix&rnum=2#d69feabbfc940b01 Cheers, Uri From warspir at gmail.com Mon Jun 12 22:51:24 2006 From: warspir at gmail.com (warspir) Date: Mon, 12 Jun 2006 22:51:24 -0400 Subject: Profiling a fork() program Message-ID: Hi I am trying to get a profile of a program using the profile module. The program itself has some fork() call in the code, but my profile.run() is placed before that fork() call. My question is will the profiler be able to pickup the execution of the child and parent processes? Or just one of those? Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From durumdara at gmail.com Mon Jun 26 03:28:52 2006 From: durumdara at gmail.com (Dara Durum) Date: Mon, 26 Jun 2006 09:28:52 +0200 Subject: Duplex communication with pipes - is possible ? In-Reply-To: <9e384ef60606210657l5f1f43adw@mail.gmail.com> References: <1150476096.873581.96560@g10g2000cwb.googlegroups.com> <9e384ef60606210657l5f1f43adw@mail.gmail.com> Message-ID: <9e384ef60606260028r6a54cf9ep@mail.gmail.com> Hi ! See this shortened, simplified example. It is not working, but I don't understand why... # Client Process import os, sys from subprocess import Popen, PIPE from time import sleep, time from cPickle import loads, dumps from binascii import hexlify, unhexlify from base64 import encodestring, decodestring from time import time def WriteData(WStm,Data): data=dumps(Data,1) bdata=hexlify(data) msg='%s#'%bdata WStm.write(msg) def ReadData(RStm): tmpl=[] while 1: c=RStm.read(1) if c=='#': break tmpl.append(c) bdata=''.join(tmpl) data=unhexlify(bdata) orgdata=loads(data) return orgdata def SubProcessFunctions(): f=open('spp_clt.log','w') print >>f,"m1" while 1: print >>f,"m2" data=ReadData(sys.stdin) print >>f,"m3",[data] if data=='quit': print >>f,"m4" WriteData(sys.stdout,'') break print >>f,"m5" WriteData(sys.stdout,'>>%s<<'%[data]) print >>f,"m6" if __name__=='__main__': SubProcessFunctions() # The Master process from spp_clt import ReadData, WriteData from subprocess import Popen, PIPE import time def MasterProcess(): print "m1" p=Popen([r'c:\python24\python.exe','spp_clt.py'], \ stdin=PIPE,stdout=PIPE) print "m2" (child_stdout, child_stdin) = (p.stdout, p.stdin) print "m3" for s in range(2): print "m4" WriteData(child_stdin,s) print "m5" ReadData(child_stdout) print "m6" print "m7" WriteData(child_stdin,'quit') print "m8" ReadData(child_stdout) print "m9" MasterProcess() It is freezed, because I got deadlock. Every process got "Read" state, and never get back. What I do wrong ? I was trying with this packet managing mode: def WriteData(WStm,Data): data=dumps(Data,1) bdata=encodestring(data) dlen=len(bdata) msg='%12d%s'%(dlen,bdata) if WStm==None: print msg else: WStm.write(msg) def ReadData(RStm): dlen=int(RStm.read(12)) bdata=RStm.read(dlen) data=decodestring(bdata) orgdata=loads(data) return orgdata but it also freezed. Why the master doesn't got the packets are sended by client ? Thanks for your help: dd 2006/6/21, Dara Durum : > Hi ! > Sorry, but I need "multios" application... > > This version for text mode is working: > > import subprocess > import os,sys > > if 'C' in sys.argv: > #sys.stdout=open(r'c:\tpp2client.log','w') > print "clt start" > while 1: > head=sys.stdin.read(4) > print "clt head",[head] > if head.lower()=='quit': > break > dsize=int(head) > if dsize: > data=sys.stdin.read(dsize) > print "clt get data",len(data) > print "clt end\n" > else: > print "MS" > p=subprocess.Popen([r'c:\python24\python.exe','tpp2.py','C'], \ > stdin=subprocess.PIPE,stdout=subprocess.PIPE) > print "MSS" > (child_stdout, child_stdin) = (p.stdout, p.stdin) > data=range(1000) > import cPickle > bdata=cPickle.dumps(data,1) > print len(bdata) > import binascii > hdata=binascii.hexlify(bdata) > print len(hdata) > import base64 > hdata=base64.encodestring(bdata) > print len(hdata) > child_stdin.write('%04d'%len(hdata)) > child_stdin.write(hdata) > child_stdin.write('quit') > output=child_stdout.readlines() > print "Client's answer:\n",'<'*80 > for s in output: > print s.strip() > print '>'*80 > print "MEE" > > I will see your idea: the bittorrent... > > Thanx: > dd > > > > 2006/6/20, Daniel Dittmar : > > Dara Durum wrote: > > > Now I trying with packet size decreasing. Are PIPE-s can handle the > > > binary data packets, or I need to convert them with base64 ? > > > > In the client, you need to set the mode of sys.stdin to binary, > > otherwise, you get the DOS translation of linefeeds. See > > http://mail.python.org/pipermail/python-list/2000-January/020463.html > > for some hints. > > > > I assume that the stream returned by subprocess.popen are also opened in > > text mode and you have to change them tobinary, see the second hint in > > the link mentioned above. > > > > Daniel > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > -------------- next part -------------- A non-text attachment was scrubbed... Name: spp_mast.py Type: text/x-python Size: 582 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: spp_clt.py Type: text/x-python Size: 1162 bytes Desc: not available URL: From j.c.sackett at gmail.com Mon Jun 26 10:25:17 2006 From: j.c.sackett at gmail.com (j.c.sackett) Date: Mon, 26 Jun 2006 10:25:17 -0400 Subject: Questions on Threading Message-ID: <54adf1910606260725x4315c85fscdff24bb11a8ab77@mail.gmail.com> Hello-- I'm using the threading module to accomplish some distributed processing on a project, and have a basic (I hope) question that I can't find an answer to elsewhere. I've noted that there's a lot of documentation saying that there is no external way to stop a thread, and yet when creating a thread through the threading module I can see that it has a method called _Thread__stop, which does indeed stop it. Is this in any way dangerous (i.e. doesn't actually stop the thread, or causes other thread timing issues down the road?) Or is there some other reason that there is officially no stop method? The code would be basically: t = threading.Thread(None, some_function) t.start() #Let t run for a while t._Thread__stop() Is this dangerous to a system using several many threads (100 max)? Thanks, J.C.Sackett -------------- next part -------------- An HTML attachment was scrubbed... URL: From pipedreamergrey at gmail.com Tue Jun 6 08:19:14 2006 From: pipedreamergrey at gmail.com (PipedreamerGrey) Date: 6 Jun 2006 05:19:14 -0700 Subject: Expanding Search to Subfolders References: <1149526866.681348.273590@c74g2000cwc.googlegroups.com> Message-ID: <1149596353.954352.264160@j55g2000cwa.googlegroups.com> Thanks everyone! From anthra.norell at tiscalinet.ch Fri Jun 2 10:14:36 2006 From: anthra.norell at tiscalinet.ch (Anthra Norell) Date: Fri, 2 Jun 2006 16:14:36 +0200 Subject: losing handles of open files References: <000c01c68558$a48a9680$0201a8c0@mcuf7> <877j40zext.fsf@benfinney.id.au> Message-ID: <001d01c6864e$e1498260$0201a8c0@mcuf7> ----- Original Message ----- From: "Ben Finney" To: Sent: Friday, June 02, 2006 12:30 AM Subject: Re: losing handles of open files > Please don't post non-text message bodies to discussion > forums. Message bodies should be plain text. > > "Anthra Norell" writes: > > > If a piece of code exits with an exception before it closes an open > > file, that file seems to remain locked, which is real pain in the > > butt > > You will want to examine the 'finally' clause, which is executed after > the 'try' suite regardless of exceptions. > > > > > You may also be interested in the 'with' statement, coming in Python > 2.5, which will be a more natural way of expressing this idiom. > > > > -- > \ "If nature has made any one thing less susceptible than all | > `\ others of exclusive property, it is the action of the thinking | > _o__) power called an idea" -- Thomas Jefferson | > Ben Finney > > -- > http://mail.python.org/mailman/listinfo/python-list Ben, Thank you very much for your input. I'm sorry about the text. I thought it was text. Could it have to do with the font? I am aware of the finally clause, though I just haven't met it face to face yet on the learning curve yet. Guess the time has come. I shall study your references. Frederic From cdsmith at twu.net Tue Jun 27 13:48:53 2006 From: cdsmith at twu.net (Chris Smith) Date: Tue, 27 Jun 2006 11:48:53 -0600 Subject: What is Expressiveness in a Computer Language References: <34aj92h0g7tqi9amhh7k3ieq5n568t0e6f@4ax.com> Message-ID: George Neuner wrote: > We're talking at cross purposes. I'm questioning whether a strong > type system can be completely static as some people here seem to > think. I maintain that it is simply not possible to make compile time > guarantees about *all* runtime behavior and that, in particular, > narrowing conversions will _always_ require runtime checking. Nah, we're not at cross-purposes. I'm discussing the same thing you are. My answer is that while narrowing conversion are not (by definition) type-safe, a sufficiently strong type system can remove these type-unsafe narrowing conversions from a program. > Again, the discussion is about narrowing the result. It doesn't > matter how much the compiler knows about the ranges. When the > computation mixes types, the range of the result can only widen as the > compiler determines the types involved. Well, there are certain operations that can reduce the range. For example, dividing a number that's known to be in the range 6-10 by the exact constant 2 yields a result that's guaranteed to be in the range 3- 5. That's a smaller range. That said, though, there is a more fundamental point here. When you perform a a narrowing type conversion, one of two things must be true: (a) you know more about the types than the compiler, and thus know that the conversion is safe, or (b) your code is broken. Exluding the possibility that you've written buggy code, you must possess some knowledge that convinces you the conversion is safe. In that case, we need only allow the type system to have that same knowledge, and the problem is solved. (One thing worth pointing out here is that it's quite possible that you want to do something different depending on the kind of data. In that case, the sufficiently powerful type system would need to have rules so that an if statemement creates a modified type environment to take that into account. This is different from a runtime type check, in that you are writing explicit code that provides correct program behavior in either case.) -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation From torbenm at app-1.diku.dk Wed Jun 14 09:42:25 2006 From: torbenm at app-1.diku.dk (=?iso-8859-1?q?Torben_=C6gidius_Mogensen?=) Date: 14 Jun 2006 15:42:25 +0200 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> Message-ID: <7zpshbsvjy.fsf@app-1.diku.dk> "Joe Marshall" writes: > > On the Expressive Power of Programming Languages, by Matthias > > Felleisen, 1990. > > http://www.ccs.neu.edu/home/cobbe/pl-seminar-jr/notes/2003-sep-26/expressive-slides.pdf > > The gist of the paper is this: Some computer languages seem to be > `more expressive' than others. But anything that can be computed in > one Turing complete language can be computed in any other Turing > complete language. Clearly the notion of expressiveness isn't > concerned with ultimately computing the answer. > > Felleisen's paper puts forth a formal definition of expressiveness > in terms of semantic equivilances of small, local constructs. In > his definition, wholescale program transformation is disallowed so > you cannot appeal to Turing completeness to claim program > equivalence. I think expressiveness is more subtle than this. Basically, it boils down to: "How quickly can I write a program to solve my problem?". There are several aspects relevant to this issue, some of which are: - Compactness: How much do I have to type to do what I want? - Naturality: How much effort does it take to convert the concepts of my problem into the concepts of the language? - Feedback: Will the language provide sensible feedback when I write nonsensical things? - Reuse: How much effort does it take to reuse/change code to solve a similar problem? Compactness is hard to measure. It isn't really about the number of characters needed in a program, as I don't think one-character symbols instead of longer keywords make a language more expressive. It is better to count lexical units, but if there are too many different predefined keywords and operators, this isn't reasonable either. Also, the presence of opaque one-liners doesn't make a language expressible. Additionally, as mentioned above, Turing-completeness (TC) allows you to implement any TC language in any other, so above a certain size, the choice of language doesn't affect size. But something like (number of symbols in program)/log(number of different symbols) is not too bad. If programs are allowed to use standard libraries, the identifiers in the libraries should be counted in the number of different symbols. Naturality is very difficult to get a grip on, and it strongly depends on the type of problem you want to solve. So it only makes sense to talk about expressiveness relative to a set of problem domains. If this set is small, domain-specific languages win hands down, so if you want to compare expressiveness of general-purpose languages, you need a large set of very different problems. And even with a single problem, it is hard to get an objective measure of how difficult it is to map the problem's concepts to those of the language. But you can normally observe whether you need to overspecify the concept (i.e., you are required to make arbitrary decisions when mapping from concept to data), if the mapping is onto (i.e., can you construct data that isn't sensible in the problem domain) and how much redundancy your representation has. Feedback is a mixture of several things. Partly, it is related to naturality, as a close match between problem concepts and language concepts makes it less likely that you will express nonsense (relative to the problem domain) that makes sense in the language. For example, if you have to code everything as natural numbers, untyped pure lambda calculus or S-expressions, there is a good chance that you can get nonsense past the compiler. Additionally, it is about how difficult it is to tie an observation about a computed result to a point in the program. Measuring reuse depends partly on what is meant by problems being similar and also on whether you at the time you write the original code can predict what types of problems you might later want to solve, i.e., if you can prepare the code for reuse. Some languages provide strong mechanisms for reuse (templates, object hierarchies, etc.), but many of those require that you can predict how the code is going to be reused. So, maybe, you should measure how difficult it is to reuse a piece of code that is _not_ written with reuse in mind. This reminds me a bit of last years ICFP contest, where part of the problem was adapting to a change in specification after the code was written. > Expressiveness isn't necessarily a good thing. For instance, in C, > you can express the addresses of variables by using pointers. You > cannot express the same thing in Java, and most people consider this > to be a good idea. I think this is pretty much covered by the above points on naturality and feedback: Knowing the address of a value or object is an overspecification unless the address maps back into something in the problem domain. On a similar note, is a statically typed langauge more or less expressive than a dynamically typed language? Some would say less, as you can write programs in a dynamically typed language that you can't compile in a statically typed language (without a lot of encoding), whereas the converse isn't true. However, I think this is misleading, as it ignores the feedback issue: It takes longer for the average programmer to get the program working in the dynamically typed language. Torben From istvan.albert at gmail.com Fri Jun 16 11:51:13 2006 From: istvan.albert at gmail.com (Istvan Albert) Date: 16 Jun 2006 08:51:13 -0700 Subject: a good programming text editor (not IDE) References: <_xgkg.2317$No6.48542@news.tufts.edu> <1150406662.900552.46650@u72g2000cwu.googlegroups.com> <4491d4ae$1@nntp0.pdx.net> Message-ID: <1150473073.647129.168640@c74g2000cwc.googlegroups.com> Scott David Daniels wrote: > Surprise, surprise. One hour is not two weeks. I wrote: > pressing Ctrl-1 while editing the source will execute the python on the > current source *and* it displays the output in a lower pane as it runs > *and* it allows me to simultanously edit the file *while* the program > is running. yet I'll bet that you could not make Vim do this above ... From onurb at xiludom.gro Fri Jun 30 12:27:31 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Fri, 30 Jun 2006 18:27:31 +0200 Subject: Way for see if dict has a key In-Reply-To: References: <6V6pg.21624$_J1.271925@twister2.libero.it><44a5041f$0$29637$636a55ce@news.free.fr><4F7pg.21676$_J1.272665@twister2.libero.it> <1151666867.604260.116320@h44g2000cwa.googlegroups.com> <44a51f34$0$6794$626a54ce@news.free.fr> <44a5409c$0$8389$626a54ce@news.free.fr> Message-ID: <44a550f4$0$8390$626a54ce@news.free.fr> Fredrik Lundh wrote: > Bruno Desthuilliers wrote: > >> Seems that if "key in dict" do a simple linear search > > > that would be rather silly. > > hint: http://pyref.infogami.com/__contains__ Of course. It's just me being silly... :( Thanks F -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From pmartin at snakecard.com Wed Jun 28 22:02:47 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Wed, 28 Jun 2006 21:02:47 -0500 Subject: Web transaction server in Python Message-ID: Hi, I know a bit Python as application programming, but very little as a web server. I need to get one server to accept connection requests from many devices (not all PC-Based) and then have a bi-lateral "conversation" with those devices prior to closing the connection. The said devices have at least a tcp-ip stack (socket level). Is Zope something for me ? what else ? Thanks, Philippe From nmm1 at cus.cam.ac.uk Thu Jun 15 12:44:09 2006 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 15 Jun 2006 16:44:09 GMT Subject: Numerics, NaNs, IEEE 754 and C99 References: <12904mjhl493t49@corp.supernews.com> <1290aik50hmk94a@corp.supernews.com> <4490329e$0$12356$636a55ce@news.free.fr> <12917f6jp7u90f8@corp.supernews.com> <44912058$0$29674$636a55ce@news.free.fr> <1292p7s46ef5off@corp.supernews.com> In article <129300g5np02c8a at corp.supernews.com>, Grant Edwards writes: |> |> > which IEEE 754 assumes that the code will test and take |> > appropriate action (which can be anything, including aborting |> > the program and replacing it by a NaN). See |> > http://www.cs.berkeley.edu/~wkahan/JAVAhurt.pdf |> |> IEEE Std 754-1985, subclause 7.2 - Division by Zero |> |> "If the divisor is zero and the dividend is a finite nonzero |> number, then the division by zero shall be signaled. The |> result, when no trap occurs, shall be a correctly signed |> (infinity symbol)(6.3)." |> |> To me it looks like the spec specifically allows for a case |> where "no trap occurrs" and the result is Inf. That is correct. And it is a mandatory case. But it does NOT say what the software should then do with the exception. Regards, Nick Maclaren. From faulkner612 at comcast.net Fri Jun 16 08:17:52 2006 From: faulkner612 at comcast.net (faulkner) Date: 16 Jun 2006 05:17:52 -0700 Subject: Video capture from webcam on Mac? In-Reply-To: References: Message-ID: <1150460272.162355.193620@y41g2000cwy.googlegroups.com> gstreamer has python bindings. http://gstreamer.net/ Joseph Chase wrote: > Is there a cross-platform solution for video capture from a webcam? > > I am aware of the Win32 videocapture library, but am unaware of how to > accomplish the same functionality on the Mac side. > > Thanks in advance. From paolopantaleo at gmail.com Sat Jun 10 13:24:28 2006 From: paolopantaleo at gmail.com (Paolo Pantaleo) Date: Sat, 10 Jun 2006 19:24:28 +0200 Subject: Getting backtrace on an axception Message-ID: <83e8215e0606101024m42748166vf0cf7a2332d7e5bb@mail.gmail.com> So I have this code try: do something except: do something else In the except block I need to print detailed output about the error occured, and in particular I need to read the backtrace for the line that raised the exception [then modify and print it]. I know about the exception.extract_tb() and friends, but I can't figure out how they works. Can somebody exlpain me? Thnx PAolo -- if you have a minute to spend please visit my photogrphy site: http://mypic.co.nr From reply.in.the.newsgroup at my.address.is.invalid Tue Jun 6 06:13:02 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Tue, 06 Jun 2006 12:13:02 +0200 Subject: Writing to a certain line? References: <1149576072.168354.14470@f6g2000cwb.googlegroups.com> <44854184$0$29904$636a55ce@news.free.fr> Message-ID: <46la821oa3s4nr4vcfa6nbg03lcq0jl1jf@4ax.com> bruno at modulix: >You can't do this in place with a text file (would be possible with a >fixed-length binary format). More precise: it's possible with any fixed-length change, in both binary and text files, with both fixed and variable formats. -- Ren? Pijlman From python.list at tim.thechases.com Sun Jun 18 08:37:00 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 18 Jun 2006 07:37:00 -0500 Subject: mapping None values to '' In-Reply-To: <1150632320.443681.42640@r2g2000cwb.googlegroups.com> References: <1150632320.443681.42640@r2g2000cwb.googlegroups.com> Message-ID: <449548EC.4020700@tim.thechases.com> > i wish to map None or "None" values to "". > eg > a = None > b = None > c = "None" > > map( , [i for i in [a,b,c] if i in ("None",None) ]) > > I can't seem to find a way to put all values to "". Can anyone help? > thanks I'd consider this a VeryBadIdea(tm). However, given Python's introspective superpowers, it *can* be done (even if it most likely *shouldn't* be done). That caveat out of the way, here goes: >>> for scope in [locals, globals]: ... s = scope() ... for vbl, value in s.items(): ... if value == None or (type(value) == type("") and value == 'None'): ... s[vbl] = '' seems to do the trick. You may, likely, just want to operate on locals, not every last global variable in your project, in which case you can just use s = locals() for vbl, value in s.items(): ... There may be some better way to determing whether an item is a string than my off-the-cufff type(value) == type("") but it worked to prevent trying to compare non-strings to the string 'None' later in the sub-clause of the if statement. Note that if you wrap this in a function, you'll may have to pass in locals() as a parameter because otherwise, inside your function, you'll have a different set of available locals that you did when you called the function. :) Beware your foot when shooting this gun...it likes to aim at feet. -tkc From intemelion at libero.it Wed Jun 14 06:37:54 2006 From: intemelion at libero.it (Quacker) Date: 14 Jun 2006 03:37:54 -0700 Subject: Greetings Message-ID: <1150281474.347119.89380@f6g2000cwb.googlegroups.com> Nice and interesting matter! From bborcic at gmail.com Fri Jun 16 18:00:16 2006 From: bborcic at gmail.com (Boris Borcic) Date: Sat, 17 Jun 2006 00:00:16 +0200 Subject: [Python-Dev] The baby and the bathwater (Re: Scoping, augmented assignment, 'fast locals' - conclusion) In-Reply-To: References: <20060614093042.F2D7.JCARLSON@uci.edu> Message-ID: <449329F0.2000703@gmail.com> Josiah Carlson wrote: >> >> [BB] >> >> I'd say a first step in convincing me I am wrong would be to show me >> examples of >> >> object methods of the standard library that are recursive, and cut out for >> >> recursion. >> >> [JC] >> > Actually, I don't believe that is necessary. I've shown that you would >> > get better performance with a non-recursive function and passing two >> > arguments, than you would passing one argument with scoping tricks to >> > get the second. >> >> Assuming my aim was purely performance clearly stretches the hints I gave that I >> wasn't unconcerned by it. Taking ground on this to unwarrantedly suppose that my >> methodology was deficient, rectify it, and then dictate the "necessary" >> conclusions I find... er, preposterous seems balanced, "thought police" not >> totally unwarranted. > > In my initial and later readings of your messages, I read 2 reasons why > you were using a closure rather than some other method to perform this > particular operation: That wording already doesn't apply. I told you I was working *not* on a program but on a *space* of programs of identical function, as of manner of probing recent features and modules of Python that I manage to apply to it. Besides learning, my purpose is also aesthetic. Some versions use closures, some don't - of course. > 1. Minimal code change. That's a reducive synonym for "being able to compare versions while changing only single factors of my choosing". Currently I would add : "without your mechanical avatar coming into the field uninvited". > 2. It was faster than using an object with a particular interface. No way. PLEASE RENEW YOUR GLASSES. > > If there were other reasons, then I obviously missed them. Excuse me, my perception is that there has not been a single one of my interventions that you took fully at face value. I am the perpetual strawman in an argument that is not adressed to myself (as manifested) but to some shadow of myself by some projection operator, onto a convenient manifold of ideally misguided contradictors. > However, since no one else has responded substantively to your postings, > other than Terry and Guido's 'not gonna change', That's "Terry's 'take the fairy tale' and Guido's 'not gonna change'", to be exact. > I can only presume that > others have found that your desired result (augmented assignments for > names not previously existing in the current scope, but existing in a > parent lexical scope, be performed on the object bound to a parent scope > name), is undesireable for Python 2.5 This is again misrepresentation. I definitely did *not* come to pydev to ask for a change, I merely intervened in the middle on an ongoing thread at the point it was being said that, in effect, I did not exist. Thereupon you intervened with no other purpose than to show, in effect, that I did not exist, forcing me into an endless chain of rectifications. Now you are telling me I want it included in the 2.x series. That's confusing the citizen for the lobbyist. > > In a portion of your message that I've cut out, you described how the > goal of your current programming project was to write a sudoku solver in > fewer than 60 lines and that ran in fewer than 10ms for arbitrary > problems. No. PLEASE RENEW YOUR GLASSES. FYI, an universal sudoku solver in distribution python, confortably less than 60 locs, and solving an average problem in confortably less than 10 ms (on my machine) : that was an early result, and indeed a surprise. The "programming project" I *did* describe was the project of *further* exploring, with systematism, the space of nearly equivalent programs - while slightly *relaxing* the frame of the initial result, and while exercizing varying parts of relatively recent distribution Python or third party modules that I did not know, or not know well. Seeking beauty, if you want. You understand the quest for beauty ? I guess not in the manner of someone who started programming when programs had to fit in a couple dozen kbytes. The "compiler feature" under discussion just pissed me off when it popped up to veto what was emergeing as the winner of my beauty contest after examining quite a few worthy candidates over weeks. > Great, wonderful, I wish you luck; I will not question or > "refuse legitimacy, motivation, efficiency or methodological soundness" > of your approach when using the Python programming language. What's wrong with chosing a set problem to compare features of the Python programming language against, and learn from it ? Please tell. And what's wrong, when seeking beauty, with picking a stringent constraint and then explore in parallel various manners to satisfy it, relaxing it slightly if need be ? How do you think nature evolved birds or flowers or anything that lives ? > However, you are offering a series of reasons as to why the Python > programming language should be changed. It's *you* who made me your mirror. I was merely saying : "hey, I find this crazy, can someone provide explanations ?". > I'm questioning your reasoning. No, you are not questioning *my* reasoning. Never. Nada. You are perpetually *making up* a reasoning for me that *very roughly* fits what I say, but has the nice feature that you know how to refute it. > You may find it insufficient, misinformed, prejudiced, nonsense, > mean-spirited, or even that I'm a loony who should be in your killfile. Well, at this point you risk an even worse fate than that ;) That is, the intersection of the file tagged "arrogant would-be mind-readers", and of the file tagged "you are late on the normal trajectory if you did not reproduce my own oh-so-significant mistakes", both well-populated already, although I forgot who I put in them. > My purpose here isn't to convince _you_ that you are wrong about this > feature, as arguing via email has never been my strong suit, but instead > to offer at least one valid reason why your change could or would hurt > some Python users, and/or the effectiveness of their code. The problem is that you fail to be polite about it more often than not. Most of the time not really talking to the reasonable person I tend to be. > > I will mention that the lack of _any_ public support in python-dev > likely says far more about the unliklihood of acceptance than anything > you or I have probably typed in the last few days. And what's the purpose of that declaration ? You are the, hum, crazed lobbyist, not me. I am just defending that my pov is perfectly legitimate, including when it's examined by your criterions - once the fallacious ones among them are filtered out. > > > [snip] >> [JC] >> > when it was an >> > actual error (a not uncommon case), >> >> I guess your insistence on the rightful methodology entitles me to enquire in >> turn on your choice of tool to establish the relative frequency of said case ? > > My measurement is quite subjective. Have I ever made that mistake, or > do I know of anyone who has made that mistake? In this case, I have made > the mistake I mention, both in personal code, as well as code I was > writing as I was tutoring. Thanks for the transparency. You mean code you were writing in real time before an audience ? Hum. Surely you take the time to debug example code before presenting it ? The error you mean - do we agree on this ? - is to intend two variables of the same name, one in the parent scope, the other shadowing it in the child scope, and mutating the variable in the child scope while having forgotten to initialize it. A few questions. First, do we agree or not that gratuitous shadowing is by itself a mistake ? Or do you mean it happened to you while the shadowing wasn't gratuitous ? Also, do you mean it happened to you in the Python context so that Python stopped it at "ref to uninitialized local" - or in some other langiage context ? In the Python case, I can only wonder as to what could make it memorable - not the debugging, certainly. In the non-Python case, well, it's not really clear that a tendency manifest in another language should spontaneously carry over to Python : for instance, Python differs from some languages in that augmented assignments aren't value-producing expressions. And some language push towards embedding scopes to a level much greater than would Python even without "the javanese watchdog" imo. My take on the issue, btw, is that the "scope capture" behavior of (non-augmented) assignment statement is in Python the residual counterpart of variable declarations in other languages; and it is significant that it shares the most typical basic form, since in most cases declaration and initialization are fused. This doesn't carry over to augmented assignments that are mutation operators. > I'm not aware of significant problems in > user code, usually because the moment the code is run, the programmer > fixes it. Thanks for your honesty. > > Here are two questions for you: > > 1. Do you have any proof showing that the error I claim exists (not > uncommonly was my description), is in fact so rare, that I am > essentially the only one who has made the mistake? Well, my take on an issue of such form is perhaps particular, but - as I already suggested with my "hate for whatever resembles a constraining curriculum of errors to make" - I really believe, as a matter of ethics, that the burden of proof is on your side, not mine. I can try to explain more, if you want. > 2. Do lexically nested augmented assignments happen so often as to make > this problem a "must solve" for any Python revision? Hum, first of all implementation of the solution is (according to recent records), so trivial that it occurs spontaneously as a bug. Therefore, even conceding to you the usage be so rare that the gain is vanishingly small, the ratio gain/effort would be one of vanishingly small quantities, which itself is a priori not determined to be close to zero. This of course does not count the cost of the decision. AFAICS, you are yourself the most significant factor in determining that cost, and because of that I think it would not be fair dialectics that I should take that cost into account to answer your own question. Right ? Second, the assumption of rarity leading to insignificance - does it escape you that's a sword that cuts both way - as concerns a sizeable part of your own argumentation ? Third, to me the matter is foremost one of aesthetics. The contentious "feature" made me briefly feel like I was confused on the identity of the lady I was making love to. Fourth, of course I can survive without it. > > >> [JC] >> > which is a bit of a no-no, >> >> What I would have believed a /bit/ of a no-no for Python, is to turn away from >> the "consenting adults" spirit to go the way of so many other programming languages. >> >> Picture of the latter way : - As a matter of course, to place the virtue of >> catching errors early, before the virtue of following programmers' legitimate >> intentions. - Designing for assumed chronic lusers in need of being protected by >> the compiler from shooting themselves in the foot. It is really denaturing to what I was saying there, that it got disconnected from the immediate context of my claim/demo that your analysis secretely referred to a situation of cumulated simultaneous mistakes while presenting it as a single error. > > Do skilled programmers make errors? Yes. Do skilled programmers make > errors when they are first using a programming language? Yes. Of course everybody makes errors, but it doesn't follow from this, that all make the same errors, or should. Think of errors as genes of the developping minds, and design better for biodiversity, I'd say. My first professional programming was on a system that did not support any form of encapsulation and gave me access to 300 distinct opaque variable names : quite a training on the matter of variable name capture, I tell you. As concerns Python, the issue is that in most aspects it is carefully crafted so that you can often "just try it and it works as you would expect". For this to work, consistency is very important. Our whole debate is that according to me the "feature" under discussion is not in the same spirit while you (and Terry indeed) found preferable not to acknowledge the notion, what also prevented the possibility to convince me that the "feature" should exist anyway, for logical reasons a reasonable mind could hear. This was further complicated by your obsession with proving *first* that I could not possibly have a legitimate use-case, whatever I said. > It has > always been my experience with Python that it seeks to be reasonable to > use for both newcomers to programming and long-time "skilled" > programmers. Nobody forces any school to present closures to beginners. Burn SICP before your class. More seriously, I believe the case you made against closures really should hit what incites to the "simultaneous mistake", eg the ease of shadowing builtins and globals, inadvertently to start with. A nicely fat set of keyword-like names that one can't shadow without special action, would that not be the best of schools against gratuitous shadowing ? Well, maybe that would be too much of a change for Python. OTOH, mhh, I would need to study the matter more in depth, but at first sight I see absolutely no obstacle to trading a ban on closures shadowing names from the outer local scope, against the current ban on augmented assignment of variables from the outer scope (even without including straightforward assignment in the bargain). This would give python closures a new educative role : a context that trains against shadowing. If I am not mistaken, it would fulfill the "use case" you find to the "feature" I dislike, just as well. > > In my statements regarding possible errors related to augmented > assignments, I merely believe that people can and will make mistakes. I > further believe that if I manage to make a particular mistake, that > someone else has, because while I'm not the most brilliant programmer > out there, I'm also certainly not the worst, and I would guess that I > lack the creativity to generate a completely new class of mistakes. Whatever, programming or not, I believe the most dangerous (in the sense of most difficult to rectify) class of mistakes is the class of diagnostic errors - meta-errors, so to say; because of that, I believe a danger with mistakes or errors is to anticipate too much on them, and, given their diversity, to overestimate the scope of the lessons learned from the sample of them that most caught our attention (usually because of their painful consequences). Besides, I think there are subtle issues with taking errors as building material for policies destined to public consomption by new generations. It is vital to find a self-standing positive goal to substitute to the negative goal of avoiding the repetition of the error, etc. Btw, how you dealt with my case tells me you don't particularly fear diagnostic errors, but your way of presenting closures and classes in Python tells me that you probably agree with my later remark. > > You talk about "Designing for assumed chronic lusers", Again, this has lost its proper context. > I'm talking about > designing for human beings, some of whom are new to the language. This starts resembling the disputes I had with my wife over the education of our child. Total divergence as to the adequacy of trying to control the child's POV. > > > - Josiah > Boris -- "on na?t tous les m?tres du m?me monde" From find at my.address.elsewhere Tue Jun 20 11:55:02 2006 From: find at my.address.elsewhere (Matthias Blume) Date: Tue, 20 Jun 2006 10:55:02 -0500 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <1150809118.677124.142230@u72g2000cwu.googlegroups.com> Message-ID: David Squire writes: > Matthias Blume wrote: >> David Squire writes: >> >>> Andreas Rossberg wrote: >>>> Rob Thorpe wrote: >>>>>>> No, that isn't what I said. What I said was: >>>>>>> "A language is latently typed if a value has a property - called it's >>>>>>> type - attached to it, and given it's type it can only represent values >>>>>>> defined by a certain class." >>>>>> "it [= a value] [...] can [...] represent values"? >>>>> ??? >>>> I just quoted, in condensed form, what you said above: namely, that >>>> a value represents values - which I find a strange and circular >>>> definition. >>>> >>> But you left out the most significant part: "given it's type it can >>> only represent values *defined by a certain class*" (my emphasis). In >>> C-ish notation: >>> >>> unsigned int x; >>> >>> means that x can only represent elements that are integers elements of >>> the set (class) of values [0, MAX_INT]. Negative numbers and >>> non-integer numbers are excluded, as are all sorts of other things. >> This x is not a value. It is a name of a memory location. >> >>> You over-condensed. >> Andreas condensed correctly. > > I should have stayed out of this. I had not realised that it had > degenerated to point-scoring off someone typing "value" when it is > clear from context that he meant "variable". If he really had meant "variable" then he would have been completely wrong. > Bye. Bye. From skip at pobox.com Sun Jun 4 22:59:36 2006 From: skip at pobox.com (skip at pobox.com) Date: Sun, 4 Jun 2006 21:59:36 -0500 Subject: Lots of orphaned PyCon wiki pages... Message-ID: <17539.40472.282924.716870@montanaro.dyndns.org> Over the past couple days I've been trying to reduce the large number of orphaned wiki pages, deleting many, stitching many others back into the fabric. There are a bunch of orphaned PyCon-related pages, mostly subpages of PyCon2005 and PyCon2006. Would someone with PyCon-fu want to check them out and decide their fate? If so, visit http://wiki.python.org/moin/OrphanedPages and scroll down to the "P" section. Thanks, Skip From andrewm at object-craft.com.au Tue Jun 20 06:55:33 2006 From: andrewm at object-craft.com.au (Andrew McNamara) Date: Tue, 20 Jun 2006 20:55:33 +1000 Subject: Albatross 1.35 released Message-ID: <20060620105533.B0F617940A1@longblack.object-craft.com.au> OVERVIEW Albatross is a small toolkit for developing highly stateful web applications. The toolkit has been designed to take a lot of the pain out of constructing intranet applications although you can also use Albatross for deploying publicly accessed web applications. In slightly more than 4500 lines of Python (according to pycount) you get the following: * An extensible HTML templating system similar to DTML including tags for: - Conditional processing. - Macro definition and expansion. - Sequence iteration and pagination. - Tree browsing. - Lookup tables to translate Python values to arbitrary template text. * Application classes which offer the following features: - Optional server side or browser side sessions. - The ability to place Python code for each page in a dynamically loaded module, or to place all page processing code in a single mainline. * The ability to deploy applications as CGI, FastCGI, mod_python or a pure python HTTP server by changing less than 10 lines of code. The toolkit application functionality is defined by a collection of fine grained mixin classes. Nine different application types and six different execution contexts are prepackaged, you are able to define your own drop in replacements for any of the mixins to alter any aspect of the toolkit semantics. Application deployment is controlled by your choice of either cgi, FastCGI, mod_python, or BaseHTTPServer Request class. It should be possible to develop a Request class for Medusa or Twisted to allow applications to be deployed on those platforms with minimal changes. Albatross comes with over 180 pages of documentation. HTML and PDF formatted documentation is available from the toolkit homepage. The toolkit homepage: http://www.object-craft.com.au/projects/albatross/ The Albatross mailing list subscription and archives: http://object-craft.com.au/cgi-bin/mailman/listinfo/albatross-users CHANGES SINCE 1.33: ==================- Note that release 1.34 was an internal release. New Features ------------ * A drop-in replacement for the fcgiapp module, called fcgiappnew has been added. This version implements the FastCGI protocol itself, rather than relying on an external module to implement the protocol. This new module addresses several minor problems with fcgi.py, and should be faster, although it should not be used in critical applications until it has received wider testing. Functional Changes ------------------ * When extension tags (alx-*) are registered, their name is now checked against the template parsing regexp to ensure they can subsequently be matched. Bug Fixes --------- * The AnyTag functionality was given knowledge of HTML tags for which the close tag is forbidden, so it can avoid generating XHTML empty tag (which could cause the page to fail HTML validation). * When the disabledbool attribute was used on input tags, the disabled state was not being passed through to the input registry within the NameRecorderMixin. * If a client closed it's connection to the session server while the server had data pending for the client, a subsequent del_write_file would generate an exception, killing the session server. -- Andrew McNamara, Senior Developer, Object Craft http://www.object-craft.com.au/ From jstroud at ucla.edu Wed Jun 14 20:37:41 2006 From: jstroud at ucla.edu (James Stroud) Date: Wed, 14 Jun 2006 17:37:41 -0700 Subject: Negative hex to int In-Reply-To: <1150326597.327669.222640@r2g2000cwb.googlegroups.com> References: <1150326597.327669.222640@r2g2000cwb.googlegroups.com> Message-ID: andreas.lydersen at gmail.com wrote: > Hi! > > While communicating with a monitoring unit, I get some hex values > representing degrees celcius from its probes. The values can be > something like '19' or '7d'. To convert it to int, I do the following: > --------------------------- > Python 2.4.2 (#1, Sep 28 2005, 10:25:47) > [GCC 3.4.3 20041212 (Red Hat 3.4.3-9.EL4)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>>>int('7d', 16) > > 125 > >>>>int('19', 16) > > 25 > > --------------------------- > > The problem is negative values. If the unit returns the hex value 'e7', > it means -25, but python says it's 231: > --------------------------- > >>>>int('e7', 16) > > 231 > --------------------------- > > Does anyone have a clue a to what I need to do? > > Thanks! > > Andreas Lydersen > py> t = lambda x: int(x, 16) - ((int(x, 16) >> 7) * 256) py> t('e7') -25 -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From invalidemail at aerojockey.com Thu Jun 15 08:32:07 2006 From: invalidemail at aerojockey.com (Carl Banks) Date: 15 Jun 2006 05:32:07 -0700 Subject: memory leak problem with arrays References: <1150317325.614389.14770@i40g2000cwc.googlegroups.com> Message-ID: <1150374727.103552.200120@p79g2000cwp.googlegroups.com> sonjaa wrote: > I've created a cellular automata program in python with the numpy array > extensions. After each cycle/iteration the memory used to examine and > change the array as determined by the transition rules is never freed. Are you aware that slicing shares memory? For example, say you defined a grid to do the automata calculations on, like this: grid = numpy.zeros([1000,1000]) And then, after running it, you took a tiny slice as a region of interest, for example: roi = grid[10:20,10:20] Then deleted grid: del grid Then stored roi somewhere, for example: run_results.append(roi) If you do this, the memory for the original grid won't get freed. Although grid was deleted, roi still contains a reference to the whole 1000x1000 array, even though it's only a tiny slice of it. Your poorly worded description--no offense--of what you did suggests that this is a possibility in your case. I recommend you try to create a new array out of any slices you make, like this (but ONLY if the slice doesn't depend on the memory being shared): roi = numpy.array(grid[10:20,10:20]) This time, when you del grid, there is no object left referencing the array data, so it'll be freed. This might not be your problem. Details are important when asking questions, and so far you've only given us enough to speculate with. Carl Banks From rogue_pedro at yahoo.com Sun Jun 25 21:02:59 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 25 Jun 2006 18:02:59 -0700 Subject: HTTP server In-Reply-To: <1151282086.450972.128790@r2g2000cwb.googlegroups.com> References: <1151134073.393065.187500@c74g2000cwc.googlegroups.com> <1151162732.819264.190560@i40g2000cwc.googlegroups.com> <1151241369.138325.173690@r2g2000cwb.googlegroups.com> <1151253325.924054.95100@c74g2000cwc.googlegroups.com> <1151282086.450972.128790@r2g2000cwb.googlegroups.com> Message-ID: <1151283779.491178.146890@c74g2000cwc.googlegroups.com> placid wrote: > Simon Forman wrote: ... > > The file was named test.cgi. I changed it too test.py and it worked > Awesome! Glad to hear it. ... > > Thanks for the help. I got it to work now. > You're welcome. I'm glad I could help you. :-D Peace, ~Simon From felipe.lessa at gmail.com Fri Jun 9 17:50:27 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Fri, 09 Jun 2006 18:50:27 -0300 Subject: Killing a thread In-Reply-To: <7c8a9a970606091354u73308bf8o2758eea5ef690c39@mail.gmail.com> References: <7c8a9a970606091338t174fbcb0wc73cdb8b385f8ccd@mail.gmail.com> <7c8a9a970606091354u73308bf8o2758eea5ef690c39@mail.gmail.com> Message-ID: <1149889827.2754.6.camel@kenshin.CASA> Em Sex, 2006-06-09 ?s 13:54 -0700, Manish Marathe escreveu: > On 6/9/06, Fredrik Lundh wrote: > Manish Marathe wrote: > > > I am creating threads using my self defined class which > inherits the > > threading.Thread class. I want to know how can I kill the > threads which > > are being created by the object of my self defined class. > > you cannot kill a thread "from the outside"; you have to > design your > thread tasks so they can kill themselves, when asked to do > that. > > Thanks for the reply. So can a thread listen to an event i.e. can we > send an event to the thread indicating to kill itself. A plain simple boolean flag will certainly do the job. For example def run(self): self.running = True while self.running: blah() def stop(self): self.running = False -- Felipe. From flaus.a at wanadoo.fr Tue Jun 13 18:23:00 2006 From: flaus.a at wanadoo.fr (flaus.a at wanadoo.fr) Date: 13 Jun 2006 15:23:00 -0700 Subject: How to select a folder with native windows dialog box? Message-ID: <1150237380.370088.29270@p79g2000cwp.googlegroups.com> I found the win32ui.CreateFileDialog() function to select a file but nothing to select a folder :'-( Maybe someone has a solution for this? Thanks! From jstroud at ucla.edu Tue Jun 13 16:16:04 2006 From: jstroud at ucla.edu (James Stroud) Date: Tue, 13 Jun 2006 13:16:04 -0700 Subject: "groupby" is brilliant! In-Reply-To: <1150180151.643245.148210@y43g2000cwc.googlegroups.com> References: <1150180151.643245.148210@y43g2000cwc.googlegroups.com> Message-ID: Frank Millman wrote: > Hi all > > This is probably old hat to most of you, but for me it was a > revelation, so I thought I would share it in case someone has a similar > requirement. > > I had to convert an old program that does a traditional pass through a > sorted data file, breaking on a change of certain fields, processing > each row, accumulating various totals, and doing additional processing > at each break. I am not using a database for this one, as the file > sizes are not large - a few thousand rows at most. I am using csv > files, and using the csv module so that each row is nicely formatted > into a list. > > The traditional approach is quite fiddly, saving the values of the > various break fields, comparing the values on each row with the saved > values, and taking action if the values differ. The more break fields > there are, the fiddlier it gets. > > I was going to do the same in python, but then I vaguely remembered > reading about 'groupby'. It took a little while to figure it out, but > once I had cracked it, it transformed the task into one of utter > simplicity. > > Here is an example. Imagine a transaction file sorted by branch, > account number, and date, and you want to break on all three. > > ----------------------------- > import csv > from itertools import groupby > from operator import itemgetter > > BRN = 0 > ACC = 1 > DATE = 2 > > reader = csv.reader(open('trans.csv', 'rb')) > rows = [] > for row in reader: > rows.append(row) > > for brn,brnList in groupby(rows,itemgetter(BRN)): > for acc,accList in groupby(brnList,itemgetter(ACC)): > for date,dateList in groupby(accList,itemgetter(DATE)): > for row in dateList: > [do something with row] > [do something on change of date] > [do something on change of acc] > [do something on change of brn] > ----------------------------- > > Hope someone finds this of interest. > > Frank Millman > I'm sure I'm going to get a lot of flac on this list for proposing to turn nested for-loops into a recursive function, but I couldn't help myself. This seems more simple to me, but for others it may be difficult to look at, and these people will undoubtedly complain. import csv from itertools import groupby from operator import itemgetter reader = csv.reader(open('trans.csv', 'rb')) rows = [] for row in reader: rows.append(row) def brn_doer(row): [doing something with brn here] def acc_doer(date): [you get the idea] [etc.] doers = [brn_doer, acc_doer, date_doer, row_doer] def doit(rows, doers, i=0): for r, alist in groupby(rows, itemgetter(i)): doit(alist, doers[1:], i+1) doers[0](r) doit(rows, doers, 0) Now all of those ugly for loops become one recursive function. Bear in mind, its not all that 'elegant', but it looks nicer, is more succinct, abstracts the process, and scales to arbitrary depth. Tragically, however, it has been generalized, which is likely to raise some hackles here. And, oh yes, it didn't answer exactly your question (which you didn't really have). I'm sure I will regret this becuase, as you will find, suggesting code on this list with additional utility is somewhat discouraged by the vociferous few who make a religion out of 'import this'. Also, I still have no idea what 'groupby' does. It looks interesting thgough, thanks for pointing it out. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From scott.daniels at acm.org Thu Jun 15 18:04:43 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Thu, 15 Jun 2006 15:04:43 -0700 Subject: a good programming text editor (not IDE) In-Reply-To: <1150406662.900552.46650@u72g2000cwu.googlegroups.com> References: <_xgkg.2317$No6.48542@news.tufts.edu><44919668$1@nntp0.pdx.net> <1150406662.900552.46650@u72g2000cwu.googlegroups.com> Message-ID: <4491d4ae$1@nntp0.pdx.net> Istvan Albert wrote: > Scott David Daniels wrote: > >> To paraphrase someone else (their identity lost in my mental fog) about >> learning VI: >> "The two weeks you'll spend hating vi (or vim) as you learn it will >> be repaid in another month, ad the rest is pure profit." > > Time and again I hear this (no shortage of Vim fans, same with Emacs), > and I know I should know better but always believe them yet again. > Invariably I download Vim play with it for an hour, get increasingly > frustrated and give up. Surprise, surprise. One hour is not two weeks. --Scott David Daniels scott.daniels at acm.org From fredrik at pythonware.com Tue Jun 27 13:22:10 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 27 Jun 2006 19:22:10 +0200 Subject: How to disable tk inclusion in py build In-Reply-To: <1151422992.208936.54600@j72g2000cwa.googlegroups.com> References: <1151422992.208936.54600@j72g2000cwa.googlegroups.com> Message-ID: venkatbo at yahoo.com wrote: > I'd like to disable the inclusion of tk graphics lib in my py build. > Looked around but couldn't find a clear answer. Which one of > the following would I need to use in the configure step: > --disable-tkbuild > --without-tk since _tkinter.so is only built if it's found by the setup script, and if built, it's only loaded if you actually use it, why bother "disabling" it ? From yumagene at gmail.com Tue Jun 20 14:11:15 2006 From: yumagene at gmail.com (genea) Date: 20 Jun 2006 11:11:15 -0700 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150823341.079992.98350@y41g2000cwy.googlegroups.com> Message-ID: <1150827075.175209.8800@i40g2000cwc.googlegroups.com> Joe Marshall wrote: {...} > The issue of `static vs. dynamic types' comes up about twice a year in > comp.lang.lisp It generally gets pretty heated, but eventually people > come to understand what the other person is saying (or they get bored > and drop out of the conversation - I'm not sure which). {...} I think that the thing about "Language Expressiveness" is just so elusive, as it is based on each programmers way of thinking about things, and also the general types of problems that that programmer is dealing with on a daily basis. There are folks out there like the Paul Grahams of the world, that do wonderfully complex things in Lisp, eschew totally the facilities of the CLOS, the lisp object system, and get the job done ... just because they can hack and have a mind picture of what all the type matches are "in there head". I used to use forth, where everything goes on a stack, and it is up to the programmer to remember what the heck the type of a thing was that was stored there... maybe an address of a string, another word {read function}, or an integer... NO TYPING AT ALL, but can you be expressive in forth... You can if you are a good forth programmer... NOW that being said, I think that the reason I like Haskell, a very strongly typed language, is that because of it's type system, the language is able to do things like lazy evaluation, and then though it is strongly typed, and has wonderful things like type classes, a person can write wildly expressive code, and NEVER write a thing like: fromtoby :: forall b a. (Num a, Enum a) => a -> a -> a -> (a -> b) -> [b] The above was generated by the Haskell Compiler for me... and it does that all the time, without any fuss. I just wrote the function and it did the rest for me... By the way the function was a replacement for the { for / to / by } construct of like a C language and it was done in one line... THAT TO ME IS EXPRESSIVE, when I can build whole new features into my language in just a few lines... usually only one line.. I think that is why guys who are good to great in dynamic or if it floats your boat, type free languages like Lisp and Scheme find their languages so expressive, because they have found the macro's or whatever else facility to give them the power... to extend their language to meet a problem, or fit maybe closer to an entire class of problems.. giving them the tool box.. Haskeller', folks using Ruby, Python, ML, Ocaml, Unicon.... even C or whatever... By building either modules, or libraries... and understand that whole attitude of tool building.. can be equally as expressive "for their own way of doing things". Heck, I don't use one size of hammer out in my workshop, and I sure as hell don't on my box... I find myself picking up Icon and it's derivative Unicon to do a lot of data washing chores.. as it allows functions as first class objects... any type can be stored in a list... tables... like a hash ... with any type as the data and the key... you can do things like i := 0 every write(i+:=1 || read()) which will append a sequence of line numbers to the lines read in from stdin.. pretty damn concise and expressive in my book... Now for other problems .. Haskell with it's single type lists... which of course can have tuples, which themselves have tuples in them with a list as one element of that tuple... etc.. and you can build accessors for all of that for function application brought to bear on one element of one tuple allowing mappings of that function to all of that particular element of ... well you get the idea.. It is all about how you see things and how your particular mindset is... I would agree with someone that early on in the discussion said the thing about "type's warping your mind" and depending on the individual, it is either a good warp or a bad warp, but that is why there is Ruby and Python, and Haskell and even forth... for a given problem, and a given programmer, any one of those or even Cobol or Fortran might be the ideal tool... if nothing else based on that persons familiarity or existing tool and code base. enough out of me... -- gene From bill_maxwell_notMyRealAddress at notreal.net Fri Jun 23 01:00:20 2006 From: bill_maxwell_notMyRealAddress at notreal.net (Bill Maxwell) Date: Fri, 23 Jun 2006 01:00:20 -0400 Subject: Network Programming in Python References: <1151002934.586359.174540@m73g2000cwd.googlegroups.com> Message-ID: On 22 Jun 2006 12:02:14 -0700, diffuser78 at gmail.com wrote: >I am a newbie in python. I want to learn and implement a small >networking concept. Please help me. Every help is appreciated. > >I have one Linux Box and one Windows PC. I want to have a daemon >running on Windows PC which listens on some specicif port number. I >want to send a TCP/IP or UDP/IP packet from Linux box to Windows PC to >start some application. As Windows PC recieves such a packet from Linux >Box it executes a certain .exe file. I want to implement this concept. > >In short I want to remotely send command from Linux to Windows PC to >start a particular application. Have you checked out Pyro (Python Remote Objects)? http://pyro.sourceforge.net/ Bill From junkytownMAKNI at gmail.com Sat Jun 10 08:12:41 2006 From: junkytownMAKNI at gmail.com (SuperHik) Date: Sat, 10 Jun 2006 14:12:41 +0200 Subject: Most elegant way to generate 3-char sequence In-Reply-To: References: <1149889784.391965.271570@h76g2000cwa.googlegroups.com> Message-ID: James Stroud wrote: > SuperHik wrote: >> and the winner is... :D >> David Isaac wrote: >> >>> alpha = string.lowercase >>> x=(a+b+c for a in alpha for b in alpha for c in alpha) >> >> >> > > Not necessarily vying for winner, but David's solution is highly > specific as it doesn't do so well for something like > > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab > . > . > . > zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzy > zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz Right. But that wasn't the question :p > > > James > From noah.gift at gmail.com Thu Jun 22 08:13:08 2006 From: noah.gift at gmail.com (Noah Gift) Date: Thu, 22 Jun 2006 08:13:08 -0400 Subject: smtplib problem for newbie Message-ID: Hi, I am writing a few different scripts that need to send email confirmation and I wanted to use smtplib instead of cheating and using os.system('mail -s "foo"....) Some of the examples I have seen don't seem to work for me. (Note, I am new to Python and probably doing something stupid...thanks :) ) Here is one I grabbed http://effbot.org/librarybook/smtplib.htm import smtplib import string, sys HOST = "localhost" FROM = "effbot at spam.egg" TO = "fredrik at spam.egg" SUBJECT = "for your information!" BODY = "next week: how to fling an otter" body = string.join(( "From: %s" % FROM, "To: %s" % TO, "Subject: %s" % SUBJECT, "", BODY), "\r\n") print body server = smtplib.SMTP(HOST) server.sendmail(FROM, [TO], body) server.quit() If I change this to suit my needs it looks like this: #!/usr/bin/python import smtplib import string, sys HOST = "localhost" FROM = "johny.carson at turner.com" TO = "noah.gift at gmail.com" SUBJECT = "for your information!" BODY = "next week: how to fling an otter" body = string.join(( "From: %s" % FROM, "To: %s" % TO, "Subject: %s" % SUBJECT, "", BODY), "\r\n") print body server = smtplib.SMTP(HOST) server.sendmail(FROM, [TO], body) server.quit() When I run it I get this: Traceback (most recent call last): File "./3mail.py", line 2, in ? import smtplib File "/usr/lib64/python2.3/smtplib.py", line 49, in ? from email.base64MIME import encode as encode_base64 File "/usr/lib64/python2.3/email/base64MIME.py", line 28, in ? from email.Utils import fix_eols File "/usr/lib64/python2.3/email/Utils.py", line 10, in ? import random File "/usr/lib64/python2.3/random.py", line 818, in ? _inst = Random() File "/usr/lib64/python2.3/random.py", line 87, in __init__ self.seed(x) File "/usr/lib64/python2.3/random.py", line 100, in seed a = long(time.time() * 256) # use fractional seconds TypeError: 'module' object is not callable From apardon at forel.vub.ac.be Mon Jun 12 05:17:32 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 12 Jun 2006 09:17:32 GMT Subject: Killing a thread References: <7c8a9a970606091338t174fbcb0wc73cdb8b385f8ccd@mail.gmail.com> <7c8a9a970606091354u73308bf8o2758eea5ef690c39@mail.gmail.com> <1149889827.2754.6.camel@kenshin.CASA> Message-ID: Op 2006-06-10, Carl J. Van Arsdall schreef : > Felipe Almeida Lessa wrote: >> Em Sex, 2006-06-09 ?s 13:54 -0700, Manish Marathe escreveu: >> >>> On 6/9/06, Fredrik Lundh wrote: >>> Manish Marathe wrote: >>> >>> > I am creating threads using my self defined class which >>> inherits the >>> > threading.Thread class. I want to know how can I kill the >>> threads which >>> > are being created by the object of my self defined class. >>> >>> you cannot kill a thread "from the outside"; you have to >>> design your >>> thread tasks so they can kill themselves, when asked to do >>> that. >>> >>> Thanks for the reply. So can a thread listen to an event i.e. can we >>> send an event to the thread indicating to kill itself. >>> >> >> A plain simple boolean flag will certainly do the job. For example >> >> def run(self): >> self.running = True >> while self.running: >> blah() >> >> def stop(self): >> self.running = False >> >> > Well, this works if your threads are able to poll. If you had a thread > doing lengthy IO you could end up waiting a long time until the thread > gets an opportunity to kill itself. > > Are there any plans in the future to add the capability to kill threads > from the outside? There already is some capability, (if you mean from the outside that one thread can kill another) However for the momemt it is only available in the C API. But with the ctypes interface (which will be available with the stdlib from version 2.5) you can provide this functionality in python. > Better yet, an interruptable thread so instead of > using a polling loop you could send a DIE_THREAD_DIE signal or > something. I think at present its not possible (or a really bad idea) > to put signal handlers in threads. Anyone have thoughts on this? It is indeed impossible to let a thread handle a signal. You can set a handler in a thread but when a signal arrives. But here is a class I toyed with, that can be used to throw an exception in one thread from another. There are some caveats however. It won't interupt C-calls. So if the thread you want to raise the exception in, is in a C-extention, the extention will have to finish before the exception will be raised. ----------------------------------------------------------------------- import ctypes from time import sleep SetAsyncExc = ctypes.pythonapi.PyThreadState_SetAsyncExc class TimeOut(Exception): pass class Alarm(Exception): pass import threading class Xthread(threading.Thread): def start(self): self.__original_run = self.run self.run = self.__run threading.Thread.start(self) def __run(self): self._thrd_id = threading._get_ident() try: self.__original_run() finally: self.run = self.__original_run def throw(self, excpt): Nr = SetAsyncExc(self._thrd_id, ctypes.py_object(excpt)) while Nr > 1: SetAsyncExc(self._thrd_id, None) sleep(0.1) Nr = SetAsyncExc(self._thrd_id, ctypes.py_object(excpt)) def alarm(self, tm): alrm = threading.Timer(tm, self.throw, (TimeOut,)) alrm.start() return alrm if __name__ == "__main__": import os from random import randint class Continue(Xthread): def run(self): self.id = os.getpid() print self.id, self._thrd_id, "Begin" i = 0 try: for _ in xrange(randint(0,20)): for e in xrange(4 * 100000): i = i + e print self.id, self._thrd_id, "Finished" except Alarm: print self.id, self._thrd_id, "Interupted" lst = [Continue() for _ in xrange(10)] for T in lst: T.start() try: sleep(10) finally: for T in lst: T.throw(Alarm) -- Antoon Pardon From td_01 at att.net.invalid Mon Jun 19 23:52:34 2006 From: td_01 at att.net.invalid (Tom Del Rosso) Date: Tue, 20 Jun 2006 03:52:34 GMT Subject: Active Python versions References: <2hElg.41514$mF2.19600@bgtnsc04-news.ops.worldnet.att.net> <1150769349.111390.280450@y41g2000cwy.googlegroups.com> Message-ID: <6iKlg.218015$Fs1.37529@bgtnsc05-news.ops.worldnet.att.net> Thanks very much guys. -- Reply in group, but if emailing add another zero, and remove the last word. From pink at odahoda.de Mon Jun 12 06:20:26 2006 From: pink at odahoda.de (Benjamin Niemann) Date: Mon, 12 Jun 2006 12:20:26 +0200 Subject: urllib behaves strangely References: Message-ID: Gabriel Zachmann wrote: > Here is a very simple Python script utilizing urllib: > > import urllib > url = > "http://commons.wikimedia.org/wiki/Commons:Featured_pictures/chronological" > print url > print > file = urllib.urlopen( url ) > mime = file.info() > print mime > print file.read() > print file.geturl() > > > However, when i ecexute it, i get an html error ("access denied"). > > On the one hand, the funny thing though is that i can view the page fine > in my browser, and i can download it fine using curl. > > On the other hand, it must have something to do with the URL because > urllib works fine with any other URL i have tried ... > > Any ideas? > I would appreciate very much any hints or suggestions. The ':' in '..Commons:Feat..' is not a legal character in this part of the URI and has to be %-quoted as '%3a'. Try the URI 'http://commons.wikimedia.org/wiki/Commons%3aFeatured_pictures/chronological', perhaps urllib is stricter than your browsers (which are known to accept every b******t you feed into them, sometimes with very confusing results) and gets confused when it tries to parse the malformed URI. -- Benjamin Niemann Email: pink at odahoda dot de WWW: http://pink.odahoda.de/ From skip at pobox.com Thu Jun 29 11:11:41 2006 From: skip at pobox.com (skip at pobox.com) Date: Thu, 29 Jun 2006 10:11:41 -0500 Subject: Python docs bug In-Reply-To: <1151593209.084822.207460@j72g2000cwa.googlegroups.com> References: <1151593209.084822.207460@j72g2000cwa.googlegroups.com> Message-ID: <17571.60845.33044.994034@montanaro.dyndns.org> >> One long-standing irritation I have with the table of contents for >> the Python Library Reference , >> is that there is one very important section, "String Methods" >> , which does not >> appear there. That's because it is section 2.3.6.1, and the table of >> contents only goes to 3 levels. John> I've found that to be quite irritating as well. Maybe someone should submit a bug report on SF... Skip From gdr at integrable-solutions.net Sun Jun 25 13:47:32 2006 From: gdr at integrable-solutions.net (Gabriel Dos Reis) Date: 25 Jun 2006 19:47:32 +0200 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150908952.804184.218990@r2g2000cwb.googlegroups.com> <1150991074.705803.211570@m73g2000cwd.googlegroups.com> <1151244628.566060.40500@p79g2000cwp.googlegroups.com> <1151252226.104247.62960@b68g2000cwa.googlegroups.com> Message-ID: rossberg at ps.uni-sb.de writes: | Gabriel Dos Reis wrote: | > | | > | (Unfortunately, you can hardly write interesting programs in any safe | > | subset of C.) | > | > Fortunately, some people do, as living job. | | I don't think so. Maybe the question is what a "safe subset" consists | of. In my book, it excludes all features that are potentially unsafe. if you equate "unsafe" with "potentially unsafe", then you have changed gear and redefined things on the fly, and things that could be given sense before ceases to have meaning. I decline following such an uncertain, extreme, path. | So in particular, C-style pointers are out, because they can easily | dangle, be uninitialisied, whatever. sorry, the specific claim I was responding to is not whether *you* can easily misuse C constructs. I would refrain from generalizing your inability to write interesting correct programs in C, to a quality of the language itself. Rather, the claim I was responding to is this: (Unfortunately, you can hardly write interesting programs in any safe subset of C.) I would suggest you give more thoughts to the claims made in http://www.seas.upenn.edu/~sweirich/types/archive/1999-2003/msg00298.html -- Gaby From johnjsal at NOSPAMgmail.com Thu Jun 8 15:44:46 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 08 Jun 2006 19:44:46 GMT Subject: follow-up to FieldStorage In-Reply-To: <1149795535.513230.85290@y43g2000cwc.googlegroups.com> References: <4484b428$0$29635$636a55ce@news.free.fr> <1149795535.513230.85290@y43g2000cwc.googlegroups.com> Message-ID: Gerard Flanagan wrote: > John Salerno wrote: >> Bruno Desthuilliers wrote: >>> John Salerno a ?crit : >>>> If I want to get all the values that are entered into an HTML form and >>>> write them to a file, is there some way to handle them all at the same >>>> time, or must FieldStorage be indexed by each specific field name? >>> AFAIK, FieldStorage is a somewhat dict-like object, but I'm not sure it >>> supports the whole dict interface. At least, it does support keys(), so >>> you should get by with: >>> >>> for k in fs.keys(): >>> print >> myfile, k, ":", fs[k] >>> >>> But reading the doc may help... >> Thanks. The cgi docs don't seem to get into too much detail, unless I >> wasn't thorough enough. But your method seems like it might work well if >> I can't find something after another read through. > > this any use: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81547 > > ? > > Gerard > Very interesting! From luismgz at gmail.com Tue Jun 13 01:18:29 2006 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 12 Jun 2006 22:18:29 -0700 Subject: Very nice python IDE (windows only) In-Reply-To: <1150167923.112598.194230@u72g2000cwu.googlegroups.com> References: <1149694235.741274.325200@u72g2000cwu.googlegroups.com> <1150167923.112598.194230@u72g2000cwu.googlegroups.com> Message-ID: <1150175909.805928.327590@h76g2000cwa.googlegroups.com> Jonathan Ellis wrote: > ago wrote: > > I have just discovered Python Scripter by Kiriakos Vlahos and it was a > > pleasant surprise. I thought that it deserved to be signalled. It is > > slim and fairly fast, with embedded graphical debugger, class browser, > > file browser... If you are into graphical IDEs you are probably going > > to enjoy it. Windows only unfortunately. > > > > http://mmm-experts.com/Products.aspx?ProductId=4 > > Not to rain on anyone's parade, but I'd recommend using an IDE that > isn't based on an obviously dead-end platform. (PyScripter is written > in Delphi.) > > -Jonathan As long as people keep on using win32, it will be just fine. After that, who knows what would be the best option? Delphi.Net perhaps? From hdante at gmail.com Wed Jun 21 02:44:12 2006 From: hdante at gmail.com (hdante at gmail.com) Date: 20 Jun 2006 23:44:12 -0700 Subject: need all python dialog equivalent References: Message-ID: <1150872252.418400.13070@i40g2000cwc.googlegroups.com> dialog binary is 110 KB. Won't it fit ? Eric S. Johansson wrote: > I'm creating a dialogue style interface for an application on a > dedicated system. All I have is basic Python 2.3. Is there anything > like an all Python dialog equivalent floating around? I'm currently > hacking away in curses but it's taking me a long way down what I fear to > be a wrong path. > > I've looked at the Python dialog web site but it clearly states that it > is a wrapper around dialogue/Xdialog. > > suggestions would be most welcome. > > ---eric From johnjsal at NOSPAMgmail.com Mon Jun 12 16:50:40 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 12 Jun 2006 20:50:40 GMT Subject: wxpython: how do i write this without the id parameter? Message-ID: I was reading in the wxPython wiki that most of the time you don't have to include the id parameter at all, and you can just use keyword arguments for other parameters. But I'm having trouble converting this code into that method (i.e., without the id parameter). I keep getting errors that involve wrong parameters, or that they are out of order, etc. So I'm hoping someone can show me how to re-write the constructors for InputForm and wx.Frame, as well as the __init__ method, so that they will just deal with parent and title. Also, the two buttons have an id parameter, but leaving them out doesn't seem to create any problems. Thanks. ----------- import wx class InputForm(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title) panel = wx.Panel(self) self.btnOK = wx.Button(panel, label='OK') self.btnCancel = wx.Button(panel, label='Cancel') sizer = wx.BoxSizer(wx.HORIZONTAL) sizer.Add(self.btnOK, 0, wx.ALL, 10) sizer.Add(self.btnCancel, 0, wx.ALL, 10) panel.SetSizer(sizer) class MyApp(wx.App): def OnInit(self): frame = InputForm(None, -1, title='Data Entry Form') self.SetTopWindow(frame) frame.Show() return True app = MyApp(redirect=False) app.MainLoop() From rossberg at ps.uni-sb.de Fri Jun 23 13:32:11 2006 From: rossberg at ps.uni-sb.de (rossberg at ps.uni-sb.de) Date: 23 Jun 2006 10:32:11 -0700 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150908952.804184.218990@r2g2000cwb.googlegroups.com> <1150991074.705803.211570@m73g2000cwd.googlegroups.com> <1151083239.829296.33030@i40g2000cwc.googlegroups.com> Message-ID: <1151083931.162325.268050@g10g2000cwb.googlegroups.com> Rob Thorpe wrote: > > But it differs from latently typed languages like python, perl or lisp. > In such a language there is no information about the type the variable > stores. The programmer cannot write code to test it, and so can't > write functions that issue errors if given arguments of the wrong type. > The programmer must use his or her memory to substitute for that > facility. As far as I can see this is a significant distinction and > warrants a further category for latently typed languages. Take one of these languages. You have a variable that is supposed to store functions from int to int. Can you test that a given function meets this requirement? You see, IMO the difference is marginal. From my point of view, the fact that you can do such tests *in some very trivial cases* in the languages you mention is an artefact, nothing fundamental. - Andreas From grante at visi.com Wed Jun 21 09:58:40 2006 From: grante at visi.com (Grant Edwards) Date: Wed, 21 Jun 2006 13:58:40 -0000 Subject: need all python dialog equivalent References: <1150872252.418400.13070@i40g2000cwc.googlegroups.com> Message-ID: <129ik4g7to9hffc@corp.supernews.com> On 2006-06-21, Eric S. Johansson wrote: > hdante at gmail.com wrote: >> dialog binary is 110 KB. Won't it fit ? > > missing library. I have ncurses and newt and dialog seems to require > something called ncursesw. I've been trying to find the Python newt > module as well and that seems to be as invisible as the creature it's > named after. The most recent version of newt I've got is at ftp://ftp.visi.com/users/grante/stuff/newt-0.50.tar.gz The python module is called "snack" -- Grant Edwards grante Yow! Yow! Am I cleansed at yet?! visi.com From xivulon at gmail.com Wed Jun 7 14:18:12 2006 From: xivulon at gmail.com (ago) Date: 7 Jun 2006 11:18:12 -0700 Subject: Very nice python IDE (windows only) In-Reply-To: References: <1149694235.741274.325200@u72g2000cwu.googlegroups.com> <1149701880.540109.10100@y43g2000cwc.googlegroups.com> Message-ID: <1149704292.676501.138530@h76g2000cwa.googlegroups.com> Bernard Lebel wrote: > Not me. I'll probably sound pedantic but > - the editor text looks awful, changing the editor options had no effect at all > - there is no network access of UNC paths other than through File > > Open and Python Paths..... all of my code is on a network location > - expanding and collapsing directories is done with a transition > effect.... that drives me nuts You can certainly change the font of the editor (Tools>Options>Editor Options>Display>Editor Font>Font), not to be confused with the font of the Gutter which only changes the font inside the left bar (i.e. for line numbers). Admittedly there are not too many fonts to choose from. From rosario_morgan at yahoo.com Wed Jun 14 01:14:31 2006 From: rosario_morgan at yahoo.com (Rosario Morgan) Date: Wed, 14 Jun 2006 05:14:31 -0000 Subject: Looping through a file a block of text at a time not by line Message-ID: Hello Help is great appreciated in advance. I need to loop through a file 6000 bytes at a time. I was going to use the following but do not know how to advance through the file 6000 bytes at a time. file = open('hotels.xml') block = file.read(6000) newblock = re.sub(re.compile(r''),'',block) print newblock I cannot use readlines because the file is 138MB all on one line. Suggestions? -Rosario From sjmachin at lexicon.net Sun Jun 4 00:47:40 2006 From: sjmachin at lexicon.net (John Machin) Date: Sun, 04 Jun 2006 14:47:40 +1000 Subject: Hostmask matching In-Reply-To: References: Message-ID: <448265ed@news.eftel.com> On 4/06/2006 1:57 PM, Nexu wrote: > I'm trying to write a def Perhaps you mean a function? > to match a string that is an irc hostmask. eg: > *one!~*name at a??-??-101-101.someisp.com > But using re.search(). If you want to find an IRC hostmask in some longer string, yes, use re.search(). However if you want to check that a given string could be an IRC hostmask, use re.match(). > I get an error when the string starts with '*'. Do you get an error when the searched string starts with anything else? > What is the best way to solve this? > A reasonable way would be to ask a question that includes the minimum useful information, so that would-be helpers are not forced to guess: 1. your inputs (the re pattern, and the searched string) 2. the expected outcome (match object that spans which part of the searched string) 3. the actual outcome (copy/paste of the traceback and error message that you got) Another way might be to Read The Fantastic Manual, in particular the section on re syntax, and nut out the answer your self. In any case, here's my guess as to what's going down: 1. You mean that the pattern starts with '*', not the searched string. 2. The error that you got was something like this: [snip] File "C:\Python24\lib\sre.py", line 180, in compile return _compile(pattern, flags) File "C:\Python24\lib\sre.py", line 227, in _compile raise error, v # invalid expression sre_constants.error: nothing to repeat 3. You haven't read this part of The Fantastic Manual: "\" Either escapes special characters (permitting you to match characters like "*", "?", and so forth), or ... === As well as TFManual, there's also a HOWTO: http://www.amk.ca/python/howto/regex/ HTH, John From ripleyfu at gmail.com Wed Jun 7 22:20:44 2006 From: ripleyfu at gmail.com (ripley) Date: 7 Jun 2006 19:20:44 -0700 Subject: Python language problem In-Reply-To: <1rvd821f13586ak592kh80gautogc79uq5@4ax.com> References: <1149678146.681370.5130@c74g2000cwc.googlegroups.com> <1149680274.133008.167140@c74g2000cwc.googlegroups.com> <1rvd821f13586ak592kh80gautogc79uq5@4ax.com> Message-ID: <1149733244.709724.5800@i40g2000cwc.googlegroups.com> Thanks all, you all are nice man. Dennis Lee Bieber ??? > while len(lst): #list is a built-in function, don't use as a name > del lst[0] #delete the first item IN the lst > I found Dennis 's code is usefull that is a way to solve my problem. From bj_666 at gmx.net Fri Jun 23 10:33:56 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Fri, 23 Jun 2006 16:33:56 +0200 Subject: re question References: Message-ID: In , Daniel Sch?le wrote: > this is the pattern > > pattern = > re.compile(r'^\s*package\s+(?P\w+)\s+is\s+(?P.*?)\s+end(\s+package)?(\s+(?P=name))?\s*;', > re.DOTALL | re.MULTILINE | re.IGNORECASE) > > and the problem is that > package TEST is xyz end; > works but > package TEST123 is xyz end; > fails For me both work: In [11]:pattern = ( t>.*?)\s+end(\s+package)?(\s+(?P=name))?\s*;', )\s+is\s+(?P In [13]:pattern.match('package TEST123 is xyz end;') Out[13]:<_sre.SRE_Match object at 0x405b15f8> I have copy and pasted you code. For debugging re's in Python you might take a look at http://kodos.sourceforge.net/ Ciao, Marc 'BlackJack' Rintsch From duncan.booth at invalid.invalid Wed Jun 28 14:39:43 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 28 Jun 2006 18:39:43 GMT Subject: Immutability References: Message-ID: Georg Brandl wrote: > In my opinion property isn't really meant to be used as a decorator since > it's impossible to create a read-write property. The decorator pattern > doesn't really fit here. > I agree that property isn't currently intended to be used as a decorator, but it isn't actually *impossible* to create a read-write property using decorators. Here is one way: --------- props.py ---------------- from inspect import getouterframes, currentframe import unittest class property(property): @classmethod def get(cls, f): locals = getouterframes(currentframe())[1][0].f_locals prop = locals.get(f.__name__, property()) return cls(f, prop.fset, prop.fdel, prop.__doc__) @classmethod def set(cls, f): locals = getouterframes(currentframe())[1][0].f_locals prop = locals.get(f.__name__, property()) return cls(prop.fget, f, prop.fdel, prop.__doc__) @classmethod def delete(cls, f): locals = getouterframes(currentframe())[1][0].f_locals prop = locals.get(f.__name__, property()) return cls(prop.fget, prop.fset, f, prop.__doc__) class PropTests(unittest.TestCase): def test_setgetdel(self): class C(object): def __init__(self, colour): self._colour = colour @property.set def colour(self, value): self._colour = value @property.get def colour(self): return self._colour @property.delete def colour(self): self._colour = 'none' inst = C('red') self.assertEquals(inst.colour, 'red') inst.colour = 'green' self.assertEquals(inst._colour, 'green') del inst.colour self.assertEquals(inst._colour, 'none') if __name__=='__main__': unittest.main() ----------------------------------- From david.nospam.hopwood at blueyonder.co.uk Fri Jun 23 21:29:26 2006 From: david.nospam.hopwood at blueyonder.co.uk (David Hopwood) Date: Sat, 24 Jun 2006 01:29:26 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150904134.520639.71070@b68g2000cwa.googlegroups.com> <4padnQn3SOWhkQfZnZ2dnUVZ_rqdnZ2d@speakeasy.net> Message-ID: Anton van Straaten wrote: > Andreas Rossberg wrote: >> Rob Warnock wrote: >> >>> http://www.schemers.org/Documents/Standards/R5RS/HTML/r5rs-Z-H-4.html >>> 1.1 Semantics >>> ... >>> Scheme has latent as opposed to manifest types. Types are assoc- >>> iated with values (also called objects) rather than with variables. >>> (Some authors refer to languages with latent types as weakly typed >>> or dynamically typed languages.) Other languages with latent types >>> are APL, Snobol, and other dialects of Lisp. Languages with manifest >>> types (sometimes referred to as strongly typed or statically typed >>> languages) include Algol 60, Pascal, and C. >> [...] > > That text goes back at least 20 years, to R3RS in 1986, and possibly > earlier, so part of what it represents is simply changing use of > terminology, combined with an attempt to put Scheme in context relative > to multiple languages and terminology usages. The fact that we're still > discussing this now, and haven't settled on terminology acceptable to > all sides, illustrates the problem. > > The Scheme report doesn't actually say anything about how latent types > relate to static types, in the way that I've recently characterized the > relationship here. However, I thought this was a good place to explain > how I got to where I am on this subject. > > There's been a lot of work done on soft type inference in Scheme, and > other kinds of type analysis. The Scheme report talks about latent > types as meaning "types are associated with values". While this might > cause some teeth-grinding amongst type theorists, it's meaningful enough > when you look at simple cases: cases where the type of a term is an > exact match for the type tags of the values that flow through that term. > > When you get to more complex cases, though, most type inferencers for > Scheme assign traditional static-style types to terms. If you think > about this in conjunction with the term "latent types", it's an obvious > connection to make that what the inferencer is doing is recovering types > that are latent in the source. But these types are not part of the Scheme language. If you combine Scheme with a type inferencer, you get a new language that is not R*RS Scheme, and *that* language is typed. Note that different inferencers will give different type assignments. They may be similar, but they may also be quite dissimilar in some cases. This casts considerable doubt on the assertion that the inferencer is "recovering types latent in the source". -- David Hopwood From david.nospam.hopwood at blueyonder.co.uk Sat Jun 24 11:15:51 2006 From: david.nospam.hopwood at blueyonder.co.uk (David Hopwood) Date: Sat, 24 Jun 2006 15:15:51 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150908952.804184.218990@r2g2000cwb.googlegroups.com> <1150991074.705803.211570@m73g2000cwd.googlegroups.com> <1151083239.829296.33030@i40g2000cwc.googlegroups.com> <1151083931.162325.268050@g10g2000cwb.googlegroups.com> <1151086320.564736.272500@y41g2000cwy.googlegroups.com> <1151100483.057344.310970@g10g2000cwb.googlegroups.com> Message-ID: Dr.Ruud wrote: > Marshall schreef: >>Rob Thorpe: > >>>Can I make a type in C that can only have values between 1 and 10? >>>How about a variable that can only hold odd numbers, or, to make it >>>more difficult, say fibonacci numbers? >> >>Well, of course you can't in *C*; you can barely zip you pants with C. >>But I believe you can do the above in C++, can't you? > > You can write self-modifying code in C, so I don't see how you can not > do that in C. ;) Strictly speaking, you can't write self-modifying code in Standard C. -- David Hopwood From mikeminer53 at hotmail.com Fri Jun 23 14:19:47 2006 From: mikeminer53 at hotmail.com (mkPyVS) Date: 23 Jun 2006 11:19:47 -0700 Subject: Flight search automation In-Reply-To: <1151073635.181128.15460@m73g2000cwd.googlegroups.com> References: <1151069276.861472.292270@r2g2000cwb.googlegroups.com> <1151070415.237973.265400@c74g2000cwc.googlegroups.com> <1151073635.181128.15460@m73g2000cwd.googlegroups.com> Message-ID: <1151086787.337886.69830@u72g2000cwu.googlegroups.com> If you look at the <> generated HTML @Travelocity **Snippet function on_load() { var finurl = "AirSearch.do?SEQ=11510863338485232006"; window.location.replace(finurl); ** It is basically a re-direct.. you should be able to re-request an HTTP to the base path from the original query w/ your new URL for the session result. Base URL= http://travel.travelocity.com/flights So now you would request http://travel.travelocity.com/flights/AirSearch.do?SEQ=11510863338485232006 George Sakkis wrote: > mkPyVS wrote: > > > Is there an http page redirect call to the client once the java > > releases it's wait que? > > Sorry, I've no idea.. not even sure if they use java or whether this > matters. Can you guess by trying, say, http://www.travelocity.com/ ? > Expedia and Orbitz have also a waiting page, hopefully I can figure > them out once I have one working. > > George > > > George Sakkis wrote: > > > I'm trying to use mechanize to fill in a "find a flight" form and then > > > get back the results, but I'm not sure how to make it wait until the > > > results page appears; the response after submitting the form is the > > > "please wait while we are searching for your flights" page. Any ideas ? > > > > > > George From jeremiah.bess at gmail.com Thu Jun 22 17:36:08 2006 From: jeremiah.bess at gmail.com (Network Ninja) Date: 22 Jun 2006 14:36:08 -0700 Subject: Clearing pythonwin environment Message-ID: <1151012168.838694.235610@c74g2000cwc.googlegroups.com> I want to restart the environment occasionally to default (like I restarted pythonwin). I wrote this script. I know why it doesn't work, cause it deletes my variable (item) on each iteration. My question is: is it possible to do this? What other things might I try? # Reset Pythonwin enviroment # Variables keep = ['__builtins__', '__doc__', '__name__', 'pywin', 'keep', 'item'] print for item in dir(): if item not in keep: del item print print dir() From dnew at san.rr.com Wed Jun 21 13:12:40 2006 From: dnew at san.rr.com (Darren New) Date: Wed, 21 Jun 2006 17:12:40 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <0%Wlg.3521$MF6.947@tornado.socal.rr.com> <44992e6c$0$664$bed64819@news.gradwell.net> Message-ID: Andreas Rossberg wrote: > Maybe I don't understand what you mean with ADT here, but all languages > with a decent module system support ADTs in the sense it is usually > understood, see ML for a primary example. OK. Maybe some things like ML and Haskell and such that I'm not intimately familiar with do, now that you mention it, yes. > Classes in most OOPLs are essentially beefed-up ADTs as well. Err, no. There's nothing really abstract about them. And their values are mutable. So while one can think about them as an ADT, one actually has to write code to (for example) calculate or keep track of how many entries are on a stack, if you want that information. > Not counting C/C++, I don't know when I last worked with a typed > language that does *not* have this ability... (which is slightly > different from ADTs, btw) Java? C#? Icon? Perl? (Hmmm... Pascal does, IIRC.) I guess you just work with better languages than I do. :-) -- Darren New / San Diego, CA, USA (PST) My Bath Fu is strong, as I have studied under the Showerin' Monks. From jes at nl.demon.net Thu Jun 1 18:11:21 2006 From: jes at nl.demon.net (Jim Segrave) Date: Thu, 01 Jun 2006 22:11:21 -0000 Subject: grouping a flat list of number by range References: <1149196642.001466.53990@c74g2000cwc.googlegroups.com> Message-ID: <127upg9qbf0b3f2@corp.supernews.com> In article <1149196642.001466.53990 at c74g2000cwc.googlegroups.com>, wrote: >hello, > >i'm looking for a way to have a list of number grouped by consecutive >interval, after a search, for example : > >[3, 6, 7, 8, 12, 13, 15] > >=> > >[[3, 4], [6,9], [12, 14], [15, 16]] > >(6, not following 3, so 3 => [3:4] ; 7, 8 following 6 so 6, 7, 8 => >[6:9], and so on) > >i was able to to it without generators/yield but i think it could be >better with them, may be do you an idea? There are probably better ways, but this works > >best regards, > >J. class IterInterval(object): """Create an iterator which, given a list of integers, for each run of consecutive integers i...j, yields a two element list [i, j + 1] Singleton lists [i] return [i, i + 1] Empty lists return None """ def __init__(self, seq): self.seq = seq self.firstval = None self.index = 0 def __iter__(self): # firstval = the start of a run of consecutive integers # lastval = the last value found in the run # nextval = the most recent value taken from the input list if not self.firstval: # set up the first iteration if self.index >= len(self.seq): # empty list, return raise StopIteration self.firstval = lastval = int(self.seq[self.index]) self.index += 1 while True: if self.index >= len(self.seq): # list exhausted, output the last value read yield [self.firstval, lastval + 1] raise StopIteration nextval = int(self.seq[self.index]) self.index += 1 if nextval == lastval + 1: lastval = nextval continue else: # end of run - output the run, reset for next call yield [self.firstval, lastval + 1] self.firstval = lastval = nextval continue if __name__ == '__main__': for l in [[3, 6, 7, 8, 12, 13, 15], [2], []]: print l, "=>", [lst for lst in IterInterval(l)] /usr/home/jes% python interval.py [3, 6, 7, 8, 12, 13, 15] => [[3, 4], [6, 9], [12, 14], [15, 16]] [3] => [[3, 4]] [] => [] -- Jim Segrave (jes at jes-2.demon.nl) From zabaione at uk2.net Tue Jun 13 14:11:40 2006 From: zabaione at uk2.net (freesteel) Date: 13 Jun 2006 11:11:40 -0700 Subject: embedded python and windows multi threading, can't get it to work Message-ID: <1150222300.661239.5870@u72g2000cwu.googlegroups.com> I am trying to run a python programme embedded from C++. I want to run the same python code concurrently in several threads. I read the manual on embedding, especially chapter 8, and searched for relevant info on google all afternoon, but I can't get this to work. What am I doing wrong? I use python2.4 and vc++7 (.net). The first thread seems to work okay, the 2nd thread crashes, but the exception information is not very useful: (An unhandled exception of type 'System.NullReferenceException' occurred in pyembed_test.exe Additional information: Object reference not set to an instance of an object.) Here is a simplified example, it is heavily based on this article: http://www.codeproject.com/cpp/embedpython_1.asp #include #include #include #include #define USE_AFX 0 #if USE_AFX UINT MyThread(LPVOID lpParam) #else void MyThread(void* lpParam) #endif { Py_Initialize(); //#if 0 // PyEval_InitThreads(); PyThreadState *mainthreadstate = PyThreadState_Get(); PyInterpreterState *maininterpreterstate = mainthreadstate->interp; PyThreadState *mythreadstate = PyThreadState_New(maininterpreterstate); PyEval_ReleaseLock(); PyEval_AcquireLock(); PyThreadState *tmpstate = PyThreadState_Swap(mythreadstate); //#endif int* num = (int *)lpParam; int ret = 0; ret = PyRun_SimpleString("x = []"); ret = PyRun_SimpleString("for i in range(10):\n x.append(i)"); char cmd[100]; sprintf(cmd, "f = open('test%d.txt', 'w')", *num); ret = PyRun_SimpleString(cmd); ret = PyRun_SimpleString("f.write('%s' % x.__str__())"); ret = PyRun_SimpleString("f.close()"); //#if 0 PyThreadState_Swap(tmpstate); PyEval_ReleaseLock(); PyThreadState_Clear(mythreadstate); PyThreadState_Delete(mythreadstate); //#endif Py_Finalize(); #if USE_AFX return 0; #else _endthread(); #endif } class CMyWinApp : public CWinApp { public: CMyWinApp() { } BOOL InitInstance() { int num0 = 0, num1 = 1; HANDLE hnd0, hnd1; #if USE_AFX CWinThread* pThread0 = AfxBeginThread(MyThread, &num0); hnd0 = pThread0->m_hThread; CWinThread* pThread1 = AfxBeginThread(MyThread, &num1); hnd1 = pThread1->m_hThread; #else hnd0 = (HANDLE) _beginthread(MyThread, 0, &num0); hnd1 = (HANDLE) _beginthread(MyThread, 0, &num1); #endif // wait for the worker thread to terminate. WaitForSingleObject(hnd0, INFINITE); WaitForSingleObject(hnd1, INFINITE); return TRUE; }; }; CMyWinApp app; From jo at durchholz.org Sat Jun 17 07:03:19 2006 From: jo at durchholz.org (Joachim Durchholz) Date: Sat, 17 Jun 2006 13:03:19 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: <2006061618250975249-raffaelcavallaro@pasdespamsilvousplaitmaccom> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <2006061410510511272-raffaelcavallaro@pasdespamsilvousplaitmaccom> <2006061501423327544-raffaelcavallaro@pasdespamsilvousplaitmaccom> <2006061611492350073-raffaelcavallaro@pasdespamsilvousplaitmaccom> <2006061618250975249-raffaelcavallaro@pasdespamsilvousplaitmaccom> Message-ID: Raffael Cavallaro schrieb: > On 2006-06-16 17:59:07 -0400, Joachim Durchholz said: > >> I think it's easier to start with a good (!) statically-typed language >> and relax the checking, than to start with a dynamically-typed one and >> add static checks. > > This is purely a matter of programming style. For explorative > programming it is easier to start with dynamic typing and add static > guarantees later rather than having to make decisions about > representation and have stubs for everything right from the start. Sorry for being ambiguous - I meant to talk about language evolution. I agree that static checking could (and probably should) be slightly relaxed: compilers should still do all the diagnostics that current-day technology allows, but any problems shouldn't abort the compilation. It's always possible to generate code that will throw an exception as soon as a problematic piece of code becomes actually relevant; depending on the kind of run-time support, this might abort the program, abort just the computation, or open an interactive facility to correct and/or modify the program on the spot (the latter is the norm in highly dynamic systems like those for Lisp and Smalltalk, and I consider this actually useful). I don't see static checking and explorative programming as opposites. Of course, in practice, environments that combine these don't seem to exist (except maybe in experimental or little-known state). Regards, Jo From listserver at tdw.net Mon Jun 26 11:52:00 2006 From: listserver at tdw.net (Tim Williams) Date: Mon, 26 Jun 2006 16:52:00 +0100 Subject: Search String for Word In-Reply-To: References: <1151332947.985001.226510@r2g2000cwb.googlegroups.com> Message-ID: <9afea2ac0606260852q1dbae28re23504194e3309da@mail.gmail.com> On 26 Jun 2006 08:24:54 -0700, digitalorganics at gmail.com wrote: > And what if I want to search for an item in a tuple, is there a > similarly easy method? > > Tim Chase wrote: > > > What's the best way to search a string for a particular word and get a > > > booleen value indicating whether it exists in the string or not? > > > > >>> substring = 'foo' > > >>> targetstring = 'blah foo bar' > > >>> substring in targetstring > > True > > >>> if substring in targetstring: print 'yup' > > yup >>> t = ('a', 'b', 'c', 'd', 'e') >>> a = 'a' >>> a in t True >>> y = 'y' >>> y in t False >>> t = ('test', 'black', 'white') >>> a = 'a' >>> [i for i in t if a in i] ['black'] >>> HTH :) From deets at nospam.web.de Sat Jun 10 06:09:23 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 10 Jun 2006 12:09:23 +0200 Subject: Killing a thread In-Reply-To: References: <7c8a9a970606091338t174fbcb0wc73cdb8b385f8ccd@mail.gmail.com> <7c8a9a970606091354u73308bf8o2758eea5ef690c39@mail.gmail.com> <1149889827.2754.6.camel@kenshin.CASA> Message-ID: <4evk2jF1h5v0dU1@uni-berlin.de> > Are there any plans in the future to add the capability to kill threads > from the outside? Better yet, an interruptable thread so instead of > using a polling loop you could send a DIE_THREAD_DIE signal or > something. I think at present its not possible (or a really bad idea) > to put signal handlers in threads. Anyone have thoughts on this? Thought - many people. And it seems to be a bad idea. I once used PyQt QThreads, because they allowed me to do it. Which immediately crashed my omniORB ORB when terminating a thread. I didn't investigate why, but I guess you are pretty much on your own releasing resources and the like. And that gets very tedious very fast. > I toyed with another idea (this is a big problem for me), but I noticed > that each python thread spawns a new interpreter. If python is doing > this, I would think that each thread could be associated with PIDs or > something. I haven't thought about it too much, its a little to > crazy/brute force for me, but I thought i'd throw it out there so you > guys could tell me if that one is a little too far fetched. Python uses the underlying OS thread implementation. It does _not_ spawn new threads. I guess you are using a LINUX that lists individual threads as subprocesses. But that is a n implementation detail that can be configured away AFAIK. Or at least it doesn't happen on _all_ linuxes. So you're out of luck there, too. Diez From marshall.spight at gmail.com Thu Jun 22 11:03:45 2006 From: marshall.spight at gmail.com (Marshall) Date: 22 Jun 2006 08:03:45 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: <4fv84rF1kp06kU1@individual.net> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150902275.129780.50260@p79g2000cwp.googlegroups.com> <1150918629.818145.143220@y41g2000cwy.googlegroups.com> <4fv081F1jh4ifU1@individual.net> <1150967543.947096.72840@g10g2000cwb.googlegroups.com> <4fv84rF1kp06kU1@individual.net> Message-ID: <1150988625.527780.148710@c74g2000cwc.googlegroups.com> Pascal Costanza wrote: > > Consider a simple expression like 'a + b': In a dynamically typed > language, all I need to have in mind is that the program will attempt to > add two numbers. In a statically typed language, I additionally need to > know that there must a guarantee that a and b will always hold numbers. I still don't really see the difference. I would not expect that the dynamic programmer will be thinking that this code will have two numbers most of the time but sometimes not, and fail. I would expect that in both static and dynamic, the thought is that that code is adding two numbers, with the difference being the static context gives one a proof that this is so. In this simple example, the static case is better, but this is not free, and the cost of the static case is evident elsewhere, but maybe not illuminated by this example. This thread's exploration of the mindset of the two kinds of programmers is difficult. It is actually quite difficult, (possibly impossible) to reconstruct mental states though introspection. Nonetheless I don't see any other way to proceed. Pair programming? > My goal is not to convince anyone, my goal is to illustrate for those > who are interested in getting a possibly different perspective. Yes, and thank you for doing so. Marshall From gandalf at designaproduct.biz Fri Jun 16 09:38:48 2006 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Fri, 16 Jun 2006 15:38:48 +0200 Subject: Pycrypto In-Reply-To: <1150462237.224431.213020@c74g2000cwc.googlegroups.com> References: <1150446904.527285.255170@g10g2000cwb.googlegroups.com> <1150458752.342042.189650@h76g2000cwa.googlegroups.com> <1150462237.224431.213020@c74g2000cwc.googlegroups.com> Message-ID: <4492B468.6050902@designaproduct.biz> > Not in this implementation: > py> from Crypto.Cipher import AES > py> crypt = AES.new('abcdefghijklmnop', AES.MODE_CBC) > py> c = crypt.encrypt('1') > Traceback (most recent call last): > File "", line 1, in ? > ValueError: Input strings must be a multiple of 16 in length > This is strange. In theory, any ECB mode cipher can be used to create a CBC mode cipher. AFAIK, CBC creates one encrypted block, and uses the one byte from the plain text to xor it with the last encrypted byte. Finally it shifts the encrypted block. This way each input byte will have a corresponding output byte, and there is no size limit for the plain text. Frankly, I could write the CBC mode cipher using the (already existing) ECB cipher. Why we have this limitation? Laszlo From steve at holdenweb.com Mon Jun 5 10:55:09 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 05 Jun 2006 15:55:09 +0100 Subject: How to add few pictures into one In-Reply-To: <1149517433.880564.128350@h76g2000cwa.googlegroups.com> References: <1149511692.796038.155930@c74g2000cwc.googlegroups.com> <1149517433.880564.128350@h76g2000cwa.googlegroups.com> Message-ID: Lad wrote: > K.S.Sreeram wrote: > >>Lad wrote: >> >>>Hello , >>>is it possible to add( with PYTHON language) several image files into >>>one? >> >>Google for 'Python Imaging Library'... >> >>Regards >>Sreeram >> >> >> > > Thank you for your reply. > I was thinking about this: > to open each image file in binary mode , read it and write into the > result image file? > Is that possible? > Regards, > L > Of course, but what you haven't said yet is how you want the resulting image file to behave. Do you want it to contain tiled copies of the original images, or be an animation with each frame being one of the original images, or something else I haven't thought of. We aren't mind readers here. though-some-regulars-get-close-ly y'rs - steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From mauriceling at gmail.com Tue Jun 6 19:46:52 2006 From: mauriceling at gmail.com (mauriceling at gmail.com) Date: 6 Jun 2006 16:46:52 -0700 Subject: what are you using python language for? In-Reply-To: <128b8cg1d0p7uce@corp.supernews.com> References: <128b8cg1d0p7uce@corp.supernews.com> Message-ID: <1149637612.712298.309010@y43g2000cwc.googlegroups.com> I am using Python to assemble a biomedical literature analysis pipeline as part of my PhD thesis. (http://ib-dwb.sf.net/Muscorian.html) From find at my.address.elsewhere Thu Jun 22 10:01:10 2006 From: find at my.address.elsewhere (Matthias Blume) Date: Thu, 22 Jun 2006 09:01:10 -0500 Subject: What is a type error? References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <7i3mg.204167$8W1.155367@fe1.news.blueyonder.co.uk> <44992e6c$2$664$bed64819@news.gradwell.net> <%Igmg.464974$xt.353729@fe3.news.blueyonder.co.uk> <4fv0v3F1kipa6U1@individual.net> Message-ID: Pascal Costanza writes: > Chris Smith wrote: > >> While this effort to salvage the term "type error" in dynamic >> languages is interesting, I fear it will fail. Either we'll all >> have to admit that "type" in the dynamic sense is a psychological >> concept with no precise technical definition (as was at least hinted >> by Anton's post earlier, whether intentionally or not) or someone is >> going to have to propose a technical meaning that makes sense, >> independently of what is meant by "type" in a static system. > > What about this: You get a type error when the program attempts to > invoke an operation on values that are not appropriate for this > operation. > > Examples: adding numbers to strings; determining the string-length of > a number; applying a function on the wrong number of parameters; > applying a non-function; accessing an array with out-of-bound indexes; > etc. Yes, the phrase "runtime type error" is actually a misnomer. What one usually means by that is a situation where the operational semantics is "stuck", i.e., where the program, while not yet arrived at what's considered a "result", cannot make any progress because the current configuration does not match any of the rules of the dynamic semantics. The reason why we call this a "type error" is that such situations are precisely the ones we want to statically rule out using sound static type systems. So it is a "type error" in the sense that the static semantics was not strong enough to rule it out. > Sending a message to an object that does not understand that message > is a type error. The "message not understood" machinery can be seen > either as a way to escape from this type error in case it occurs and > allow the program to still do something useful, or to actually remove > (some) potential type errors. I disagree with this. If the program keeps running in a defined way, then it is not what I would call a type error. It definitely is not an error in the sense I described above. From a at tempinbox.com Sun Jun 18 17:01:31 2006 From: a at tempinbox.com (a) Date: 18 Jun 2006 14:01:31 -0700 Subject: any subway web dev experiences In-Reply-To: <1150533811.911621.112430@y41g2000cwy.googlegroups.com> References: <1150533811.911621.112430@y41g2000cwy.googlegroups.com> Message-ID: <1150664491.533947.61090@p79g2000cwp.googlegroups.com> subway is pythons ruby on rails competitor pls tell me if u hav any expereinces thanks From grflanagan at yahoo.co.uk Thu Jun 8 07:16:55 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 8 Jun 2006 04:16:55 -0700 Subject: language-x-isms In-Reply-To: <1149764092.806419.322130@i39g2000cwa.googlegroups.com> References: <1149753206.451066.120960@h76g2000cwa.googlegroups.com> <1149759486.695563.110640@g10g2000cwb.googlegroups.com> <1149760633.796809.166430@h76g2000cwa.googlegroups.com> <1149762625.346302.135220@y43g2000cwc.googlegroups.com> <1149764092.806419.322130@i39g2000cwa.googlegroups.com> Message-ID: <1149765414.968798.251700@g10g2000cwb.googlegroups.com> Alan Kennedy wrote: > [Alan Kennedy] > >> Your comment makes "using a user-defined enumerate [on cpython] is > >> slower than using the built-in version" makes no sense in relation to > >> the code I posted > > Fredrik Lundh wrote: > > try combining with the second sentence in my post. > > OK, so putting "at least in CPython, using a user-defined enumerate > function is a bit > slower than using the built-in version" > > together with > > """ > in fact, if performance is important, the following can sometimes be > the most efficient way to loop over things > > ix = 0 > for fibo in my_list: > do something with ix and my_list[ix] > ix += 1 > """ > > We still don't get anything that sheds light on how the code I posted > is deficient. > > Why can't you just say "I made a mistake, I thought your code replaced > the builtin enumerate, but it doesnt"? > > I'm sorry I posted it now, what a rigmarole. > I think this is a misunderstanding. Personally, I read Fredrik's post as a Point of Information not a Point of Criticism - as in "To you, and anyone reading this thread, here's a detail you might consider..." - I don't think it was ad hominem ( or ad code hominis! ) necessarily. all the best Gerard From rupole at hotmail.com Wed Jun 7 15:37:10 2006 From: rupole at hotmail.com (Roger Upole) Date: Wed, 7 Jun 2006 15:37:10 -0400 Subject: Converting binary sid's to a hex string References: Message-ID: <1149708725_1865@sp6iad.superfeed.net> You can use the binascii module to convert the raw bytes of the sid to hex. binascii.b2a_hex(buffer(MySid)) Roger "LittlePython" wrote in message news:Y6Ehg.6441$im3.3067 at trnddc01... >I am trying to create a hexstring of a NT4 user account sid which I can in > turn use to query an exchange 55 database. I believe I need to convert a > binary sid to a hex string. ADsSID com object will do this for me however it > is a little slow. Can anybody point me in the right direction to converting > a PySID to a hexstring. > Thx > > import win32netcon > import win32net > import win32security > def report(): > resume = 0 > while 1: > filter = win32netcon.FILTER_NORMAL_ACCOUNT > data, total, resume = win32net.NetUserEnum('nt4pridc1', 20, filter, > resume) > for user in data: > MySid, string, int = win32security.LookupAccountName('nt4pridc1', > user['name']) > sString = win32security.ConvertSidToStringSid(MySid) > print MySid > print sString > if resume ==0: > break > > report() > ## sString prints = S-1-5-21-357043131-537017027-1947940980-1289 > ## MySid prints = PySID:S-1-5-21-357043131-537017027-1947940980-1289 > ## I need this , I believe this is a hex string of the SID > ## 010500000000000515000000BB0B4815C33A022074381B7409050000 > > ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= East/West-Coast Server Farms - Total Privacy via Encryption =--- From bignose+hates-spam at benfinney.id.au Tue Jun 13 17:46:07 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 14 Jun 2006 07:46:07 +1000 Subject: Writing PNG with pure Python References: <1149853401.521169.112530@i39g2000cwa.googlegroups.com> <1149889778.182865.181600@f6g2000cwb.googlegroups.com> <1149910872.025017.60160@i40g2000cwc.googlegroups.com> <1150152913.315502.16840@u72g2000cwu.googlegroups.com> <1150215317.349097.326970@p79g2000cwp.googlegroups.com> Message-ID: <87lks0ohk0.fsf@benfinney.id.au> "Johann C. Rocholl" writes: > How about this here construct? > > #!/usr/bin/env python > # png.py - PNG encoder in pure Python > # Copyright (C) 2006 Johann C. Rocholl > # > # This file is licensed alternatively under one of the following: > # 1. GNU Lesser General Public License (LGPL), Version 2.1 or newer > # 2. GNU General Public License (GPL), Version 2 or newer > # 3. Apache License, Version 2.0 or newer > # 4. The following license (aka MIT License) Pointless. Licensing it under the Expat license (what you're calling "MIT License", but we've already discussed the ambiguities in that term) allows all the rights granted in all the other license you name, plus just about anything else. Hence, there's no point listing the others if you are also happy for people to have it under the Expat license. On the other hand, if you want to be more restrictive than the terms of the Expat license, you need to choose a different license. Simplify. Please don't attempt to write yet another set of license terms without expert legal assistance. You've already chosen the Expat license as being acceptable; use that, and you grant all the rest without even mentioning it. -- \ "[On the Internet,] power and control will shift to those who | `\ are actually contributing something useful rather than just | _o__) having lunch." -- Douglas Adams | Ben Finney From chris.uppal at metagnostic.REMOVE-THIS.org Thu Jun 22 11:24:46 2006 From: chris.uppal at metagnostic.REMOVE-THIS.org (Chris Uppal) Date: Thu, 22 Jun 2006 16:24:46 +0100 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <4fo19aF1jsudeU1@individual.net> <1150902731.828394.175560@m73g2000cwd.googlegroups.com> <1150915614.636327.233490@p79g2000cwp.googlegroups.com> Message-ID: <449acc54$0$664$bed64819@news.gradwell.net> Joe Marshall wrote: > What we need is an FAQ entry for how to talk about types with people > who are technically adept, but non-specialists. Or alternatively, an > FAQ of how to explain the term `dynamic typing' to a type theorist. You could point people at "a regular series on object-oriented type theory, aimed specifically at non-theoreticians." which was published on/in JoT from: http://www.jot.fm/issues/issue_2002_05/column5 to http://www.jot.fm/issues/issue_2005_09/column1 Only 20 episodes ! (But #3 seems to be missing.) Actually the first one has (in section four) a quick and painless overview of several kinds of type theory. I haven't read the rest (yet, and maybe never ;-) -- chris From pemboa at gmail.com Thu Jun 1 03:36:06 2006 From: pemboa at gmail.com (Arthur Pemberton) Date: Thu, 1 Jun 2006 02:36:06 -0500 Subject: Best way to do data source abstraction Message-ID: <16de708d0606010036j65d64096m5a4dcb0c04c5656a@mail.gmail.com> What is the best way to do data source abtraction? For example have different classes with the same interface, but different implementations. I was thinking of almost having classA as my main class, and have classA dynamically "absorb" classFood into to based on the extension of the input file received by classA. But this doesn't seem possible. Please advise. Thank you. -- To be updated... From frithiof.jensen at die_spammer_die.ericsson.com Thu Jun 1 08:03:58 2006 From: frithiof.jensen at die_spammer_die.ericsson.com (Frithiof Andreas Jensen) Date: Thu, 1 Jun 2006 14:03:58 +0200 Subject: creating a new database with mysqldb References: Message-ID: "John Salerno" wrote in message news:gcKag.2113$No6.46302 at news.tufts.edu... > Since the connect method of mysqldb requires a database name, it seems > like you can't use it without having a database already created. The web hotel I use create *one* database together with the account. I.O.W: I cannot create any databases; I can create/delete as many tables as I like within the database (up to the disk space that I have). This is pretty normal, I think. From nospam at nospam.com Fri Jun 23 17:12:00 2006 From: nospam at nospam.com (3c273) Date: Fri, 23 Jun 2006 14:12:00 -0700 Subject: subprocess.Popen on Windows References: <1151094433.181414.164410@g10g2000cwb.googlegroups.com> Message-ID: "madpython" wrote in message news:1151094433.181414.164410 at g10g2000cwb.googlegroups.com... > playing with subprocess.Popen on Windows I stumbled into the following > problem: > Python 2.4.3 (#69, Mar 29 2006, 17:35:34) > > IDLE 1.1.3 > > >>> import subprocess > >>> p1=subprocess.Popen("c:\\asd.bat") #works OK > >>> p2=subprocess.Popen("c:\\asd.bat",stdout=subprocess.PIPE) > > Traceback (most recent call last): > File "", line 1, in -toplevel- > p2=subprocess.Popen("c:\\asd.bat",stdout=subprocess.PIPE) > File "C:\Python24\lib\subprocess.py", line 533, in __init__ > (p2cread, p2cwrite, > File "C:\Python24\lib\subprocess.py", line 593, in _get_handles > p2cread = self._make_inheritable(p2cread) > File "C:\Python24\lib\subprocess.py", line 634, in _make_inheritable > DUPLICATE_SAME_ACCESS) > TypeError: an integer is required > >>> > What do I do wrongly? > I get the same thing. This only happens when using IDLE. From a command prompt, everthing works as expected. Hopefully somebody else will know why. Louis From jstroud at ucla.edu Sat Jun 10 19:36:44 2006 From: jstroud at ucla.edu (James Stroud) Date: Sat, 10 Jun 2006 16:36:44 -0700 Subject: Most elegant way to generate 3-char sequence In-Reply-To: References: <1149889784.391965.271570@h76g2000cwa.googlegroups.com> Message-ID: James Stroud wrote: > SuperHik wrote: > >> James Stroud wrote: >> >>> SuperHik wrote: >>> >>>> and the winner is... :D >>>> David Isaac wrote: >>>> >>>>> alpha = string.lowercase >>>>> x=(a+b+c for a in alpha for b in alpha for c in alpha) >>>> >>>> >>>> >>>> >>>> >>> >>> Not necessarily vying for winner, but David's solution is highly >>> specific as it doesn't do so well for something like >>> >>> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >>> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab >>> . >>> . >>> . >>> zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzy >>> zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz >> >> >> >> Right. But that wasn't the question :p >> >>> >>> >>> James >>> > > highly specific > > The only question mark was in this sentence, which I believe I answered. How would you construct a generator to acheive this? -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From propheci at gmail.com Wed Jun 21 01:59:00 2006 From: propheci at gmail.com (Xiaolei Li) Date: 20 Jun 2006 22:59:00 -0700 Subject: Initializing a set from a list Message-ID: <1150869540.796459.202330@u72g2000cwu.googlegroups.com> Hi, I'm trying to initialize a set from a list but am unable to do so. My list "c", looks like: [(1.00909, 0.91969999999999996, -0.13550388182991072, 0), (0.87423999999999991, 0.6666700000000001, -0.21230487137222254, 0)] So basically a list of 2 tuples, each with 4 elements. Since tuples are immutable, I think a set should be able to support them. Anyway, I then do: set_c = set(c) And instead of getting a set, I get "None" when I try to print out set_c. len(set_c) complains "TypeError: len() of unsized object." Help? Thank you. From deets at nospam.web.de Tue Jun 20 06:57:22 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 20 Jun 2006 12:57:22 +0200 Subject: Specifing arguments type for a function References: <4fq09iF1k0h0eU1@uni-berlin.de> Message-ID: <4fq2kqF1k7a5mU1@uni-berlin.de> > What about > def f(arg): > if type(arg)=='list': > #do something Several things: - list is a string in your code - which wont work: >>> type([]) == 'list' False It needs to be list w/o quotes. - you won't get sublclasses of list: >>> class Foo(list): ... pass ... >>> type(Foo()) == list False So better use isinstance, as I already mentioned. Diez From chris.uppal at metagnostic.REMOVE-THIS.org Fri Jun 23 08:21:46 2006 From: chris.uppal at metagnostic.REMOVE-THIS.org (Chris Uppal) Date: Fri, 23 Jun 2006 13:21:46 +0100 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150908952.804184.218990@r2g2000cwb.googlegroups.com> <1150991074.705803.211570@m73g2000cwd.googlegroups.com> Message-ID: <449bde5f$2$663$bed64819@news.gradwell.net> David Hopwood wrote: > > But some of the advocates of statically > > typed languages wish to lump these languages together with assembly > > language a "untyped" in an attempt to label them as unsafe. > > A common term for languages which have defined behaviour at run-time is > "memory safe". For example, "Smalltalk is untyped and memory safe." > That's not too objectionable, is it? I find it too weak, as if to say: "well, ok, it can't actually corrupt memory as such, but the program logic is still apt go all over the shop"... -- chris From find at my.address.elsewhere Mon Jun 19 15:21:19 2006 From: find at my.address.elsewhere (Matthias Blume) Date: Mon, 19 Jun 2006 14:21:19 -0500 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <4fo91pF1jr7gpU1@individual.net> Message-ID: Pascal Costanza writes: > Matthias Blume wrote: >> "Rob Thorpe" writes: >> >>> I don't think dynamic typing is that nebulous. I remember this being >>> discussed elsewhere some time ago, I'll post the same reply I did then >>> .. >>> >>> >>> A language is statically typed if a variable has a property - called >>> it's type - attached to it, and given it's type it can only represent >>> values defined by a certain class. >> By this definition, all languages are statically typed (by making >> that >> "certain class" the set of all values). Moreover, this "definition", >> when read the way you probably wanted it to be read, requires some >> considerable stretch to accommodate existing static type systems such >> as F_\omega. >> Perhaps better: A language is statically typed if its definition >> includes (or ever better: is based on) a static type system, i.e., a >> static semantics with typing judgments derivable by typing rules. >> Usually typing judgmets associate program phrases ("expressions") with >> types given a typing environment. > > How does your definition exclude the trivial type system in which the > only typing judgment states that every expression is acceptable? It does not. From sonaldgr8 at gmail.com Mon Jun 12 02:41:03 2006 From: sonaldgr8 at gmail.com (sonal) Date: 11 Jun 2006 23:41:03 -0700 Subject: How to link foreign keys & primary keys using python? References: <1149856668.055162.209650@u72g2000cwu.googlegroups.com> Message-ID: <1150094463.850719.312650@i40g2000cwc.googlegroups.com> Hi Mr. George, Sorry for confusing u so much... Let me try it again... I am not using any relational database to store the required tables with primary keys & foreign keys.... When I say PRIMARY KEY => 1. It means an index is created on the specified fields (Out of various fields given in the comma separated txt file) FileFormat: CODE, FIRST_NAME, last_name, area_of_expertise, country Eg: A1,Harry,George, python, XYZCOUNTRY--------(1st record) 2. The index can be formed on a single field or on multiple fields Eg: a. 'CODE' (single field ) {pk_code} b. 'CODE' & 'NAME' (multiple fields ) {pk_code_fname} Now when I say FOREIGN KEY => 1. If the foreign Key is formed on the field 'CODE' in another text file Format: subsriber_code,CODE,first_name, no_of_posts,active(Y/N) Eg: SUB_001, A1, Harry, 50, Y This means the CODE (A1) given here is checked in the index formed above with primary key: pk_code... 2. If the foreign Key is formed on the fields 'CODE' & 'FIRST_NAME' Format: subsriber_code,CODE,FIRST_NAME, no_of_posts,active(Y/N) Eg: SUB_001, A1, Harry, 50, Y This means the CODE (A1) & FIRST_NAME (Harry) given here are checked in the index formed above with primary key: pk_code_fname... I am done till here..... The problem starts if I have defined an index on multiple fields (composite PK) say: CODE & FIRST_NAME (pk_code_fname) and if I need to define a FK on a single field out of these say: CODE I am unable to do that... Mr. George, I thought i must explain the code i am dealin with, for better understanding.., but i am sorry i confused you all the more (incase, u want to view the code please refer to the code snippets in my first query posted) Thanks & regards, sonal From fc14301589 at icqmail.com Sat Jun 10 11:44:23 2006 From: fc14301589 at icqmail.com (TheSaint) Date: Sat, 10 Jun 2006 23:44:23 +0800 Subject: Very newbie programming Message-ID: <448ae8ce_1@news.tm.net.my> Hello! Is there a more pythonic way to implement the following program: 8<--------------8<--------------8<--------------8<-------------- #! /usr/bin/env python import os import sys a = os.listdir('/media') # no mount dirs were found, exit nicely if len(a) == 0: sys.exit(0) # Maybe collecting the arguments via command line # will make the program more flexible mnt = open("/etc/mtab") ptn = open("/proc/partitions") dskt = '/home/user/Desktop/' c =[] # Filling the c with the list of devices which are recorded to be mounted d = filter((lambda a: a[:2] =='/d'),mnt.readlines()) # non /dev-mounts are off d = map((lambda a: a.split()[:1]),d) # only the first info column is used [c.append(str(a)[2:-2]) for a in d] # checking against /proc/partitions to see if there're mountpoints without # corresponding partition which has been removed from the list # ALL mountpoints with available partition will be removed from the list x = ptn.readlines() for a in x[2:]: b = a.split()[-1] for d in c: if b == d.rsplit('/',1)[-1]: c.remove(d) if len(c) != 1: sys.exit(0) # if none or more than one match exit cmnd = str(c)[2:-2] err = os.system('umount ' + cmnd) a = os.listdir(dskt) #retrieve the info from the KDE desktop icons for i in a: if 'desktop' not in i: continue y = open(dskt + i) d = y.readlines() for x in d: if 'URL=/media' not in x: continue icon = i dvc = x[11:-1] break err += os.system('rm -f ' + dskt + icon) err += os.system('rmdir /media/' + dvc) sys.exit(err) # if something went wrong exit with high number 8<--------------8<--------------8<--------------8<-------------- I still have a long learnig curve, please give some advise in order to make the program a bit faster o nicer :) F From jal at machinefx.co.uk Fri Jun 23 18:44:13 2006 From: jal at machinefx.co.uk (John Lockwood) Date: Fri, 23 Jun 2006 23:44:13 +0100 Subject: Python on intel osx Message-ID: Can someone please suggest the most suitable python for mac osx 10.4.6 Finding the right installs doesn?t seem quite as cut and dried as it is for linux or windows. I?m also looking for numeric and pyopengl. Cheers From bnblazer at gmail.com Wed Jun 7 10:34:50 2006 From: bnblazer at gmail.com (Brian) Date: 7 Jun 2006 07:34:50 -0700 Subject: Django Quick Start with Schema Evolution Support In-Reply-To: References: <1149446706.085692.174980@h76g2000cwa.googlegroups.com> <1149505316.406428.242450@c74g2000cwc.googlegroups.com> <448429E1.90305@kered.org> <35081.132.60.240.80.1149530454.squirrel@kered.org> <4486D6F2.7000407@lazaridis.com> Message-ID: <1149690890.340282.205710@h76g2000cwa.googlegroups.com> Ilias Lazaridis wrote: > http://lazaridis.com I would agree with you that this is a place to discuss python. However, your posts primarily deal with your expulsion from another group. Instead of discussing that, why don't your discuss the python technicalities of your project and leave the rest alone since we want to hear about the former and not the later. Brian From grante at visi.com Thu Jun 8 11:23:51 2006 From: grante at visi.com (Grant Edwards) Date: Thu, 08 Jun 2006 15:23:51 -0000 Subject: Select hangs after some reads References: <1149737234.816833.177710@j55g2000cwa.googlegroups.com> <1149764138.868847.326250@i39g2000cwa.googlegroups.com> <128g8uvi6aj4240@corp.supernews.com> <1149779056.498540.46620@f6g2000cwb.googlegroups.com> Message-ID: <128gg87h3sgqu93@corp.supernews.com> On 2006-06-08, alsmeirelles at gmail.com wrote: >>> Well, actually I?m using a very simple protocol wich sends >>> only strings ended by newline. I need to send 3 chunks of >>> information and a newline after them. On the reader side I >>> make 3 readline(), this way I wouldn?t have to care about this >>> problem, but maybe that?s where I?m falling. If that?s the >>> case, I?ll have to use a more complex protocol. >> >> You can't use readline() with select(). Select tells you >> whether recv() called on the underlying socket will block or >> not. What's probably happening is that all of the data has >> been read from the underlying socket and is being held in a >> buffer waiting to be read by readline(). > > Yes, as I expected, its the buffers. In my opinion the problem > is that the socket module doesn't provide a way of reading all > its internal buffer. What internal buffer? > readlines() just make subsequent calls to readline and > readline may call recv, so we have a locked scene. I want to > know if I will block anyway. I'm lost. > Of course I can clean the buffer myself, but I think the > socket module should provide a way of doing this. I'm afraid I don't understand what you mean. Since you talked about calling readline(), I assumed that you had called the socket object's makefile() method to create a file-object. The select system call can only tell you whether a recv on the socket will block or not. It knows nothing about the state of the file object on which you're calling readline(). -- Grant Edwards grante Yow! Is this an out-take at from the "BRADY BUNCH"? visi.com From __peter__ at web.de Wed Jun 14 08:35:22 2006 From: __peter__ at web.de (Peter Otten) Date: Wed, 14 Jun 2006 14:35:22 +0200 Subject: Using "external" vars on module load time References: Message-ID: Marco Aschwanden wrote: > Load a module and hand in already the server_api. How can I achieve this? Using execfile() is the simplest approach: import imp import sys def import_preloaded(name, path=None, variables={}): if path is None: file, path, description = imp.find_module(name) module = imp.new_module(name) module.__dict__.update(variables) execfile(path, module.__dict__) sys.modules[name] = module return module if __name__ == "__main__": demo = import_preloaded("demo", variables=dict(whatever=42)) I think you should consider a class instead of a module, though. Peter From fzhenglee23 at yahoo.com.cn Wed Jun 7 18:15:16 2006 From: fzhenglee23 at yahoo.com.cn (=?gb2312?q?=C0=EE=D5=FE?=) Date: Thu, 8 Jun 2006 06:15:16 +0800 (CST) Subject: Regular expression - dot problem! In-Reply-To: Message-ID: <20060607221516.44749.qmail@web15810.mail.cnb.yahoo.com> Fredrik Lundh wrote? ?? wrote: > I've a problem with regular express(dot problem). I checked Python > Library Reference, but i can't find any infomation that is useful. like what a dot means in a regular expression? you really need to work on your google fu ;-) in the meantime, look under "The special characters are" on this page: http://docs.python.org/lib/re-syntax.html May be my bad writing english confused you. I know what a dot means in a regular expression. In the case you are forced to use regular expression in the way: patter = 'www.' if re.compile(pattern).match(string) is not None: ...... but not: if re.compile(r'www.').match(string) is not None: or if re.compile('www\.').match(string) is not None: , how you process special characters, like dot. > * if re.compile(pattern).match(urldomain) is not None:* > return INTERNAL_LINK # match. url is internal link if you want to check if the url starts with a given prefix, use if url.startswith(prefix): Your suggestion is really helpful. I use both startswith(prefix) and endswith(suffix) in my program, and it works better. Here is the new one: ===================================================== def getLinkType(url, sitedomain): # get the domain which 'url' belongs to urldomain = urlparse4esa(url)[1] tmpsd = '' if sitedomain.startswith('www'): tmpsd = sitedomain[4:] if urldomain.endswith(tmpsd): return INTERNAL_LINK # match. url is internal link else: return EXTERNAL_LINK # doesn't match. url is external link ===================================================== Thks for your help! Alex, China __________________________________________________ ??????????????? http://cn.mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From antroy at gmail.com Fri Jun 16 03:45:41 2006 From: antroy at gmail.com (Ant) Date: 16 Jun 2006 00:45:41 -0700 Subject: a good programming text editor (not IDE) In-Reply-To: References: <_xgkg.2317$No6.48542@news.tufts.edu> <1150393919.514359.55580@h76g2000cwa.googlegroups.com> Message-ID: <1150443941.513439.321570@c74g2000cwc.googlegroups.com> John Salerno wrote: > Larry Bates wrote: > > > Nope, no Java knowledge necessary. Jython just compiles Python code > > to java bytecode instead of python bytecode. Once it is in java bytecode > > the JVM doesn't know where it came from. > > Well that's good to know. I guess there's not much of a point in writing > pure Python code with Jython, but at least now I know it works that way! That's right - but it's very useful for scripting Java (for example in jEdit) as you have access not only to the Python library, but to the Java API (which you just use as if they were Python modules). From atul_wankhade at hotmail.com Mon Jun 19 19:01:54 2006 From: atul_wankhade at hotmail.com (Atul Wankhade) Date: Tue, 20 Jun 2006 04:31:54 +0530 Subject: Missing fpconst? Message-ID: Hi All, I im searching for fpconst. I had gone thru both the links mentioned below. But both seem to be broken.. Can any body point me to correct one. Thanks in advance.. Atul phansen wrote: >I was trying to start some experiments with SOAP, but >fairly quickly discovered that SOAPpy (required by >twisted.web.soap and other things) relies on something >called fpconst, which was apparently available from the >page http://www.analytics.washington.edu/Zope/projects/fpconst/ >which no longer exists. Attempts to find the project >in other ways have so far failed. > Hi Peter, you can download fpconst from http://www.analytics.washington.edu/statcomp/projects/testfolder/rzope/fpconst HTH Rainer From pc at p-cos.net Fri Jun 16 10:48:28 2006 From: pc at p-cos.net (Pascal Costanza) Date: Fri, 16 Jun 2006 16:48:28 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: <7zwtbh8h59.fsf@app-1.diku.dk> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <4ffdntF1iei4hU1@individual.net> <7zwtbh8h59.fsf@app-1.diku.dk> Message-ID: <4ffulsF1ie6ifU1@individual.net> Torben ?gidius Mogensen wrote: > Pascal Costanza writes: > >> Torben ?gidius Mogensen wrote: > >>> So while it may take longer to get a program that gets >>> past the compiler, it takes less time to get a program that works. >> That's incorrect. See http://haskell.org/papers/NSWC/jfp.ps - >> especially Figure 3. > > There are many other differences between these languages than static > vs. dynamic types, and some of these differences are likely to be more > significant. What you need to test is langauges with similar features > and syntax, except one is statically typed and the other dynamically > typed. > > And since these languages would be quite similar, you can use the same > test persons: First let one half solve a problem in the statically > typed language and the other half the same problem in the dynamically > typed language, then swap for the next problem. If you let a dozen > persons each solve half a dozen problems, half in the statically typed > language and half in the dynamically typed language (using different > splits for each problem), you might get a useful figure. ...and until then claims about the influence of static type systems on the speed with which you can implement working programs are purely guesswork. That's the only point I need to make to show that your original unqualified statement, namely that it takes less time to get a program that works, is incorrect. Pascal -- 3rd European Lisp Workshop July 3 - Nantes, France - co-located with ECOOP 2006 http://lisp-ecoop06.bknr.net/ From deets at nospam.web.de Thu Jun 8 04:29:49 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 08 Jun 2006 10:29:49 +0200 Subject: Newbie question about updating multiple objects ... References: <1149753137.498806.314640@c74g2000cwc.googlegroups.com> Message-ID: <4eq5g6F1fl78oU1@uni-berlin.de> fivenastydisco at hotmail.com wrote: > I've copied in the code I'm using below, as it's not very long -- can > anyone help me? I'll have some remarks: > <--START--> > > from visual import * > from random import randrange # to create random numbers > > numballs = 5 # number of balls > balls = [] # a list to contain the balls > > # set up a box to collide with > side_length = 100 > minx = side_length * -10 > maxx = side_length * 10 > miny = side_length * -4 > maxy = side_length * 4 > > # create a wireframe of space > left = curve(pos=[(minx, miny),(minx, maxy)], color = color.white) > top = curve(pos = [(minx, maxy),(maxx, maxy)], color = color.white) > right = curve(pos = [(maxx, maxy),(maxx, miny)], color = color.white) > bottom = curve(pos = [(maxx, miny),(minx,miny)], color = color.white) > > #create some balls > for b in range(numballs): # for each ball > x = randrange(minx, maxx) > y = randrange(miny, maxy) Don't use range - use xrange. range actually creates a list of numbers, where xrange creates a iterator that will just return the subsequent numbers. The difference: the first solution consumes memory linear to the number of numbers! > balls.append(sphere(pos = (x,y), radius = 50, color = color.red)) # > add balls > > dt = 0.05 # time interval > velocity = vector(2,0.2,1) # velocity of the balls > > while (1==1): # forever ... > rate(50) > for b in range(numballs): # for each ball ... This is a C-ism (or JAVA-ism if you like). The for-loop in python allows you to iterate over objects in iterables. And list is one of those. So for ball in balls: ball.x = ... does the trick. And if you need an index, the commonly used idiom is for i, ball in enumerate(balls): ... > if balls[b].x < minx: # check it hasn't overrun a boundary > balls[b].x = maxx > if balls[b].x > maxx: > balls[b].minx > if balls[b].y < miny: > balls[b].y = maxy > if balls[b].y > maxy: > balls[b].y = miny You should do that checks above _after_ you changed the coordinates, not before! > # NB betting this is where it's going wrong ... > balls[b].pos = balls[b].pos + (velocity * dt) # update the > position of the ball This could be the problem: you are using a python tuple and a vector object and add them. Are you sure that works? The python tuples themselves concatenate under the +-operator. So you'd create a large tuple of coordinate differences here. I suppose that using a vector for the coordinates or doing the calculation component-wise will solve the problem. HTH, Diez From bnblazer at gmail.com Wed Jun 7 17:42:06 2006 From: bnblazer at gmail.com (Brian) Date: 7 Jun 2006 14:42:06 -0700 Subject: creating and naming objects In-Reply-To: References: <1149696358.065614.76150@h76g2000cwa.googlegroups.com> Message-ID: <1149716526.542364.276730@y43g2000cwc.googlegroups.com> Maarten van Veen wrote: Hi Brian, > > If you would do it like this: > Class Student: > def setName(self, name) > self.name = name > def setId(self, id) > self.id = id > > > def createStudent(): > foo = Student() > foo.setName("Brian") > foo = Student() > print foo.getName() > > You would get an error here, because foo now equals the second Student > object which has no name. And you can't get to the first one. > Perhaps you could do something like this. > > Class Student: > def setName(self, name) > self.name = name > def setId(self, id) > self.id = id > > listWithStudents = [] > > def createStudent(): > listWithStudent.append(Student()) > > Now every student you create is put in the list with students so you can > access them but don't have to give them names. > You could do something to all of them like this: > for student in listWithStudent: > student.doSomething() > > Or change just one student: > listWithStudent[23].doSomething() # this is the 24th student though!!! > > Hope this is what you're looking for. > Maarten This is of great help. Thank you, Brian From jo at durchholz.org Tue Jun 20 18:16:08 2006 From: jo at durchholz.org (Joachim Durchholz) Date: Wed, 21 Jun 2006 00:16:08 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> Message-ID: Matthias Blume schrieb: > Perhaps better: A language is statically typed if its definition > includes (or ever better: is based on) a static type system, i.e., a > static semantics with typing judgments derivable by typing rules. > Usually typing judgmets associate program phrases ("expressions") with > types given a typing environment. This is defining a single term ("statically typed") using three undefined terms ("typing judgements", "typing rules", "typing environment"). Regards, Jo From nmm1 at cus.cam.ac.uk Wed Jun 14 10:32:16 2006 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 14 Jun 2006 14:32:16 GMT Subject: Numerics, NaNs, IEEE 754 and C99 References: <12904mjhl493t49@corp.supernews.com> Message-ID: In article <12904mjhl493t49 at corp.supernews.com>, Grant Edwards writes: |> > |> > Now, I should like to improve this, but there are two problems. The |> > first is political, and is whether it would be acceptable in Python to |> > restore the semantics that were standard up until about 1980 in the |> > numerical programming area. I.e. one where anything that is numerically |> > undefined or at a singularity which can deliver more than one value is |> > an error state (e.g. raises an an exception or returns a NaN). |> |> That's fine as long as the behavior is selectable. I almost |> always want a quiet NaN. That is one of the two modes that I regard as respectable. However, because integer arithmetic doesn't have a NaN value (which could be fixed, in Python), anything that returns an integer has to raise an exception. On that matter, division by zero and several other currently trapped numeric errors could be modified to return NaN for people like you (if the option were selected, of course). I will take a look at adding NaN to integers, but that is a much hairier hack - and it STILL doesn't deal with comparisons (which can be done only in a purely functional programming language). |> While you're at it, the pickle modules need to be fixed so they |> support NaN and Inf. ;) Yup. On my list :-) Regards, Nick Maclaren. From sjmachin at lexicon.net Sat Jun 10 00:20:34 2006 From: sjmachin at lexicon.net (John Machin) Date: Sat, 10 Jun 2006 14:20:34 +1000 Subject: More pythonic shell sort? In-Reply-To: <1149886830.566152.304500@h76g2000cwa.googlegroups.com> References: <1149886830.566152.304500@h76g2000cwa.googlegroups.com> Message-ID: <448A4892.1090402@lexicon.net> On 10/06/2006 7:00 AM, akameswaran at gmail.com wrote: > Disclaimer - I recognize this is not a practical exercise. There are > many implementations around that would do the job better, more > efficiently (Meaning in C) or whatever. > > I caught some thread about sorting and started thinking about shell > sort.... and as part of my trying to pythonise my mind and break my > java mindset > > So I decided to tackle this old school problem with the python mindset. > > > I played around with some list comprehensions, trying to use slicing > inteligently etc. Slicing? I don't see any, and besides you don't want to be copying chunks of your list anyway -- see below. > Anyway this is what I came up with. If anyone has > suggestions on a more pythonic way to go (all attempts at using list > comprehensions turned into unruly rubbish quite quickly) I'd > appreciate the input. An aside - can anyone tell me where the use += > and -= is documented? it works but I can't find it in my docs. > (don't ask about shellSorters 1 thru 3) > > class shellSorter4(object): > > def __init__(self,gapSeq): > self.gapSeq = gapSeq # gap sequences are > notoriously hard to tune > self.gapSeq.sort(reverse=True) Not exactly stand-alone, if it needs another sort for its initialisation :-) > > def sort(self,myList): > for gap in self.gapSeq: > for i in range(1,gap+1): Use xrange instead of range, to save memory. > self.gapInsertionSort(myList,i,gap) > > def gapInsertionSort(self,theList,start,gap): Having a method call here will slow it down somewhat. > for i in range(start,len(theList),gap): > j = i > curElem = theList[j] > while (j > 0) and (theList[j-gap] > curElem): I think that you mean "while j >= gap" ... otherwise theList[j-gap] will be using Python's wrap-around negative subscripting to access something at the other end of the list! And you'll never know, because the last pass with gap == 1 will (laboriously) clean up any mess. You should instrument your code with counts of comparisons and rearrangements, and compare those with examples from the textbooks and the literature *AND* your pencil-and-paper experiments with a gap-list of (say) [5, 1] on a small number of elements. > j -=gap # undocumented > feature?? > if j!=i: > theList.insert(j,theList.pop(i)) > theList.insert(j+gap,theList.pop(j+1)) Quadruple yuck. Each pop() and insert() could involve moving many list elements unnecessarily. It's not "pythonic" to use advanced language features when they are inefficient for the job at hand. All you need is len(alist), alist[i] = value, and value = alist[i]. A simple translation of a shellsort written in C would do the job admirably. Perhaps to Pythonise your mind you should try an object-oriented example -- one that truly needs a class or two; your shellsort doesn't really need a class (that's your Java background shining through!). HTH, John From and-google at doxdesk.com Tue Jun 13 23:33:23 2006 From: and-google at doxdesk.com (and-google at doxdesk.com) Date: 13 Jun 2006 20:33:23 -0700 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jun 12) References: Message-ID: <1150256003.535950.157580@u72g2000cwu.googlegroups.com> John Salerno wrote: > I love the new 'folder' icon, but how can I access it as an icon? I've just given these are proper home, so here: http://doxdesk.com/software/py/pyicons.html cheers! -- And Clover mailto:and at doxdesk.com http://www.doxdesk.com/ From belred at gmail.com Tue Jun 13 02:04:06 2006 From: belred at gmail.com (Bryan) Date: Mon, 12 Jun 2006 23:04:06 -0700 Subject: numeric/numpy/numarray Message-ID: hi, what is the difference among numeric, numpy and numarray? i'm going to start using matplotlib soon and i'm not sure which one i should use. this page says, "Numarray is a re-implementation of an older Python array module called Numeric" http://www.stsci.edu/resources/software_hardware/numarray this page says, "NumPy derives from the old Numeric code base and can be used as a replacement for Numeric." http://numeric.scipy.org/ i looked at the matplotlib examples today and if i remember correctly, the examples didn't use numarray. so i'm a bit confused. thanks, bryan From nmm1 at cus.cam.ac.uk Wed Jun 28 11:11:57 2006 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 28 Jun 2006 15:11:57 GMT Subject: Immutability References: <1151493892.192120.113760@p79g2000cwp.googlegroups.com> Message-ID: In article <1151493892.192120.113760 at p79g2000cwp.googlegroups.com>, "Gerard Flanagan" writes: |> |> There are (unofficial) documentation wikis here: |> |> pytut.infogami.com |> pyref.infogami.com |> pyfaq.infogami.com Thanks very much. |> You might like to consider adding the information you perceive to be |> lacking. Consider it considered, but I have to start by understanding what is supposed to happen and what does happen, precisely and in detail. Regards, Nick Maclaren. From *firstname*nlsnews at georgea*lastname*.com Wed Jun 14 13:26:03 2006 From: *firstname*nlsnews at georgea*lastname*.com (Tony Nelson) Date: Wed, 14 Jun 2006 17:26:03 GMT Subject: Trace KeyboardInterrupt exception? References: <*firstname*nlsnews-B3800F.13431013062006@news.verizon.net> <1150293702.090195.324550@y43g2000cwc.googlegroups.com> Message-ID: <*firstname*nlsnews-04EFB8.13261714062006@news.verizon.net> In article <1150293702.090195.324550 at y43g2000cwc.googlegroups.com>, andrewdalke at gmail.com wrote: > Tony Nelson wrote: > > I'm trying to find out what is eating some KeyboardInterrupt exceptions > > in a fairly large program (yum). My KeyboardInterrupt handler is called > > for some Ctl-C presses, but for others nothing seems to happen. > > > ... I'd like to use a debugger to trace > > KeyboardInterrupt exceptions, make sure that they're happening, and see > > what is handling them. > > I don't know how to do that in Idle. You can replace the default > Ctrl-C interrupt handler with your own and use that to inspect the > current stack. Thanky you, that helps. Interestingly, some Ctl-Cs don't get caught. Presumably they're happening in a subprocess. Now to see if I can get into that situation again where Ctl-C is ignored. I need to know what's eating the exceptions. I don't think it's a subprocess in the case I'm concerned with. I don't think yum is threaded, but apparantly importing the tread module anywhere should keep KeyboardInterrupt on the main thread anyway (?). It would be nice if I could inspect the stack and find the exception handlers. I'm using trace handlers, but their output seems somewhat spotty and inconsistent, or maybe just confusing. ________________________________________________________________________ TonyN.:' *firstname*nlsnews at georgea*lastname*.com ' From sreeram at tachyontech.net Sun Jun 4 14:12:20 2006 From: sreeram at tachyontech.net (K.S.Sreeram) Date: Sun, 04 Jun 2006 23:42:20 +0530 Subject: grouping a flat list of number by range In-Reply-To: <1149443841.948685.148840@i39g2000cwa.googlegroups.com> References: <1149196642.001466.53990@c74g2000cwc.googlegroups.com> <1149443841.948685.148840@i39g2000cwa.googlegroups.com> Message-ID: <44832284.30203@tachyontech.net> Yup! '_' is just used as a dummy. Its a pretty common idiom. There's nothing special about that variable. joh12005 at yahoo.fr wrote: > Hello > >> ... _, first_n = group[0] > > what is the meaning of the underscore "_" ? is it a special var ? or > should it be readed as a way of unpacking a tuple in a non useful var ? > like > > lost, first_n = group[0] > > best regards. > -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 260 bytes Desc: OpenPGP digital signature URL: From yairchu at gmail.com Wed Jun 7 04:01:27 2006 From: yairchu at gmail.com (yairchu at gmail.com) Date: 7 Jun 2006 01:01:27 -0700 Subject: how not to run out of memory in cursor.execute References: <1149447895.037396.81550@j55g2000cwa.googlegroups.com> Message-ID: <1149667287.092087.111270@c74g2000cwc.googlegroups.com> whenever you are using a package that leaks memory. it can be appropriate to use Rpyc (http://rpyc.wikispaces.com/) to run the leaking code in a different process, and restart it from time to time. I've been using this method to avoid the leaks of matplotlib. From eval.apply at gmail.com Mon Jun 26 13:00:32 2006 From: eval.apply at gmail.com (Joe Marshall) Date: 26 Jun 2006 10:00:32 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150998222.352746.65520@i40g2000cwc.googlegroups.com> <1151026856.064429.36460@c74g2000cwc.googlegroups.com> <1151079774.429512.68840@c74g2000cwc.googlegroups.com> <1151098655.828408.286630@y41g2000cwy.googlegroups.com> Message-ID: <1151341232.468150.254980@c74g2000cwc.googlegroups.com> David Hopwood wrote: > > Joe Marshall wrote: > >> > >>I do this quite often. Sometimes I'll develop `in the debugger'. I'll > >>change some piece of code and run the program until it traps. Then, > >>without exiting the debugger, I'll fix the immediate problem and > >>restart the program at the point it trapped. This technique takes a > >>bit of practice, but if you are working on something that's complex and > >>has a lot of state, it saves a lot of time because you don't have to > >>reconstruct the state every time you make a change. > > The problem with this is that from that point on, what you're running > is neither the old nor the new program, since its state may have been > influenced by the bug before you corrected it. Yes. The hope is that it is closer to the new program than to the old. > I find it far simpler to just restart the program after correcting > anything. If this is too difficult, I change the design to make it > less difficult. In the most recent case where I was doing this, I was debugging transaction rollback that involved multiple database extents. It was somewhat painful to set up a clean database to the point where I wanted to try the rollback, and I wanted a pristine database for each trial so I could examine the raw bits left by a rollback. It was pretty easy to deal with simple errors in the debugger, so I chose to do that instead. > > > Wow, interesting. > > > > (I say the following only to point out differing strategies of > > development, not to say one or the other is right or bad or > > whatever.) > > > > I occasionally find myself doing the above, and when I do, > > I take it as a sign that I've screwed up. I find that process > > excruciating, and I do everything I can to avoid it. Over the > > years, I've gotten more and more adept at trying to turn > > as many bugs as possible into type errors, so I don't have > > to run the debugger. > > > > Now, there might be an argument to be made that if I had > > been using a dynamic language, the process wouldn't be > > so bad, and I woudn't dislike it so much. But mabe: > > > > As a strawman: suppose there are two broad categories > > of mental strategies for thinking about bugs, and people > > fall naturally into one way or the other, the way there > > are morning people and night people. One group is > > drawn to the static analysis, one group hates it. > > One group hates working in the debugger, one group > > is able to use that tool very effectively and elegantly. > > > > Anyway, it's a thought. > > I don't buy this -- or at least, I am not in either group. > > A good debugger is invaluable regardless of your attitude to type > systems. Recently I was debugging two programs written to do similar > things in the same statically typed language (C), but where a debugger > could not be used for one of the programs. It took maybe 5 times > longer to find and fix each bug without the debugger, and I found it > a much more frustrating experience. > > -- > David Hopwood From nospamformeSVP at gmail.com Mon Jun 19 21:00:06 2006 From: nospamformeSVP at gmail.com (Don Taylor) Date: Mon, 19 Jun 2006 21:00:06 -0400 Subject: wxPython GUI designer In-Reply-To: References: <1150661348.837969.46870@r2g2000cwb.googlegroups.com> Message-ID: aum wrote: > On Sun, 18 Jun 2006 13:09:08 -0700, diffuser78 wrote: > >> I am newbie learning wxPython. I tried using GUI designer called >> wxGlade. When it generated code I couldnt get the same level of >> flexibility as writing the code by oneself. >> >> Any view on what you think about using GUI designer tools. >> >> Every help is appreciated. > > I use wxGlade all the time, and find it's great. My only complaint is that > there are some controls it doesn't know about, such as wx.HtmlWindow, and > I have to add these controls in wxGlade as 'custom' controls. But to me, > that's pretty minor. > > To get the best out of wxGlade, you really need to subclass the classes > that wxGlade generates. Don't look to wxGlade to write your app for you. > It's there for gui structure (the 'view'), and it's up to you to flesh out > the 'controller' side. > > So I'd recommend you persist with wxGlade - subclass all the classes that > wxGlade generates, and add your own methods to handle events, set up the > gui as you want, and (in some rare cases) do some extra initial bindings. > > I typically set wxGlade to generate a file called 'myapp_ui.py', and I > write my own 'myapp.py', in which I 'import myapp_ui', then subclass the > wxGlade-generated classes in 'myapp_ui'. > > Works a treat for me, and saves a lot of time compared to hand-coding the > GUI. > I second this approach to using wxGlade, it works really well although I have not seen it documented anywhere. I am not sure if 'aum' meant this, but I let wxGlade generate the event methods for me in 'myapp_ui.py' and then override them in 'myapp.py'. You have full control over the code in your own 'myapp.py' and you rarely have to mess with 'myapp_ui.py' so you can let wxGlade keep control of that file. wxGlade does not support GridBag sizers, which is a shame, but otherwise its support for sizers is good. I find it easy to use sizers in wxGlade. Pythoncard does not yet support sizers and I have never been able to get Boa's sizers to work consistently. wxGlade is a bit flaky on Windows but if you save often then it is OK. I was unsure about it at first, but now I like wxGlade's notion of not being a full-up IDE as it lets me choose the rest of the tool chain. wxGlade will play happily with anything: vim, emacs, Eclipse/Pydev, etc... Don. From Mike.S.Duffy at gmail.com Wed Jun 28 18:24:36 2006 From: Mike.S.Duffy at gmail.com (Mike Duffy) Date: 28 Jun 2006 15:24:36 -0700 Subject: ? on scipy.fftpack In-Reply-To: References: <1151513772.828636.225540@p79g2000cwp.googlegroups.com> Message-ID: <1151533476.160844.22670@75g2000cwc.googlegroups.com> Robert Kern wrote: > You will probably want to ask scipy questions on scipy-user. There aren't many > scipy people here. > > http://www.scipy.org/Mailing_Lists > > I haven't run your code, yet, but one of the things you are running into is the > FFT packing convention for FFTs on real functions. Please read the docstring: Ok, thanks a lot. I was unaware of that mailing list, I will certainly go there next. I have read the documentation, but I'm not sure what packing convention you are referring to. From max at alcyone.com Sun Jun 11 00:09:53 2006 From: max at alcyone.com (Erik Max Francis) Date: Sat, 10 Jun 2006 21:09:53 -0700 Subject: Xah Lee network abuse In-Reply-To: <1149998343.493200.144990@h76g2000cwa.googlegroups.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148495974.975395.12920@i40g2000cwc.googlegroups.com> <1149998343.493200.144990@h76g2000cwa.googlegroups.com> Message-ID: Mallor wrote: > I know I'm coming late to the barbeque. In passing, I ask: do you have > an objective, impartial perspective on the subject of committing > crimes? Because libel is a crime. No, it is a tort. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Bachelors have consciences, married men have wives. -- H.L. Mencken From alexreinhart at satx.rr.com Tue Jun 13 22:45:48 2006 From: alexreinhart at satx.rr.com (Alex Reinhart) Date: Wed, 14 Jun 2006 02:45:48 GMT Subject: [*SPAM*] Python open proxy honeypot In-Reply-To: References: Message-ID: Eric S. Johansson wrote: > Alex Reinhart wrote: >> Yeah, I just realized that. What would I do to act as an open proxy as >> well? > > emulate the Apache proxy capability, especially the reverse proxy. > > more seriously, what you need to do is from common proxy and web server > ports, accept proxy requests with a destination port number of 25 and > pretend to relay them. at least, that was the behavior I saw on a > misconfigured Apache web server proxy. Is there a library that implements such functionality (that I can override) or will I have to implement SOCKS and such myself? I've found one SOCKS library and it's rather old and out of date... From avelldiroll at yahoo.fr Wed Jun 21 01:44:58 2006 From: avelldiroll at yahoo.fr (Avell Diroll) Date: Wed, 21 Jun 2006 07:44:58 +0200 Subject: OS specific command in Python In-Reply-To: <1150783324.258644.65770@u72g2000cwu.googlegroups.com> References: <1150781429.090359.148560@c74g2000cwc.googlegroups.com> <1150783324.258644.65770@u72g2000cwu.googlegroups.com> Message-ID: <4498dcd5$0$25503$626a54ce@news.free.fr> stephanearnold at yahoo.fr wrote: > When you connect (via ssh or telnet) to a remote machine, you need to > type (manually) > your username and your password. Programming that is never easy. > This is really eased by the module getpass (std library) : ### import getpass login = getpass.getuser() password = getpass.getpass() ### If the username is different from your system login this can be changed to : ### import getpass login = raw_input('login: ') password = getpass.getpass() ### Python definitely comes with batteries included ! From tim.peters at gmail.com Thu Jun 8 18:10:32 2006 From: tim.peters at gmail.com (Tim Peters) Date: Thu, 8 Jun 2006 18:10:32 -0400 Subject: Large Dictionaries In-Reply-To: References: <1147699064.107490@teuthos> <1147772420.405097@teuthos> <1147818548.532882.94180@i39g2000cwa.googlegroups.com> <1147874585.728471@teuthos> <1148514158.790760.205630@i40g2000cwc.googlegroups.com> <447af556$1@nntp0.pdx.net> Message-ID: <1f7befae0606081510q5e9b6775r9e7d817c921f4ae4@mail.gmail.com> [Tim Peters] >> ... >> O(N log N) sorting algorithms helped by pre-existing order are >> uncommon, unless they do extra work to detect and exploit >> pre-existing order. [Lawrence D'Oliveiro] > Shellsort works well with nearly-sorted data. It's basically a smarter > version of bubblesort with much improved efficiency. It's also very > compact to implement. shellsort is much more a refinement of insertion-sort than of bubblesort, but is not an O(N log N) algorithm regardlesss. A nice, succinct summary of what was known about shellsort's behavior as of Sedgewick's 1996 "Analysis of Shellsort and Related Algorithms" can be found here: http://www.inf.fh-flensburg.de/lang/algorithmen/sortieren/shell/shellen.htm From jack at performancedrivers.com Wed Jun 7 14:41:55 2006 From: jack at performancedrivers.com (Jack Diederich) Date: Wed, 7 Jun 2006 14:41:55 -0400 Subject: Writing to a certain line? In-Reply-To: References: <1149576072.168354.14470@f6g2000cwb.googlegroups.com> <44854184$0$29904$636a55ce@news.free.fr> <1149630414.246008.270720@f6g2000cwb.googlegroups.com> <448697f7$0$10260$626a54ce@news.free.fr> <44869dd3$0$31210$626a54ce@news.free.fr> Message-ID: <20060607184155.GJ5748@performancedrivers.com> On Wed, Jun 07, 2006 at 08:17:22PM +0200, Fredrik Lundh wrote: > Christophe wrote: > > > Use /dev/zero as source and /dev/null as destination :D > > have you tried looping over an endless null-byte stream? > > on a random Linux server, this statement > > >>> for line in open("/dev/zero"): > ... print len(line) > ... > > terminates without printing anything after about three seconds, which is > a bit odd. in contrast, > > >>> f = open("/dev/zero") > >>> len(f.readline()) > > raises a MemoryError exception after about 10 seconds. hmm. looks like > a bug in the file iterator, really... svn log Objects/fileobject.c r43506 | georg.brandl | 2006-03-31 15:31:02 -0500 (Fri, 31 Mar 2006) | 2 lines Bug #1177964: make file iterator raise MemoryError on too big files So it always the error on the trunk. -Jack From rupole at hotmail.com Tue Jun 13 22:47:31 2006 From: rupole at hotmail.com (Roger Upole) Date: Tue, 13 Jun 2006 22:47:31 -0400 Subject: How to select a folder with native windows dialog box? References: <1150237380.370088.29270@p79g2000cwp.googlegroups.com> Message-ID: <1150252926_60371@sp6iad.superfeed.net> You can use SHBrowseForFolder: from win32com.shell import shell shell.SHBrowseForFolder() Roger wrote in message news:1150237380.370088.29270 at p79g2000cwp.googlegroups.com... >I found the win32ui.CreateFileDialog() function to select a file but > nothing to select a folder :'-( > Maybe someone has a solution for this? > Thanks! > ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups ----= East and West-Coast Server Farms - Total Privacy via Encryption =---- From fredrik at pythonware.com Thu Jun 15 17:26:36 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 15 Jun 2006 23:26:36 +0200 Subject: Which compiler will Python 2.5 / Windows (Intel) be built with? In-Reply-To: <1150406005.948538.188950@h76g2000cwa.googlegroups.com> References: <1150367139.495114.148550@g10g2000cwb.googlegroups.com> <44917535$1@nntp0.pdx.net> <1150391891.130185.4640@f6g2000cwb.googlegroups.com> <4491b9e1$1@nntp0.pdx.net> <1150406005.948538.188950@h76g2000cwa.googlegroups.com> Message-ID: meyer at mesw.de wrote: > I'm not sure how that backs the point you made. Infact, you're saying > that people accepted that Python 2.4 was compiled with VS2003 because > VC6 could not longer be bought. How is that different from the current > situation where the VS2003 toolkit cannot longer be downloaded and it > is at least becoming increasingly difficult to buy versions of VS2003? > You also seem to imply that there is a large group of people that want > you to stay with VS2003 for compiling Python 2.5. what part of "Python 2.4 is built with VC2003 and everyone who's ever built Windows stuff for Python 2.4 already has it" do you have trouble understanding ? From meyer at mesw.de Thu Jun 15 17:19:52 2006 From: meyer at mesw.de (meyer at mesw.de) Date: 15 Jun 2006 14:19:52 -0700 Subject: Which compiler will Python 2.5 / Windows (Intel) be built with? In-Reply-To: References: <1150367139.495114.148550@g10g2000cwb.googlegroups.com> <44917535$1@nntp0.pdx.net> <1150391891.130185.4640@f6g2000cwb.googlegroups.com> <4491b9e1$1@nntp0.pdx.net> Message-ID: <1150406392.321505.224820@h76g2000cwa.googlegroups.com> Hi Fredrik, first, thanks for PIL, I use it extensively in my daily work ;) Fredrik Lundh wrote: > huh? 2.5 isn't released yet. if you *have* a Python app, you can > continue to use the same compiler when you upgrade from 2.4 and 2.5. > it's not like anyone is forcing you to uninstall the compiler just > because you upgrade Python... No, but the compiler that used to be available for compiling 2.4 extensions is no longer available and/or supported. So there is/was hope that 2.5 might improve the situation because then compiling extensions would be possible again with the currently available compiler from Microsoft. This would require that Python 2.5 be built with this compiler of course. So the situation is actually worse than before (when the 2003 toolkit was available), and the decision for 2003 means that it won't improve with the release of 2.5. I believe this is what the gp was trying to say... Markus From slawomir.nowaczyk.847 at student.lu.se Tue Jun 27 18:55:16 2006 From: slawomir.nowaczyk.847 at student.lu.se (Slawomir Nowaczyk) Date: Wed, 28 Jun 2006 00:55:16 +0200 Subject: How do you use this list ? In-Reply-To: <12a2foromcuj30b@corp.supernews.com> References: <12a2foromcuj30b@corp.supernews.com> Message-ID: <20060628004930.B7B3.SLAWOMIR.NOWACZYK.847@student.lu.se> On Tue, 27 Jun 2006 14:22:19 +0000 Grant Edwards wrote: #> Actually having mailing lists send you mail is insane. Just curious: what's insane about it? -- Best wishes, Slawomir Nowaczyk ( Slawomir.Nowaczyk at cs.lth.se ) Never attribute to malice that which can be adequately explained by stupidity. From flippa at flippac.org Sun Jun 11 02:57:04 2006 From: flippa at flippac.org (Philippa Cowderoy) Date: Sun, 11 Jun 2006 07:57:04 +0100 Subject: Xah Lee network abuse In-Reply-To: References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148495974.975395.12920@i40g2000cwc.googlegroups.com> <1149998343.493200.144990@h76g2000cwa.googlegroups.com> Message-ID: On Sat, 10 Jun 2006, Erik Max Francis wrote: > Mike Schilling wrote: > > > If I were to write, say, that Tony Blair's tax policy will lead to higher > > deficits, I could be convicted of libel? Even if that's true, it's not a > > priori provable. > > I think what he was getting at is that, unlike many jurisdictions, writing > something factually true is _not_ in and of itself a defense against a libel > suit in the UK. > It is. However, the onus is on the defendant to show that it's true, rather than on the claimant to show that it's false. I assume the "he" refers to Brandon? -- flippa at flippac.org A problem that's all in your head is still a problem. Brain damage is but one form of mind damage. From johnjsal at NOSPAMgmail.com Fri Jun 2 11:15:34 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 02 Jun 2006 15:15:34 GMT Subject: integer to binary... In-Reply-To: <1149197110.225383.107770@f6g2000cwb.googlegroups.com> References: <1149189570.376091.319890@j55g2000cwa.googlegroups.com> <1149197110.225383.107770@f6g2000cwb.googlegroups.com> Message-ID: mensanator at aol.com wrote: > Use the gmpy module. Yes, it's good. :) From jmbc at nospam.fr Wed Jun 14 16:38:31 2006 From: jmbc at nospam.fr (jean-michel bain-cornu) Date: Wed, 14 Jun 2006 22:38:31 +0200 Subject: wxPython, tree Control text cutoff In-Reply-To: <1150312112.865135.199390@g10g2000cwb.googlegroups.com> References: <1150312112.865135.199390@g10g2000cwb.googlegroups.com> Message-ID: <4490740c$0$7765$7a628cd7@news.club-internet.fr> Kiran a ?crit : > Hello all, > I am using a tree to display stuff, and it is constantly updated, but > what I have noticed is in the lowest level, there is clearly noticable > cutoff of the text I place there. The cutoff is existent even if I do > not update the text inside the tree constantly. It seems that the text > is halfway below where it should line up. I tried placing an image to > see if that would correct it, but it does not. The image is perfectly > lined up, but the text is still misaligned. > > Any known issues of this and how to fix it? By the way, it happens in > both Linux and Windows. Hi Kiran, It works fine if you change : x = self.tree.AppendItem(self.connections[i][j][0], "") to x = self.tree.AppendItem(self.connections[i][j][0], " ") I let you imagine the explanation... Regards, jm Just a hint : it'd be helpfull to solve such a bug if you make your program more simple. To find out the solution, I reduced your program to what's following, and the light came : import wx import wx.gizmos as gizmos class AlarmsWindow(wx.MDIChildFrame): def __init__(self, parent, title, size, pos): wx.MDIChildFrame.__init__(self, parent, -1, title, size = size, pos =pos) self.tree = gizmos.TreeListCtrl(self, -1, style = wx.TR_DEFAULT_STYLE| wx.TR_FULL_ROW_HIGHLIGHT) # create some columns self.tree.AddColumn("Connection") self.tree.AddColumn("Alarm") self.tree.AddColumn("Value") self.tree.SetMainColumn(0) self.root = self.tree.AddRoot("Connections") self.tree.Expand(self.root) self.tree.GetMainWindow().Bind(wx.EVT_RIGHT_UP, self.OnRightUp) self.Show() child = self.tree.AppendItem(self.root, 'name') self.tree.SetItemText(child, 'name') child2= self.tree.AppendItem(child,'name2') ## x = self.tree.AppendItem(child2, "") x = self.tree.AppendItem(child2, "XXX") self.tree.SetItemText(x, 'alarm', 1) self.tree.SetItemText(x, 'value', 2) def OnRightUp(self, evt): pass class MDIFrame(wx.MDIParentFrame): def __init__(self): wx.MDIParentFrame.__init__(self, None, -1, "MDI Parent", size =(600, 400)) child = AlarmsWindow(self, "Alarm", (400, 300), (0, 0)) if __name__=='__main__': app = wx.PySimpleApp() frame = MDIFrame() frame.Show() app.MainLoop() From david.nospam.hopwood at blueyonder.co.uk Sat Jun 24 11:38:08 2006 From: david.nospam.hopwood at blueyonder.co.uk (David Hopwood) Date: Sat, 24 Jun 2006 15:38:08 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> Message-ID: Anton van Straaten wrote: > I'm suggesting that if a language classifies and tags values in a way > that supports the programmer in static reasoning about the behavior of > terms, that calling it "untyped" does not capture the entire picture, > even if it's technically accurate in a restricted sense (i.e. in the > sense that terms don't have static types that are known within the > language). > > Let me come at this from another direction: what do you call the > classifications into number, string, vector etc. that a language like > Scheme does? And when someone writes a program which includes the > following lines, how would you characterize the contents of the comment: > > ; third : integer -> integer > (define (third n) (quotient n 3)) I would call it an informal type annotation. But the very fact that it has to be expressed as a comment, and is not checked, means that the *language* is not typed (even though Scheme is dynamically tagged, and even though dynamic tagging provides *partial* support for a programming style that uses this kind of informal annotation). -- David Hopwood From brochu121 at gmail.com Wed Jun 14 10:18:06 2006 From: brochu121 at gmail.com (david brochu jr) Date: Wed, 14 Jun 2006 10:18:06 -0400 Subject: newbe: tuple Message-ID: <9583ed900606140718w2ddf1d9k5257de94c431e165@mail.gmail.com> I am trying to get my ip address through a script and I am using the following code: import socket ip = socket.gethostbyaddr(socket.gethostname()) ip then becomes a tuple and takes on three values. I am trying to pull the value of ip[2] which when printed displays: ['10.5.100.17']. I want this ip that is being returned, but I would like it as a string, without the [' and ']. Any idea how I would trim this down? -------------- next part -------------- An HTML attachment was scrubbed... URL: From gene.tani at gmail.com Fri Jun 2 13:55:36 2006 From: gene.tani at gmail.com (gene tani) Date: 2 Jun 2006 10:55:36 -0700 Subject: Are there something like "Effective Python"? In-Reply-To: <1149224468.481470.74580@i39g2000cwa.googlegroups.com> References: <1149224468.481470.74580@i39g2000cwa.googlegroups.com> Message-ID: <1149270936.264741.39820@y43g2000cwc.googlegroups.com> Mike Meng wrote: > Hi all, > I just finished reading Learning Python 3rd ed, and am doing my > first Python application, which retrieves and process text and XML > documents from Web. Python helped me to write the application in a few > hours, I'm very happy with its productivity. But the performance is not > satisfactory. I decide to optimized it in Python before trying C/C++ > extensions. But I don't know Python much and have no clu to tune my > program. Also, I don't know what Pythonist's preferred styles. Are > there any books/documents which play the similar role for Python as > 'Effective C++' does for C++? > > For example, one of my friends read my program and suggest me to > move the re.compile() out of a for-loop, since the regular pattern is > fixed, and re.compile() is slow. I want to find more such advice, where > can I find them? > Here's some links to profiling tools http://www.python.org/doc/current/lib/profile.html http://www.onlamp.com/lpt/a/6376 http://www.vrplumber.com/programming/runsnakerun/ http://mail.python.org/pipermail/python-list/2006-January/318295.html From kydavis77 at gmail.com Mon Jun 26 13:47:58 2006 From: kydavis77 at gmail.com (kydavis77 at gmail.com) Date: 26 Jun 2006 10:47:58 -0700 Subject: Beginner Programmer Question In-Reply-To: <1151343949.958134.257960@b68g2000cwa.googlegroups.com> References: <1151342733.742416.180370@r2g2000cwb.googlegroups.com> <1151343383.139891.219270@u72g2000cwu.googlegroups.com> <1151343641.509435.245210@u72g2000cwu.googlegroups.com> <1151343759.716134.169950@c74g2000cwc.googlegroups.com> <1151343949.958134.257960@b68g2000cwa.googlegroups.com> Message-ID: <1151344078.584742.95990@y41g2000cwy.googlegroups.com> Rune Strand wrote: > kydavis77 at gmail.com wrote: > > Rune Strand wrote: > > > > > > > > I am doing alot of reading, and the problem didnt come with an answer. > > > > I dont understand how to get it to continually input numbers and add > > > > all those together > > > > > > Use while, raw_input, sys.argv[1] and int() and break the loop when the > > > sum is above 100. > > > > > > ;-) > > > > thanks for the help..but i am extremley new and what you said makes no > > sense to me > > In the code you posted above here: Move the input into the while loop. > You may prefer raw_input() to input(). > > I don't want to write the code for you ;-) whats the difference between raw input and input? From maric at aristote.info Mon Jun 26 19:41:32 2006 From: maric at aristote.info (Maric Michaud) Date: Tue, 27 Jun 2006 01:41:32 +0200 Subject: replace a method in class: how? In-Reply-To: <44A06A6B.6010200@bryant.edu> References: <44A06A6B.6010200@bryant.edu> Message-ID: <200606270141.33741.maric@aristote.info> Le mardi 27 juin 2006 01:14, Brian Blais a ?crit?: > t=This() > t.update(5) > t.update=another_update > t.update(5) ?# this one doesn't work, gives > # TypeError: another_update() takes exactly 2 arguments (1 given) > > > clearly it isn't seeing it as a method, just an attribute which happens to > be a function. ?Is there a preferred way to do this? Yes, this is because you assigned it to the instance, not the class, it should be : t=This() t.update(5) This.update=another_update t.update(5) In OOP Methods are defined in *classes* not in any arbitrary object (ie. instances). You can learn more on how it works in python reading about the descriptor protocol of new style class (__getattribute__ special method). To clearly understand what belongs to class and what belongs to instances, try : u=This() t.prop = None t.prop u.prop This.other_prop = None t.other_prop, u.other_prop This.__dict__.items() t.__dict__, u.__dict__ -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From yairchu at gmail.com Wed Jun 7 04:03:15 2006 From: yairchu at gmail.com (yairchu at gmail.com) Date: 7 Jun 2006 01:03:15 -0700 Subject: A more elegant way to do this list comprehension? In-Reply-To: References: <12428afb0606062046nda97570j2b5eb7cab5518352@mail.gmail.com> Message-ID: <1149667395.758813.25010@g10g2000cwb.googlegroups.com> > > [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 7, 7, > > 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8] > [i+1 for i in range(8) for j in range(i+1)] [i for i in range(9) for j in range(i)] From siona at chiark.greenend.org.uk Wed Jun 14 07:39:16 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 14 Jun 2006 12:39:16 +0100 (BST) Subject: determining file type References: <1150276935.270798.5550@i40g2000cwc.googlegroups.com> <1150281704.342529.206640@u72g2000cwu.googlegroups.com> Message-ID: Ritesh Raj Sarraf wrote: >Also, >f =3D file ('some_file.jpg') > >throws an error. >"str object is not callable" You know all the times people say in this group "Don't use list or str or file[HINT] or anything else that shadows a built in as a variable name"? Now you know why. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From fredrik at pythonware.com Fri Jun 2 02:01:26 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 02 Jun 2006 08:01:26 +0200 Subject: image lib & Qt4 In-Reply-To: References: <1149173540.470829.34940@c74g2000cwc.googlegroups.com> <4e8haiF1dp2heU1@uni-berlin.de> <1149180814.585713.209640@i39g2000cwa.googlegroups.com> Message-ID: Fredrik Lundh wrote: > To get better performance, you should be able to use PIL's tostring() > method together with the QImage(buffer, width, height, depth, > colortable, numColors, bitOrder) form of the QImage constructor. for PyQt4, that seems to have changed to QImage(buffer, width, height, format), where format is a QImage.Format_XXX specifier. in other words, this should work: if im.mode != "RGB": im = im.convert("RGB") data = im.tostring("raw", "BGRX") image = QImage(data, im.size[0], im.size[1], QImage.Format_RGB32) note that the QImage descriptor will point into the data buffer, so you must hang on to data for as long you're using image. (I haven't found a way to attach a user attribute to a QImage class; it doesn't complain when I do that, but it doesn't seem to do the right thing...) From fredrik at pythonware.com Sun Jun 11 03:49:16 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 11 Jun 2006 09:49:16 +0200 Subject: Most elegant way to generate 3-char sequence In-Reply-To: References: <1149889784.391965.271570@h76g2000cwa.googlegroups.com> Message-ID: James Stroud wrote: > See the actual question: > > >How would you construct a generator to acheive this? if you don't think the context provided by the subject line and the sentence before the question is important, how come you're so sure what "this" refers to ? From pc at p-cos.net Sat Jun 24 15:17:06 2006 From: pc at p-cos.net (Pascal Costanza) Date: Sat, 24 Jun 2006 21:17:06 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: <1151171007.230666.235430@r2g2000cwb.googlegroups.com> References: <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150904134.520639.71070@b68g2000cwa.googlegroups.com> <1151056505.908723.162580@u72g2000cwu.googlegroups.com> <1151171007.230666.235430@r2g2000cwb.googlegroups.com> Message-ID: <4g5hdiF1lpuniU1@individual.net> Marshall wrote: > Anton van Straaten wrote: >> But beyond that, there's an issue here about the definition of "the >> language". When programming in a latently-typed language, a lot of >> action goes on outside the language - reasoning about static properties >> of programs that are not captured by the semantics of the language. >> >> This means that there's a sense in which the language that the >> programmer programs in is not the same language that has a formal >> semantic definition. As I mentioned in another post, programmers are >> essentially mentally programming in a richer language - a language which >> has informal (static) types - but the code they write down elides this >> type information, or else puts it in comments. >> >> We have to accept, then, that the formal semantic definitions of >> dynamically-checked languages are incomplete in some important ways. >> Referring to those semantic definitions as "the language", as though >> that's all there is to the language in a broader sense, is misleading. >> >> In this context, the term "latently-typed language" refers to the >> language that a programmer experiences, not to the subset of that >> language which is all that we're typically able to formally define. > > That is starting to get a bit too mystical for my tastes. To paraphrase Abelson & Sussman: Programs must be written for people to read, and only incidentally for compilers to check their types. ;) Pascal -- 3rd European Lisp Workshop July 3 - Nantes, France - co-located with ECOOP 2006 http://lisp-ecoop06.bknr.net/ From onurb at xiludom.gro Fri Jun 9 10:25:58 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 09 Jun 2006 16:25:58 +0200 Subject: removing dictionary key-pair In-Reply-To: <448984a9$0$14889$626a54ce@news.free.fr> References: <128j0r7tla1qi12@corp.supernews.com> <448984a9$0$14889$626a54ce@news.free.fr> Message-ID: <448984f7$0$1667$626a54ce@news.free.fr> bruno at modulix wrote: > JD wrote: > >>Hello, >> >>I try to remove a dictionary key-pair (remove an entry), >>but I'm unsuccessful. Does anyone know how to achieve this? >> >>Thanks > > > mydict = {"key" : "value"} > del mydict(key) grmf... Typo. This is: del mydict['key'] of course... -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From sanxiyn at gmail.com Thu Jun 8 01:00:23 2006 From: sanxiyn at gmail.com (Sanghyeon Seo) Date: Thu, 8 Jun 2006 14:00:23 +0900 Subject: ctypes for IronPython (preliminary) Message-ID: <5b0248170606072200k111bc8acw649d06ee2511713@mail.gmail.com> ctypes is a popular CPython extension planned for inclusion in Python 2.5. It is a foreign function interface library. Homepage: http://starship.python.net/crew/theller/ctypes/ Documentation: http://docs.python.org/dev/lib/module-ctypes.html I would like to announce a preliminary implementation of ctypes for IronPython using .NET's P/Invoke machinery. Code is here: http://sparcs.kaist.ac.kr/~tinuviel/fepy/lib/ctypes.py Example is here: http://sparcs.kaist.ac.kr/~tinuviel/fepy/example/ctypes_test.py The example can be run on IronPython as well as on CPython. What's missing: * Many primitive types * .value on primitive types * Buffers and .raw * Pointer and .contents * Reference * Array * Structure and union and .offset * Recursive type * Callback * External value * Windows goodies In short, everything except those needed to demo anything interesting. :-) But you can do this now: IronPython 1.0.60523 (Beta) on .NET 2.0.50727.42 Copyright (c) Microsoft Corporation. All rights reserved. >>> from ctypes import * >>> print cdll.msvcrt.strlen('hello') 5 >>> Enjoy! Seo Sanghyeon From onurb at xiludom.gro Thu Jun 22 10:36:00 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Thu, 22 Jun 2006 16:36:00 +0200 Subject: Registry of Methods via Decorators In-Reply-To: <1150983145.387222.5600@c74g2000cwc.googlegroups.com> References: <1150983145.387222.5600@c74g2000cwc.googlegroups.com> Message-ID: <449aaad1$0$4477$636a55ce@news.free.fr> bayerj wrote: > I want to make a registry of methods of a class during creation. My > attempt was this > > """ classdecorators.py > > Author: Justin Bayer > Creation Date: 2006-06-22 > Copyright (c) 2006 Chess Pattern Soft, > All rights reserved. """ > > class decorated(object): > > methods = [] > > @classmethod > def collect_methods(cls, method): > cls.methods.append(method.__name__) > return method > > class dec2(decorated): > > @collect_methods > def first_func(self): > pass > > @collect_methods > def second_func(self): > pass > > > def main(): > print dec2.methods > > if __name__ == '__main__': > main() > > This does not work and exits with "NameError: ("name 'collect_methods' > is not defined",)". Which is understandable due to the fact that the > class dec2 is not complete. > > Anyone can give me a hint how to work around this? If you insist on doing black-magic (else go directly to the end of this post), here's a way to do it, based on Ian Bicking's __classinit__ recipe http://blog.ianbicking.org/a-conservative-metaclass.html (BTW, Ian, many many thanks for this trick - I really love it). class DeclarativeMeta(type): def __new__(meta, class_name, bases, new_attrs): cls = type.__new__(meta, class_name, bases, new_attrs) cls.__classinit__.im_func(cls, new_attrs) return cls class Declarative(object): __metaclass__ = DeclarativeMeta def __classinit__(cls, new_attrs): pass class MethodCollector(Declarative): def __classinit__(cls, new_attrs): cls.methods = [name for name, attr in new_attrs.items() \ if callable(attr)] class dec2(MethodCollector): def first_func(self): pass def second_func(self): pass If you want to choose which methods to collect, then it's just a matter of adding a simple decorator and a test in MethodCollector.__classinit__: def collect(func): func._collected = True return func class MethodCollector(Declarative): def __classinit__(cls, new_attrs): cls.methods = [name for name, attr in new_attrs.items() \ if callable(attr) \ and getattr(attr, '_collected', False)] class dec2(MethodCollector): @collect def first_func(self): pass @collect def second_func(self): pass def not_collected(self): pass *BUT* is it really useful to go thru all this mess ? class DeadSimple(object): @classmethod def methods(cls): return [name for name in dir(cls) \ if not name.startswith('__') \ and callable(getattr(cls, name))] My 2 cents... -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From scott.daniels at acm.org Tue Jun 13 01:06:14 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Mon, 12 Jun 2006 22:06:14 -0700 Subject: wxpython: how do i write this without the id parameter? In-Reply-To: References: Message-ID: <448e430d$1@nntp0.pdx.net> John Salerno wrote: > I was reading in the wxPython wiki that most of the time you don't have > to include the id parameter at all, and you can just use keyword > arguments for other parameters. But I'm having trouble converting this > code into that method (i.e., without the id parameter).... > > import wx > > class InputForm(wx.Frame): > def __init__(self, parent, id, title): > wx.Frame.__init__(self, parent, id, title) > panel = wx.Panel(self) > self.btnOK = wx.Button(panel, label='OK') > self.btnCancel = wx.Button(panel, label='Cancel') > sizer = wx.BoxSizer(wx.HORIZONTAL) > sizer.Add(self.btnOK, 0, wx.ALL, 10) > sizer.Add(self.btnCancel, 0, wx.ALL, 10) > panel.SetSizer(sizer) > > class MyApp(wx.App): > def OnInit(self): > frame = InputForm(None, -1, title='Data Entry Form') > self.SetTopWindow(frame) > frame.Show() > return True > > app = MyApp(redirect=False) > app.MainLoop() import wx __version__ = '0.0' class InputForm(wx.Frame): def __init__(self, parent=None, id=-1, title=__file__): # or, if you prefer: ..., id=wx.ID_ANY, ... wx.Frame.__init__(self, parent=parent, id=id, title='%s v%s' % (title, __version__)) panel = wx.Panel(self) sizer = wx.BoxSizer(wx.HORIZONTAL) panel.SetSizer(sizer) sizer.Add(wx.Button(panel, label='OK'), 0, wx.ALL, 10) sizer.Add(wx.Button(panel, label='Cancel'), 0, wx.ALL, 10) class MyApp(wx.App): def OnInit(self): frame = InputForm(title='Data Entry Form') self.SetTopWindow(frame) frame.Show() return True if __name__ == '__main__': MyApp(redirect=False).MainLoop() --Scott David Daniels scott.daniels at acm.org From grflanagan at yahoo.co.uk Sun Jun 11 07:45:54 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 11 Jun 2006 04:45:54 -0700 Subject: Algorithm for Labels like in Gmail References: <1149985001.668803.121260@c74g2000cwc.googlegroups.com> Message-ID: <1150026354.741489.273420@g10g2000cwb.googlegroups.com> rhcarvalho at gmail.com wrote: > Hello there! > > I'm trying to make a simple Contact Manager using python (console > only), however i'm having trouble implementing a division by "Groups" > or "Labels" just like in Gmail. I don't have any real code to post > because all i got now is a raw TXT file holding the names and phones of > my contacts. > > The only idea I could figure out until now seems too weak, so that's > why i'm asking for help. I thought of making a separate list (in a text > file) holding all the possible groups, where each group hold the names > of the contacts. Then if i access a group, i'll be able to see all > contacts related to that group. On the other hand, i'll also need to > attach to the contact instance a list of every group it is present. > I think it's a bad idea because it seems to be very easy to get things > messed up. Like I can get things corrupted or bad linked, and i'll > always need to run functions to check all the realations between > contact names and groups... > > I like the way i can "label" emails on Gmail, does anyone know how I > can implement such kind of feature? What's the best/broadly used > algorithm? > > Sorry for the long message, and thanks in advance > > Rodolfo Carvalho There's a program called 'buzhug' (http://buzhug.sourceforge.net/) which is described as "a pure-Python database engine, using a Pythonic, no-SQL syntax". I think it's in its early stages of development but it might be suitable for your project. I spent the morning playing about with it using your example of a (Very Simple) Contact Manager, and there's some runnable but unfinished code below. It only implements a 'Many-to-one' relationship between Contacts and Groups - in other words, a Contact can only belong to one Group. There's probably a lot I haven't considered, it will break easily, and the docstrings are in the post, but there you go. Have fun! Gerard (also - http://groups.google.com/group/buzhug) ------------------------------------------------------------ print from buzhug import Base import os def get_bases(): if os.path.exists('data'): return Base('data/dt_groups'), Base('data/dt_contacts') else: #Bases don't exist, so create them os.mkdir('data') groups = Base('data/dt_groups') groups.create( ('name', str) ) groups.insert( 'Family' ) groups.insert( 'Friends' ) groups.commit() contacts = Base('data/dt_contacts') contacts.create( ('group', groups), ('first_name', str), ('last_name', str), ('email', str) ) contacts.insert( groups[0], 'Jack', 'Jones', 'jj at abcd.com' ) contacts.insert( groups[0], 'John', 'Jones', 'jj at wxyz.com' ) contacts.insert( groups[1], 'James', 'diGriz', 'digriz at stainless.com' ) contacts.insert( groups[1], 'Dirk', 'Gently', 'dirk at dogstoerd.com' ) contacts.commit() return groups, contacts def usage(): print ''' ADD - Add a Contact eg. ADD Family, Susan, Smith, suzie at hatmail.com eg. ADD Work, Jason, Jones, jj at mywork.com DEL - Delete a Contact or Group eg. DEL firstname=Susan, lastname=Smith eg. DEL group=Family FIND - Search for contacts eg. FIND lastname=Smith eg. FIND group=Family EXIT - End the program ''' def intro(): print '\n' * 5 print '#' * 52 print '#' * 20, ' CONTACTS ', '#' * 20 print '#' * 52 usage() print '\n' * 2 def get_input(prompt): s = raw_input(prompt).strip() if s.upper() == 'EXIT': raise EOFError return s def ADD(groupname, firstname, lastname, email): groups, contacts = get_bases() try: groups.open() #see if a group with this name exists records = [ g for g in groups if g.name == groupname ] if len(records) == 0: #no group with this name, so create it gid = groups.insert( name=groupname.strip() ) group = groups[gid] else: group = records[0] finally: groups.commit() try: contacts.open() contacts.insert(group, firstname.strip(), lastname.strip(), email.strip()) finally: contacts.commit() def test(): groups, contacts = get_bases() try: contacts.open() for contact in contacts: print contact.group.name, contact.first_name, contact.last_name finally: contacts.commit() if __name__ == '__main__': intro() while True: try: s = get_input('-> ') if s[0] == '?': usage() elif s == 'test': test() elif s[:4] == 'ADD ': grp, fname, lname, email = s[4:].split(',') try: ADD(grp, fname, lname, email) except Exception, e: print e except EOFError: break print '\nbye' -------------------------------------------------------------------- From onurb at xiludom.gro Tue Jun 6 06:44:57 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 06 Jun 2006 12:44:57 +0200 Subject: Writing to a certain line? In-Reply-To: <46la821oa3s4nr4vcfa6nbg03lcq0jl1jf@4ax.com> References: <1149576072.168354.14470@f6g2000cwb.googlegroups.com> <44854184$0$29904$636a55ce@news.free.fr> <46la821oa3s4nr4vcfa6nbg03lcq0jl1jf@4ax.com> Message-ID: <44855ca9$0$11207$636a55ce@news.free.fr> Rene Pijlman wrote: > bruno at modulix: > >>You can't do this in place with a text file (would be possible with a >>fixed-length binary format). > > > More precise: it's possible with any fixed-length change, in both binary > and text files, with both fixed and variable formats. > Granted. But this is somewhat limited in what you can do when working with text files... -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From jd at something.com Fri Jun 9 10:19:19 2006 From: jd at something.com (JD) Date: Fri, 09 Jun 2006 14:19:19 -0000 Subject: removing dictionary key-pair Message-ID: <128j0r7tla1qi12@corp.supernews.com> Hello, I try to remove a dictionary key-pair (remove an entry), but I'm unsuccessful. Does anyone know how to achieve this? Thanks From timr at probo.com Thu Jun 1 00:42:22 2006 From: timr at probo.com (Tim Roberts) Date: Thu, 01 Jun 2006 04:42:22 GMT Subject: TIming References: Message-ID: WIdgeteye wrote: >On Tue, 30 May 2006 16:15:44 +1000, John McMonagle wrote: > >> Tim Roberts is right. As you are on linux, I suggest you investigate the >> at command - very user friendly and not at all complicated. > >I have been using Slackware for over 10 years I know all about the >commands on the OS. > >If you guys don't have an answer to the question just say so. But don't >give me suggestions on how to use an OS I have been using most likely >longer than 90% of the people using linux today. > >This is the comp.lang.python news group not the linux news group. If I >didn't want to write the Python code and I wanted to use the OS commands >instead I would. Utter nonsense. If someone posted on comp.lang.python that they wanted to know how to write a DMA-based PCI driver in Python, I am sure as heck going to tell them that there are better tools for the job and better newsgroups for the question. >Python is cross platform. Linux is not. I intend to release the software >to the general public someday when it is done. I want it cross platform. Windows also has an "at" command. However, you are not going to be able to write a television-based application that is cross platform. The video tools are just too different. >BTW in the time it took me NOT to get an answer for my question in this so >called Python NG, I figured it out for myself. That's almost always the case with newsgroups. They are NOT a real-time medium. >This PYTHON NG blows to high heaven. Whats worse, the answers I got were >most likely from people who know SQUAT about Python scripting. That's why >they gave me such lame fucking answers. We did not give you "lame fucking answers". We gave you solutions to the problem you posed. If the problem statement wasn't clear enough, that isn't our fault. >Idiots. It takes one to know one. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From kadeko at gmail.com Fri Jun 30 07:35:33 2006 From: kadeko at gmail.com (looping) Date: 30 Jun 2006 04:35:33 -0700 Subject: Way for see if dict has a key In-Reply-To: <4F7pg.21676$_J1.272665@twister2.libero.it> References: <6V6pg.21624$_J1.271925@twister2.libero.it> <44a5041f$0$29637$636a55ce@news.free.fr> <4F7pg.21676$_J1.272665@twister2.libero.it> Message-ID: <1151667333.569664.152670@h44g2000cwa.googlegroups.com> Michele Petrazzo wrote: > Bruno Desthuilliers wrote: > >> but what the better > > > > Depends on the context. > > > > If know only one context: see if the key are into the dict... What other > context do you know? > > Michele Why do you want to do that ? if key in dict: value = dict[key] else: value = None could be write: try: value = dict[key] except KeyError: value = None so depends of the context... From jzgoda at o2.usun.pl Thu Jun 15 14:46:44 2006 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Thu, 15 Jun 2006 20:46:44 +0200 Subject: code folding, a unique problem to python? In-Reply-To: References: Message-ID: Paul McGuire napisa?(a): >>But my question is more general: is it possible to implement code >>folding with Python given that it has no real block delimiters? > > SciTE can fold Python. All other good editors can too. So general answer to this question is "yes". Because Python *has* real block delimiters... -- Jarek Zgoda http://jpa.berlios.de/ From luismgz at gmail.com Thu Jun 29 20:45:47 2006 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 29 Jun 2006 17:45:47 -0700 Subject: Reddit broke - should have remained on Lisp? In-Reply-To: <1151627924.322764.6040@y41g2000cwy.googlegroups.com> References: <1151626961.232761.255550@d56g2000cwd.googlegroups.com> <1151627462.297352.205150@i40g2000cwc.googlegroups.com> <1151627924.322764.6040@y41g2000cwy.googlegroups.com> Message-ID: <1151628347.551890.48050@y41g2000cwy.googlegroups.com> Alok wrote: > I was merely describing my experience and inviting others' response > about theirs. That's exactly what I'm doing. > Please don't misconstrue that as a blame on any language. I think it can be interpreted in many ways. Now if you're not ready to read other people's oppinions, don't ask. > And of course, I disagree with your comments about ridicule etc. Ok. From maric at aristote.info Mon Jun 26 10:23:06 2006 From: maric at aristote.info (Maric Michaud) Date: Mon, 26 Jun 2006 16:23:06 +0200 Subject: DictProxy? What is this? In-Reply-To: <1151330771.142051.312380@b68g2000cwa.googlegroups.com> References: <1151328077.677523.57820@b68g2000cwa.googlegroups.com> <1151330771.142051.312380@b68g2000cwa.googlegroups.com> Message-ID: <200606261623.07992.maric@aristote.info> Le lundi 26 juin 2006 16:06, digitalorganics at gmail.com a ?crit?: > Fredrik Lundh wrote: > > digitalorganics at gmail.com wrote: > > > When I tried to update a class's __dict__, I got an error saying that > > > there is no 'update' attribute for dictproxy object. What is a > > > dictproxy object? > > > > a CPython implementation detail, used to protect an internal data > > structure used by new-style objects from unexpected modifications. > > > > > > Ah, so I'm not suppose to be able to change a class's __dict__? Thanks > Fredrik. Of course, yes : In [1]: class a(object) : pass ...: In [2]: a.__dict__ Out[2]: In [3]: a.__dict__.items() Out[3]: [('__dict__', ), ('__module__', '__main__'), ('__weakref__', ), ('__doc__', None)] In [4]: a.__dict__['foo'] = lambda s : True --------------------------------------------------------------------------- exceptions.TypeError... TypeError: object does not support item assignment hmmm, not this way, but : In [5]: a.foo = lambda s : True In [6]: a.__dict__.items() Out[6]: [('__dict__', ), ('__module__', '__main__'), ('foo', at 0xa79528ec>), ('__weakref__', ), ('__doc__', None)] In [7]: a().foo() Out[7]: True or : In [9]: setattr(a, 'bar', lambda s : False) In [10]: a().bar() Out[10]: False -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From faulkner612 at comcast.net Tue Jun 20 19:32:00 2006 From: faulkner612 at comcast.net (faulkner) Date: 20 Jun 2006 16:32:00 -0700 Subject: Getting external name of passed variable In-Reply-To: References: <4498420F.1050504@ilm.com> Message-ID: <1150846320.921138.285100@c74g2000cwc.googlegroups.com> >>> import sys >>> tellme = lambda x: [k for k, v in sys._getframe(1).f_locals.iteritems() if v == x] >>> a=1 >>> tellme(a) ['a'] Michael Spencer wrote: > David Hirschfield wrote: > > I'm not sure this is possible, but it sure would help me if I could do it. > > > > Can a function learn the name of the variable that the caller used to > > pass it a value? For example: > > > > def test(x): > > print x > > > > val = 100 > > test(val) > > > > Is it possible for function "test()" to find out that the variable it is > > passed, "x", was called "val" by the caller? > > Some kind of stack inspection? > > Perhaps, but don't try it ;-) > > > > Any help greatly appreciated, > > -David > > > Can't you use keyword arguments? > > >>> def test(**kw): > ... print kw > ... > >>> test(val=3) > {'val': 3} > >>> test(val=3, otherval = 4) > {'otherval': 4, 'val': 3} > >>> > > Michael From dnew at san.rr.com Mon Jun 26 18:53:25 2006 From: dnew at san.rr.com (Darren New) Date: Mon, 26 Jun 2006 22:53:25 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <7zpshbsvjy.fsf@app-1.diku.dk><4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150904134.520639.71070@b68g2000cwa.googlegroups.com> <1151030140.202720.245140@y41g2000cwy.googlegroups.com> <1151255749.436492.70680@m73g2000cwd.googlegroups.com> Message-ID: Joachim Durchholz wrote: > That's actually not a design choice It's certainly a choice you can get wrong, as you say. ;-) I mean, if "without runtime safety" is a choice, I expect picking the wrong choice here can be. :-) -- Darren New / San Diego, CA, USA (PST) Native Americans used every part of the buffalo, including the wings. From yairchu at gmail.com Thu Jun 15 03:38:22 2006 From: yairchu at gmail.com (yairchu at gmail.com) Date: 15 Jun 2006 00:38:22 -0700 Subject: Trace KeyboardInterrupt exception? In-Reply-To: <*firstname*nlsnews-04EFB8.13261714062006@news.verizon.net> References: <*firstname*nlsnews-B3800F.13431013062006@news.verizon.net> <1150293702.090195.324550@y43g2000cwc.googlegroups.com> <*firstname*nlsnews-04EFB8.13261714062006@news.verizon.net> Message-ID: <1150357101.984761.63310@u72g2000cwu.googlegroups.com> if you want to interrupt the code to find out where it is, you can instead connect to it in gdb and get the python traceback of each thread. if you're interested I'll post the necesary gdb-macro for that (didn't put it on the net yet) From bdesth.quelquechose at free.quelquepart.fr Sat Jun 3 13:08:30 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 03 Jun 2006 19:08:30 +0200 Subject: after del list , when I use it again, prompt 'not defined'.how could i delete its element,but not itself? In-Reply-To: References: <1149235087.256704.309360@g10g2000cwb.googlegroups.com> <1149236355.221540.136120@y43g2000cwc.googlegroups.com> Message-ID: <4481927b$0$12362$626a54ce@news.free.fr> Piet van Oostrum a ?crit : >>>>>>SuperHik (S) escribi?: > > >>S> bearophileHUGS at lycos.com wrote: >> >>>>python wrote: >>>> >>>>>after del list , when I use it again, prompt 'not defined'.how could i >>>>>delete its element,but not itself? >>>> >>>>This is a way: >>>> >>>>>>>a = range(10) >>>>>>>del a[:] >> >>S> or simply >>S> a = [] >> >>>>>>>a >>>> >>>>[] > > > Then you *have* deleted the list Not necessarily: >>> a = range(10) >>> b = a >>> id(a) 1078034316 >>> id(b) 1078034316 >>> a is b True >>> a = [] >>> b [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> id(a) 1078043724 >>> id(b) 1078034316 >>> What as been deleted is the association ('binding') between the name 'a' and the list object at 1078034316. This object won't be suppressed until there are no more names bound to it. > and created a new one, which is different > from keeping the list and deleting the elements: indeed !-) From robert.kern at gmail.com Tue Jun 13 14:31:35 2006 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 13 Jun 2006 13:31:35 -0500 Subject: numeric/numpy/numarray In-Reply-To: References: Message-ID: Bryan wrote: > hi, > > what is the difference among numeric, numpy and numarray? i'm going to start > using matplotlib soon and i'm not sure which one i should use. There's a reasonably complete telling (and up-to-date!) of the history behind these packages here: http://www.scipy.org/History_of_SciPy -- 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 From alanalan at newsgroup.nospam Thu Jun 1 12:49:06 2006 From: alanalan at newsgroup.nospam (A.M) Date: Thu, 1 Jun 2006 12:49:06 -0400 Subject: New to Python: Do we have the concept of Hash in Python? References: Message-ID: "Fredrik Lundh" wrote in message news:mailman.6414.1149178232.27775.python-list at python.org... > "A.M" wrote: > >> I am new to Python, with C#/Java background > > that's not really much of an excuse for not reading *any* Python tutorial > before > you jump in... Hi Fredrik, 1st of all, I am really impressed by this Python community. Answers are helpful and I am having excellent progress. I appreciate everybody's help. This is my 1st day that I am seriously diving into Python and I have to finish this application by the end of today. Maybe it wasn't a good idea to choose the language that I don't know when I have to deliver my work in such short time. I understand that my question might seems very trivial to you, but please consider the fact that I am in time pressure and I cannot go through a 400 book today. I promises I'll do that this weekend ;) Wish luck for me! Thank you for your post, Alan From rossberg at ps.uni-sb.de Wed Jun 21 12:01:29 2006 From: rossberg at ps.uni-sb.de (Andreas Rossberg) Date: Wed, 21 Jun 2006 18:01:29 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <0%Wlg.3521$MF6.947@tornado.socal.rr.com> <44992e6c$0$664$bed64819@news.gradwell.net> Message-ID: Darren New wrote: > > As far as I know, LOTOS is the only > language that *actually* uses abstract data types Maybe I don't understand what you mean with ADT here, but all languages with a decent module system support ADTs in the sense it is usually understood, see ML for a primary example. Classes in most OOPLs are essentially beefed-up ADTs as well. > Indeed, the ability to declare a new type that has the exact same > underlying representation and isomorphically identical operations but > not be the same type is something I find myself often missing in > languages. It's nice to be able to say "this integer represents vertical > pixel count, and that represents horizontal pixel count, and you don't > get to add them together." Not counting C/C++, I don't know when I last worked with a typed language that does *not* have this ability... (which is slightly different from ADTs, btw) - Andreas From maric at aristote.info Fri Jun 2 04:27:11 2006 From: maric at aristote.info (Maric Michaud) Date: Fri, 2 Jun 2006 10:27:11 +0200 Subject: An oddity in list comparison and element assignment In-Reply-To: <1149199942.955228.281950@u72g2000cwu.googlegroups.com> References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1149199942.955228.281950@u72g2000cwu.googlegroups.com> Message-ID: <200606021027.12616.maric@aristote.info> Le Vendredi 02 Juin 2006 00:12, michael.f.ellis at gmail.com a ?crit?: > I believe that 'is' tests equality of reference, such that > > >>> a = range(1,3) > >>> b = range(1,3) > >>> a is b > > False > > The 'is' operator tells you whether a and b refer to the same object. Yeah ! That's it. And you proposed a definition of identity : for all operator op, op(a) = op(b) => a = b This is of poor use in real life where two thing are never identical, just comparable. > What I've been discussing is whether == should test for "structural" > equality so that a and b remain equivalent under parallel mutations > (and also under single mutations to common references) So you wanted a comparison opertor of twto sequence dafined like this : seq1 == seq2 => for all e in seq1, seq2[seq1.index(e) *is* e !!! this would not be very useful nor consistent I guess and prefer the one used in python : seq1 == seq2 => for all e in seq1, seq2[seq1.index(e) == e -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From david.nospam.hopwood at blueyonder.co.uk Sat Jun 24 13:11:24 2006 From: david.nospam.hopwood at blueyonder.co.uk (David Hopwood) Date: Sat, 24 Jun 2006 17:11:24 GMT Subject: Saying "latently-typed language" is making a category mistake In-Reply-To: <86Qmg.10725$o4.1907@newsread2.news.pas.earthlink.net> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <86Qmg.10725$o4.1907@newsread2.news.pas.earthlink.net> Message-ID: <0neng.213767$8W1.1948@fe1.news.blueyonder.co.uk> Patricia Shanahan wrote: > Vesa Karvonen wrote: > ... > >> An example of a form of informal reasoning that (practically) every >> programmer does daily is termination analysis. There are type systems >> that guarantee termination, but I think that is fair to say that it is >> not yet understood how to make a practical general purpose language, whose >> type system would guarantee termination (or at least I'm not aware of >> such a language). It should also be clear that termination analysis need >> not be done informally. Given a program, it may be possible to formally >> prove that it terminates. > > To make the halting problem decidable one would have to do one of two > things: Depend on memory size limits, or have a language that really is > less expressive, at a very deep level, than any of the languages > mentioned in the newsgroups header for this message. I don't think Vesa was talking about trying to solve the halting problem. A type system that required termination would indeed significantly restrict language expressiveness -- mainly because many interactive processes are *intended* not to terminate. A type system that required an annotation on all subprograms that do not provably terminate, OTOH, would not impact expressiveness at all, and would be very useful. Such a type system could work by treating some dependent type parameters as variants which must strictly decrease in a recursive call or loop. For example, consider a recursive quicksort implementation. The type of the 'sort' routine would take an array of length (dependent type parameter) n. Since it only performs recursive calls to itself with parameter strictly less than n, it is not difficult to prove automatically that the quicksort terminates. The programmer would probably just have to give hints in some cases as to which parameters are to be treated as variants; the rest can be inferred. -- David Hopwood From russandheather at gmail.com Tue Jun 27 11:03:15 2006 From: russandheather at gmail.com (Russell Warren) Date: 27 Jun 2006 08:03:15 -0700 Subject: Is Queue.Queue.queue.clear() thread-safe? References: <1151008374.303940.251300@c74g2000cwc.googlegroups.com> <1f7befae0606221440p619c9865y66e4b404fcd142c1@mail.gmail.com> Message-ID: <1151420595.433064.207390@i40g2000cwc.googlegroups.com> Thanks guys. This has helped decipher a bit of the Queue mechanics for me. Regarding my initial clear method hopes... to be safe, I've re-organized some things to make this a little easier for me. I will still need to clear out junk from the Queue, but I've switched it so that least I can stop the accumulation of new data in the Queue while I'm clearing it. ie: I can just loop on .get until it is empty without fear of a race, rather than needing a single atomic clear. My next Queue fun is to maybe provide the ability to stuff things back on the queue that were previously popped, although I'll probably try and avoid this, too (maybe with a secondary "oops" buffer). If curious why I want stuff like this, I've got a case where I'm collecting data that is being asynchronously streamed in from a piece of hardware. Queue is nice because I can just have a collector thread running and stuffing the Queue while other processing happens on a different thread. The incoming data *should* have start and stop indications within the stream to define segments in the stream, but stream/timing irregularities can sometimes either cause junk, or cause you to want to rewind the extraction a bit (eg: in mid stream-assembly you might realize that a stop condition was missed, but can deduce where it should have been). Fun. Russ From onurb at xiludom.gro Wed Jun 7 13:55:27 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 07 Jun 2006 19:55:27 +0200 Subject: Writing to a certain line? In-Reply-To: <44869dd3$0$31210$626a54ce@news.free.fr> References: <1149576072.168354.14470@f6g2000cwb.googlegroups.com> <44854184$0$29904$636a55ce@news.free.fr> <1149630414.246008.270720@f6g2000cwb.googlegroups.com> <448697f7$0$10260$626a54ce@news.free.fr> <44869dd3$0$31210$626a54ce@news.free.fr> Message-ID: <44871310$0$21281$626a54ce@news.free.fr> Christophe wrote: > bruno at modulix a ?crit : (snip) >> Wrong guess - unless, as Fredrik suggested, you have an infinite disk >> with an infinite file on it. If so, please share with, we would be >> *very* interested !-) > > > Use /dev/zero as source and /dev/null as destination :D Lol !-) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From aurora00 at gmail.com Mon Jun 26 16:32:04 2006 From: aurora00 at gmail.com (aurora00 at gmail.com) Date: 26 Jun 2006 13:32:04 -0700 Subject: Find the context of importer In-Reply-To: <1149091076.533062.302640@c74g2000cwc.googlegroups.com> References: <1149091076.533062.302640@c74g2000cwc.googlegroups.com> Message-ID: <1151353924.002099.255600@r2g2000cwb.googlegroups.com> I find the answer to my own question. The inspect module have what I need. Here is the sample code: a.py ------------------------------------------------------------------------ import b print 'hello world from module a' ------------------------------------------------------------------------ b.py ------------------------------------------------------------------------ import inspect def globals_of_importer(): """ Return the global namespace of the module that imports this module. """ # scan the stack using the inspect module stack = inspect.stack() # current frame is on the top of the stack top_rec = stack[0] current_filename = top_rec[1] # look for the frame those filename different from current frame for frame_rec in stack: filename = frame_rec[1] if filename != current_filename: break else: return None # return the globals from the frame object frame = frame_rec[0] members = inspect.getmembers(frame) for name, value in members: if name == 'f_globals': return value else: return None print globals_of_importer() ------------------------------------------------------------------------ wy From tjreedy at udel.edu Fri Jun 2 15:22:00 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 2 Jun 2006 15:22:00 -0400 Subject: Sampling a population References: <1149275394.499808.31460@i39g2000cwa.googlegroups.com> Message-ID: "Paddy" wrote in message news:1149275394.499808.31460 at i39g2000cwa.googlegroups.com... > Brian Quinlan wrote: >> This is less a Python question and more a optimization/probability >> question. Imaging that you have a list of objects and there frequency in >> a population e.g. >> >> lst = [(a, 0.01), (b, 0.05), (c, 0.50), (d, 0.30), (e, 0.04), (f, 0.10)] >> >> and you want to drawn n items from that list (duplicates allowed), with >> that probability distribution. For a set of probabilities that uneven, you *might* do better to sort high to low and do a linear search. Or check the two common cases and then do a binary search on the rest. tjr From eval.apply at gmail.com Wed Jun 21 14:46:54 2006 From: eval.apply at gmail.com (Joe Marshall) Date: 21 Jun 2006 11:46:54 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: <1150902731.828394.175560@m73g2000cwd.googlegroups.com> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <4fo19aF1jsudeU1@individual.net> <1150902731.828394.175560@m73g2000cwd.googlegroups.com> Message-ID: <1150915614.636327.233490@p79g2000cwp.googlegroups.com> Marshall wrote: > > That's really coming home to me in this thread: the terminology is *so* > bad. I have noticed this previously in the differences between > structural > and nominal typing; many typing issues associated with this distinction > are falsely labeled as a static-vs-dynamic issues, since so many > statically > type languages are nominally typed. > > We need entirely new, finer grained terminology. Agreed. That's why I've been biting my tongue and avoiding posting. The discussion is going along the lines of the blind men and the elephant. I've seen about seven different definitions of what a `type' is, and most of the arguments seem to come from people misunderstanding the other person's definition. I think that *most* of the people arguing here would agree with each other (possibly in detail) if only they understood each other. Static type aficionados have a specialized jargon that has precise meaning for a number of the terms being used. People that aren't into that field of computer science use the same terms in a much looser sense. But static type aficionados are definitely in the minority in comp.lang.lisp, and probably in a few of the other comp.langs as well. What we need is an FAQ entry for how to talk about types with people who are technically adept, but non-specialists. Or alternatively, an FAQ of how to explain the term `dynamic typing' to a type theorist. From rpdooling at gmail.com Thu Jun 15 13:32:39 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 15 Jun 2006 10:32:39 -0700 Subject: a good programming text editor (not IDE) References: <_xgkg.2317$No6.48542@news.tufts.edu> Message-ID: <1150392759.297671.168330@u72g2000cwu.googlegroups.com> I see Eclipse mentioned here a lot. Never tried it (i use Komodo). http://www.eclipse.org/ It uses plugins. So, e.g., if you decide you do want an IDE, you add PyDev http://pydev.sourceforge.net/index.html From userprogoogle-139 at yahoo.co.uk Thu Jun 22 05:22:27 2006 From: userprogoogle-139 at yahoo.co.uk (rodmc) Date: 22 Jun 2006 02:22:27 -0700 Subject: Help req: Problems with MySQLdb Message-ID: <1150968147.565850.156870@u72g2000cwu.googlegroups.com> I have written an application that connects to a database on a remote machine which uses MySQLdb 1.2.0. The application works perfectly when connecting to the database from a remote machine, however when it attempts to connect to a database on the same machine a connection error is generated. I have attached what little info I can below. DBSERVERIP = "1.2.3.4" db = MySQLdb.connect(host=DBSERVERIP, user="user", passwd="password", db="nuke") --- it refuses to connect on the above line and the exception is caught and a message displayed. I have tried changing the server IP to "localhost" or the hostname, however the same problem arises. Information: Python 2.3.5, MySQLdb 1.2.0, MySQL 5.0.21 and Windows 2K pro. I would be grateful for any help with this problem. Kind regards, rod From owen at metamachine.com Thu Jun 15 00:59:58 2006 From: owen at metamachine.com (Wallace Owen) Date: Wed, 14 Jun 2006 21:59:58 -0700 Subject: Perl XML::Simple and Data::Dumper - exists in Python? In-Reply-To: References: Message-ID: <7K5kg.236174$5Z.165973@dukeread02> Miguel Manso wrote: > Hi there, > > I'm a Perl programmer trying to get into Python. I've been reading some > documentation and I've choosed Python has being the "next step" to give. > > Can you point me out to Python solutions for: > > 1) Perl's Data::Dumper > > It dumps any perl variable to the stdout in a "readable" way. All Python objects support reflection and can be serialized to a data stream. There's about four ways to do it (Kinda perl-like in that regard, but typically for a particular application there's one obvious right choice). You control the way your objects appear as strings, by defining a __str__ member function that'll be invoked if the user does: % print str(yourObject) You can print any builtin type with just: >>> lst = ["one", "two", (3, 4.56), 1] >>> print lst ['one', 'two', (3, 4.5599999999999996), 1] >>> > > 2) Perl's XML::Simple > > It maps a XML file into a Perl data structure. Python's got a Document Object Model lib that essentially maps an XML file to objects that have built-in-type behavior - you can treat a NodeList object as a python list, indexing into it, iterating over it's contents, etc. It's also got SAX and expat bindings. > > Does Python have something like these two tools? I've been googling > before posting this and didn't find anything. Do your searches at python.org. // Wally From tontudelbot at gmail.com Thu Jun 15 06:49:59 2006 From: tontudelbot at gmail.com (tontudelbot at gmail.com) Date: 15 Jun 2006 03:49:59 -0700 Subject: IntCtrl doesn't found? and arrays (newbie) Message-ID: <1150368599.613361.266160@i40g2000cwc.googlegroups.com> Hello, I'm a newbie doing my first program. I'm doing the GUI of it and I need IntCtrl. I do: wx.IntCtrl(self, id=wx.NewId(), min=1, max=9) but Python says: AttributeError: 'module' object has no attribute 'IntCtrl' I tried doing this like I find somewhere else, but the result is the same..: wx.lib.intctrl.IntCtrl Huh? I have to import it from another side? Another question: I have to do an array, and I thing what I need and adjust more for me is the method array from Numeric module. But there is another form to do the same best? Thank you! From junkytownMAKNI at gmail.com Sat Jun 17 16:44:49 2006 From: junkytownMAKNI at gmail.com (SuperHik) Date: Sat, 17 Jun 2006 22:44:49 +0200 Subject: Popen3 on Windows In-Reply-To: References: Message-ID: Dennis Lee Bieber wrote: > On Sat, 17 Jun 2006 11:46:29 -0600, Jeffrey Barish > declaimed the following in comp.lang.python: > >> I start. Is there a way to do this on Windows? > > There is no safe, easy, way to reliably kill a program on Windows... > > Hmmm, there's one I hadn't know about... > http://www.tech-recipes.com/windows_tips446.html > Ah, not supplied in WinXP Home (my desktop is Pro) > > Seems besides taskkill, there is also a tskill with different > arguments... > > The M$ response > http://support.microsoft.com/default.aspx?scid=KB;en-us;178893& > > > Granted, these don't explain how to get the PID in the first place > from Python. > > If possible, try using the subprocess module... It seems to have a > PID attribute. > from http://docs.python.org/dev/lib/module-subprocess.html """ 16.1 subprocess -- Subprocess management New in version 2.4. The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. This module *intends to replace* several other, older modules and functions, such as: os.system os.spawn* os.popen* popen2.* commands.* """ From awaretek at gmail.com Tue Jun 13 11:05:36 2006 From: awaretek at gmail.com (Ron Stephens) Date: 13 Jun 2006 08:05:36 -0700 Subject: Python 411. In-Reply-To: <1150152755.474292.39010@j55g2000cwa.googlegroups.com> References: <1150152755.474292.39010@j55g2000cwa.googlegroups.com> Message-ID: <1150211136.267983.185690@f6g2000cwb.googlegroups.com> Steve, thanks for the note. The name Python411 comes from me copying my good friend Rob Walch, who named his podcast Podcast411, which is a popular show on which he interviews other podcasters like Adam Curry etc. He also has a book just published about podcasting. Ron Stephens From duncan.booth at invalid.invalid Mon Jun 26 04:00:45 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 26 Jun 2006 08:00:45 GMT Subject: Pygame.draw challenge is over! References: <1fmu92dode2idgq260vfnb6ona6qljtd7k@4ax.com> <449f67d5$0$22363$afc38c87@news.optusnet.com.au> Message-ID: Richard Jones wrote: > spiffy wrote: >> Congrats to Seth Yastrov for 'gravity.py' ... THE ONLY ONE THAT >> WORKED! > > I did test that they all worked on my machine before putting them > online... > > What issues are you having? What OS? The only issue I found is that goop dies with "IndexError: list index out of range" if you move to to the top right corner. From fredrik at pythonware.com Sat Jun 10 03:22:45 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 10 Jun 2006 09:22:45 +0200 Subject: Allowing zero-dimensional subscripts In-Reply-To: <1149896299.760886.52810@f6g2000cwb.googlegroups.com> References: <1149801040.936452.26270@i40g2000cwc.googlegroups.com> <1149896299.760886.52810@f6g2000cwb.googlegroups.com> Message-ID: Carl Banks wrote: > How would you index a 2-D array? With a 2-tuple. > How would you index a 1-D array? With a 1-tuple. > How would you index a 0-D array? ... array dimensions don't exist at the Python level. you're confusing behaviour that a custom class may provide with Python's view of things. (and None is of course the standard value for "not there") From sjmachin at lexicon.net Fri Jun 9 18:01:04 2006 From: sjmachin at lexicon.net (John Machin) Date: Sat, 10 Jun 2006 08:01:04 +1000 Subject: Win XP: Problem with shell scripting in Python In-Reply-To: References: Message-ID: <4489efa0@news.eftel.com> On 10/06/2006 3:00 AM, A.M wrote: > Here is what I came up with after John and Fredrik's help. > > import os > import sys > def Execute(shell_command,logStream = sys.stdout): > print >>logStream, shell_command > child_stdin, child_stdout_and_stderr = os.popen4(shell_command) > commad_output = child_stdout_and_stderr.read() > print >>logStream, commad_output > return_code = child_stdout_and_stderr.close() > return_code = return_code or child_stdin.close() > print >>logStream, "Return Code: " , return_code > > Execute ("DIR") > > Execute ("MD :") > > I tested it and so far it behaves the way that I want. > Does it overcome the problem that you reported earlier, that the contents of the output file from BCP were out of order? If not, you may like to try popen3(). It's quite possible (and indeed desirable) that the child's stderr is not buffered (so that error messages appear immediately) but the child's stdout is buffered (for efficiency), and when the buffer is flushed governs the order of appearance in a single output stream. > > > The tricky part is that when you use popen4, you have to close both returned > streams to be able to get the return code. I wasn't able to find that in the > documentation. In general it is good practice to hand back resources (e.g. close files) explicitly as soon as you are finished with them. This is especially important for files open for writing, in case there are problems like out of disk space, device not functioning etc. Also when you are dealing with a child process it makes some sense to close its stdin first just in case it is waiting for that, and will then write something to stdout, which may fail, causing it to write to stderr. So I guess that the documenter didn't stumble onto the "tricky part" :-) The "tricky part" for popen and friends seems to be that the return code is handed back upon close of the *last* file: |>>> h = os.popen3('md : ') |>>> [h[x].close() for x in 2, 1, 0] [None, None, 1] Looks like you get to report a documentation "problem" after all :-) Cheers, John From marc.t.davies at gmail.com Thu Jun 8 06:36:11 2006 From: marc.t.davies at gmail.com (MTD) Date: 8 Jun 2006 03:36:11 -0700 Subject: How to generate k+1 length strings from a list of k length strings? In-Reply-To: <1149762869.692025.164140@c74g2000cwc.googlegroups.com> References: <1149762869.692025.164140@c74g2000cwc.googlegroups.com> Message-ID: <1149762971.803450.69670@j55g2000cwa.googlegroups.com> actually, minor fix: MTD wrote: > Try this: > > def k2k1(string1, string2): > for c in string1: > string2 = string2.replace(c,"",1) > > if len(string2) == 1: > string1 += string2 else: string1 = "" > > return string1 > > print k2k1("abcd", "ebcd") From leventyilmaz at gmail.com Sat Jun 17 03:22:59 2006 From: leventyilmaz at gmail.com (levent) Date: 17 Jun 2006 00:22:59 -0700 Subject: add elements to indexed list locations References: <1150478265.122559.283000@f6g2000cwb.googlegroups.com> <7rmdnTyLF8gNcw_ZnZ2dnUVZ_v2dnZ2d@comcast.com> Message-ID: <1150528979.036821.246410@g10g2000cwb.googlegroups.com> Thanks for the answers. Enumerating in reverse is indeed quite a smart idea. The fact is though, I overly simplified the task in the super-hero example. In the real case, the dictionary keys are not necessarily the indices for inserts; that is to say, the inserts do not necessarily take place in some sorted order. I think I was thinking more of a linked-list idea, where you do not store the indices as integers to some random access array but rather as pointers into list's nodes. Then the subsequent inserts would not hurt previously stored pointers. For those who know a bit C++/STL here is a sketch of the idea: name_list heros; heros.push_back("clark"); // ... add the rest indexed_name_list surnames; surnames.push_back( make_pair( find( heros.begin(), heros.end(), "clark"), "kent") ) ); // the find function returns an iterator to appropriate location // ... add the rest for_each(surnames.begin(), surnames.end(), insert_surnames) // insert_surnames is a callback that receives a single indexed surname // at a time and does the job, without affecting outer iterators. I was wondering how to make indices as *robust* in Python... Any ideas? PS: following is the compilable code-let of the task in C++ // ==================================================== #include #include #include #include #include #include using namespace std; typedef string name; typedef pair::iterator, string> indexed_name; void insert_name( list* into, indexed_name in ) { into->insert(in.first, in.second); } int main() { using namespace std; // Define super-heros (fathers ignored) list heros; heros.push_back("super"); heros.push_back("clark"); heros.push_back("spider"); heros.push_back("peter"); heros.push_back("bat"); heros.push_back("bruce"); // Assign father names to proper son list surnames; surnames.push_back( // ++ is to have surname inserted _after_ the name make_pair(++find(heros.begin(),heros.end(),"clark"), string("kent")) ); surnames.push_back( make_pair(++find(heros.begin(),heros.end(),"peter"), string("parker")) ); surnames.push_back( make_pair(++find(heros.begin(),heros.end(),"bruce"), string("wayne")) ); // Insert surnames succeeding appropriate heros for_each(surnames.begin(), surnames.end(), bind1st(ptr_fun(insert_name), &heros) ); // Salute the heros copy(heros.begin(),heros.end(),ostream_iterator(cout," ")); cout << endl; return 0; } // ===================================================== From jmbc at nospam.fr Fri Jun 16 03:14:56 2006 From: jmbc at nospam.fr (jean-michel bain-cornu) Date: Fri, 16 Jun 2006 09:14:56 +0200 Subject: Newbie wxpython staticbitmap help please In-Reply-To: <1150376832.271801.19920@f6g2000cwb.googlegroups.com> References: <1150325882.038508.122780@g10g2000cwb.googlegroups.com> <4490f8b6$0$7766$7a628cd7@news.club-internet.fr> <1150376832.271801.19920@f6g2000cwb.googlegroups.com> Message-ID: <44925ab7$0$7761$7a628cd7@news.club-internet.fr> Hi, janama a ?crit : > jean-michel bain-cornu wrote: >> Why won't you write it yourself using the demo ? >> It's clear and well documented. >> Regards, >> jm > > Hi, have been just trying for 5 hours with the timer demo in wx, i just > havnt clicked with how to tie it in together, > > I know (think) i need the following features from the timer demo , > where you can periodically call a function using the wx.timer > > self.Bind(wx.EVT_TIMER, self.OnTest1Timer) > #---(bind to the frame ?) Bind to any method > > self.Bind(wx.EVT_BUTTON, self.OnTest3Start, t3b1) > #---(this binds to a button, how do i bind to my application on load or > startup instead ?) ??? > > def OnTest1Timer(self, evt): > self.log.write("got EVT_TIMER event\n") > #---(dont think i need the logging?) You don't need of course, it's just for demo information. > > def OnTest3Start(self, evt): > self.t3 = NotifyTimer(self.log) > self.t3.Start(1000) > self.log.write("NotifyTimer timer started\n") > self.t3b2.Enable() > > #---(the Start i guess i will work if i remap the button event to an on > load type? event? > > def OnTest3Stop(self, evt): > self.t3.Stop() > self.log.write("NotifyTimer timer stoped\n") > del self.t3 > self.t3b2.Disable() > #---(Guess i wont need to stop the timer, as i want it to trigger the > 'refreshing' of the StaticBitmaps ?) > > # When deriving from wx.Timer you must provide a Notify method > # that will be called when the timer expires. > class NotifyTimer(wx.Timer): > def __init__(self, log): > wx.Timer.__init__(self) > self.log = log > > def Notify(self): > self.log.write("got NotifyTimer event\n") > #---(dont know if i need this if i dont want to use this log feature)? > > > Im sorry if this all seems really amatuerish, i have genuially tried > hard to get my head around it , but i get error after error in boa. Boa is well done for editing, simple objects generation, also for learning, but not for complex operation. It's not a good idea to use it for your present need. > Somewhone couldnt append a timer and perhaps help to refresh the > StaticBitmaps described, with the code, in first post). I will be able > to see and learn greatly from this. > > Maybe some advice on where to find lists of the methods used in > wxpython > For example it took me hours to find methods ? like In the help file, there is an alphabetic classes list, with (quite) all the methods. > > StaticBitmap.SetImage("imageName") > > Is there any good lists of these methods, properties etc for wxpython > controls? See before. This is the best, and also the demo (and also the sources). > > Any good wxpython ide/editors that can "intellisense" them? boa, > komodo, stani's arnt working with "intellisensing" wx for me, (maybe i > cant configure them though) The best is probably boa, because it have got a debugger, with a separate process launched for testing. > > Thanks for any help with any of this > > Regards > All what you have to do is : def __init__(self, parent): self._init_ctrls(parent) self.t1 = wx.Timer(self) self.t1.Start(2000) # 2 seconds self.Bind(wx.EVT_TIMER, self.OnTest1Timer) def OnTest1Timer(self, evt): if os.path.isfile('App1.py'): i = wx.Image('image.jpg',wx.BITMAP_TYPE_JPEG) b1 = wx.BitmapFromImage(i) self.staticBitmap1.SetBitmap(b1) And you can continue to use Boa as usual. Hope you'll enjoy, jm Ps: tested on xp, pretty sure it works also on linux. From 63q2o4i02 at sneakemail.com Sat Jun 17 04:44:41 2006 From: 63q2o4i02 at sneakemail.com (63q2o4i02 at sneakemail.com) Date: 17 Jun 2006 01:44:41 -0700 Subject: a good programming text editor (not IDE) References: <_xgkg.2317$No6.48542@news.tufts.edu> <1150406662.900552.46650@u72g2000cwu.googlegroups.com> Message-ID: <1150533881.540254.270400@i40g2000cwc.googlegroups.com> Istvan Albert wrote: > Scott David Daniels wrote: > > > To paraphrase someone else (their identity lost in my mental fog) about > > learning VI: > > "The two weeks you'll spend hating vi (or vim) as you learn it will > > be repaid in another month, ad the rest is pure profit." > > Time and again I hear this (no shortage of Vim fans, same with Emacs), > and I know I should know better but always believe them yet again. > Invariably I download Vim play with it for an hour, get increasingly > frustrated and give up. Most likely I'm greatly spoiled by using > EditPlus (Windows only), it just makes it so easy to do the basic > programming tasks that I need, everywhere else I turn I see far more > functionality but at the price of not being able to do basic tasks as > efficiently as I need them. > > Say I want to be able to execute the python program I'm currently > editing. Nothing simpler in EditPlus, Tools->Configure Tools->Add Tool > then specify which program you want to run, what parameters it takes > and whether to capture the output or not ... total time it took me > first time I wanted to do this ... about 3 minutes ... from now on > pressing Ctrl-1 while editing the source will execute the python on the > current source *and* it displays the output in a lower pane as it runs > *and* it allows me to simultanously edit the file *while* the program > is running. Outstanding. > > Yet after searching and reading stuff for more than an hour I was > unable to accomplish the same thing in Vim though I'm already familiar > enough with basic editing and setup (through my previous trials and > tribulations) ... I have a few solutions that end up doing something > similar but are quite a few keypresses longer both to invoke or to get > back to the source that I'm writing, or I lose editing control while > the program is running ... etc... > > So if the OP is on windows just head over and get EditPlus (UltraEdit > and TextPad seem to be similar), and just accept the fact that you are > already using an editor that as good as an editor can get ... I know > I'd pay that registration once again for an editor that works the same > way on Linux... > > i. I'm a huge EditPlus fan and there are not enough good things I can say about it. The main thing about GUIs which unix people don't seem to get is discoverability is key. Every time I've tried using x-emacs or x-anything (or even Scite as it seems to be popular), there is very little that is intuitive or obvious about the interface, and even though you have a GUI right there in front of you, things are still controlled in dot whatever files, with some special syntax and magic words for everything! Even doing a search and replace in x-emacs is f*cked up. I was trying to use it for something a few years ago (I dunno, maybe 2002 or 2003 on debian or 2000 on redhat), and it just didn't work the way I expected it to work, ie it didn't follow what has become the standard GUI (read: windows) way of doing things. There should be a dialog for search and replace. If it doesn't do it that way, then don't pretend to be a gui, because you're not, you're pandering to the "we want a gui crowd" while still stickin' it to 'em by forcing them to remember commands for shit like changing word wrapping (oh my god there's a *mode* for word wrapping? m-x-wtf change-the-mode-to-something-I-forget-what) and reminding everyone what a privilege it is to learn f***king lisp to enable some obscure little tweak which could just as easily have shown up in a checkbox. Scite was jacked because the main window didn't have anything discoverable on it, and one of the main menus just had a list of syntaxes you could use to highlight your code... and the other menu opened up your dot whatever file to change the settings. That's just retarded. I think there is a fine line between being too dumbed down to do anything (point click ooh aahh), and so "flexible", "customizable", and "free" that it feels you have to roll-your-own text editor each time you want to start a new project. This is the best article on guis and stuff I've read in a while. http://www.joelonsoftware.com/uibook/fog0000000249.html Anyway, the only thing editplus doesn't do that I wish it did is code folding. All the stuff you guys are talking about: line numbers, syntax highlighting, custom tools (running the interpreter), regexp search and replace, keeping your environment the same between sessions, soft word wrap, tab-vs-spaces, auto-indent, braces-matching, bla bla... it does it all in an appropriately gui manner without making you feel like a moron for not psychically knowing the command ahead of time, or for not having someone to copy a dot whatever file from, or not Reading TFM (which of course never tells you what you want to know anyway -- it's either a patronizingly simple-minded 3rd grade tutorial, or it tells you what a command does if you already know its f***king name!). And of course all these editplus things are accessible via the keyboard without necessarily hitting alt to go to the menu. And no, it doesn't read email or newsgroups, run custom scripts to beautify your code, or have 20MB of stuff to download and 20 years of history to catch up on. I've rarely needed anything more than straightforward editing, so I guess I'm not worthy to have an opinion of how shitty *nix is for pretending to have guis. If you (meaning y'all) like to feel superior by memorizing commands how to change the word wrapping mode, braces-indenting mode, background color, foreground color, braces-matching, apropos-me-this, then by all means make things difficult for the rest of us lowly non-professional programmers (I'm a hardware designer by trade, but like to fuck around python for fun). For me, when I just have something quick and dirty, I use editplus and that makes me sooo happpyyyyy. If there were something like this for Linux I might even consider switching long term. From robert.kern at gmail.com Sat Jun 3 23:16:30 2006 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 03 Jun 2006 22:16:30 -0500 Subject: reordering elements of a list In-Reply-To: <1149390075.653265.193370@j55g2000cwa.googlegroups.com> References: <1149382009.640607.217470@y43g2000cwc.googlegroups.com> <1149390075.653265.193370@j55g2000cwa.googlegroups.com> Message-ID: greenflame wrote: > Thank you all for your replies. The only thing is I do not understand > how the code is working. The following are more particular questions. Actually, these are statements, not questions. But anyways: > Travis: Iam sorry, but I do not know what list comprehension is. > Roberto: I do not understand the first half of the last line of your > code. That's what a list comprehension is. > Also thank you for also teaching me to use '+' to append one list > to another. This will be very useful for me. > Christoph: I do not undertand the map method. There is documentation on map() about halfway down this page: http://docs.python.org/lib/built-in-funcs.html Here's a tutorial which you should read: http://docs.python.org/tut/tut.html -- 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 From jvvhie at gmail.com Mon Jun 26 02:25:38 2006 From: jvvhie at gmail.com (jvvhie at gmail.com) Date: 25 Jun 2006 23:25:38 -0700 Subject: Python "sub-interpreter," security In-Reply-To: <1151302366.426298.202590@i40g2000cwc.googlegroups.com> References: <1151298465.155786.317310@u72g2000cwu.googlegroups.com> <1151302366.426298.202590@i40g2000cwc.googlegroups.com> Message-ID: <1151303137.966220.20320@p79g2000cwp.googlegroups.com> faulkner wrote: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496746 > Thanks! I was searching everywhere but couldn't find the right terms, I guess. From jUrner at arcor.de Tue Jun 13 20:47:48 2006 From: jUrner at arcor.de (jUrner at arcor.de) Date: 13 Jun 2006 17:47:48 -0700 Subject: Screen capturing on Windows In-Reply-To: <1150192149.757557.163820@y43g2000cwc.googlegroups.com> References: <1150192149.757557.163820@y43g2000cwc.googlegroups.com> Message-ID: <1150246068.129668.46870@y43g2000cwc.googlegroups.com> Rune Strand schrieb: > Is it possible by use of pyWin32 or ctypes to make a screen capture of > an inactive, or a hidden window if the hwnd/WindowName/ClassName is > known? I've seen dedicated screen capture software do this. While > PIL.ImageGrab.grab() is excellent, it will only capture the foreground > of the desktop. I've tried for hours, but I soon get helplessly lost in > the labyrinths of the Win32API. As it says: the window is hidden. You can not make a screen shot of a hidden window 'cos it has no visual representation at the very moment. Simply show it. And if you do not want to see it while it's shown show it somewhere out of the bounds of your virtual screen. regards Juergen From digitalorganics at gmail.com Mon Jun 26 22:55:18 2006 From: digitalorganics at gmail.com (digitalorganics at gmail.com) Date: 26 Jun 2006 19:55:18 -0700 Subject: TypeError: Cannot create a consistent method resolution order (MRO) for bases object In-Reply-To: References: <1151345197.691600.200060@y41g2000cwy.googlegroups.com> Message-ID: <1151376918.242180.301210@m73g2000cwd.googlegroups.com> Maric Michaud wrote: > Le lundi 26 juin 2006 20:06, digitalorganics at gmail.com a ?crit : > > What are the reason one would get this error: TypeError: Cannot create > > a consistent method resolution order (MRO) for bases object ?? > > > > I can provide the code if needed.... > This is the python solution to the diamond problem (cf. wikipedia). > > In [61]: class a(object) : pass > ....: > In [62]: class b(a) : pass > ....: > In [63]: class c(object, a) : pass > ....: > --------------------------------------------------------------------------- > exceptions.TypeError Traceback (most recent > call last) > > /home/maric/ > > TypeError: Error when calling the metaclass bases > Cannot create a consistent method resolution > order (MRO) for bases object, a > > In [64]: b.mro() > Out[64]: [, , ] > > In [65]: class c(a, object) : pass > ....: > > In [66]: c.mro() > Out[66]: [, , ] > > In [67]: class d(b, c) : pass > ....: > > In [69]: d.mro() > Out[69]: > [, > , > , > , > ] > > mro means "method resolution order", this is the path the interpreter will > look for attributes for a given class. You cannot introduce inconsistency in > this path, for example duplicate the type object before another type (or any > type wich appear to be the ancestor of another). > > -- Ah, thank you Maric, I see the problem. I diagrammed the flow of class inheritance and I can see the problem clearly. Ruby doesn't have this problem because it uses a single inheritance model complemented by the power of mixins (modules of functionality mixed into classes as needed). So what's the Pythonic solution to this problem? From michael.f.ellis at gmail.com Sat Jun 3 08:24:35 2006 From: michael.f.ellis at gmail.com (michael.f.ellis at gmail.com) Date: 3 Jun 2006 05:24:35 -0700 Subject: An oddity in list comparison and element assignment In-Reply-To: <1hgbhhi.mcrge51cyj2isN%aleax@mac.com> References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> <1hg9nl6.xivwcd7n0j5N%aleax@mac.com> <1149277242.199765.213600@g10g2000cwb.googlegroups.com> <1hgbhhi.mcrge51cyj2isN%aleax@mac.com> Message-ID: <1149337475.944457.168300@y43g2000cwc.googlegroups.com> Hey Alex, lighten up! Python is a programming language -- not your family, religion, or civil rights. Cheers, Mike Alex Martelli wrote: > wrote: > ... > > (As an aside, may I point out that Python In A Nutshell states on page > > 46 "The result of S*n or n*S is the concatenation of n copies of S". It > > might be well to put a warning in a future edition that this is not > > strictly the case.) > > Can you give me an example where, say, for a sequence S, > > x = S * 3 > > is not structurally the same as > > x = copy.copy(S) + copy.copy(S) + copy.copy(S) > > ...? That is, where the "* 3" on a sequence is NOT the concatenation of > three copies (ordinary copies, of course!) of that sequence? I don't > think you can... and I can't repeatedly explain or point to the > distinction between normal, ordinary, shallow copies on one side, and > "deep copies" on the other, every single time in which that distinction > MIGHT be relevant (because some reader might not be aware of it); such > endless repetition would bloat the Nutshell totally away from its role > as a CONCISE desktop reference, and seriously hamper its usefulness > (particularly by DESTROYING any trace of usefulness for anybody who's > finally *GOT* this crucial bit, but not just in that way). > > > > languages and methodologies. As I noted in an earlier reply, I don't > > realistically expect Python to change the behavior of the == operator. > > Then you might have avoided trying to convince anybody, or even trying > to IMPLY, that in an ideal version of Python == *SHOULD* behave your way > -- Python's semantics *ARE* entirely up for rediscussion at the moment, > with an eye on the future "Python 3000" release, so this is one of the > very rare periods of the history of the language where backwards > incompatibility of a potential change is _NOT_ a blocking point. > > By asserting that your version of == would be "more natural", and trying > to defend that assertion by vague handwaving references to maths and > "real world", you managed to entirely shift MY mindstate (and possibly > that of several other discussants) into one of total and absolute > opposition to the proposal -- having by now spent considerable time and > energy pondering and debating the issue, I am now entirely convinced > that a language with such an == operator instead of Python's current one > would be such a total, unadulterated disaster that I would refuse to use > that language, no matter what other "good" features it might present to > me. I've walked away from great jobs, just because they would have > required me to use some technology I just could not stand, more than > once already in my life: and this IS how strongly (and negatively) I > feel about your claim that, for built-in ==, your semantics would be in > any way preferable to Python's. > > By managing to thus focus my mindset (and make me spend my energy and > time) in opposition to your claims of "more natural", you have at least > managed to ensure that I will not now lend any scrap of help or support > to your debugging needs. If you were as pragmatic as you claim to be, > this kind of consideration WOULD have weighed highly in your choices. > > I.ie., if you had WANTED to attract any such support and help, a > completely different attitude than that "most natural" claim would have > been ENORMOUSLY more productive -- and your continuing attempts to > debate that issue aren't helping AT ALL either: > > > I do think that a problem arose when it was adopted from C and extended > > to allow comparison of containers. In C, you can use it to compare > > integers, floats, and pointers and everyone understands that p==q does > > not imply *p == *q. > > If that is so, then everyone is utterly, totally, entirely, horribly > *WRONG*, because, in C, p==q ***DOES*** imply *p == *q (whenever p -- > and by consequence q, given equality -- may legitimately be > dereferenced: p == q == 0 does not imply anything about *p and/or *q, > which may produce random results, crash the process, or whatever -- of > course). > > You no doubt meant to say something entirely different from what you > ACTUALLY said, but I respectfully suggest you spare your breath rather > than keep trying to defend an indefensible position. > > I do NOT agree, and I cannot imagine any state of the world that would > get me to agree, with your claim that "a problem arose" by allowing > equality comparison of containers in Python (many other languages allow > such comparisons, BTW; I would consider it a horrible wart if a language > claiming to be "higher level" did NOT). That you're "supporting" (HA!) > your absurd claim with an equally absurd (and obviously, wholly false, > unfounded, and misplaced) claim about C pointers doesn't "help", of > course, but even perfectly accurate claims about C (or machine code, or > Cobol, or RPG...) would be pretty much uninteresting and irrelevant. > > > Moreover, compilers issue warnings about > > comparisons between different types. > > Some do, some don't, depending on the case -- e.g., I do not believe > that even with -Wall (or the equivalent setting) any C compiler whines > about EQUALITY comparisons of signed and unsigned integers (as well they > shouldn't, of course)! > > And, just as of course, this umpteenth side-path you're introducing has > really nothing to do with the case, since when you're comparing two > lists-containing-lists which are equal by Python's rules but according > to your original claims about what's "more natural" ``should not'' be, > you ARE anyway comparing object of equal types. > > > Basically, I'm looking for simple diagnostic tools that make it easy to > > understand what's really going on when code produces an unexpected > > result. A 'strengthened equivalence' operator, to use your terminology > > would have been useful to me. > > A *FUNCTION* performing such checks in a debugging and diagnostics > package would have been -- and if you hadn't pushed me to spend so much > time and energy defending Python's design choices against your claims > that other choices would be "more natural", you might have gotten help > and support in developing it. But you chose to make ill-founded claims > of "more natural", and therefore you got a flamewar instead: your > choice. > > > will serve to move the discussion beyond terms like 'crazy' and > > 'handwaving' and 'ill-founded'. I haven't used such perjoratives in > > any of my posts and would appreciate the same courtesy. > > You claimed that Python's semantics are "contrary to one of my > fundamental expectations", "an oddity", resulting only (you said in your > second post) from a "performance and memory optimization", and tried to > justify this severe criticism of Python by vague (i..e, "handwaving") > appeals to analogies with "maths" and "the real world". > > I do not believe that such scathing criticism had any sound foundations, > nor that calling it "ill-founded" is anything but a fittingly accurate > description: and a language where the == operator DID satisfy the > constraints you claimed to desire for *THE EQUALITY OPERATOR ITSELF* (as > opposed to, for some helper/checker function in a separate module for > checking and debugging) would be a crazy one indeed. If my opinions > that, I believe, accurately reflect the facts of the case, sound > "pejorative" to you, well, that's not a matter of choice of words on my > part, as much as of your choice of what to express in the first place. > > Take your recent claim that in C "everyone understands that p==q does > not imply *p == *q"; which of the many ("pejorative") adjectives I > tagged your assertion with do you think are inaccurate or inappropriate? > I called it wrong, absurd, false, unfounded, and misplaced, and seasoned > the mix with a choice of adverbs including "utterly" and "horribly". It > appears to me that each of these adjectives and adverbs is appropriate > and accurate (though it's repetitious on my part to use them all, that > repetition does convey the intensity of my opinions in the matter). > > This is a factual issue where it's easy to defend strongly held opinions > (which may be checked against "facts"); in matters of "should" (what > semantics "should" a certain language construct HAVE, in order to be > most natural, simplest, and most useful -- quite apart from any issues > of optimization) such ease is, alas, not given... but the fact that > veryfying clashing opinons about what "should" be the case is way harder > than opinions easily checkable against "facts", does not mean that the > "should"'s (which are even more important, potentially, in their effect > on future language design!) are any less important -- on the contrary. > > > I do not believe I am going to follow this thread any more; I wish you > best of luck in your future endeavors -- and, if you can get back to > being the pragmatist that you claim to be, perhaps in the future you may > chose to express your debugging needs and desiderata in ways that > dispose the experts on some give technology to help and support you, > rather than to fight against the damage which, they opine, it would > cause to the future of that technology if certain ("crazy") suggestions > were to be part of it. > > > Alex From josef.cihal at siemens.com Fri Jun 30 10:12:30 2006 From: josef.cihal at siemens.com (Cihal Josef) Date: Fri, 30 Jun 2006 16:12:30 +0200 Subject: string replace Message-ID: <94CEBD2AC72A3D478BC8381A196FD7CCA00858@vie012.at.sat-automation.com> Hi Mechele, In string s u want to replace string "b" or "c" to -> "x" import re s ="a1b2c3" re.sub("[bc]","x",s) Sincerely josef Josef -----Original Message----- From: python-list-bounces+josef.cihal=sat-automation.com at python.org [mailto:python-list-bounces+josef.cihal=sat-automation.com at python.org] On Behalf Of Michele Petrazzo Sent: Friday, June 30, 2006 4:03 PM To: python-list at python.org Subject: string replace Hi, a lot of times I need to replace more than one char into a string, so I have to do something like value = "test" chars = "e" for c in chars: value = value.replace(c, "") A solution could be that "replace" accept a tuple/list of chars, like that was add into the new 2.5 for startswith. I don't know, but can be this feature included into a future python release? Thanks, Michele -- http://mail.python.org/mailman/listinfo/python-list From robert.thorpe at antenova.com Tue Jun 20 13:08:17 2006 From: robert.thorpe at antenova.com (Rob Thorpe) Date: 20 Jun 2006 10:08:17 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <1150809118.677124.142230@u72g2000cwu.googlegroups.com> <1150815461.210286.53120@r2g2000cwb.googlegroups.com> Message-ID: <1150823297.816352.75370@u72g2000cwu.googlegroups.com> Andreas Rossberg wrote: > Rob Thorpe wrote: > >Andreas Rossberg wrote: > >>Rob Thorpe wrote: > >> > >>>>>"A language is latently typed if a value has a property - called it's > >>>>>type - attached to it, and given it's type it can only represent values > >>>>>defined by a certain class." > >>>> > >>>>"it [= a value] [...] can [...] represent values"? > >>> > >>>??? > >> > >>I just quoted, in condensed form, what you said above: namely, that a > >>value represents values - which I find a strange and circular definition. > > > > Yes, but the point is, as the other poster mentioned: values defined by > > a class. > > I'm sorry, but I still think that the definition makes little sense. > Obviously, a value simply *is* a value, it does not "represent" one, or > several ones, regardless how you qualify that statement. You've clipped a lot of context. I'll put some back in, I said:- > > Yes, but the point is, as the other poster mentioned: values defined by > > a class. > > For example, in lisp: > > "xyz" is a string, #(1 2 3) is an array, '(1 2 3) is a list, 45 is a > > fixed-point number. > > Each item that can be stored has a type, no item can be stored without > > one. The types can be tested. Most dynamic typed languages are like > > that. > > Compare this to an untyped language where types cannot generally be > > tested. I think this should make it clear. If I have a "xyz" in lisp I know it is a string. If I have "xyz" in an untyped language like assembler it may be anything, two pointers in binary, an integer, a bitfield. There is no data at compile time or runtime to tell what it is, the programmer has to remember. (I'd point out this isn't true of all assemblers, there are some typed assemblers) > >>>Well I haven't programmed in any statically typed language where values > >>>have types themselves. > >> > >>They all have - the whole purpose of a type system is to ensure that any > >>expression of type T always evaluates to a value of type T. > > > > But it only gaurantees this because the variables themselves have a > > type, > > No, variables are insignificant in this context. You can consider a > language without variables at all (such languages exist, and they can > even be Turing-complete) and still have evaluation, values, and a > non-trivial type system. Hmm. You're right, ML is no-where in my definition since it has no variables. > > But the value itself has no type > > You mean that the type of the value is not represented at runtime? True, > but that's simply because the type system is static. It's not the same > as saying it has no type. Well, is it even represented at compile time? The compiler doesn't know in general what values will exist at runtime, it knows only what types variables have. Sometimes it only has partial knowledge and sometimes the programmer deliberately overrides it. From what knowledge it you could say it know what types values will have. > > in a C program for example I can take > > the value from some variable and recast it in any way I feel and the > > language cannot correct any errors I make because their is no > > information in the variable to indicate what type it is. > > Nothing in the C spec precludes an implementation from doing just that. True, that would be an interesting implementation. > The problem with C rather is that its semantics is totally > underspecified. In any case, C is about the worst example to use when > discussing type systems. For starters, it is totally unsound - which is > what your example exploits. Yes. Unfortunately it's often necessary to break static type systems. Regarding C the problem is, what should we discuss instead that would be understood in all these newsgroups we're discussing this in. From colincolehour at gmail.com Fri Jun 16 20:48:09 2006 From: colincolehour at gmail.com (colincolehour at gmail.com) Date: 16 Jun 2006 17:48:09 -0700 Subject: Need Help comparing dates In-Reply-To: <1150502102.377475.38140@u72g2000cwu.googlegroups.com> References: <1150419503.224684.320550@c74g2000cwc.googlegroups.com> <1150502102.377475.38140@u72g2000cwu.googlegroups.com> Message-ID: <1150505289.249498.190450@i40g2000cwc.googlegroups.com> Thanks for the reply, the book I'm actually using is Python Programming for the absolute beginner. The book has been good to pick up basic things but it doesn't cover time or dates as far as I can tell. As for previous programming experience, I have had some lite introductions to C & C++ about 6 years ago but I never went past the introductions.So far "my first program" has been written from snippets from many different websites. Also i'm using ActiveState Active Python 2.4 on a Windows XP machine. I will try to work through Tim's response. I tried using it yesterday but I was really confused on what I was doing. Colin From grflanagan at yahoo.co.uk Wed Jun 7 14:08:37 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 7 Jun 2006 11:08:37 -0700 Subject: creating and naming objects In-Reply-To: <1149700072.369465.230280@c74g2000cwc.googlegroups.com> References: <1149696358.065614.76150@h76g2000cwa.googlegroups.com> <1149700072.369465.230280@c74g2000cwc.googlegroups.com> Message-ID: <1149703717.215666.79960@h76g2000cwa.googlegroups.com> Brian wrote: > Thank you all for your response. I think that I am getting it. Based > on those responses, would I be correct in thinking that this would be > the way to initialize my Student object and return the values? > > class Student: > def __init__(self, name, id): > self.name = name > self.id = id > > def getName(self): > return self.name > > def getId(self): > return self.id > > Additionally, correct me if I am wrong but I can recycle: > > foo = Student() > > And doing so will just create a new instance of Student (with whatever > attributes it is given) and the original foo is gone? > > Thanks for your help and patience. After reading my original post and > then this one, I could see that it may look suspiciously like a home > work assignment. Trust me it's not. The student example just seemed > like a good fit to discuss this. > > Thanks again, > Brian Here's a page from the Python tutorial wiki which may be helpful to you: http://pytut.infogami.com/node11-baseline.html It's an introduction to classes which, appositely, uses a Student class as an example. Still a work in progress. Feel free to leave a comment if you find it helpful or not - your input would be very much valued. (Note the StudentTracker class). Gerard From marshall.spight at gmail.com Sun Jun 25 13:15:49 2006 From: marshall.spight at gmail.com (Marshall) Date: 25 Jun 2006 10:15:49 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <7zpshbsvjy.fsf@app-1.diku.dk><4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150904134.520639.71070@b68g2000cwa.googlegroups.com> <1151030140.202720.245140@y41g2000cwy.googlegroups.com> Message-ID: <1151255749.436492.70680@m73g2000cwd.googlegroups.com> Joachim Durchholz wrote: > Anton van Straaten schrieb: > >> It seems we have languages: > >> with or without static analysis > >> with or without runtime type information (RTTI or "tags") > >> with or without (runtime) safety > >> with or without explicit type annotations > >> with or without type inference > >> > >> Wow. And I don't think that's a complete list, either. > > > > Yup. > > What else? > (Genuinely curious.) I left off a big one: nominal vs. structural Also: has subtyping polymorphism or not, has parametric polymorphism or not. Marshall From __peter__ at web.de Thu Jun 1 08:51:09 2006 From: __peter__ at web.de (Peter Otten) Date: Thu, 01 Jun 2006 14:51:09 +0200 Subject: Function mistaken for a method References: Message-ID: Eric Brunel wrote: > On Thu, 01 Jun 2006 13:34:53 +0200, Peter Otten <__peter__ at web.de> wrote: > >> Eric Brunel wrote: >> >>> My actual question is: why does it work in one case and not in the >>> other? >>> As I see it, int is just a function with one parameter, and the lambda >>> is >>> just another one. So why does the first work, and not the second? What >>> 'black magic' takes place so that int is not mistaken for a method in >>> the >>> first case? >> A python-coded function has a __get__ attribute, a C-function doesn't. >> Therefore C1.f performs just the normal attribute lookup while C2.f also >> triggers the f.__get__(C2(), C2) call via the descriptor protocol which >> happens to return a bound method. > > Thanks for your explanations, Peter. I'll have to find another way to do > what I want... Maybe just class C2(C): f?=?staticmethod(lambda?x:?x?!=?0) Peter From digitalorganics at gmail.com Mon Jun 26 09:16:59 2006 From: digitalorganics at gmail.com (digitalorganics at gmail.com) Date: 26 Jun 2006 06:16:59 -0700 Subject: Mix-In Class Methods At Run-Time In-Reply-To: <449fa027$0$24929$626a54ce@news.free.fr> References: <1151191406.755252.210300@i40g2000cwc.googlegroups.com> <1151193767.589325.158820@m73g2000cwd.googlegroups.com> <1151269186.710343.41210@c74g2000cwc.googlegroups.com> <1151270770.030282.237050@u72g2000cwu.googlegroups.com> <449fa027$0$24929$626a54ce@news.free.fr> Message-ID: <1151327819.320233.305400@i40g2000cwc.googlegroups.com> Bruno Desthuilliers wrote: > digitalorganics at gmail.com wrote: > (snip) > > > Two additional questions though: 1) is there a way for a function to > > get a reference to its caller automatically (as in, without the caller > > having to pass it in)? > > It's possible with sys._getframe() and a decorator - but consider it a > hack. Gotcha, thanks. > > > and 2) what's the reason to use newstyle classes > > versus the old? > > All this is explained on python.org (there's a menu entry for this in > the documentation menu). AFAICT, newstyle classes can do whatever > oldstyle classes did, *and much more* (descriptors and usable > metaclasses) - and they are somewhat faster too. So - compatibility with > older Python versions (< 2.2 IIRC) set aside -, there's just no reason > to use oldstyle classes. > > > In order to create the dynamic class "NewClass" in the > > code above I called type() but that requires at least one new style > > class as a base. Thus, I had to have at least one of my animals inherit > > from "object" and this seemed a nuisance since > > OMG, eight more keystrokes - talk about a nuisance... Like, Oh My God! *claps hand to mouth* lol You humor me. Yes, eight more keystrokes. I follow the general rule of, if I'm going to put in extra effort, I'd like to know why. So you see, it's not so much an adversion to the eight keystrokes (multiplied by however many classes I have mind you), but to not knowing why I should use them. If I don't care for descriptors or metaclasses, I don't see why I should feel compelled to use them. And when I decide I want/need these features, I can put the eight keystroke in at that time. No biggy. :-) Thanks Bruno. > > > I don't at this point > > know what the benefit of "newstyle" classes is. > > See it the other way round : the *only* benefit of oldstyle classes is > compatibility with pre-2.2 Python versions. > > -- > bruno desthuilliers > python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for > p in 'onurb at xiludom.gro'.split('@')])" From wblock at wonkity.com Sat Jun 3 00:47:24 2006 From: wblock at wonkity.com (Warren Block) Date: Sat, 03 Jun 2006 04:47:24 -0000 Subject: Can Python format long integer 123456789 to 12,3456,789 ? References: <8oKfg.1621$Su3.139425@news20.bellglobal.com> <447f7f43$1@news.eftel.com> Message-ID: John Machin wrote: > On 2/06/2006 9:08 AM, A.M wrote: >> Hi, >> >> Is there any built in feature in Python that can format long integer >> 123456789 to 12,3456,789 ? >> >> Thank you, >> Alan > > Not that I know of, but this little kludge may help: > 8<--- > import re > > subber = re.compile(r'^(-?\d+)(\d{3})').sub > > def fmt_thousands(amt, sep): > if amt in ('', '-'): > return '' > repl = r'\1' + sep + r'\2' > while True: > new_amt = subber(repl, amt) > if new_amt == amt: > return amt > amt = new_amt > > if __name__ == "__main__": > for prefix in ['', '-']: > for k in range(11): > arg = prefix + "1234567890.1234"[k:] > print "<%s> <%s>" % (arg, fmt_thousands(arg, ",")) > 8<--- Why not just port the Perl "commify" code? You're close to it, at least for the regex: # From perldoc perlfaq5 # 1 while s/^([-+]?\d+)(\d{3})/$1,$2/; # Python version import re def commify(n): while True: (n, count) = re.subn(r'^([-+]?\d+)(\d{3})', r'\1,\2', n) if count == 0: break return n -- Warren Block * Rapid City, South Dakota * USA From codecraig at gmail.com Thu Jun 1 09:10:03 2006 From: codecraig at gmail.com (abcd) Date: 1 Jun 2006 06:10:03 -0700 Subject: PythonDoc Ant Task In-Reply-To: <1149165032.870017.254980@i40g2000cwc.googlegroups.com> References: <1149165032.870017.254980@i40g2000cwc.googlegroups.com> Message-ID: <1149167403.532618.22370@y43g2000cwc.googlegroups.com> i found that the problem is because of an import, which is strange. The imported module looks something like this [code] import time class Foo: pass class Bar: global javax.swing import javax.swing [/code] ....so it seems that pydoc cant giggity-giggit! From duncan.booth at invalid.invalid Thu Jun 1 11:29:21 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 1 Jun 2006 15:29:21 GMT Subject: argmax References: Message-ID: David Isaac wrote: > 1. Why is there no argmax built-in? > (This would return the index of the largest element in a sequence.) Probably there isn't a built-in because it isn't a commonly needed function. What is your use-case for argmax? If for example you want to repeatedly remove the largest element from a list, then sort the list and pop the last element (or use a heap, except heapq lets you pop the smallest so you can't use it directly). From florian.reiser at ra-bc.de Fri Jun 9 02:12:37 2006 From: florian.reiser at ra-bc.de (Florian Reiser) Date: Fri, 9 Jun 2006 08:12:37 +0200 Subject: Extended zip() for lists References: <1149772973.297794.68720@i39g2000cwa.googlegroups.com> Message-ID: Hello Gene, a big THANKS for this tip. This is exactly what I was looking for. Regards Florian Reiser "gene tani" schrieb im Newsbeitrag news:1149772973.297794.68720 at i39g2000cwa.googlegroups.com... > > Florian Reiser wrote: >> Hello, >> >> I have 4 lists: a, b, c and d >> Out of this 4 lists I want to build a table (e.g. list of lists): >> >> a|b|c|d >> --------------------------- >> a1|b1|c1|d1 >> a1|b2| |d2 >> >> You see: the lists are not equally sized. >> Is there a command which fills up the shorter lists with blanks? >> Like an enhanced zip() command, maybe? >> > > map(None, list1, list2, list3) > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/410687 > From fredrik at pythonware.com Sat Jun 17 04:54:28 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 17 Jun 2006 10:54:28 +0200 Subject: Legitimate use of the "is" comparison operator? In-Reply-To: <1150533733.252877.238120@c74g2000cwc.googlegroups.com> References: <20060617075308.29014.1287982850.divmod.quotient.2368@ohm> <1150533733.252877.238120@c74g2000cwc.googlegroups.com> Message-ID: Mike Duffy wrote: > Ahh, thank you. That explains why Fredrick's and Jean-Paul's example > did not work, but mine did (I was using *small* integers). "small integers" is what the phrase "small integers" in the "small integers" and "small integers" parts of my reply referred too, of course. From python.list at tim.thechases.com Thu Jun 15 12:15:09 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 15 Jun 2006 11:15:09 -0500 Subject: code folding, a unique problem to python? In-Reply-To: References: Message-ID: <4491878D.9090200@tim.thechases.com> > But my question is more general: is it possible to implement > code folding with Python given that it has no real block > delimiters? Or is this still a matter of which particular > editor/IDE you use? Yes, it is an editor thing. In Vim, it's as simple as :set foldmethod=indent and presto! I'm sure other quality editors provide similar options. ;) > So maybe I'm stuck in UE, but I'm curious if there is some > general way to do this, or is Python just too simple and > concise for its own good? :) Most editors are "just too simple and concise for [their] own good". :) -tkc From pc at p-cos.net Mon Jun 26 19:28:53 2006 From: pc at p-cos.net (Pascal Costanza) Date: Tue, 27 Jun 2006 01:28:53 +0200 Subject: What is a type error? In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <7i3mg.204167$8W1.155367@fe1.news.blueyonder.co.uk> <44992e6c$2$664$bed64819@news.gradwell.net> <%Igmg.464974$xt.353729@fe3.news.blueyonder.co.uk> <4fv0v3F1kipa6U1@individual.net> <4gakhiF1m698cU1@individual.net> <4galqlF1mae4qU1@individual.net> Message-ID: <4gb8tiF1e75njU1@individual.net> Chris Smith wrote: > Pascal Costanza wrote: >> Chris Smith wrote: >>> Of course zero is not appropriate as a second argument to the division >>> operator! I can't possibly see how you could claim that it is. The >>> only reasonable statement worth making is that there doesn't exist a >>> type system in widespread use that is capable of checking this. >> ...and this is typically not even checked at the stage where type tags >> are checked in dynamically-typed languages. Hence, it is not a type >> error. (A type error is always what you define to be a type error within >> a given type system, right?) > > Sure, it's not a type error for that language. > >> Note, this example was in response to David's reply that my definition >> turns every runtime error into a type error. That's not the case, and >> that's all I want to say. > > But your definition does do that. Your definition of a type error was > when a program attempts to invoke an operation on values that are not > appropriate for this operation. In my definition, I didn't say who or what decides what values are appropriate for operations. > Clearly, in this example, the program > is invoking an operation (division) on values that are not appropriate > (zero for the second argument). Hence, if your definition really is a > definition, then this must qualify. Here, you are asking more from dynamic type systems than any existing type system provides. The definition of what is considered to be a type error and what not is always part of the specification of a type system. >>> However, it sounds as >>> if you're claiming that it wouldn't be possible for the type system to >>> do this? >> No. I only need an example where a certain error is not a type error in >> _some_ language. I don't need to make a universal claim here. > > Definitions are understood to be statements of the form "if and only > if". They assert that /everything/ that fits the definition is > describable by the word, and /everything/ that doesn't is not > describable by the word. If that's not what you meant, then we are > still in search of a definition. > > If you want to make a statement instead of the sort you've implied > above... namely that a type error is *any* error that's raised by a type > system, then that's fine. It certainly brings us closer to static > types. Now, though, the task is to define a type system without making > a circular reference to types. You've already rejected the statement > that all runtime errors are type errors, because you specifically reject > the division by zero case as a type error for most languages. What is > that distinction? I don't need such a distinction. I can just define what is covered by a type system and what is not. All type systems work that way. Pascal -- 3rd European Lisp Workshop July 3 - Nantes, France - co-located with ECOOP 2006 http://lisp-ecoop06.bknr.net/ From pmartin at snakecard.com Tue Jun 20 21:22:06 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Tue, 20 Jun 2006 20:22:06 -0500 Subject: Python with Eclipse References: <449679c3@news.uni-ulm.de> <9OBlg.6681$FR1.4810@dukeread05> <449849dc$1@news.uni-ulm.de> Message-ID: <2b1mg.10171$FR1.7058@dukeread05> Dennis Benzinger wrote: > Philippe Martin wrote: >> Dennis Benzinger wrote: >> >>> Stan Cook wrote: >>>> I've been trying to use Eclipse with Python on Linux for a while and >>>> have noticed something odd. After running the code or debugging a few >>>> times, its responsiveness gets really bad. Upon checking the >>>> equivalent >>>> of the task manager, I find several instances of Python running. When >>>> I >>>> kill these instances, the responsiveness comes back. I'm not sure if >>>> there is a better place to post this, but it is Python related. Is >>>> this just an issue with Eclipse or is there something else I should >>>> inspect? >>>> >>>> Any help would be appreciated. >>>> >>>> Regards, >>>> >>>> S Cook >>> Which Python plugin are you using? PyDev? >>> >>> >>> Bye, >>> Dennis >> >> Hi, >> >> What other plugins are there ? >> >> Regards, >> >> Philippe >> > > > In the Python wiki there is a page about Eclipse plugins for Python: > > http://wiki.python.org/moin/EclipsePythonIntegration > > > Bye, > Dennis Thanks, Philippe From shejo284 at gmail.com Thu Jun 22 04:34:29 2006 From: shejo284 at gmail.com (Sheldon) Date: 22 Jun 2006 01:34:29 -0700 Subject: comparing two arrays In-Reply-To: <4fpvr0F1k8dauU1@uni-berlin.de> References: <1150721380.948808.231760@h76g2000cwa.googlegroups.com> <4fnlbiF1j83q2U1@uni-berlin.de> <4fnqoqF1k8n10U1@uni-berlin.de> <1150795424.752973.303420@g10g2000cwb.googlegroups.com> <4fpvr0F1k8dauU1@uni-berlin.de> Message-ID: <1150965269.339874.192160@i40g2000cwc.googlegroups.com> Thanks Diez, It will take a little while for this one to sink in but it gets the job done now and will for future cases. /Sheldon Diez B. Roggisch skrev: > >> print [i for i, _ in enumerate((None for x, y in zip(a, b) where x == > >> y))] > >> > >> instead. > >> > >> Diez > > > > Hi Diez, > > > > I wish I say that I understood what you wrote here but I can't. > > Do you mind explaining a little more? > > I actually made a typo, instead of "where" in the above use "if". and the > whole thing won't compute what you are after. This will: > > [i for i, equals in enumerate((x == y for x, y in zip(a, b))) if equals] > > Sorry for that. > > Its a nested list-comprehension. Actually, the outer thingy is a > list-comprehension while the inner is a generator expression. There is of > course a difference, but for now this doesn't matter too much. > > a list comprehension of form > > [ for in if ] > > is a more compact form for > > result = [] > for in : > if : > result.append() > > > A generator expression works the same with () instead of []. > > Now let's decompose the above statment: > > (x == y for x, y in zip(a, b) )) > > = x, y > = zip(a, b) > = x == y > > So: the iterable is returned by the function zip. That is a built-in which > will take 2 or more lists and return a list of tuples, where the first > element is from the first list, then the second and so on. So your example > lists become: > > a = [0,1,2,5,6,6] > b = [5,4,1,6,4,6] > zip(a, b) = [(0,5), (1,4), (2,1), (5,6), (6,4), (6,6)] > > So iterating over this yields the pairs of (0,5) and so forth. > > Next thing is that with > > x, y = p > > python unpacks a tuple and refers to its contents by name x for the first > one and y for the second. So overall, we loop in sync over both lists, and > getting x and y to point to the corresponding elements. > > Now the expression x == y will result True if x == y - False otherwise. > > So the result of the inner listcomp/genexp looks like this: > > res = [False, False, False, False, False, True] > > As you can see: for each pair x,y in the original lists we come up with the > result of comparing them. > > Now the outer listcomp using "res" instead of the genexps for clarity reads > like this: > > > > [i for i, equals in enumerate(res) if equals] > > = i, equals > = enumerate(res) > = i > = equals > > enumerate is another built-in that takes an iterable and returns a tuple of > > (pos, element) > > for each element in the iterable. > > So for our list, it will return: > > [(0, False), (1, False), (2, False), (3, False), (4, False), (5, True)] > > These tupkes values are assigened to i and equals for each element of the > above list. The condtion > > equals > > will then guarantee that only those expressions are evaluated where equals > is True - the last pair, so to speak. The expression then only stores the > index i. Which will give us the desired result. > > Diez From ketil+news at ii.uib.no Mon Jun 26 06:42:43 2006 From: ketil+news at ii.uib.no (Ketil Malde) Date: Mon, 26 Jun 2006 12:42:43 +0200 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> Message-ID: Anton van Straaten writes: > But a program as seen by the programmer has types: the programmer > performs (static) type inference when reasoning about the program, and > debugs those inferences when debugging the program, finally ending up > with a program which has a perfectly good type scheme. I'd be tempted to go further, and say that the programmer performs (informally, incompletely, and probably incorrectly ) a proof of correctness, and that type correctness is just a part of general correctness. -k -- If I haven't seen further, it is by standing in the footprints of giants From defcon8 at gmail.com Sat Jun 24 13:30:17 2006 From: defcon8 at gmail.com (defcon8) Date: 24 Jun 2006 10:30:17 -0700 Subject: Python and cellular automata (It works this time!) In-Reply-To: <1151158859.422817.239810@y41g2000cwy.googlegroups.com> References: <1151158859.422817.239810@y41g2000cwy.googlegroups.com> Message-ID: <1151170217.279140.306370@m73g2000cwd.googlegroups.com> blog-of-justin.blogspot.com Sorry for the error. From michael.f.ellis at gmail.com Fri Jun 2 15:40:42 2006 From: michael.f.ellis at gmail.com (michael.f.ellis at gmail.com) Date: 2 Jun 2006 12:40:42 -0700 Subject: An oddity in list comparison and element assignment References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> <1hg9nl6.xivwcd7n0j5N%aleax@mac.com> Message-ID: <1149277242.199765.213600@g10g2000cwb.googlegroups.com> Perhaps a little background to my original post will defuse some of the controversy. While working during an airline flight, I ran into an unexpected outcome from using the * replication operator to initialize an array of lists. When I modified a single element of the array an entire column changed. Having no reference books or internet access available, I tried to understand what was going on by creating some small arrays on the command line to see if there was a difference between explicit initialization and initialization with range() and the * operator. The arrays looked identical when printed and a == b returned True. Yet the arrays were clearly not equivalent because mutating the corresponding elements produced different outcomes. I put the problem aside until the next day when I looked at it some more and and created the example script I posted. Just as I was about to hit the Send button, I realized that the * operator must have been creating references instead of copies. And then I appended the now much debated opinion that == should have detected the difference. (As an aside, may I point out that Python In A Nutshell states on page 46 "The result of S*n or n*S is the concatenation of n copies of S". It might be well to put a warning in a future edition that this is not strictly the case.) My viewpoint is that of a working professional software consultant. I'm essentially a pragmatist with no strong 'religious' views about languages and methodologies. As I noted in an earlier reply, I don't realistically expect Python to change the behavior of the == operator. I do think that a problem arose when it was adopted from C and extended to allow comparison of containers. In C, you can use it to compare integers, floats, and pointers and everyone understands that p==q does not imply *p == *q. Moreover, compilers issue warnings about comparisons between different types. Basically, I'm looking for simple diagnostic tools that make it easy to understand what's really going on when code produces an unexpected result. A 'strengthened equivalence' operator, to use your terminology would have been useful to me. As to constructing pseudocode for such an operator, I've appended a working script below. The counterexamples and questions from Slawomir, Maric, and Jim were really useful in sharpening my thinking about the matter. I'm sure there are many ways to break it. For example, tuples have no index method, so one would have to be written. Still, I hope it will serve to move the discussion beyond terms like 'crazy' and 'handwaving' and 'ill-founded'. I haven't used such perjoratives in any of my posts and would appreciate the same courtesy. Cheers, Mike ''' StrongEquality -- a first cut at the definition proposed by M. Ellis. Author: Michael F. Ellis, Ellis & Grant, Inc. ''' def indices(item,seq): '''Utility function that returns a list of indices where item occurs in seq''' result=[] for i in xrange(len(seq)): try: result.append(i+seq[i:].index(item)) except ValueError: return result def StrongEquality(a,b): '''True if a and b are numerically and "structurally" equal''' if a is b: return True if a != b: return False ## At this point we know a and b have the same length and ## evaluate numerically equivalent. We now need to figure out ## whether there are any references to identical objects in non-corresponding ## positions of a & b (per Slawomir's example). We also need to inspect ## a and b for non-matching patterns of identical references (per my example) ida=[] ; idb=[] for i in xrange(len(a)): if a[i] is b[i]: continue if isinstance(a[i], (int, float, str)) and isinstance(b[i], (int, float, str)): continue ## we already know they're numerically equal ida.append(id(a[i])) idb.append(id(b[i])) ## We know that ida[n] is not idb[n] for all n because we omitted all ## cases where a is b. Therefore Slawomir's example is detected if ## any id appears in both lists. for n in ida: if n in idb: return False ## Next we test for my example. I'm sure this can be coded more ## more elegantly ... for j in xrange(len(ida)): if indices(ida[j],ida) != indices(idb[j],idb): return False ## Lastly, recurse ... if not StrongEquality(a[i],b[i]): return False return True if __name__=='__main__': ## Rudimentary test cases assert StrongEquality(1,1) assert not StrongEquality(0,1) ## Slawomir's example x, y, z = [1],[1],[1] a, b = [x,y], [y,z] c, d = [[1],[1]], [[1],[1]] assert StrongEquality(c,d) assert a == b assert not StrongEquality(a,b) ## My example a =[[[1,2],[1,2]],[[1,2],[1,2]]] b = [[range(1,3)]*2]*2 assert a==b assert not StrongEquality(a,b) print "All tests ok." Alex Martelli wrote: > wrote: > > > Hi Alex, > > With all due respect to your well-deserved standing in the Python > > community, I'm not convinced that equality shouldn't imply invariance > > under identical operations. > > So, why aren't you satisfying my request? Provide a simple concrete > definition of what your idea of equality WOULD behave like. I notice > that your lack of response stands out like a sore thumb -- all you're > providing is a set of constraints you desire and a collection of > illfounded analogies and handwaving. Traditional mathematics does not > support the concept of "change", nor the distinction between equality > and identity; the "real world" has no way to define what modifications > are "identical" except by their effects (if the results differ, either > the original equality was ill-posited or the modifications were not > "identical"). But the real world DOES have the concept of "performing > exactly the same sequence of operational steps", and, by THAT definition > of "equal modifications", then your assertion: > > > make identical modifications to the engines of two identical > > automobiles, I expect the difference in performance to be identical. > > is ill-founded -- or, rather, your *expectation* may be ill-founded. > > Take two systems of any significant complexity that are similar enough > to be called "identical" by ALL observers (because trying to ascertain > the differences, if any, would inevitably perturb the systems > irretrievably by Heisenberg's effect -- i.e., there are no OBSERVABLE > differences, which by Occam's Razor requires you to posit the systems > are equal, because you cannot prove otherwise -- and entities must not > be multiplied beyond necessity, so supposing that "observably equal" > systems are indeed equal is Occam-compliant). > > Now, perform "identical" (ditto) modifications: in the real world, due > to quantum effects, there WILL be sub-observable differences in what > you're doing to the first one and to the second one. If the systems are > unstable to start with, they may well amplify those differences to > observable proportions -- and there you are: the effect of the "equal" > change on "equal" system may easily become observably unequal. > Philosophically, you may classify this as an "observation" of both > systems, which reasoning backwards lead you to posit that either the > systems were NOT equal to start with or the modifications weren't... > that is, IF you also posit determinism, which, as well we know, is an > unwarrantedly strong hypothesis for systems in which the differences at > quantum level matter. Feel free to follow Einstein (and diverse > light-years away from the last few decades of physics) in positing that > there MUST exist "hidden variables" (unobservable except maybe in > destructive, irreversible ways) explaining the difference -- I'll stick > with the mainstream of physics and claim your expectation was badly > founded to start with. > > I can debate epistemology with the best, but this is not really the > proper forum for this -- starting with the crucial distinction, what it > means, in mathematics OR in the real world, to state that two systems > are "equal but NOT identical"? In the end, such debates tend to prove > rather futile and unproductive, however. > > In the world of programming languages, we cut through the chase by > requesting *operational* (Brouwer-ian, mathematically speaking) > definitions. Provide the *operational* definition of how you WANT > equality checking to work, contrast it with my simple two-lines one, and > THEN we can have a meaningful debate of which one is the correct one to > use in the core of a programming language that has the (blessing and > curse of) mutable data objects... > > > Alex From daniel.dittmar at sap.corp Thu Jun 1 09:54:00 2006 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Thu, 01 Jun 2006 15:54:00 +0200 Subject: DB-API: how can I find the column names in a cursor? In-Reply-To: References: Message-ID: A.M wrote: > for row in out_cur: > > print row > [...] > > The other problem is accessing data in each row by column name. One useful technique is for col1, col2, col3 in out_cur: sum = sum + col3 Access is still by index, but your code uses ordinary Python variables. It works better with SELECTs as you can choose the output columns in the SQL. With stored procedures, there's always the possibility of someone changing the structure of the result set. There exists a general library for your solution: http://opensource.theopalgroup.com/ Daniel From harlinseritt at yahoo.com Thu Jun 1 12:24:10 2006 From: harlinseritt at yahoo.com (Harlin Seritt) Date: 1 Jun 2006 09:24:10 -0700 Subject: Finding web host headers Message-ID: <1149179050.315297.79470@j55g2000cwa.googlegroups.com> Is there any way to fetch a website's host/version headers using Python? Thanks, Harlin From siona at chiark.greenend.org.uk Wed Jun 28 10:03:29 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 28 Jun 2006 15:03:29 +0100 (BST) Subject: Immutability References: <4Qj*cEjkr@news.chiark.greenend.org.uk> Message-ID: <1vF*mmkkr@news.chiark.greenend.org.uk> Fredrik Lundh wrote: >Sion Arrowsmith wrote: >> What I've not seen documented anywhere is the: >> @property >> def fset(self, value): >> ... >> idiom. It's not obvious from the documentation of the property >> function that it can be used as a decorator like this. >probably because it cannot be used in that way: the "property" function >takes the *getter* as its first argument, so you can only use this for read- >only properties... Ahem. Yes. What I obviously meant to write was: What I've not seen documented anywhere is the: @property def fget(self): ... idiom. [ ... ] (As correctly written by someone else further upthread.) It is possible to find it described by Googling, but the Cookbook (and python.org) hits provide much more complicated general-purpose (ie setters as well) property decorators. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From utabintarbo at gmail.com Wed Jun 14 07:40:29 2006 From: utabintarbo at gmail.com (utabintarbo) Date: 14 Jun 2006 04:40:29 -0700 Subject: Bundling an application with third-party modules In-Reply-To: References: Message-ID: <1150285229.237626.36440@y41g2000cwy.googlegroups.com> A couple of alternatives: 1. py2exe/csFreeze-type thing. This would even relieve the customer of installing python 2. An Installshield-type installer can place files (essentially) wherever you want them HTH From meyer at mesw.de Thu Jun 15 06:25:39 2006 From: meyer at mesw.de (meyer at mesw.de) Date: 15 Jun 2006 03:25:39 -0700 Subject: Which compiler will Python 2.5 / Windows (Intel) be built with? Message-ID: <1150367139.495114.148550@g10g2000cwb.googlegroups.com> Hi everyone, which compiler will Python 2.5 on Windows (Intel) be built with? I notice that Python 2.4 apparently has been built with the VS2003 toolkit compiler, and I read a post from Scott David Daniels [1] where he said that probably the VS2003 toolkit will be used for Python 2.5 again. However, even before the release of Python 2.5, I cannot seem to find many retailers around here that still carry Visual Studio 2003, and some were a bit surprised about my request since Visual Studio 2005 has been available for some months now. Even more importantly, there does not seem to be an official way to still get the 2003 toolkit from Microsoft. The site where it used to be available [2] now redirects you to the 2005 toolkit. The 2003 toolkit also seems to have disappeared from the browseable downloads on the Microsoft page. Searching for VCToolkitSetup.exe on the net, I found a few pages that still appear to carry the file, but most are down or just redirect to a broken link on the Microsoft site. That means that if Python 2.5 will be based on the 2003 toolkit compiler, it will be increasingly difficult to get a compiler for extensions. Since we have some Python extensions here that use MFC internally (MFC is only available in the retail version of Visual Studio .NET), we need to know in which compiler we have to invest to keep our extensions compatible with Python 2.5. Furthermore, since we also have legacy C++ applications that link to the same libraries that are also used in the Python extensions, we would be disappointed when we now had to switch to Visual Studio 2003 just to be compatible with Python 2.5, loosing official support from Microsoft in near future, and having to use an outdated compiler throughout the lifetime of Python 2.5. Thanks in advance for your comments! Markus Meyer [1] Google Groups: Python 2.5 Schedule (18 messages) http://groups.google.ca/group/comp.lang.python/browse_thread/thread/2f8be89236999a37/f6f95174484c24cc?hl=en [2] Microsoft Visual C++ Toolkit 2003 http://msdn.microsoft.com/visualc/vctoolkit2003/ From brian at sweetapp.com Fri Jun 30 11:57:16 2006 From: brian at sweetapp.com (Brian Quinlan) Date: Fri, 30 Jun 2006 17:57:16 +0200 Subject: VPW: early registration deadline today! Message-ID: <44A549DC.9070107@sweetapp.com> What's New? =========== The deadline for early-bird registration for the Vancouver Python Workshop is today! Early-bird registration is significantly discounted over normal registration, so register now at: http://www.vanpyz.org/conference/registration.html About the Vancouver Python Workshop =================================== The conference will begin with keynote addresses on August 4st by Guido van Rossum [1] and Jim Hugunin [2]. Further talks (and tutorials for beginners) will take place on August 5th and 6th. Ian Cav?n [3] will give the closing address. The Vancouver Python Workshop is a community organized and designed for both the beginner and for the experienced Python programmer with: * tutorials for beginning programmers * advanced lectures for Python experts * case studies of Python in action * after-hours social events * informative keynote speakers More information see: http://www.vanpyz.org/conference/ or contact Brian Quinlan at: brian at sweetapp.com Vancouver ========= In addition to the opportunity to learn and socialize with fellow Pythonistas, the Vancouver Python Workshop also gives visitors the opportunity to visit one of the most extraordinary cities in the world [4]. For more information about traveling to Vancouver, see: http://www.vanpyz.org/conference/vancouver.html http://www.tourismvancouver.com http://en.wikipedia.org/wiki/Vancouver Important dates =============== Early registration (discounted): May 22nd to June 30th Normal registration: from July 1st Keynotes: August 4th Conference and tutorial dates: August 5th and 6th [1] Guido van Rossum (Google) is the inventor of Python and has managed its growth and development for more than a decade. Guido was awarded the Free Software Foundation Award in 2002 and Dr.Dobb's 1999 Excellence in Programming Award. Guido works at Google and spends half of his time on Python. [2] Jim Hugunin (Microsoft) is the creator of numerous innovations that take Python into new application domains. Jim's most recent project, IronPython integrates Python into Microsoft's .NET runtime. Jim's previous project, Jython is Python for the Java runtime and was the second production-quality implementation of Python. Before that, Jim's Numeric Python adapted Python to the needs of number crunching applications. Jim works at Microsoft adapting the .NET runtime to the needs of dynamic languages like Python. [3] Ian Cav?n is the primary developer of the Lowry Digital Images motion picture restoration system. This Python and Zope-based system has been used to restore over 150 motion pictures. Highlights include Citizen Kane, Sunset Boulevard and both the Indiana Jones and Star Wars trilogies. While Ian was Chief Scientist at Lowry Digital, his rack of computers grew from a few Macintoshes on his desktop to over six hundred Macintosh and Linux servers - at one point earning Lowry the title as the second biggest installation of parallel processing Maintoshes in the world. In 2005, Lowry Digital Images was acquired by DTS (the famous movie audio company) and renamed DTS Digital Images. The motion picture restoration system has been discussed in publications as diverse as IEEE Spectrum, USA Today, the BBC NEWS, the New York Times and Apple.com. Ian has been a Python enthusiast since 1999. [4] http://news.bbc.co.uk/2/hi/business/2299119.stm http://edition.cnn.com/2006/BUSINESS/06/15/btn.cities/index.html Cheers, Brian From m.yanowitz at kearfott.com Tue Jun 27 07:46:15 2006 From: m.yanowitz at kearfott.com (Michael Yanowitz) Date: Tue, 27 Jun 2006 07:46:15 -0400 Subject: SWIG problems with gcc and Cygwin? In-Reply-To: Message-ID: -----Original Message----- From: python-list-bounces+m.yanowitz=kearfott.com at python.org [mailto:python-list-bounces+m.yanowitz=kearfott.com at python.org]On Behalf Of Steve Holden Sent: Tuesday, June 27, 2006 2:55 AM To: python-list at python.org Subject: Re: SWIG problems with gcc and Cygwin? Michael Yanowitz wrote: > No response yet. The SWIG test works fine in Linux no problems. > However, I still have the problem in Cygwin. > Also, not sure if related but I do have a win32 Python 2.4.3 and > Cygwin Python 2.4.1. Not sure if there are any conflicts. Any advice > in making these two co-exist? > The only C/C++ compiler I have presently is Cygwin gcc. > I wouldn't claim to be an expert but it looks like you are missing libraries. Shouldn't you at least be loading -l c to get functions defined in libc? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden Possibly. I thought of that, but Linux doesn't require that I link in the C Library. Maybe Cygwin does or maybe a parameter is needed in gcc to do that automatically. The sample program (in http://www.swig.org/tutorial.html ) does not mention this. Thanks: Michael Yanowitz From alf at merlin.fayauffre.org Thu Jun 1 09:51:23 2006 From: alf at merlin.fayauffre.org (Alexandre Fayolle) Date: Thu, 1 Jun 2006 13:51:23 +0000 (UTC) Subject: default argument values qns References: <1149169482.717737.241410@g10g2000cwb.googlegroups.com> Message-ID: Le 01-06-2006, micklee74 at hotmail.com nous disait: > hi > i have declared a function like this: > > def aFunction ( arg1 , arg2 = 0): > .... > print type(arg2) > > when i try to print the type of arg2, it gives me 'str' type..why is it > not integer type, since i have > declared it as 0 ?? You probably either called the function with a string as the second argument, or assigned a string to arg2 in the ... part of the function. On my box, I get what you would expect: >>> def aFunction ( arg1 , arg2 = 0): ... print type(arg2) ... >>> aFunction(2) Now, remember that there are no variables in Python, only identifiers, which are refering to values. When you print type(arg2), you are not printing the "type of variable arg2", but the "type of the value referenced by arg2", which is quite different, especially because it can change during the execution of the program. -- Alexandre Fayolle LOGILAB, Paris (France) Formations Python, Zope, Plone, Debian: http://www.logilab.fr/formations D?veloppement logiciel sur mesure: http://www.logilab.fr/services Python et calcul scientifique: http://www.logilab.fr/science From digitalorganics at gmail.com Sun Jun 11 18:06:46 2006 From: digitalorganics at gmail.com (digitalorganics at gmail.com) Date: 11 Jun 2006 15:06:46 -0700 Subject: direct initialization of class attributes vs. declarations w/in __init__ In-Reply-To: References: <1150041510.139609.171120@f6g2000cwb.googlegroups.com> <4f2thrF1fd4r4U1@uni-berlin.de> <1150043792.136250.99770@u72g2000cwu.googlegroups.com> <1150047314.025241.260750@c74g2000cwc.googlegroups.com> <1150062413.303012.177330@f6g2000cwb.googlegroups.com> Message-ID: <1150063606.929384.300040@j55g2000cwa.googlegroups.com> Fredrik Lundh wrote: > digitalorganics at gmail.com wrote: > > > Any clue what's behind this behavior? > > a missing plus sign. > > Thanks for the guess but not possible given the following: class Boo: jerk = 10 def killjerk(self): counter = 3 while counter !=0: counter -= 1 self.jerk += 1 print self.jerk print self.__class__.jerk bing = Boo() bing.killjerk() Output from desktop comp.: 11 10 12 10 13 10 Output from laptop comp.: 1 10 2 10 3 10 ?? . . . From girish at cse.iitb.ac.in Wed Jun 7 22:39:11 2006 From: girish at cse.iitb.ac.in (Girish Sahani) Date: Thu, 8 Jun 2006 08:09:11 +0530 (IST) Subject: How to generate k+1 length strings from a list of k length strings? Message-ID: <45427.10.209.4.1.1149734351.squirrel@10.105.1.3> I have a list of strings all of length k. For every pair of k length strings which have k-1 characters in common, i want to generate a k+1 length string(the k-1 common characters + 2 not common characters). e.g i want to join 'abcd' with bcde' to get 'abcde' but i dont want to join 'abcd' with 'cdef' Currently i'm joining every 2 strings, then removing duplicate characters from every joined string and finally removing all those strings whose length != k+1.Here's the code i've written: for i in range(0,len(prunedK) - 1,1): if k in range(1,len(prunedK),1) & i+k <= len(prunedK) -1: colocn = prunedK[i] + prunedK[i+k] prunedNew1.append(colocn) continue for string in prunedNew1: stringNew = withoutDup(string) prunedNew.append(stringNew) continue But this one is quite bad in the time aspect :(. Thanks in advance, girish From bearophileHUGS at lycos.com Thu Jun 22 18:57:57 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 22 Jun 2006 15:57:57 -0700 Subject: map() return of flat tuple list References: Message-ID: <1151017077.211517.47940@u72g2000cwu.googlegroups.com> Maybe you want something like this (but this doesn't use map): def indexes(m): return [(r,c) for r, row in enumerate(m) for c in xrange(len(row))] m1 = [[2,2,5], [2,2], [2,2,2,2]] m2 = [[], [2], [1,2,3,4]] print indexes(m1) print indexes(m2) Output: [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (2, 0), (2, 1), (2, 2), (2, 3)] [(1, 0), (2, 0), (2, 1), (2, 2), (2, 3)] Bye, bearophile From harry.g.george at boeing.com Mon Jun 5 01:09:55 2006 From: harry.g.george at boeing.com (Harry George) Date: Mon, 5 Jun 2006 05:09:55 GMT Subject: Open Source Charting Tool References: <1L0gg.1841$Su3.159041@news20.bellglobal.com> Message-ID: "A.M" writes: > Hi, > > > > I developed a HTML reporting tool that renders Oracle data to HTML and > Oracle. > > > > At this point I have to add charts (3d bars and pie charts) to this > application. I don't think that I have to do it from scratch. > > > > Is there any open source charting tool that help me create charts in JPG or > gif format? > > > > Thanks, > > Alan > > See pygdchart http://www.nullcube.com/software/pygdchart.html -- Harry George PLM Engineering Architecture From tim.peters at gmail.com Sun Jun 11 15:58:42 2006 From: tim.peters at gmail.com (Tim Peters) Date: Sun, 11 Jun 2006 15:58:42 -0400 Subject: math.pow(x,y) In-Reply-To: <448C6D0A.9000407@islandtraining.com> References: <1150049976.916474.186580@j55g2000cwa.googlegroups.com> <448C6D0A.9000407@islandtraining.com> Message-ID: <1f7befae0606111258j2259d019p6ba4302c99ee7efe@mail.gmail.com> [Wojciech Mu?a] >> You have to use operator **, i.e. 34564323**456356 Or the builtin pow() instead of math.pow(). [Gary Herron] > That's not very practical. That computation will produce a value with > more than 3.4 million digits. Yes. > (That is, log10(34564323)*456356 = 3440298.) Python will attempt this, but > I was not patient enough to see if it could calculate an answer today (or even > this week). On my box it took less than 30 seconds to do x = 34564323**456356 If you try to _display_ that as a decimal string, it will take enormously longer. Python uses a power-of-2 base internally, and conversion to decimal takes time quadratic in the number of digits. Doing y = hex(x) instead is very fast (small fraction of a second). > I doubt that you really *want* all 3.4 million digits. So what is it you > really want? A scientific or engineering result as a floating point > number accurate to some reasonable number of digits? That integer value > modulo some other integer (as used in various cryptology schemes)? For example, if you only want the last 6 digits, pow(34564323, 456356, 1000000) returns 986961 in an eyeblink. From jurgenex at hotmail.com Fri Jun 23 09:50:50 2006 From: jurgenex at hotmail.com (Jürgen Exner) Date: Fri, 23 Jun 2006 13:50:50 GMT Subject: Saying "latently-typed language" is making a category mistake References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> Message-ID: <_kSmg.983$Wh.149@trnddc04> Vesa Karvonen wrote: > In comp.lang.functional Anton van Straaten > wrote: [...] >> I reject this comparison. There's much more to it than that. The > > I think that we're finally getting to the bottom of things. While > reading your reponses something became very clear to me: > latent-typing and latent- types are not a property of languages. > Latent-typing, also known as informal reasoning, is something that And what does this have to do with Perl? Are you an alter ego of Xha Lee who spills his 'wisdom' across any newsgroup he can find? jue From digitalorganics at gmail.com Mon Jun 26 14:06:37 2006 From: digitalorganics at gmail.com (digitalorganics at gmail.com) Date: 26 Jun 2006 11:06:37 -0700 Subject: TypeError: Cannot create a consistent method resolution order (MRO) for bases object Message-ID: <1151345197.691600.200060@y41g2000cwy.googlegroups.com> What are the reason one would get this error: TypeError: Cannot create a consistent method resolution order (MRO) for bases object ?? I can provide the code if needed.... From percivall at gmail.com Sat Jun 3 19:52:19 2006 From: percivall at gmail.com (Simon Percivall) Date: 3 Jun 2006 16:52:19 -0700 Subject: Python less error-prone than Java References: Message-ID: <1149378739.429512.26310@f6g2000cwb.googlegroups.com> Actually, you're wrong on all levels. First: It's perfectly simple in Java to create a binary sort that sorts all arrays that contain objects; so wrong there. Secondly: The bug has nothing to do with static typing (I'm guessing that's what you meant. Both Python and Java are strongly typed). The problem is that ints are bounded in Java. They could easily have been ints and then automatically coerced to (equivalent to) longs when they got bigger; that they aren't is more a design fault than anything to do with static typing. The equivalent in Python would have been if an overflow exception was raised when the int got too big. It might have been that way, typing or no typing. Christoph Zwerschke wrote: > You will often hear that for reasons of fault minimization, you should > use a programming language with strict typing: > http://turing.une.edu.au/~comp284/Lectures/Lecture_18/lecture/node1.html > > I just came across a funny example in which the opposite is the case. > > The following is a binary search algorithm in Java. It searches a value > in an ordered array a of ints: > > public static int binarySearch(int[] a, int key) { > int low = 0; > int high = a.length - 1; > while (low <= high) { > int mid = (low + high) / 2; > int midVal = a[mid]; > if (midVal < key) > low = mid + 1; > else if (midVal > key) > high = mid - 1; > else > return mid; // key found > } > return -(low + 1); // key not found. > } > > Now the same thing, directly converted to Python: > > def binarySearch(a, key): > low = 0 > high = len(a) - 1 > while low <= high: > mid = (low + high) / 2 > midVal = a[mid] > if midVal < key: > low = mid + 1 > elif midVal > key: > high = mid - 1; > else: > return mid # key found > return -(low + 1) # key not found. > > What's better about the Python version? First, it will operate on *any* > sorted array, no matter which type the values have. > > But second, there is a hidden error in the Java version that the Python > version does not have. > > See the following web page if you dont find it ;-) > http://googleresearch.blogspot.com/2006/06/extra-extra-read-all-about-it-nearly.html > > -- Christoph From Dennis.Benzinger at gmx.net Wed Jun 7 12:19:36 2006 From: Dennis.Benzinger at gmx.net (Dennis Benzinger) Date: Wed, 07 Jun 2006 18:19:36 +0200 Subject: How do I automatically redirect stdout and stderr when using os.popen2? In-Reply-To: <1149696430.511354.276460@i40g2000cwc.googlegroups.com> References: <1149696430.511354.276460@i40g2000cwc.googlegroups.com> Message-ID: <4486fc95$1@news.uni-ulm.de> mikem76 at gmail.com wrote: > How do I automatically redirect stdout and stderr when using os.popen2 > to start a long running process. If the process prints a lot of stuff > to stdout it will eventually stop because it runs out of buffer space. > Once I start reading the stdout file returned by os.popen2 then the > process resumes. I know that I could just specify > /dev/null when > starting the process but I'd like to know if there is a way to start a > process using os.popen2 or some other way so that all standard out and > standard error goes to /dev/null or some other file. > > Thanks, > Mike > Use the POpen class from the subprocess module. Bye, Dennis From felipe.lessa at gmail.com Tue Jun 6 13:43:24 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Tue, 06 Jun 2006 14:43:24 -0300 Subject: 10GB XML Blows out Memory, Suggestions? In-Reply-To: <2Qfhg.18186$0v4.787@tornado.texas.rr.com> References: <1149594519.098115.8980@u72g2000cwu.googlegroups.com> <2Qfhg.18186$0v4.787@tornado.texas.rr.com> Message-ID: <1149615804.6856.3.camel@kenshin.CASA> Em Ter, 2006-06-06 ?s 13:56 +0000, Paul McGuire escreveu: > (just can't open it up like a text file) Who'll open a 10 GiB file anyway? -- Felipe. From cvanarsdall at mvista.com Wed Jun 28 13:21:12 2006 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Wed, 28 Jun 2006 10:21:12 -0700 Subject: to py or not to py ? In-Reply-To: References: Message-ID: <44A2BA88.1060604@mvista.com> Robert Kern wrote: >> Carl , what are the problems that could arise with threading ?? >> Because of the GIL only one thread can actually run at a time. So if you are going for speed (say you have an SMP box) and your two requests require significant computation, you'd want each processor to take on a little bit of that work to get things done faster. Now say you want these two to be computed simultaneously and you are using python, you won't get that, one thread will process and then the other will process as the GIL is passed around between the python threads. Now if your bottleneck is IO then you are in good shape for python threads (Your machine only has one network port and you don't have a lot of computation overhead, so your single processor can serve things up faster than your network card can take it). So its not problems that arise, its more like inefficiency. Anyhow, it all depends on what you are trying to do and the needs of your application. -carl -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From da404lewzer at gmail.com Wed Jun 28 22:09:33 2006 From: da404lewzer at gmail.com (da404LewZer) Date: 28 Jun 2006 19:09:33 -0700 Subject: need help with a new site Message-ID: <1151546973.296901.304810@b68g2000cwa.googlegroups.com> hell all, i'm starting a new wiki for programming called "CoderWiki" i plan on documenting all functions of all programming languages. I have started a couple portals for C, VB, PHP, HTML, Java, Smalltalk, etc, and just added a API Guide section for talking about the Google API, Win32 API, etc etc. any help would be awesome, thanks in advance! coderwiki.com From andrew-news at andros.org.uk Sun Jun 25 16:10:31 2006 From: andrew-news at andros.org.uk (Andrew McLean) Date: Sun, 25 Jun 2006 21:10:31 +0100 Subject: Looking for Python code to obsfucate mailto links on web site Message-ID: I'm looking at putting some e-mail contact addresses on a web site, and wanted to make it difficult for spammers to harvest them. I found some Python code that I can call within my application. http://www.zapyon.de/spam-me-not/ It works exactly as expected. However, I am concerned that the technique used for obsfucating the e-mail address may be a bit weak. Searching the web it looks like the best solution for me might be to embed JavaScript in the web page that dynamically generates the e-mail address in the browser client. I've found on-line tools that will generate suitable JavaScript, but need to automate the "encoding" process in Python. Now I could write suitable code myself, but would be surprised if it wasn't already available. Any pointers? To head of a few comments I'm anticipating ;-) - no I don't want to use a contact form - accessibility is an issue, but I'm also including postal addresses and phone numbers giving alternatives to e-mail. Also the main enquiry address won't be obfuscated. From exarkun at divmod.com Thu Jun 22 15:23:54 2006 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 22 Jun 2006 15:23:54 -0400 Subject: Network Programming in Python In-Reply-To: <1151002934.586359.174540@m73g2000cwd.googlegroups.com> Message-ID: <20060622192354.29014.740373951.divmod.quotient.7084@ohm> On 22 Jun 2006 12:02:14 -0700, diffuser78 at gmail.com wrote: >I am a newbie in python. I want to learn and implement a small >networking concept. Please help me. Every help is appreciated. > >I have one Linux Box and one Windows PC. I want to have a daemon >running on Windows PC which listens on some specicif port number. I >want to send a TCP/IP or UDP/IP packet from Linux box to Windows PC to >start some application. As Windows PC recieves such a packet from Linux >Box it executes a certain .exe file. I want to implement this concept. > >In short I want to remotely send command from Linux to Windows PC to >start a particular application. > >Thanks, Every help is appreciated. > Untested: from twisted.internet import protocol, reactor from twisted.protocols import basic COMMANDS = { "xterm": ("/usr/bin/xterm", {"DISPLAY": ":1.0"}), } class CommandLauncher(basic.LineReceiver): def lineReceived(self, line): try: cmd, env = COMMANDS[line] except KeyError: self.sendLine("error") else: reactor.spawnProcess(None, cmd, env=env) self.sendLine("okay") f = protocol.ServerFactory() f.protocol = CommandLauncher reactor.listenTCP(12345, f) reactor.run() You should be able to telnet to this (port 12345) and type in names of commands for it to run. Of course, xterm isn't a very good win32 program to run but I couldn't think of a better example. You could also write a program to send command requests to this server, instead of using telnet. Jean-Paul From fredrik at pythonware.com Fri Jun 30 07:13:55 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 30 Jun 2006 13:13:55 +0200 Subject: efficiency question References: <6AD91BEE-08AF-446D-AE17-B2FB5532E7FE@math.harvard.edu> Message-ID: David Harvey wrote: > Suppose I write > > if x in ("abc", "def", "xyz"): > doStuff() > > elif x in ("pqr", "tuv", "123"): > doOtherStuff() > > elif ... > When is python building the tuples? Does it need to build the tuple > every time it comes through this code? Or does it somehow recognise > that they are constant and cache them? when in doubt, ask the compiler: def code(x): if x in ("abc", "def", "xyz"): doStuff() elif x in ("pqr", "tuv", "123"): doOtherStuff() import dis dis.dis(code) prints: 2 0 LOAD_FAST 0 (x) 3 LOAD_CONST 7 (('abc', 'def', 'xyz')) 6 COMPARE_OP 6 (in) 9 JUMP_IF_FALSE 11 (to 23) 12 POP_TOP 3 13 LOAD_GLOBAL 1 (doStuff) 16 CALL_FUNCTION 0 19 POP_TOP 20 JUMP_FORWARD 25 (to 48) >> 23 POP_TOP 4 24 LOAD_FAST 0 (x) 27 LOAD_CONST 8 (('pqr', 'tuv', '123')) 30 COMPARE_OP 6 (in) 33 JUMP_IF_FALSE 11 (to 47) 36 POP_TOP 5 37 LOAD_GLOBAL 2 (doOtherStuff) 40 CALL_FUNCTION 0 43 POP_TOP 44 JUMP_FORWARD 1 (to 48) >> 47 POP_TOP >> 48 LOAD_CONST 0 (None) 51 RETURN_VALUE so the answer is "yes, in this specific case". > (The tuples I have in mind are of course much longer than three > elements) in that case, you should probably use pre-calculated sets instead of tuples. From sjmachin at lexicon.net Wed Jun 7 19:28:58 2006 From: sjmachin at lexicon.net (John Machin) Date: Thu, 08 Jun 2006 09:28:58 +1000 Subject: Using C struct in Python In-Reply-To: References: Message-ID: <4487613A.8050502@lexicon.net> On 8/06/2006 7:35 AM, Sudheer Gupta wrote: > Hi, Hi. Your later "correction" doesn't clear up the confusion below. Quick eye-balling revealed no difference. If you have to correct a minor typo in a posting, please consider saying "change X to Y" instead of reposting the whole thing. > > I am having trouble using C struct in python. Hope anyone can help me > out ... > > Say, I have my C struct as > > typedef struct call > { > struct call *next; > // ..... > > } call_t; > > I have a global variable, namely call_pool, which is of type call_t * You really need to explain what sort of glue you have between your Python code and your C code. 1. Are you the author of the glue? If not, better ask the author. 2. Are you extending Python with a module written in C, or are you embedding Python in a C program? 3. If extending, what's your glue? SWIG? something else? hand-crafted? > > My python program: > > cp = call_pool # no error doing this, means that call_pool is accessable Acessible from where? How do you bind the name "call_pool" to an object? > > while cp: > print cp > print cp.next > > > This is giving me error: " There is no member or method name c_next" Not a Python error message. Must be coming from inside your extension module. > > Now, If I just do: > > print cp > print cp.next > > there is no problem. Sorry, I don't understand. Above you said it was "giving me error". > But I am seeing a difference in the way python is > looking at the struct: > > print cp -> (call_t*) 0xb0... > print cp.next -> (struct call *) 0xb0... If they are actual results from a Python print statement, then I can only assume the extension module defines types which have (in effect) str() and/or repr() methods which produce such output. Python does not know that the C type of cp is (call_t*) and that of cp.next is (struct call *). In fact it doesn't care, and it shouldn't care. The extension module could be written in assembly language or APL or even INTERCAL if it obeys the conventions, which don't include exposing a C type for each object. Another way of looking at it: methods in extension modules are mostly expected to behave like methods written in Python. I get the impression that you are using some "superglue" that parses C declarations and writes (parts of) Python extension modules in C. Do you think you could possibly tell us what the name of this superglue is? > Is python not intelligent enough to diagnose the next pointer ?? To the extent to which I can understand what your question means, the answer is: It by design makes no attempt to be what you are calling intelligent. Python does only limited inspection of the tables of methods that an extension type says it supports. It uses only the very basic information: is the pointer to method X NULL? I hope some of the above helps you amplify your question. Cheers, John From duncan.booth at invalid.invalid Thu Jun 15 03:58:32 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 15 Jun 2006 07:58:32 GMT Subject: nested functions References: <1150319279.865335.323530@u72g2000cwu.googlegroups.com> <1150344748.652441.316680@g10g2000cwb.googlegroups.com> Message-ID: Georg Brandl wrote: > That's right. However, if the outer function is only called a few times > and the nested function is called a lot, the locals lookup for the > function name is theoretically faster than the globals lookup. Also, > in methods you can use closures, so you don't have to pass, for example, > self to the inner function. If you are worried about the overhead of looking up the function name in the local rather than global scope then you should also worry about the overhead of accessing self through a closure rather than as a parameter. As always in these cases, don't worry about it until you know definitely (by timing) that performance is an issue in that part of your code, and then time the different options and refuse the temptation to guess as you will probably get it wrong. The relative times here will depend on a lot of factors, such as how often you access the closure/parameter, and whether or not there are other arguments to the function. I frequently nest functions, but I do it in cases where I want to simplify a function body and don't see any case for creating yet another generally accessible method or function. Some benefits of nested functions: you can use a function name which is short by self-explanatory within the context of the outer function without having to worry about it conflicting with other function/variable names. The extracted functions are kept close to the place where they are used: a small support function which is a few hundred lines away from where it is used is more accident prone than one right next to the place it is used. Also, if you later refactor out the main method the support functions will disappear as well rather than lying around unused. You can use closures, not because you have to, but because it simplifies the calls and therefore keeps expressions simpler and easier to read. Of course you can also mess things up totally by overdoing it. From bearophileHUGS at lycos.com Wed Jun 21 09:01:01 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 21 Jun 2006 06:01:01 -0700 Subject: Search substring in a string and get index of all occurances In-Reply-To: References: <4499034A.9040306@gmail.com> Message-ID: <1150894861.880424.207650@b68g2000cwa.googlegroups.com> Maric Michaud: > I'd love str implement a xsplit(sub, start, end) method, so I could have > wrote : enumerate(s.xsplit(subs, 0, -1)). Some of such str.x-methods (or str.i-methods, etc) can be useful (especially for Py3.0), but keeping APIs simple and compact is very important, otherwise when you program you have to waste some time looking things up in the manuals. Such lists of methods are a compromise between (among other things) completeness and compactness. Bye, bearophile From deets at nospam.web.de Sun Jun 11 18:13:53 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 12 Jun 2006 00:13:53 +0200 Subject: direct initialization of class attributes vs. declarations w/in __init__ In-Reply-To: <1150061669.491796.95700@g10g2000cwb.googlegroups.com> References: <1150041510.139609.171120@f6g2000cwb.googlegroups.com> <4f2thrF1fd4r4U1@uni-berlin.de> <1150043792.136250.99770@u72g2000cwu.googlegroups.com> <1150047314.025241.260750@c74g2000cwc.googlegroups.com> <1150061669.491796.95700@g10g2000cwb.googlegroups.com> Message-ID: <4f3it1F1gptbcU1@uni-berlin.de> > No need to be obnoxious. I do appreciate your efforts to help, but you > must admit, your last statement is a bit snide and certainly not > useful. > I'm telling you that the code runs differently on my laptop. It certainly doesn't. There is absolutely no imaginable way how this behavior could be different, even if the python versions would differ considerably. Apart from quantum-fluctuations. Or other SciFi voodoo. > Why this is, I don't know any more /or/ less than you do apparently. Frederik (as one of the most profiled python developers out there) might not be the most amicable of posters, but he certainly is not wrong when it comes to the most basic parts of python's semantics. > Now, it is of course possible that I'm interpreting the results > incorrectly, but that doesn't change the fact that I'm getting > different results per computer with identical code. It is NOT identical code, otherwise you won't see different results. It might be code from which you _believe_ it is identical, and the difference might be subtle to see. But if you'd store it in a file, execute on your laptop, use an usb-stick and then transfer it to whatever the other machine of yours is, it will yield the exact same results. Diez From scott.daniels at acm.org Wed Jun 14 17:56:12 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Wed, 14 Jun 2006 14:56:12 -0700 Subject: better Python IDE? Mimics Maya's script editor? In-Reply-To: <1149810048.765664.107820@i40g2000cwc.googlegroups.com> References: <1149810048.765664.107820@i40g2000cwc.googlegroups.com> Message-ID: <44908136$1@nntp0.pdx.net> warpcat wrote: > I've been scripting in Maya, via mel for years now. Recently learning > to Python, love it. Thing that's driving me nuts it the IDE. I'm > using PythonWin right now and trying to find something better, mainly > with this functionality: I'm not certain, but you could take a look at Komodo from ActiveState. I do have an interactive window, edit window(s), and an output window. You can get a free trial from them, as I remember. --Scott David Daniels scott.daniels at acm.org From 3dbernard at gmail.com Thu Jun 1 12:07:00 2006 From: 3dbernard at gmail.com (Bernard Lebel) Date: Thu, 1 Jun 2006 12:07:00 -0400 Subject: Tkinter: select multiple entries in Listbox widget? Message-ID: <61d0e2b40606010907v4846da5dt39ab4f5f58293069@mail.gmail.com> Hello, Is there an option or a way to allow the selection of multiple entries in the Listbox widget? I could not find any, and would like to allow the end user to select multiple entries. Thanks Bernard From egodet at equisys.com Tue Jun 20 06:33:54 2006 From: egodet at equisys.com (egodet at equisys.com) Date: 20 Jun 2006 03:33:54 -0700 Subject: Debugging C++ code called from Python 2.2 with Visual Studio.NET Message-ID: <1150799634.503338.302780@b68g2000cwa.googlegroups.com> Hi, I'm trying to debug some VS native C++ code called from a python script (version is 2.2). For that, I added the _DEBUG macro in Setup.py but when I rebuild the pyd file, I get a compilation error whereby it says that python22_d.lib could not be found. I've seen in various groups that python22_d.lib is not available for download anymore but that it is easy to recompile. Could someone send it to me, explain how to build it or, even better, both. I expect that after that, if I recompile the python pyd file, I will be able to attach a debugger to it. Could someone confirm this? Cheers, Emmanuel PS: I'm new to Python and I'm using legacy code. From grante at visi.com Wed Jun 14 11:25:38 2006 From: grante at visi.com (Grant Edwards) Date: Wed, 14 Jun 2006 15:25:38 -0000 Subject: convert floats to their 4 byte representation References: <1150297093.191223.152330@c74g2000cwc.googlegroups.com> Message-ID: <1290aji9iovpb9@corp.supernews.com> On 2006-06-14, godavemon wrote: > I need to take floats and dump out their 4 byte hex representation. struct -- Grant Edwards grante Yow! Darling, my ELBOW at is FLYING over FRANKFURT, visi.com Germany... From kbk at shore.net Thu Jun 22 01:39:59 2006 From: kbk at shore.net (Kurt B. Kaiser) Date: Thu, 22 Jun 2006 01:39:59 -0400 (EDT) Subject: Weekly Python Patch/Bug Summary Message-ID: <200606220540.k5M5dxTF016810@bayview.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 378 open ( +3) / 3298 closed (+34) / 3676 total (+37) Bugs : 886 open (-24) / 5926 closed (+75) / 6812 total (+51) RFE : 224 open ( +7) / 227 closed ( +7) / 451 total (+14) New / Reopened Patches ______________________ Improve super() objects support for implicit method calls (2006-05-31) http://python.org/sf/1498363 opened by Collin Winter Improve itertools.starmap (2006-05-31) http://python.org/sf/1498370 opened by Collin Winter Change *args from a tuple to list (2006-05-31) http://python.org/sf/1498441 opened by Collin Winter Correctly unpickle exceptions (2006-06-01) CLOSED http://python.org/sf/1498571 opened by ?iga Seilnacht Fault in XMLRPC not always returned to client (2006-05-31) CLOSED http://python.org/sf/1498627 opened by Daniel Savard Generate from Unicode database instead of manualy coding. (2006-06-01) http://python.org/sf/1498930 opened by Anders Chrigstr?m Optimise "in" operations on tuples of consts (2006-06-01) CLOSED http://python.org/sf/1499095 opened by Collin Winter Fix for memory leak in WindowsError_str (2006-06-02) CLOSED http://python.org/sf/1499797 opened by ?iga Seilnacht Alternate RFC 3896 compliant URI parsing module (2006-06-05) http://python.org/sf/1500504 opened by Nick Coghlan Remove dependencies on the sets module (2006-06-04) http://python.org/sf/1500609 opened by Collin Winter (py3k) Remove the sets module (2006-06-04) http://python.org/sf/1500611 opened by Collin Winter Remove the repr()-backticks (2006-06-04) http://python.org/sf/1500623 opened by Collin Winter wm_attributes doesn't take keyword arguments (2006-06-04) http://python.org/sf/1500773 opened by Greg Couch AF_NETLINK support for socket module (2006-06-05) CLOSED http://python.org/sf/1500815 opened by lplatypus Cyclic garbage collection support for slices (2006-06-05) CLOSED http://python.org/sf/1501180 opened by ?iga Seilnacht Fix Bug #1339007 - shelve.open('non-existant-file', 'r') (2006-06-06) CLOSED http://python.org/sf/1501534 opened by Jeung Mun Sic syntax errors on continuation lines (2006-06-06) http://python.org/sf/1501979 opened by Roger Miller Remove randomness from test_exceptions (2006-06-07) CLOSED http://python.org/sf/1501987 opened by ?iga Seilnacht Conditional compilation of zlib.(de)compressobj.copy (2006-06-08) CLOSED http://python.org/sf/1503046 opened by Chris AtLee Allow Empty Subscript List Without Parentheses (2006-06-09) CLOSED http://python.org/sf/1503556 opened by Noam Raphael Tiny patch to stop make spam (2006-06-09) http://python.org/sf/1503717 opened by Chris AtLee Rough documentation for xml.etree.ElementTree (2006-06-10) http://python.org/sf/1504046 opened by Fredrik Lundh Patch for 1496501 tarfile opener order (2006-06-10) http://python.org/sf/1504073 opened by Jack Diederich Switch syntax (partial PEP 275) (2006-06-11) http://python.org/sf/1504199 opened by Thomas Lee winerror module (2006-06-13) http://python.org/sf/1505257 opened by M.-A. Lemburg curses.resizeterm() (2006-06-15) CLOSED http://python.org/sf/1506645 opened by Walter D?rwald Patch for 1506758 - popen2/subprocess MAXFD MemoryErrors (2006-06-15) http://python.org/sf/1506760 opened by Peter Vetere Use a set to keep interned strings (2006-06-15) http://python.org/sf/1507011 opened by Alexander Belopolsky tarfile extraction does not honor umask (2006-06-16) http://python.org/sf/1507247 opened by Faik Uygur improve object.c and abstract.c exception messages (2006-06-17) CLOSED http://python.org/sf/1507676 opened by Georg Brandl transparent gzip compression in liburl2 (2006-06-19) http://python.org/sf/1508475 opened by Jakob Truelsen uuid documentation (2006-06-20) http://python.org/sf/1508766 opened by George Yoshida Make Lib/test/regrtest.py NetBSD 3 aware. (2006-06-20) CLOSED http://python.org/sf/1509001 opened by Matt Fleming MS Toolkit Compiler no longer available (2006-06-20) http://python.org/sf/1509163 opened by Paul Moore skip tests in test_socket__ssl when connection refused (2006-06-20) CLOSED http://python.org/sf/1509404 reopened by bcannon skip tests in test_socket__ssl when connection refused (2006-06-20) CLOSED http://python.org/sf/1509404 opened by Brett Cannon Small fix for sqlite3 test suite (2006-06-20) CLOSED http://python.org/sf/1509584 opened by Gerhard H??ring tarfile stops iteration with some longfiles (2006-06-21) CLOSED http://python.org/sf/1509889 opened by Faik Uygur Patches Closed ______________ Possible fix to #1334662 (int() wrong answers) (2006-03-31) http://python.org/sf/1462361 closed by gbrandl Correctly unpickle exceptions (2006-05-31) http://python.org/sf/1498571 closed by gbrandl Fault in XMLRPC not always returned to client (2006-06-01) http://python.org/sf/1498627 closed by gbrandl Fix test_exceptions.py (2006-05-27) http://python.org/sf/1496135 closed by gbrandl Let dicts propagate the exceptions in user __eq__ (2006-05-29) http://python.org/sf/1497053 closed by arigo Optimise "in" operations on tuples of consts (2006-06-01) http://python.org/sf/1499095 closed by rhettinger potential crash and free memory read (2005-11-15) http://python.org/sf/1357836 closed by nnorwitz Fix for memory leak in WindowsError_str (2006-06-02) http://python.org/sf/1499797 closed by nnorwitz Better dead code elimination for the AST compiler (2005-11-02) http://python.org/sf/1346214 closed by gbrandl Speed charmap encoder (2005-11-18) http://python.org/sf/1359618 closed by loewis AF_NETLINK support for socket module (2006-06-05) http://python.org/sf/1500815 closed by loewis patch for SIGSEGV in arraymodule.c (2006-03-20) http://python.org/sf/1454485 closed by loewis Cyclic garbage collection support for slices (2006-06-05) http://python.org/sf/1501180 closed by zseil Fix Bug #1339007 - shelve.open('non-existant-file', 'r') (2006-06-06) http://python.org/sf/1501534 closed by gbrandl Remove randomness from test_exceptions (2006-06-06) http://python.org/sf/1501987 closed by tim_one Corrupt Berkeley DB using Modify bsddb.dbtables (2006-01-17) http://python.org/sf/1408584 closed by greg Conditional compilation of zlib.(de)compressobj.copy (2006-06-08) http://python.org/sf/1503046 closed by nnorwitz Allow Empty Subscript List Without Parentheses (2006-06-09) http://python.org/sf/1503556 closed by gbrandl Add help reference on Mac (04/25/06) http://python.org/sf/1476578 closed by sf-robot Windows CE support (part 2) (2006-05-27) http://python.org/sf/1495999 closed by loewis Update documentation for __builtins__ (2005-09-24) http://python.org/sf/1303595 closed by fdrake Suggested Additional Material for urllib2 docs (2005-06-08) http://python.org/sf/1216942 closed by fdrake AssertionError when building rpm under RedHat 9.1 (2003-05-02) http://python.org/sf/731328 closed by jafo patch for mbcs codecs (2006-03-22) http://python.org/sf/1455898 closed by loewis BaseWidget.destroy updates master's childern too early (2006-05-25) http://python.org/sf/1494750 closed by loewis curses.resizeterm() (2006-06-15) http://python.org/sf/1506645 closed by doerwalter improve object.c and abstract.c exception messages (2006-06-17) http://python.org/sf/1507676 closed by gbrandl Minor enhancements to Variable class (2003-07-01) http://python.org/sf/763580 closed by loewis Fix for wm_iconbitmap to allow .ico files under Windows. (2005-01-05) http://python.org/sf/1096231 closed by loewis upgrade pyexpat to expat 2.0.0 (2006-03-31) http://python.org/sf/1462338 closed by tmick Make Lib/test/regrtest.py NetBSD 3 aware. (2006-06-20) http://python.org/sf/1509001 closed by gbrandl skip tests in test_socket__ssl when connection refused (2006-06-20) http://python.org/sf/1509404 closed by bcannon skip tests in test_socket__ssl when connection refused (2006-06-20) http://python.org/sf/1509404 closed by bcannon Small fix for sqlite3 test suite (2006-06-20) http://python.org/sf/1509584 closed by ghaering tarfile stops iteration with some longfiles (2006-06-21) http://python.org/sf/1509889 closed by gbrandl New / Reopened Bugs ___________________ Pickling exceptions crashes Python (2006-05-30) CLOSED http://python.org/sf/1497319 opened by ?iga Seilnacht __self reserved WATCOM 10.6 word (2006-05-30) CLOSED http://python.org/sf/1497414 opened by kbob_ru Leak in tarfile.py (2006-05-31) CLOSED http://python.org/sf/1497962 opened by Jens J?rgen Mortensen MSVC compiler problems with .NET v2.0 (2006-05-31) CLOSED http://python.org/sf/1498051 opened by Retief Gerber optparse does not hande unicode help strings (2006-05-31) CLOSED http://python.org/sf/1498146 opened by Tom Cato Amundsen tp_alloc for subtypes of PyComplex_Type is not called (2006-05-31) CLOSED http://python.org/sf/1498638 opened by Travis Oliphant lstrip does not work properly (2006-06-01) CLOSED http://python.org/sf/1499049 opened by rpache lstrip does not work properly (2006-06-02) CLOSED http://python.org/sf/1499316 opened by rpache interpret termination, object deleting (2006-06-03) CLOSED http://python.org/sf/1500167 opened by Jan Martinek re.escape incorrectly escape literal. (2006-06-03) CLOSED http://python.org/sf/1500179 opened by Baptiste Lepilleur Memory leak in subprocess module (2006-06-04) CLOSED http://python.org/sf/1500293 opened by ?iga Seilnacht Lang ref '<' description in 5.9 not consistent with __lt__ (2006-06-05) CLOSED http://python.org/sf/1501122 opened by Andy Harrington Possible buffer overflow in Python/sysmodule.c (2006-06-05) CLOSED http://python.org/sf/1501223 opened by Brett Cannon python/ncurses bug in 2.4.3 with extended ascii (2006-06-05) http://python.org/sf/1501291 opened by UnixOps failure of test_ossaudiodev; elapsed time .1 sec faster (2006-06-05) http://python.org/sf/1501330 opened by Brett Cannon method format of logging.Formatter caches incorrectly (2006-06-06) http://python.org/sf/1501699 opened by Boris Lorbeer incorrect LOAD/STORE_GLOBAL generation (2006-06-07) http://python.org/sf/1501934 opened by Thomas Wouters crash in expat when compiling with --enable-profiling (2006-06-07) http://python.org/sf/1502517 opened by Ronald Oussoren HP-UX shared library does not reference librt (2006-06-08) CLOSED http://python.org/sf/1502728 opened by G?ran Uddeborg PyArg_ParseTuple(args, "i") and sys.maxint (2006-06-08) CLOSED http://python.org/sf/1502750 reopened by lemburg PyArg_ParseTuple(args, "i") and sys.maxint (2006-06-08) CLOSED http://python.org/sf/1502750 opened by M.-A. Lemburg 'with' sometimes eats exceptions (2006-06-08) CLOSED http://python.org/sf/1502805 opened by Armin Rigo "/".join() throws OverflowError (2006-06-08) CLOSED http://python.org/sf/1503157 opened by Wummel 'make install' fails on OS X 10.4 when running compileall (2006-06-08) CLOSED http://python.org/sf/1503294 opened by Brett Cannon Pdb doesn't call flush on its stdout file descriptor (2006-06-09) http://python.org/sf/1503502 opened by Matt Fleming logger.config problems with comma separated lists (2006-06-09) http://python.org/sf/1503765 opened by cuppatea stdin directory causes crash (SIGSEGV) (2006-06-09) CLOSED http://python.org/sf/1503780 opened by Ben Liblit Cannot write source code in UTF16 (2006-06-09) http://python.org/sf/1503789 opened by Wai Yip Tung csv.Sniffer - says "1 method", shows 2 (2006-06-10) CLOSED http://python.org/sf/1503883 opened by Frank Millman sgmlib should allow angle brackets in quoted values (2006-06-11) http://python.org/sf/1504333 opened by Sam Ruby xmlcore needs to be documented (2006-06-11) http://python.org/sf/1504456 opened by Fred L. Drake, Jr. Make sgmllib char and entity references pluggable (2006-06-12) CLOSED http://python.org/sf/1504676 opened by Sam Ruby There should be a Python build using Visual Studio 2005 (2006-06-12) http://python.org/sf/1504947 opened by Vincent Manis under Windows XP, os.walk problem with path >256? chars (2006-06-12) CLOSED http://python.org/sf/1504998 opened by Mike Coleman Wrong grammar (2006-06-12) CLOSED http://python.org/sf/1505081 opened by Milind Incorrect comment in socket.py (2006-06-12) CLOSED http://python.org/sf/1505095 opened by Bruce Christensen Add support for GNU --long options (interpreter) (2006-06-14) CLOSED http://python.org/sf/1505841 opened by Jari Aalto If MAXFD too high, popen2/subprocess produce MemoryErrors (2006-06-15) http://python.org/sf/1506758 opened by Peter Vetere Misleading error message from PyObject_GenericSetAttr (2006-06-15) CLOSED http://python.org/sf/1506776 opened by Alexander Belopolsky list bug (2006-06-15) CLOSED http://python.org/sf/1506799 opened by SPlyer pydoc fails on package in ZIP archive (2006-06-15) CLOSED http://python.org/sf/1506945 opened by Christopher Dunn pydoc fails on package in ZIP archive (2006-06-15) http://python.org/sf/1506951 opened by Christopher Dunn HTTPResponse instance has no attribute 'code' (2006-06-16) CLOSED http://python.org/sf/1507166 opened by yodalf sys.path issue if sys.prefix contains a colon (2006-06-16) http://python.org/sf/1507224 opened by Ronald Oussoren Broken example in optparse module documentation (2006-06-16) CLOSED http://python.org/sf/1507379 opened by Michal Krenek logging fileConfig swallows handler exception (2006-06-18) http://python.org/sf/1508253 opened by tdir logging module formatter problem with %(filename)s (2006-06-18) http://python.org/sf/1508369 opened by David Hess "...." (four dots) confuses doctest's ellipsis matching (2006-06-19) CLOSED http://python.org/sf/1508564 opened by Andrew Bennetts os.spawnv fails when argv is a length 1 tuple (2006-06-19) CLOSED http://python.org/sf/1508833 opened by ncloud failed to load tuxedo libs (2006-06-19) CLOSED http://python.org/sf/1508848 opened by William Ding threading.Timer breaks when you change system time on win32 (2006-06-19) http://python.org/sf/1508864 opened by Russell Warren compiler module builds incorrect AST for TryExceptFinally (2006-06-20) CLOSED http://python.org/sf/1509132 opened by Adrien Di Mascio Absolute/relative import not working? (2006-06-21) http://python.org/sf/1510172 opened by Mitch Chapman Bugs Closed ___________ Pickling exceptions crashes Python (2006-05-30) http://python.org/sf/1497319 closed by gbrandl __self reserved WATCOM 10.6 word (2006-05-30) http://python.org/sf/1497414 closed by akuchling hyper-threading locks up sleeping threads (2006-05-08) http://python.org/sf/1484172 closed by tim_one strptime: wrong default values used to fill in missing data (2006-05-28) http://python.org/sf/1496315 closed by bcannon Leak in tarfile.py (05/30/06) http://python.org/sf/1497962 closed by sf-robot MSVC compiler problems with .NET v2.0 (2006-05-31) http://python.org/sf/1498051 closed by loewis optparse does not hande unicode help strings (2006-05-31) http://python.org/sf/1498146 closed by gward SimpleXMLRPCServer responds to any path (2006-04-19) http://python.org/sf/1473048 closed by akuchling tp_alloc for subtypes of PyComplex_Type is not called (2006-06-01) http://python.org/sf/1498638 closed by gbrandl dictobject.c:dictresize() vulnerability (2006-03-22) http://python.org/sf/1456209 closed by arigo dict key comparison swallows exceptions (2005-08-29) http://python.org/sf/1275608 closed by arigo Traceback error when compiling Regex (2006-03-22) http://python.org/sf/1456280 closed by gbrandl lstrip does not work properly (2006-06-01) http://python.org/sf/1499049 closed by gbrandl lstrip does not work properly (2006-06-02) http://python.org/sf/1499316 closed by gbrandl sgmllib do_tag description error (2006-04-17) http://python.org/sf/1472084 closed by akuchling time module missing from global mod index (2006-05-16) http://python.org/sf/1489648 closed by akuchling Poorly worded description for socket.makefile() (2006-04-24) http://python.org/sf/1475554 closed by akuchling Omission in docs for urllib2.urlopen() (2006-03-02) http://python.org/sf/1441864 closed by akuchling interpret termination, object deleting (2006-06-03) http://python.org/sf/1500167 closed by loewis re.escape incorrectly escape literal. (2006-06-03) http://python.org/sf/1500179 closed by blep Memory leak in subprocess module (2006-06-04) http://python.org/sf/1500293 closed by gbrandl Lang ref '<' description in 5.9 not consistent with __lt__ (2006-06-05) http://python.org/sf/1501122 closed by gbrandl distutils.core: link to list of Trove classifiers (2006-04-13) http://python.org/sf/1470026 closed by akuchling Possible buffer overflow in Python/sysmodule.c (2006-06-05) http://python.org/sf/1501223 closed by bcannon bsddb: db never opened for writing forgets its size (2006-05-22) http://python.org/sf/1493322 closed by greg Make logging consistent in the standard library (2003-08-19) http://python.org/sf/791410 closed by gbrandl Distutils does not use logging (2005-07-19) http://python.org/sf/1241006 closed by gbrandl argvemulator doesn't work on intel mac (2006-05-19) http://python.org/sf/1491468 closed by ronaldoussoren OS X framework build for python 2.5 fails, configure is odd (2006-05-11) http://python.org/sf/1486897 closed by ronaldoussoren bsddb3 hash craps out with threads (2003-07-21) http://python.org/sf/775414 closed by greg HP-UX shared library does not reference librt (2006-06-08) http://python.org/sf/1502728 closed by gbrandl PyArg_ParseTuple(args, "i") and sys.maxint (2006-06-08) http://python.org/sf/1502750 closed by gbrandl PyArg_ParseTuple(args, "i") and sys.maxint (2006-06-08) http://python.org/sf/1502750 closed by gbrandl 'with' sometimes eats exceptions (2006-06-08) http://python.org/sf/1502805 closed by gbrandl built-in method .__cmp__ (2005-11-07) http://python.org/sf/1350060 closed by arigo int/long assume that the buffer ends in \0 => CRASH (2006-05-25) http://python.org/sf/1495033 closed by bcannon "/".join() throws OverflowError (2006-06-08) http://python.org/sf/1503157 closed by gbrandl xml.sax.saxutils.XMLGenerator mangles \r\n\t in attributes (2006-04-19) http://python.org/sf/1472827 closed by akuchling Recursive class instance "error" (2002-03-20) http://python.org/sf/532646 closed by bcannon stdin from directory causes crash (SIGSEGV) (2006-06-10) http://python.org/sf/1503780 closed by gbrandl -Wi causes a fatal Python error (2006-06-09) http://python.org/sf/1503294 closed by arigo Install under osx 10.4.6 breaks shell. (05/25/06) http://python.org/sf/1495210 closed by sf-robot csv.Sniffer - says "1 method", shows 2 (2006-06-10) http://python.org/sf/1503883 closed by frankmillman optparse: extending actions missing ALWAYS_TYPED_ACTIONS (2006-03-13) http://python.org/sf/1449311 closed by gward dest parameter in optparse (2005-04-15) http://python.org/sf/1183972 closed by gward textwrap.dedent() expands tabs (2005-11-19) http://python.org/sf/1361643 closed by gward packman upgrade issue (2004-05-31) http://python.org/sf/963494 closed by ronaldoussoren incorrect documentation for optparse (2005-11-25) http://python.org/sf/1366250 closed by gward Make sgmllib char and entity references pluggable (2006-06-12) http://python.org/sf/1504676 closed by fdrake under Windows XP, os.walk problem with path >256? chars (2006-06-12) http://python.org/sf/1504998 closed by loewis Wrong grammar (2006-06-12) http://python.org/sf/1505081 closed by tim_one Incorrect comment in socket.py (2006-06-13) http://python.org/sf/1505095 closed by gbrandl code that generates a segfault on Python 2.1-2.3 (2004-07-15) http://python.org/sf/992017 closed by bcannon shelve.Shelf.__del__ throws exceptions (2005-10-26) http://python.org/sf/1339007 closed by gbrandl "u#" doesn't check object type (2002-11-13) http://python.org/sf/637547 closed by gbrandl str.join() intercepts TypeError raised by iterator (2004-02-26) http://python.org/sf/905389 closed by gbrandl Add support for GNU --long options (interpreter) (2006-06-14) http://python.org/sf/1505841 closed by gbrandl reflected operator not used when operands have the same type (2005-02-28) http://python.org/sf/1153163 closed by gbrandl mimetypes.py does not find mime.types on Mac OS X (2005-05-14) http://python.org/sf/1202018 closed by gbrandl SimpleHTTPServer and mimetypes: almost together (2005-02-06) http://python.org/sf/1117556 closed by gbrandl No struct.pack exception for some out of range integers (2005-06-28) http://python.org/sf/1229380 closed by gbrandl SIGSEGV causes hung threads (Linux) (2003-06-18) http://python.org/sf/756924 closed by gbrandl os.listdir fails for pathprefix \\?\d:... (2004-02-12) http://python.org/sf/895567 closed by gbrandl PyUnicode_FromEncodedObject (2003-09-12) http://python.org/sf/805015 closed by gbrandl raw_input() displays wrong unicode prompt (2005-01-10) http://python.org/sf/1099364 closed by gbrandl Misleading error message from PyObject_GenericSetAttr (2006-06-15) http://python.org/sf/1506776 closed by gbrandl list bug (2006-06-15) http://python.org/sf/1506799 closed by tim_one pydoc fails on package in ZIP archive (2006-06-15) http://python.org/sf/1506945 deleted by christopherdunn HTTPResponse instance has no attribute 'code' (2006-06-16) http://python.org/sf/1507166 closed by yodalf Broken example in optparse module documentation (2006-06-16) http://python.org/sf/1507379 closed by nnorwitz turtle.py deferres exec of stmnts with tracer(0) (2003-09-26) http://python.org/sf/812986 closed by loewis tkMessageBox functions reject type and ico (2003-10-01) http://python.org/sf/815924 closed by loewis "...." (four dots) confuses doctest's ellipsis matching (2006-06-19) http://python.org/sf/1508564 closed by gbrandl os.spawnv fails when argv is a length 1 tuple (2006-06-19) http://python.org/sf/1508833 closed by gbrandl failed to load tuxedo libs (2006-06-19) http://python.org/sf/1508848 closed by nnorwitz expat symbols should be namespaced in pyexpat (2005-09-19) http://python.org/sf/1295808 closed by tmick compiler module builds incorrect AST for TryExceptFinally (2006-06-20) http://python.org/sf/1509132 closed by gbrandl New / Reopened RFE __________________ C API to retain GIL during Python Callback (2006-05-30) http://python.org/sf/1497532 opened by Martin Gfeller Add write buffering to gzip (2006-06-05) http://python.org/sf/1501108 opened by Raymond Hettinger Add "compose" function to the functools (2006-06-14) http://python.org/sf/1506122 opened by Gregory Petrosyan Add "methodcaller" to the operator module (2006-06-14) http://python.org/sf/1506171 opened by Gregory Petrosyan Add "methodcaller" to the operator module (2006-06-14) CLOSED http://python.org/sf/1506190 opened by Gregory Petrosyan Add "methodcaller" to the operator module (2006-06-14) CLOSED http://python.org/sf/1506211 opened by Gregory Petrosyan Add "methodcaller" to the operator module (2006-06-14) CLOSED http://python.org/sf/1506216 opened by Gregory Petrosyan Add some dicts to datetime module (2006-06-14) http://python.org/sf/1506296 opened by Gregory Petrosyan Add some dicts to datetime module (2006-06-15) CLOSED http://python.org/sf/1506313 opened by Gregory Petrosyan Add some dicts to datetime module (2006-06-15) CLOSED http://python.org/sf/1506324 opened by Gregory Petrosyan Add some dicts to datetime module (2006-06-15) http://python.org/sf/1506340 opened by Gregory Petrosyan Interrupt/kill threads w/exception (2006-06-20) http://python.org/sf/1509060 opened by Oliver Bock replace dist/src/Tools/scripts/which.py with tmick's which (2006-06-21) http://python.org/sf/1509798 opened by wrstl prmpft RFE Closed __________ str.startswith/endswith could take a tuple? (2006-05-19) http://python.org/sf/1491485 closed by gbrandl Add "methodcaller" to the operator module (2006-06-14) http://python.org/sf/1506190 closed by gbrandl Add "methodcaller" to the operator module (2006-06-14) http://python.org/sf/1506211 closed by gbrandl Add "methodcaller" to the operator module (2006-06-14) http://python.org/sf/1506216 closed by gbrandl Add some dicts to datetime module (2006-06-14) http://python.org/sf/1506313 closed by gbrandl Add some dicts to datetime module (2006-06-14) http://python.org/sf/1506324 closed by gbrandl Use new expat version 2.0 (2006-02-17) http://python.org/sf/1433435 closed by gbrandl From g.brandl-nospam at gmx.net Fri Jun 30 11:06:38 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Fri, 30 Jun 2006 17:06:38 +0200 Subject: Way for see if dict has a key In-Reply-To: <44a50e5c$0$11383$626a54ce@news.free.fr> References: <6V6pg.21624$_J1.271925@twister2.libero.it> <44a5041f$0$29637$636a55ce@news.free.fr> <4F7pg.21676$_J1.272665@twister2.libero.it> <1151667333.569664.152670@h44g2000cwa.googlegroups.com> <44a50e5c$0$11383$626a54ce@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > looping wrote: >> Michele Petrazzo wrote: >> >>>Bruno Desthuilliers wrote: >>> >>>>>but what the better >>>> >>>>Depends on the context. >>>> >>> >>>If know only one context: see if the key are into the dict... What other >>>context do you know? >>> >> >> Why do you want to do that ? >> >> if key in dict: >> value = dict[key] >> else: >> value = None >> >> could be write: > > value = dict.get(key, None) value = dict.get(key) ;) Georg From dpickles at pacbell.net Tue Jun 27 17:29:55 2006 From: dpickles at pacbell.net (dylpkls91) Date: 27 Jun 2006 14:29:55 -0700 Subject: Execute Commands on Remote Computers over Network In-Reply-To: References: <1151378614.481850.271340@c74g2000cwc.googlegroups.com> Message-ID: <1151443795.343874.290790@u72g2000cwu.googlegroups.com> Lawrence D'Oliveiro wrote: > In article <1151378614.481850.271340 at c74g2000cwc.googlegroups.com>, > "dylpkls91" wrote: > > >I have been researching this topic and come up with some code to make > >it work. It uses SSL and requires the 3rd party package Paramiko (which > >requires PyCrypto). > > Why not just spawn an invocation of SSH? @Dennis: yes, I know, but I wasn't thinking, and it doesn't solve the problem. @Lawrence: I'm sorry, but I'm a newbie. Can you explain what this means, and how I could do it in Python? Thank you very much. From aum at spam.me.please Mon Jun 19 08:37:09 2006 From: aum at spam.me.please (aum) Date: Tue, 20 Jun 2006 00:37:09 +1200 Subject: pyfcp References: Message-ID: On Mon, 19 Jun 2006 14:45:19 +0800, Thomas Moore wrote: >> http://www.python.org/pyfcp >> > > It gets me to Error 404. Apologies - that URL should have been: http://www.python.org.nz/pyfcp -- Cheers aum From girodt at gmail.com Thu Jun 22 14:00:04 2006 From: girodt at gmail.com (TG) Date: 22 Jun 2006 11:00:04 -0700 Subject: Numeric N-dimensional array initialization Message-ID: <1150999204.839644.179940@g10g2000cwb.googlegroups.com> Hi there ! I'm just starting to use Numeric here, and I'm wondering : how can I efficiently initialize every values of a N-dimensional array, given I don't know the number of dimensions ? I'm looking for something like a map function, or a way to conveniently iterate through the whole N-array, but I didn't find anything ... yet. If anyone has a clue, I'm listening. Thanks From forestiero at qwest.net Tue Jun 13 18:24:43 2006 From: forestiero at qwest.net (Dog Walker) Date: Tue, 13 Jun 2006 15:24:43 -0700 Subject: .py and running in Windows: In-Reply-To: References: Message-ID: <200606131524.43096.forestiero@qwest.net> On Tuesday 13 June 2006 07:04, Michael Yanowitz wrote: > Thanks. > > XP looks to be the same as 2000. > Works as expected now. Thank You. > > Not sure what this 'thread' issue is. > I never specified a thread. I think perhaps though because I did > open another message in this mailing list (to get the correct > email address to send to), but I deleted all its contents i put > it under that other thread, however there is no indication of a > thread in Outlook email. I am sorry if it came up in another > thread that was not my intention. > To start a new thread use a new email: even though you deleted the contents, In-Reply-To: and References: headers remain in the email, and when they are present, they determine the thread rather than the Subject: header. > -----Original Message----- > From: python-list-bounces+m.yanowitz=kearfott.com at python.org > [mailto:python-list-bounces+m.yanowitz=kearfott.com at python.org]On Behalf > Of Iain King > Sent: Tuesday, June 13, 2006 9:48 AM > To: python-list at python.org > Subject: Re: .py and running in Windows: > > > > Andrew Gwozdziewycz wrote: > > You'll have better results posting this to it's own thread. > > [...] From esj at harvee.org Fri Jun 30 08:11:03 2006 From: esj at harvee.org (Eric S. Johansson) Date: Fri, 30 Jun 2006 08:11:03 -0400 Subject: list comprehension In-Reply-To: <1151603446.189159.240580@75g2000cwc.googlegroups.com> References: <1151600332.552024.119990@y41g2000cwy.googlegroups.com> <1151603446.189159.240580@75g2000cwc.googlegroups.com> Message-ID: tac-tics wrote: > a wrote: >> can someone tell me how to use them >> thanks > > sigh... > You do a google on them: > > http://docs.python.org/tut/node7.html#SECTION007140000000000000000 > thank you for the reminder. But after reading it, I was left with a question. Why the new syntax for what appears to be nothing more than a different way of expressing nested for loops? at first I tried rearranging the one of the examples from the previously referenced document to clarify (in my mind) what was going on: [x*y for x in vec1 for y in vec2 ] then when I tried to rewrite it as a nested for loop, that's when I realized list comprehensions is a method of returning the calculation in the interior of a for loop as an assignment without requiring aggregation of results in a temporary variable. so a double thank you to you because you've clarified something that has been a mystery to me for awhile. now if I could find someone to explain distutils and eggs so that I understand that as well... ;-) Heck, I would even settle for a wizard tool generating the first approximation for me. ---eric From micklee74 at hotmail.com Tue Jun 13 09:42:20 2006 From: micklee74 at hotmail.com (micklee74 at hotmail.com) Date: 13 Jun 2006 06:42:20 -0700 Subject: a string problem Message-ID: <1150206140.912224.113420@p79g2000cwp.googlegroups.com> hi if i have a some lines like this a ) "here is first string" b ) "here is string2" c ) "here is string3" When i specify i only want to print the lines that contains "string" ie the first line and not the others. If i use re module, how to compile the expression to do this? I tried the re module and using simple search() and everytime it gives me all the 3 lines that have "string" in it, whereas i only need line 1. If re module is not needed, how can i use string manipulation to do this? thanks From aahz at pythoncraft.com Mon Jun 5 10:06:30 2006 From: aahz at pythoncraft.com (Aahz) Date: 5 Jun 2006 07:06:30 -0700 Subject: Large Dictionaries References: <1147699064.107490@teuthos> <447af556$1@nntp0.pdx.net> Message-ID: In article , Lawrence D'Oliveiro wrote: >In article <447af556$1 at nntp0.pdx.net>, > Scott David Daniels wrote: >> >>For example, time timsort (Python's internal sort) on pre-sorted >>data; you'll find it is handled faster than random data. > >But isn't that how a reasonable sorting algorithm should behave? Less >work to do if the data is already sorted? Read some of the old discussions in the python-dev archives. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I saw `cout' being shifted "Hello world" times to the left and stopped right there." --Steve Gonedes From christopher.helck at gmail.com Sun Jun 25 10:35:08 2006 From: christopher.helck at gmail.com (Christopher Helck) Date: Sun, 25 Jun 2006 10:35:08 -0400 Subject: How to parse timestamps containing milliseconds Message-ID: Hi, I'm trying to read a file containing timestamps with milliseconds ("2006/3/18 8:20:34.050"). The DateTime object seems to take milliseconds (microseconds really) but the strftime method doesn't have a format code for the millisecond field (in other languages I've used %s.). When I try to parse I get an error about the trailing ".050". How should I approach this? Thanks, C. Helck -------------- next part -------------- An HTML attachment was scrubbed... URL: From Sebastien.Boisgerault at gmail.com Tue Jun 6 13:49:49 2006 From: Sebastien.Boisgerault at gmail.com (=?iso-8859-1?q?S=E9bastien_Boisg=E9rault?=) Date: 6 Jun 2006 10:49:49 -0700 Subject: capture video from camera In-Reply-To: <1149603488.012417.269760@j55g2000cwa.googlegroups.com> References: <1149598946.182874.121650@c74g2000cwc.googlegroups.com> <1149603488.012417.269760@j55g2000cwa.googlegroups.com> Message-ID: <1149616188.965740.122650@i39g2000cwa.googlegroups.com> aljosa wrote: > i searched on google and found http://videocapture.sourceforge.net/ > before i posted here. yup. > videocapture has no docs With the API docs in the ".zip" and the examples provided, you should be able to handle it.I did :) > and doesn't provide additional options like > motion detection nor any info on possibility of motion detection or > howto implement (use of minimal system resources). Sure. You may try to use some external lib such as Camellia (http://camellia.sourceforge.net/). There are (swig-generated) bindings for Ruby, writing a bridge to python should be straightforward By the way, if you want to be cross-platform, you can use pyv4l as a replacement of videocapture for Linux. Combine this with a pygame integration and you're done. Cheers, SB From marshall.spight at gmail.com Fri Jun 23 22:14:04 2006 From: marshall.spight at gmail.com (Marshall) Date: 23 Jun 2006 19:14:04 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150908952.804184.218990@r2g2000cwb.googlegroups.com> <1150991074.705803.211570@m73g2000cwd.googlegroups.com> <1151083239.829296.33030@i40g2000cwc.googlegroups.com> <1151083931.162325.268050@g10g2000cwb.googlegroups.com> <1151086320.564736.272500@y41g2000cwy.googlegroups.com> <1151100483.057344.310970@g10g2000cwb.googlegroups.com> Message-ID: <1151115244.951029.56060@g10g2000cwb.googlegroups.com> Dr.Ruud wrote: > Marshall schreef: > > Rob Thorpe: > > >> Can I make a type in C that can only have values between 1 and 10? > >> How about a variable that can only hold odd numbers, or, to make it > >> more difficult, say fibonacci numbers? > > > > Well, of course you can't in *C*; you can barely zip you pants with C. > > But I believe you can do the above in C++, can't you? > > You can write self-modifying code in C, so I don't see how you can not > do that in C. > ;) I stand corrected: if one is using C and writing self-modifying code, then one *can* zip one's pants. Marshall From uval at rz.uni-karlsruhe.de Fri Jun 30 10:12:51 2006 From: uval at rz.uni-karlsruhe.de (=?ISO-8859-1?Q?Sch=FCle_Daniel?=) Date: Fri, 30 Jun 2006 16:12:51 +0200 Subject: string replace In-Reply-To: <1aapg.21924$_J1.275201@twister2.libero.it> References: <1aapg.21924$_J1.275201@twister2.libero.it> Message-ID: > A solution could be that "replace" accept a tuple/list of chars, like > that was add into the new 2.5 for startswith. > > I don't know, but can be this feature included into a future python > release? I don't know, but I think it would be useful as for now I use this >>> import re >>> chars = re.compile(r'[abc]') >>> text = "aAbBcCdD" >>> chars.sub("",text) 'ABCdD' >>> > > Thanks, > Michele Regards, Daniel From nexu.jin at gmail.com Sat Jun 3 23:57:13 2006 From: nexu.jin at gmail.com (Nexu) Date: Sun, 04 Jun 2006 05:57:13 +0200 Subject: Hostmask matching Message-ID: <1149393433.5979.6.camel@localhost.localdomain> I'm trying to write a def to match a string that is an irc hostmask. eg: *one!~*name at a??-??-101-101.someisp.com But using re.search(). I get an error when the string starts with '*'. What is the best way to solve this? From antroy at gmail.com Fri Jun 2 07:08:03 2006 From: antroy at gmail.com (Ant) Date: 2 Jun 2006 04:08:03 -0700 Subject: Selection in Tkinter Text widget. Message-ID: <1149246483.809582.8310@i39g2000cwa.googlegroups.com> Hi all, I have been trying to select text in a Text widget programmatically. I have been trying the following minimal example: #================================= from Tkinter import * def showgui(): win = Tk() area = Text(win, width = 50, height = 20) area.pack() new = """Lots of text here and here and here...""" area.insert("1.0", new) area.tag_add(SEL, "1.0", END) win.mainloop() if __name__ == "__main__": showgui() #================================== The area.tag_add(...) line should - from what I have read in Frederik's Intro to Tkinter guide - select all of the text in the text area. It doesn't however... Does anyone have any idea how to get this to work? Or tell me what I am doing wrong. Cheers, -- Ant... From deets at nospam.web.de Thu Jun 29 10:10:17 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 29 Jun 2006 16:10:17 +0200 Subject: Event notification system - where to start ? References: <1151589497.327662.115100@p79g2000cwp.googlegroups.com> Message-ID: <4gi5a7F1mp6a4U1@uni-berlin.de> geskerrett at hotmail.com wrote: > We have been asked to develop and application for a client that is a > 'notification" system. We would like to use python, but are struggling > to find the right starting point. Any suggestions, tips or sample code > would be appreciated. > We also looked at the asyncore and asynchat, but are having difficulty > gettng starting with these. If someone has a working example of a > "chat" server using these modules they could share it would be very > helpful. > > So ... any suggestions ? I just implemented such a thing using Pyro[1]. I in fact rolled out my own event-system, but I guess I could have used the pyro event system[2] instead. Diez [1] http://pyro.sourceforge.net/ [2] http://pyro.sourceforge.net/manual/6-eventserver.html From david.nospam.hopwood at blueyonder.co.uk Tue Jun 20 23:54:02 2006 From: david.nospam.hopwood at blueyonder.co.uk (David Hopwood) Date: Wed, 21 Jun 2006 03:54:02 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: <4fo19aF1jsudeU1@individual.net> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <4fo19aF1jsudeU1@individual.net> Message-ID: Pascal Costanza wrote: > Chris Smith wrote: > >> Knowing that it'll cause a lot of strenuous objection, I'll >> nevertheless interject my plea not to abuse the word "type" with a >> phrase like "dynamically typed". If anyone considers "untyped" to be >> perjorative, as some people apparently do, then I'll note that another >> common term is "type-free," which is marketing-approved but doesn't >> carry the misleading connotations of "dynamically typed." We are >> quickly losing any rational meaning whatsoever to the word "type," and >> that's quite a shame. > > The words "untyped" or "type-free" only make sense in a purely > statically typed setting. In a dynamically typed setting, they are > meaningless, in the sense that there are _of course_ types that the > runtime system respects. > > Types can be represented at runtime via type tags. You could insist on > using the term "dynamically tagged languages", but this wouldn't change > a lot. Exactly _because_ it doesn't make sense in a statically typed > setting, the term "dynamically typed language" is good enough to > communicate what we are talking about - i.e. not (static) typing. Oh, but it *does* make sense to talk about dynamic tagging in a statically typed language. That's part of what makes the term "dynamically typed" harmful: it implies a dichotomy between "dynamically typed" and "statically typed" languages, when in fact dynamic tagging and static typing are (mostly) independent features. -- David Hopwood From robert.kern at gmail.com Thu Jun 8 21:25:10 2006 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 08 Jun 2006 20:25:10 -0500 Subject: Exeucte a system command in python script In-Reply-To: <1149815748.856808.200140@j55g2000cwa.googlegroups.com> References: <1149815748.856808.200140@j55g2000cwa.googlegroups.com> Message-ID: ken.carlino at gmail.com wrote: > Hi, > > I would like to execute a shell command like this in python: > cmd = 'ant release -Dbuild=build_proxyonly -Drev=5.1.130f > -Dprops=\"-MIDP20_LARGE;PUSH_FEATURE=false;MIDlet-Version=5.0;version=5.0;MIDlet-Icon=midicon15x15.png;-FOUR_WAY_NAV_FEATURE\" > -DThree_Branding=true' > > Which of the execl command described here should I use? > http://pydoc.org/1.6/os.html None. You should use the subprocess module in 2.4 (I really do hope that you're not using 1.6). http://docs.python.org/lib/module-subprocess.html It also works in Pythons as old as 2.2, but you'll have to install it separately. The website for the separate release is down at the moment, but when it comes back up: http://www.lysator.liu.se/~astrand/popen5/ -- 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 From martin.wiechert at gmx.de Mon Jun 5 13:47:30 2006 From: martin.wiechert at gmx.de (Martin Wiechert) Date: Mon, 05 Jun 2006 19:47:30 +0200 Subject: linking errors with debug build of Python2.4.3 In-Reply-To: <200606041617.09198.martin.wiechert@gmx.de> References: <1148781211.487215.260090@j73g2000cwa.googlegroups.com> <200606041617.09198.martin.wiechert@gmx.de> Message-ID: <200606051947.31136.martin.wiechert@gmx.de> Nonsense! I meant leaving out --enable-shared. On Sunday 04 June 2006 16:17, Martin Wiechert wrote: > You were right, leaving out --with-pydebug did the trick. > > Thanks, Martin > > On Sunday 28 May 2006 03:53, nnorwitz at gmail.com wrote: > > Martin Wiechert wrote: > > > Hi list, > > > > > > I've created a fresh build of Python 2.4.3 using the following > > > configuration > > > > > > $ ./configure --with-pydebug --prefix=/usr/local/debug --enable-shared > > > --with-fpectl --with-signal-module > > > > > > What did I do wrong? > > > > Try with just: ./configure --with-pydebug --prefix=/usr/local/debug > > > > I think the problem is --enable-shared. I'm not sure what you are > > doing, but you probably don't need the other options. The signal > > module should always be built, I've never even seen the > > --with-signal-module option. :-) > > > > n From iainking at gmail.com Fri Jun 30 06:59:05 2006 From: iainking at gmail.com (Iain King) Date: 30 Jun 2006 03:59:05 -0700 Subject: conecting with a MsAcces DB by dao In-Reply-To: <1151663549.731904.259030@d56g2000cwd.googlegroups.com> References: <1151650208.783778.186690@d56g2000cwd.googlegroups.com> <1151655436.083906.143380@75g2000cwc.googlegroups.com> <1151663549.731904.259030@d56g2000cwd.googlegroups.com> Message-ID: <1151665145.582514.262970@75g2000cwc.googlegroups.com> luis wrote: > Iain King ha escrito: > > > luis wrote: > > > while not rs.EOF: > > > id=rs.Fields(colName.Value) #colName, valid column name > > > ... > > > rs.MoveNext() > > > rs.Close() > > > conn.Close() > > > > I don't know if it's the problem your asking about, but your > > rs.MoveNext() should be inside the while loop, no? > Yes, is inside > > You mean, it is inside the while loop in your code, but you made a mistake copying it into your post? In the code you posted it is not inside the while loop - it would have to be indented one more level for that. Iain From bapolis at gmail.com Tue Jun 13 05:28:28 2006 From: bapolis at gmail.com (Tgone) Date: 13 Jun 2006 02:28:28 -0700 Subject: Decimals In-Reply-To: References: <1150188516.739925.102810@h76g2000cwa.googlegroups.com> Message-ID: <1150190908.231517.314040@h76g2000cwa.googlegroups.com> Laszlo Nagy wrote: > Tgone ?rta: > > Hello, > > > > I have a price column in a MySQL table: price decimal(5,2) > > > > When I access them in Python with SQLObject, prices display as 15.0 > > instead of 15.00. Why is this happening? I can't figure out why Python > > is trimming off the hundredth place. I'm not doing any formatting... > > > What do you mean by 'displays as 15.0'? Do you print in with the print > statement? If your DB access module returns decimal.Decimal instances, > then you are right. It should print as 15.00 instead of 15.0. Try to > determine the type of the returned value. Maybe your DB module uses > float instead of Decimal? Sorry, when I print out the variable it displays as '15.0'. The price is '15.00' in the database though. Here's my code: product = Product.get(2) print product.price # 15.0 I'm using MySQLdb if that helps. From xivulon at gmail.com Fri Jun 2 10:57:33 2006 From: xivulon at gmail.com (ago) Date: 2 Jun 2006 07:57:33 -0700 Subject: win32com: how to connect to a specific instance of a running object? In-Reply-To: <1149254270.790703.145700@j55g2000cwa.googlegroups.com> References: <1149254270.790703.145700@j55g2000cwa.googlegroups.com> Message-ID: <1149260253.337452.65770@c74g2000cwc.googlegroups.com> The other approach I tried (as suggested by Tim, thanks) involves browsing the ROT. import pythoncom SPREADSHEET_NAME = r'\MySpreadsheet.xls' lenstr = len(SPREADSHEET_NAME) obj = None rot = pythoncom.GetRunningObjectTable() rotenum = rot.EnumRunning() while True: monikers = rotenum.Next() if not monikers: break ctx = pythoncom.CreateBindCtx(0) name = monikers[0].GetDisplayName(ctx, None); if name[-lenstr:] == SPREADSHEET_NAME: obj = rot.GetObject(monikers[0]) break The obj I get is a PyIUnknown... How do I use it? From claudio.grondi at freenet.de Wed Jun 7 07:04:24 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Wed, 07 Jun 2006 13:04:24 +0200 Subject: what are you using python language for? In-Reply-To: References: Message-ID: hacker1017 wrote: > im just asking out of curiosity. It appears to me, that the natural language is not enough to record thoughts/observations/enlightenments for being reviewed and used with ease after a longer time, as for this purpose it is necessary to include in such records some sort of activity and/or interactivity and this requires utilization of a computer and a programming language. Usage of Python (on top of the English language I am not native speaker of and HTML way of formatting texts) saves me the work of documenting the very basics of the programming language add-on used on top of natural language for above purpose as it comes with documentation of own elements [i.e. keywords and concepts in form of definitions like: global_stmt ::= "global" identifier ("," identifier)*] from the very basic parser point of view. Python makes an intuitive way of expressing algorithms and processes easier by having many of for this purpose useful concepts already built-in. By the way: Which other programming languages provide documentation also via giving definitions of keywords and concepts? Are there e.g. similar definitions [i.e e.g.: global_stmt ::= "global" identifier ("," identifier)*] available for C/C++, Java, JavaScript? Short expressed: I use Python (and its huge amount of available modules) mainly as an extension on top of natural English language and HTML formatted texts leveraging this way the (re)use of textual recordings of ideas by turning plain ASCII texts into interactive and searchable multimedia content. Claudio From robert.thorpe at antenova.com Thu Jun 22 11:44:42 2006 From: robert.thorpe at antenova.com (Rob Thorpe) Date: 22 Jun 2006 08:44:42 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150908952.804184.218990@r2g2000cwb.googlegroups.com> Message-ID: <1150991074.705803.211570@m73g2000cwd.googlegroups.com> David Hopwood wrote: > Rob Thorpe wrote: > > Vesa Karvonen wrote: > > > >>In comp.lang.functional Anton van Straaten wrote: > >> > >>>Let me add another complex subtlety, then: the above description misses > >>>an important point, which is that *automated* type checking is not the > >>>whole story. I.e. that compile time/runtime distinction is a kind of > >>>red herring. > >> > >>I agree. I think that instead of "statically typed" we should say > >>"typed" and instead of "(dynamically|latently) typed" we should say > >>"untyped". > [...] > >>>It's certainly close enough to say that the *language* is untyped. > >> > >>Indeed. Either a language has a type system and is typed or has no > >>type system and is untyped. I see very little room for confusion > >>here. In my experience, the people who confuse these things are > >>people from the dynamic/latent camp who wish to see types everywhere > >>because they confuse typing with safety or having well-defined > >>semantics. > > > > No. It's because the things that we call latent types we use for the > > same purpose that programmers of static typed languages use static > > types for. > > > > Statically typed programmers ensure that the value of some expression > > is of some type by having the compiler check it. Programmers of > > latently typed languages check, if they think it's important, by asking > > what the type of the result is. > > > > The objection here is that advocates of statically typed language seem > > to be claiming the "type" as their own word, and asking that others use > > their definitions of typing, which are really specific to their > > subjects of interest. > > As far as I can tell, the people who advocate using "typed" and "untyped" > in this way are people who just want to be able to discuss all languages in > a unified terminological framework, and many of them are specifically not > advocates of statically typed languages. Its easy to create a reasonable framework. My earlier posts show simple ways of looking at it that could be further refined, I'm sure there are others who have already done this. The real objection to this was that latently/dynamically typed languages have a place in it. But some of the advocates of statically typed languages wish to lump these languages together with assembly language a "untyped" in an attempt to label them as unsafe. From sunwho at msn.com Sun Jun 11 14:19:36 2006 From: sunwho at msn.com (fl1p-fl0p) Date: 11 Jun 2006 11:19:36 -0700 Subject: math.pow(x,y) Message-ID: <1150049976.916474.186580@j55g2000cwa.googlegroups.com> import math math.pow(34564323, 456356) will give math range error. how can i force python to process huge integers without math range error? Any modules i can use possibly? From baiju.m.mail at gmail.com Wed Jun 7 09:38:16 2006 From: baiju.m.mail at gmail.com (baiju) Date: 7 Jun 2006 06:38:16 -0700 Subject: Python language problem References: <1149678146.681370.5130@c74g2000cwc.googlegroups.com> Message-ID: <1149687496.124937.18310@g10g2000cwb.googlegroups.com> May be you are looking for weakref module: http://www.python.org/doc/current/lib/module-weakref.html -- Baiju M From aleax at mac.com Fri Jun 9 21:56:16 2006 From: aleax at mac.com (Alex Martelli) Date: Fri, 9 Jun 2006 18:56:16 -0700 Subject: __getattr__ question References: <4489AE08.2080407@designaproduct.biz> <128k7qtra9ku72f@corp.supernews.com> Message-ID: <1hgohv2.rk4cz8178h81gN%aleax@mac.com> Andrew Robert wrote: > If I remember correctly, this behavior depends on how the class is > created (classic mode versus modern). > > Modern > > class foo(object): > pass > > Classic ( pre python 2.2 I believe ) > > class foo(): No parentheses allowed here (they do become optional in 2.5). > pass > > The modern method of specifying object in the class definition gets all > of the class attributes cleanly. > > The classic method does not have this so the behavior is simulated. No, you can specify normal attributes in classic as well as new-style classes. You may rather be thinking of *property*, which doesn't completely work for classic classes. Alex From prophet621 at cox.net Fri Jun 2 20:09:30 2006 From: prophet621 at cox.net (Rob Johnson) Date: Fri, 2 Jun 2006 20:09:30 -0400 Subject: beginner code problem References: <2006060218415316807-victimorcrime@yahoocom> <4480C8E8.50800@lexicon.net> Message-ID: <2006060220093075249-prophet621@coxnet> On 2006-06-02 19:25:28 -0400, John Machin said: > Thanks for the reply John. I seem to be getting all the same problems > with your code that I had with mine so it may be an issue with Python > on this computer though I haven't had one prior to now. I'm running it > on OSX Tiger so I'll give it a shot on my Windows box. With pythons > portability I didn't think it would be an issue so didn't mention it in > the post. The different problems I was having was a result of moving some of the code around thinking I had messed up and trying to fix it. The code I posted was just running but never stopping to give the the output. Thanks for explaining about getting a new value for flip, I wasn't positive about that and you really helped clear up any confusion I was having. Rob > > This can't happen with the code that you posted. It *could* happen if > the statement count += 1 was not being executed once each time around > the while loop -- like if it was *not* indented. > > # Bad code #1 > import random > flip = random.randrange(2) > heads = tails = count = 0 > while count < 100: > if flip == 0: > heads += 1 > else: > tails += 1 > count += 1 > print "The coin landed on heads", heads, 'times ' \ > "and tails", tails, 'times' > >> A few times I would get it to print 'heads 0 (or 1) times and tails 1 >> (or 0) times' 100 times. > > Again, can't happen with the code you have posted. If it is printing > 100 times, that would be because you have indented the print statement > so that it is being executed once each trip around the loop. > > # Bad code #2 > import random > flip = random.randrange(2) > heads = tails = count = 0 > while count < 100: > if flip == 0: > heads += 1 > else: > tails += 1 > count += 1 > print "The coin landed on heads", heads, 'times ' \ > "and tails", tails, 'times' > >> >> Here's the code I wrote: >> >> import random >> >> flip = random.randrange(2) >> heads = 0 >> tails = 0 >> count = 0 >> >> while count < 100: > > To help you see what is happening, insert a print statement here; e.g.: > print flip, count, heads, tails >> >> if flip == 0: >> heads += 1 >> else: >> tails += 1 >> >> count += 1 >> >> print "The coin landed on heads", heads, 'times ' \ >> "and tails", tails, 'times' >> > > The code that you posted sets flip only once i.e. only 1 toss, not 100. > If it is 0, you get 100 heads and 0 tails. Otherwise you get 0 heads > and 100 tails. You need to get a new value for flip each trip. > > # Not quite so bad code > import random > heads = tails = count = 0 > while count < 100: > flip = random.randrange(2) > # print flip, count, heads, tails # un-comment as/when required :-) > if flip == 0: > heads += 1 > else: > tails += 1 > count += 1 > print "The coin landed on heads", heads, 'times ' \ > "and tails", tails, 'times' > > HTH, > John From jo at durchholz.org Sun Jun 25 09:01:40 2006 From: jo at durchholz.org (Joachim Durchholz) Date: Sun, 25 Jun 2006 15:01:40 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150904134.520639.71070@b68g2000cwa.googlegroups.com> <1151030140.202720.245140@y41g2000cwy.googlegroups.com> Message-ID: Anton van Straaten schrieb: >> It seems we have languages: >> with or without static analysis >> with or without runtime type information (RTTI or "tags") >> with or without (runtime) safety >> with or without explicit type annotations >> with or without type inference >> >> Wow. And I don't think that's a complete list, either. > > Yup. What else? (Genuinely curious.) Regards, Jo From scott.daniels at acm.org Thu Jun 15 16:10:21 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Thu, 15 Jun 2006 13:10:21 -0700 Subject: Which compiler will Python 2.5 / Windows (Intel) be built with? In-Reply-To: <1150391891.130185.4640@f6g2000cwb.googlegroups.com> References: <1150367139.495114.148550@g10g2000cwb.googlegroups.com> <44917535$1@nntp0.pdx.net> <1150391891.130185.4640@f6g2000cwb.googlegroups.com> Message-ID: <4491b9e1$1@nntp0.pdx.net> meyer at mesw.de wrote: > ... So I'd like to ask you: > why was the decision taken a while ago (and is not subject to > reconsideration) and what are the reasons for using VS2003? I mean > there must be a real good reason why you're doing this, as I only see > disadvantages in it. The disruption in Python 2.4 in switching from one compiler (VC6) to another VS2003 was not insubstantial. By sticking with VS2003, sometime users can at least use the same tool for Python 2.4 and Python 2.5. It does seem inevitable we will have to switch for 2.6. We are very far along in the process of releasing Python 2.5 (beta1 is due out soon), and rebuilding and testing with a new translation system is too big a change at this point. Note there was strong resistance to leaving VC6 for Python 2.4. That resistance was overcome only by the fact that it was no longer possible to purchase suitable versions of VC6. --Scott David Daniels scott.daniels at acm.org From johnjsal at NOSPAMgmail.com Thu Jun 15 16:53:01 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 15 Jun 2006 20:53:01 GMT Subject: GUI in Python using wxGlade In-Reply-To: <1150403353.755218.292100@c74g2000cwc.googlegroups.com> References: <1150380251.279150.73620@u72g2000cwu.googlegroups.com> <1150386216.365531.157690@g10g2000cwb.googlegroups.com> <1150403353.755218.292100@c74g2000cwc.googlegroups.com> Message-ID: diffuser78 at gmail.com wrote: > I am a newbie. I was looking for some code where I could a list of > different items from a file and display it in a list box. Then give a > user the capability to select some. > > Basically, reading and writing to a file and displaying them in > different widgets...thats something I am looking for. If anybody can > point me to some good example tutorials...I will be greatly helped. > > Thanks, > > Every help is appreciated > Have you tried looking at the code in the wxPython demo? In the ListBox control demo, it populates a ListBox with items from a list, but you could easily translate that into reading from a file, I think. Here's the full code in case you don't have the demo: > > import wx > > #--------------------------------------------------------------------------- > > # This listbox subclass lets you type the starting letters of what you want to > # select, and scrolls the list to the match if it is found. > class FindPrefixListBox(wx.ListBox): > def __init__(self, parent, id, pos=wx.DefaultPosition, size=wx.DefaultSize, > choices=[], style=0, validator=wx.DefaultValidator): > wx.ListBox.__init__(self, parent, id, pos, size, choices, style, validator) > self.typedText = '' > self.log = parent.log > self.Bind(wx.EVT_KEY_DOWN, self.OnKey) > > > def FindPrefix(self, prefix): > self.log.WriteText('Looking for prefix: %s\n' % prefix) > > if prefix: > prefix = prefix.lower() > length = len(prefix) > > # Changed in 2.5 because ListBox.Number() is no longer supported. > # ListBox.GetCount() is now the appropriate way to go. > for x in range(self.GetCount()): > text = self.GetString(x) > text = text.lower() > > if text[:length] == prefix: > self.log.WriteText('Prefix %s is found.\n' % prefix) > return x > > self.log.WriteText('Prefix %s is not found.\n' % prefix) > return -1 > > > def OnKey(self, evt): > key = evt.GetKeyCode() > > if key >= 32 and key <= 127: > self.typedText = self.typedText + chr(key) > item = self.FindPrefix(self.typedText) > > if item != -1: > self.SetSelection(item) > > elif key == wx.WXK_BACK: # backspace removes one character and backs up > self.typedText = self.typedText[:-1] > > if not self.typedText: > self.SetSelection(0) > else: > item = self.FindPrefix(self.typedText) > > if item != -1: > self.SetSelection(item) > else: > self.typedText = '' > evt.Skip() > > def OnKeyDown(self, evt): > pass > > > #--------------------------------------------------------------------------- > > class TestListBox(wx.Panel): > def __init__(self, parent, log): > self.log = log > wx.Panel.__init__(self, parent, -1) > > sampleList = ['zero', 'one', 'two', 'three', 'four', 'five', > 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', > 'twelve', 'thirteen', 'fourteen'] > > wx.StaticText(self, -1, "This example uses the wx.ListBox control.", (45, 10)) > wx.StaticText(self, -1, "Select one:", (15, 50)) > self.lb1 = wx.ListBox(self, 60, (100, 50), (90, 120), sampleList, wx.LB_SINGLE) > self.Bind(wx.EVT_LISTBOX, self.EvtListBox, self.lb1) > self.Bind(wx.EVT_LISTBOX_DCLICK, self.EvtListBoxDClick, self.lb1) > self.lb1.Bind(wx.EVT_RIGHT_UP, self.EvtRightButton) > self.lb1.SetSelection(3) > self.lb1.Append("with data", "This one has data"); > self.lb1.SetClientData(2, "This one has data"); > > > wx.StaticText(self, -1, "Select many:", (220, 50)) > self.lb2 = wx.ListBox(self, 70, (320, 50), (90, 120), sampleList, wx.LB_EXTENDED) > self.Bind(wx.EVT_LISTBOX, self.EvtMultiListBox, self.lb2) > self.lb2.Bind(wx.EVT_RIGHT_UP, self.EvtRightButton) > self.lb2.SetSelection(0) > > sampleList = sampleList + ['test a', 'test aa', 'test aab', > 'test ab', 'test abc', 'test abcc', > 'test abcd' ] > sampleList.sort() > wx.StaticText(self, -1, "Find Prefix:", (15, 250)) > fp = FindPrefixListBox(self, -1, (100, 250), (90, 120), sampleList, wx.LB_SINGLE) > fp.SetSelection(0) > > > def EvtListBox(self, event): > self.log.WriteText('EvtListBox: %s, %s, %s, %s\n' % > (event.GetString(), > event.IsSelection(), > event.GetSelection(), > event.GetClientData())) > > lb = event.GetEventObject() > data = lb.GetClientData(lb.GetSelection()) > > if data is not None: > self.log.WriteText('\tdata: %s\n' % data) > > > def EvtListBoxDClick(self, event): > self.log.WriteText('EvtListBoxDClick: %s\n' % self.lb1.GetSelection()) > self.lb1.Delete(self.lb1.GetSelection()) > > def EvtMultiListBox(self, event): > self.log.WriteText('EvtMultiListBox: %s\n' % str(self.lb2.GetSelections())) > > def EvtRightButton(self, event): > self.log.WriteText('EvtRightButton: %s\n' % event.GetPosition()) > > if event.GetEventObject().GetId() == 70: > selections = list(self.lb2.GetSelections()) > selections.reverse() > > for index in selections: > self.lb2.Delete(index) > > > #--------------------------------------------------------------------------- > > def runTest(frame, nb, log): > win = TestListBox(nb, log) > return win > > #--------------------------------------------------------------------------- > > > > > overview = """ > A listbox is used to select one or more of a list of > strings. The strings are displayed in a scrolling box, with the > selected string(s) marked in reverse video. A listbox can be single > selection (if an item is selected, the previous selection is removed) > or multiple selection (clicking an item toggles the item on or off > independently of other selections). > > """ > > > if __name__ == '__main__': > import sys,os > import run > run.main(['', os.path.basename(sys.argv[0])] + sys.argv[1:]) > From iainking at gmail.com Tue Jun 13 09:48:23 2006 From: iainking at gmail.com (Iain King) Date: 13 Jun 2006 06:48:23 -0700 Subject: .py and running in Windows: In-Reply-To: References: Message-ID: <1150206503.313636.50130@c74g2000cwc.googlegroups.com> Andrew Gwozdziewycz wrote: > You'll have better results posting this to it's own thread. > He certainly should have, but since I've read it here anyway: > On Jun 13, 2006, at 9:29 AM, Michael Yanowitz wrote: > > > Hello: > > > > Presently in my Windows 2000 system, when I double-click on a > > .py file (open it) it automatically runs it in Python. I would > > like to change that behavour. That is fine for .pyc file, but > > for .py files, I would either like to have it run in Python but > > return to the Python shell prompt when finished rather than > > exit the shell. How do I do that? > > Or would it cause a problem (so that Python no longer works) if > > I change the default .py extension to open in an editor rather > > than execute it if I open it? > > In an explorer window, go to Tools->Folder Options Go to the File Types tab, find the PY extension, then click on Advanced* Select the 'open' action, and click Edit... change the 'Application used to perform action', inserting a '-i' between the exe and the first parameter. For example, I changed mine to: "C:\Python\python.exe" -i "%1" %* The exact line will depend on where your python.exe is. OK all the dialogs you've opened, then double click a .py file to test it. *I'm using WinXP, so the exact name of some of the buttons may be different for you. Iain From python at hope.cz Mon Jun 5 13:41:09 2006 From: python at hope.cz (Lad) Date: 5 Jun 2006 10:41:09 -0700 Subject: How to add few pictures into one In-Reply-To: References: <1149511692.796038.155930@c74g2000cwc.googlegroups.com> <1149517433.880564.128350@h76g2000cwa.googlegroups.com> Message-ID: <1149529269.228019.120480@u72g2000cwu.googlegroups.com> Steve Holden wrote: > Lad wrote: > > K.S.Sreeram wrote: > > > >>Lad wrote: > >> > >>>Hello , > >>>is it possible to add( with PYTHON language) several image files into > >>>one? > >> > >>Google for 'Python Imaging Library'... > >> > >>Regards > >>Sreeram > >> > >> > >> > > > > Thank you for your reply. > > I was thinking about this: > > to open each image file in binary mode , read it and write into the > > result image file? > > Is that possible? > > Regards, > > L > > > Of course, but what you haven't said yet is how you want the resulting > image file to behave. Do you want it to contain tiled copies of the > original images, or be an animation with each frame being one of the > original images, or something else I haven't thought of. > > We aren't mind readers here. > > though-some-regulars-get-close-ly y'rs - steve > -- Steve Thank you for your reply All that I want is this: I download ( via Python) some pictures from internet and I want to add all these pictures into one =one file/ So far, I managed to download pictures but I do not know how to add i them nto one file. How can I do that? Thank you for reply and help L. From k.retheesh at gmail.com Fri Jun 9 15:27:26 2006 From: k.retheesh at gmail.com (k.retheesh at gmail.com) Date: 9 Jun 2006 12:27:26 -0700 Subject: TypeError: unsubscriptable object In-Reply-To: References: <1149874726.470436.279200@i40g2000cwc.googlegroups.com> <1149878331.500752.8170@j55g2000cwa.googlegroups.com> Message-ID: <1149881246.482799.323370@i39g2000cwa.googlegroups.com> I did the same, The function type is < NoneType> and the description type is so how can i print a part of this 2 output. These values are returned by database. Thanks Retheesh Laszlo Nagy wrote: > k.retheesh at gmail.com ?rta: > > So wat should I do ?? > > > You should do this: > > print type(Function),type(Description) > raise SystemExit > > Instead of this: > > print template % (ID, IID, Function[:10], Description[:10],ErrorNumber, StatusCD) > > Then probably you will see: > > > > instead of > > > > > or something similar. (Of course in your case, it can be 'float instead of list' or 'dictionary instead of tuple' etc.) > > Then you should debug your program and find out why the 'Function' and 'Description' objects are not string but int. > > > Laszlo From cdsmith at twu.net Mon Jun 19 15:17:15 2006 From: cdsmith at twu.net (Chris Smith) Date: Mon, 19 Jun 2006 13:17:15 -0600 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <4fo91pF1jr7gpU1@individual.net> Message-ID: Pascal Costanza wrote: > How does your definition exclude the trivial type system in which the > only typing judgment states that every expression is acceptable? It is not necessary to exclude that trivial type system. Since it is useless, no one will implement it. However, if pressed, I suppose one would have to admit that that definition includes a type system that is just useless. I do, though, prefer Pierce's definition: A type system is a tractable syntactic method for proving the absence of certain program behaviors by classifying phrases according to the kinds of values they compute. (Benjamin Pierce, Types and Programming Languages, MIT Press, pg. 1) Key words include: - tractable: it's not sufficient to just evaluate the program - syntactic: types are tied to the kinds of expressions in the language - certain program behaviors: while perhaps confusing out of context, there is nowhere in the book a specification of which program behaviors may be prevented by type systems and which may not. In context, the word "certain" there is meant to make it clear that type systems should be able to specifically identify which behaviors they prevent, and not that there is some universal set. -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation From jim at zope.com Fri Jun 16 12:36:08 2006 From: jim at zope.com (Jim Fulton) Date: Fri, 16 Jun 2006 12:36:08 -0400 Subject: PythonPerl 0.9 In-Reply-To: References: Message-ID: Have you looked at PyPerl? http://wiki.python.org/moin/PyPerl I think it was further along. It might be good to build on. Jim On Jun 16, 2006, at 11:37 AM, Bruno Obsomer wrote: > You love Python, but think Perl can be useful anyway. You can now > mix the > two in a single program with the new Python module: > PythonPerl (version 0.9, GPL license) > > It is as simple to use as: >>>> import perl >>>> perl.addVariable('a', ['foo', 'bar']) >>>> perl.execute('$b = $a[0]') >>>> perl.getVariable('b') > foo > > Questions and comments at bobzomer AT gmail.com. > >

A Second CGI script

>
>

Hello, CGI World!

> """ > print text > >
> > > using this http server from > http://effbot.org/librarybook/cgihttpserver.htm > > > > import CGIHTTPServer > import BaseHTTPServer > > class Handler(CGIHTTPServer.CGIHTTPRequestHandler): > cgi_directories = ["/cgi"] > > PORT = 8000 > > httpd = BaseHTTPServer.HTTPServer(("", PORT), Handler) > print "serving at port", PORT > httpd.serve_forever() > > > > i get the error number 403, when i try to access the cgi script which > is located in a subdirectory called cgi where this file is (http > server). I have a feeling that i need to change the Handler class or > something, implement , but i couldnt find any examples other then this > from eff-bot. > > It could also be this line of code, that a google search turned up, its > the way of running cgi scripts on windows > > #!c:/Python/python.exe -u > > > Cheers Your cgi and server scripts look fine to me. Some diagnostic questions: What is the filename of your cgi script? (It must end in ".py" or ".pyw" for CGIHTTPRequestHandler to recognize it as a python script. See the is_python() method in the handler class. Also, in this case the "#!c:/Python/python.exe -u" line isn't needed, but it doesn't hurt. CGIHTTPRequestHandler should find the python interpreter for you without it.) What was the exact URL that you're using to try to reach your script? (It should look something like: "http://localhost:8000/cgi/myscript.py") What was the error message that accompanied the 403 error? Did you start the server script from the directory it's in? What was the log output from your server script when you tried to access the cgi script? Peace, ~Simon From rbann11 at hotmail.com Fri Jun 9 17:43:59 2006 From: rbann11 at hotmail.com (rbann11 at hotmail.com) Date: 9 Jun 2006 14:43:59 -0700 Subject: wxpython wxgrid question In-Reply-To: <44872b73$0$7769$7a628cd7@news.club-internet.fr> References: <1149366330.999234.299880@u72g2000cwu.googlegroups.com> <1149393484.553463.286220@i39g2000cwa.googlegroups.com> <44872b73$0$7769$7a628cd7@news.club-internet.fr> Message-ID: <1149889439.527285.69620@c74g2000cwc.googlegroups.com> jean-michel bain-cornu wrote: > rbann11 at hotmail.com a ?crit : > > Tim Roberts wrote: > >> rbann11 at hotmail.com wrote: > >>> I am looking for example code that consists of just a frame and a > >>> grid(10x2). The grid must fill the its parent even if the frame is > >>> resized. > >> Have you gone through the wxPython demo application? It contains examples > >> of every standard control and almost every behavior you might want. > >> -- > >> - Tim Roberts, timr at probo.com > >> Providenza & Boekelheide, Inc. > > > > Yes, and i have even checked out "wxpython in action". All of the > > examples tend to leave white space on the right of the frame. I tried > > basic a example with sizers and it didnt work. That why I was > > wondering if someone had got it to work. > > > > > > Roger > > > Hi Roger, > A key point is that the Grid manages itself its available space > according to the size it can have. > If you just tried to create a simple grid within a simple frame, you > probably got a grid filling all the frame space, and it's what you want. > Why that ? > If you do it (for instance with the script below), and you try to > manually reduce/increase the size of the window, you should see > scrollbars at the edge of the window ; these scrollbars come from the > grid, because they take in account the labels row and col (wxGrid comes > from wxScrolledWindow). You can see that no more space is available > beyond the scrollbar, so the grid takes the whole space. > And why the white space on the right ? This space is not on the right of > the grid, but on the right of the last col. We could think it's like > that because it's not possible to compute an appropriate col size for > the grid cols, but it's not displayed exactly the same in linux and in > windows. In one case it's over the last col (not enough space) and in > the other case it's beyond (too much space). I think that as the program > must work on all the environments, the interface must stay enough > global, and sometimes the display is not perfectly done. > The advantage is that if we let wx decide, we won't have to think how to > set the widgets. > Regards, > jm > > #---------------------------------------------------------------------- > import wx,wx.grid > #---------------------------------------------------------------------- > class MainWindow(wx.Frame): > def __init__(self,parent,id,title): > wx.Frame.__init__(self,parent,wx.ID_ANY,title) > #-- > self.grid= wx.grid.Grid(id=wx.ID_ANY,parent=self) > self.grid.CreateGrid(numRows=10,numCols=2) > self.grid.Fit() > self.Fit() > #-- > self.Show(1) > #---------------------------------------------------------------------- > app = wx.PySimpleApp() > frame=MainWindow(None,-1,'Grid sizer') > app.MainLoop() > del app > #---------------------------------------------------------------------- Thanks Tim, I knew it was something like that, but I had to ask the question. I was hoping that there was a way around the problem. Roger From rossberg at ps.uni-sb.de Thu Jun 22 05:51:18 2006 From: rossberg at ps.uni-sb.de (Andreas Rossberg) Date: Thu, 22 Jun 2006 11:51:18 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: <4padnQn3SOWhkQfZnZ2dnUVZ_rqdnZ2d@speakeasy.net> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150904134.520639.71070@b68g2000cwa.googlegroups.com> <4padnQn3SOWhkQfZnZ2dnUVZ_rqdnZ2d@speakeasy.net> Message-ID: Rob Warnock wrote: > > Here's what the Scheme Standard has to say: > > http://www.schemers.org/Documents/Standards/R5RS/HTML/r5rs-Z-H-4.html > 1.1 Semantics > ... > Scheme has latent as opposed to manifest types. Types are assoc- > iated with values (also called objects) rather than with variables. > (Some authors refer to languages with latent types as weakly typed > or dynamically typed languages.) Other languages with latent types > are APL, Snobol, and other dialects of Lisp. Languages with manifest > types (sometimes referred to as strongly typed or statically typed > languages) include Algol 60, Pascal, and C. Maybe this is the original source of the myth that static typing is all about assigning types to variables... With all my respect to the Scheme people, I'm afraid this paragraph is pretty off, no matter where you stand. Besides the issue just mentioned it equates "manifest" with static types. I understand "manifest" to mean "explicit in code", which of course is nonsense - static typing does not require explicit types. Also, I never heard "weakly typed" used in the way they suggest - in my book, C is a weakly typed language (= typed, but grossly unsound). > To me, the word "latent" means that when handed a value of unknown type > at runtime, I can look at it or perform TYPE-OF on it or TYPECASE or > something and thereby discover its actual type at the moment[1], whereas > "manifest" means that types[2] are lexically apparent in the code. Mh, I'd say typecase is actually a form of reflection, which is yet a different issue. Moreover, there are statically typed languages with typecase (e.g. Modula-3, and several more modern ones) or related constructs (consider instanceof). - Andreas From grante at visi.com Wed Jun 14 19:35:12 2006 From: grante at visi.com (Grant Edwards) Date: Wed, 14 Jun 2006 23:35:12 -0000 Subject: Numerics, NaNs, IEEE 754 and C99 References: <12904mjhl493t49@corp.supernews.com> <4490315e$1@nntp0.pdx.net> <1150306401.423825.39490@g10g2000cwb.googlegroups.com> Message-ID: <129179g8663q7ce@corp.supernews.com> On 2006-06-14, S?bastien Boisg?rault wrote: > Jeez, 12 posts in this IEEE 754 thread, and still no message > from uncle timmy ? ;) > > Please, we need enlightenment here and *now* :) What we need is fewer people like me who do nothing but complain about it... -- Grant Edwards grante Yow! I am covered with at pure vegetable oil and I am visi.com writing a best seller! From noway at sorry.com Thu Jun 1 08:35:16 2006 From: noway at sorry.com (Giovanni Bajo) Date: Thu, 01 Jun 2006 12:35:16 GMT Subject: struct: type registration? References: <447e4b98$1@news.eftel.com> Message-ID: <8aBfg.20673$cX1.313575@twister2.libero.it> Giovanni Bajo wrote: > You need struct.unpack() to parse these datas, and you need custom > packer/unpacker to avoid post-processing the output of unpack() just > because it just knows of basic Python types. In binary structs, there > happen to be *types* which do not map 1:1 to Python types, nor they > are just basic C types (like the ones struct supports). Using custom > formatter is a way to better represent these types (instead of > mapping them to the "most similar" type, and then post-process it). > > In my example, "S" is a basic-type which is a "A 0-terminated 20-byte > string", and expressing it in the struct format with the single > letter "S" is more meaningful in my code than using "20s" and then > post-processing the resulting string each and every time this happens. Another compelling example is the SSH protocol: http://www.openssh.com/txt/draft-ietf-secsh-architecture-12.txt Go to section 4, "Data Type Representations Used in the SSH Protocols", and it describes the data types used by the SSH protocol. In a perfect world, I would write some custom packers/unpackers for those types which struct does not handle already (like the "mpint" format), so that I could use struct to parse and compose SSH messages. What I ended up doing was writing a new module sshstruct.py from scratch, which duplicates struct's work, just because I couldn't extend struct. Some examples: client.py: cookie, server_algorithms, guess, reserverd = sshstruct.unpack("16b10LBu", data[1:]) client.py: prompts = sshstruct.unpack("sssu" + "sB"*num_prompts, pkt[1:]) connection.py: pkt = sshstruct.pack("busB", SSH_MSG_CHANNEL_REQUEST, self.recipient_number, type, reply) + custom kex.py: self.P, self.G = sshstruct.unpack("mm",pkt[1:]) Notice for instance how "s" is a SSH string and unpacks directly to a Python string, and "m" is a SSH mpint (infinite precision integer) but unpacks directly into a Python long. Using struct.unpack() this would have been impossible and would have required much post-processing. Actually, another thing that struct should support to cover the SSH protocol (and many other binary protocols) is the ability to parse strings whose size is not known at import-time (variable-length data types). For instance, type "string" in the SSH protocol is a string prepended with its size as uint32. So it's actual size depends on each instance. For this reason, my sshstruct did not have the equivalent of struct.calcsize(). I guess that if there's a way to extend struct, it would comprehend variable-size data types (and calcsize() would return -1 or raise an exception). -- Giovanni Bajo From sekhon.hari at googlemail.com Tue Jun 20 04:07:21 2006 From: sekhon.hari at googlemail.com (Hari Sekhon) Date: Tue, 20 Jun 2006 09:07:21 +0100 Subject: difference between import from mod.func() and x=mod.func() Message-ID: <4497ACB9.4020905@gmail.com> What is the difference in terms of efficiency and speed between from os import path and import os path=os.path I would think that the import from would be better, just curious since I read somewhere on the web, some guy's code tutorial where he did the latter and said it was for efficiency/speed. Not sure if this is right. Seeing as python folks seem to value simplicity and cleanness, is there a preferred coding method? (again I would think the first to the the preferred) Hari From nicholas.farrell at gmail.com Mon Jun 12 10:18:05 2006 From: nicholas.farrell at gmail.com (nicholas.farrell at gmail.com) Date: 12 Jun 2006 07:18:05 -0700 Subject: logging magic Message-ID: <1150121885.792603.125780@f6g2000cwb.googlegroups.com> Hi everyone. I've just been trying to add a bit more granularity to my logging code, as the jump from INFO (level 20) to DEBUG (level 10) is a bit too big. I was thinking of borrowing a few levels from java: fine (18), finer (16) and finest(14). This is what I've tried: log = logging.getLogger(appName) logging.FINE = 18 logging.FINER = 16 logging.FINEST = 14 log.fine = lambda msg, self=log, level=logging.FINE: self.log(level, msg) log.finer = lambda msg, self=log, level=logging.FINER: self.log(level, msg) log.finest = lambda msg, self=log, level=logging.FINEST: self.log(level, msg) I could expand this to support kwargs, etc, but that's the least of my problems. The real issue is that by adding this extra method into the stack, the logging module incorrectly reports the module name/line number. I assume it's because logging.log(...) accesses the stack to find out where it was being invoked from. Does anyone know I can add such methods to my log object and still have it correctly report the context of the log message? Thanks to all in advance. From onurb at xiludom.gro Wed Jun 7 14:25:23 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 07 Jun 2006 20:25:23 +0200 Subject: creating and naming objects In-Reply-To: <1149700072.369465.230280@c74g2000cwc.googlegroups.com> References: <1149696358.065614.76150@h76g2000cwa.googlegroups.com> <1149700072.369465.230280@c74g2000cwc.googlegroups.com> Message-ID: <44871a16$0$20889$626a54ce@news.free.fr> Brian wrote: > Thank you all for your response. I think that I am getting it. Based > on those responses, would I be correct in thinking that this would be > the way to initialize my Student object and return the values? > > class Student: Do yourself a favour: use new-style classes class Student(object): > def __init__(self, name, id): > self.name = name > self.id = id ok until here. > def getName(self): > return self.name > > def getId(self): > return self.id These to getters are totally useless in Python. Python doesn't have access restrictors [1], so you can directly access the attributes. Python also has support for computed attributes (looks like an ordinary attribute but is accessed thru a getter/setter), so there's no problem wrt/ encapsulation. Just get rid of these two methods and you'll be fine. [1] it's on purpose - we prefer to use conventions like using _names_starting_with_a_leading_underscore to denote implementation stuff that should not be accessed by client code. > Additionally, correct me if I am wrong but I can recycle: > > foo = Student() This won't work - will raise a TypeError. You defined Student.__init__() to take 2 mandatory parameters name and id,so you must pass them at call time. FWIW, you would have noticed this just by trying it into your Python shell. The interactive Python shell is a very valuable tool. It makes exploring APIs and testing ideas a breeze, with immediate feedback. It is one of the things that makes Python so easy and usable (not that it's a Python invention - but it's a GoodThing(tm) Python have it). > And doing so will just create a new instance of Student (with whatever > attributes it is given) and the original foo is gone? Yes. Or more exactly, the identifier 'foo' will refer to the newly created Student object, and if there are no other references to the object previously pointed by 'foo', it will be disposed of... > Thanks for your help and patience. After reading my original post and > then this one, I could see that it may look suspiciously like a home > work assignment. Trust me it's not. It could have been homework, this is not a problem - as long as you effectively tried to do your homework by yourself, and only ask for help when stuck. FWIW, in this job, knowing when and how to ask for help is as important as knowing how to first try to solve the problem oneself !-) HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From bj_666 at gmx.net Thu Jun 15 14:02:02 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Thu, 15 Jun 2006 20:02:02 +0200 Subject: list of polynomial functions References: <1150390140.459461.169900@i40g2000cwc.googlegroups.com> Message-ID: In <1150390140.459461.169900 at i40g2000cwc.googlegroups.com>, Josiah Manson wrote: > def make_polys(n): > """Make a list of polynomial functions up to order n. > """ > p = lambda x: 1 > polys = [p] > > for i in range(n): > polys.append(lambda x: polys[i](x)*x) The `i` is the problem. It's not evaluated when the lambda *definition* is executed but when the lambda function is called. And then `i` is always == `n`. You have to explicitly bind it as default value in the lambda definition: polys.append(lambda x, i=i: polys[i](x)*x) Then it works. Ciao, Marc 'BlackJack' Rintsch From ilias at lazaridis.com Mon Jun 5 07:05:10 2006 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Mon, 05 Jun 2006 14:05:10 +0300 Subject: John Bokma harassment In-Reply-To: <1149083474.097849.262460@i40g2000cwc.googlegroups.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1149083474.097849.262460@i40g2000cwc.googlegroups.com> Message-ID: Xah Lee wrote: > Thanks to the great many people who has written to my ISP in support of [...] > As to dreamhost my webhosting company canceling my account, i will try > to reason with them, and see what is the final outcome. They have the > legal right to kick me because in the contract that allowed them to do > so with 30 days advanced noticed and without cause. However, it is my > interest and my right, if they actually do kick me in the end, i'll try > to contact Electronic Frontier Foundation and Better Business bureau > for whatever advice or action i can solicit. Meanwhile, if you do know > a web hosting company that can take some 80 G of bandwidth/month for > less than $25 a month, please let me know! (i do hope if someone here > runs a hosting business and can host my site. I will certainly return > the favor.) [...] > Xah Lee wrote: [...] >> I wrote some full detail here: >> http://xahlee.org/Periodic_dosage_dir/t2/harassment.html >> >> If you believe this lobbying to my webhosting provider is unjust, >> please write to my web hosting provider abuse at dreamhost.com >> >> Your help is appreciated. Thank you. HOST - dreamhost.com / Liberality (Hosting, Basic Requirement) http://groups.google.com/group/comp.lang.python/browse_frm/thread/25618913752c457a . -- http://lazaridis.com From david.huard at gmail.com Wed Jun 21 12:32:07 2006 From: david.huard at gmail.com (David Huard) Date: Wed, 21 Jun 2006 12:32:07 -0400 Subject: How to override the doc of an object instance. References: <200606211539.02663.maric@aristote.info> <200606211715.16926.maric@aristote.info> Message-ID: On Wed, 21 Jun 2006 17:15:16 +0200, Maric Michaud wrote: > > In [53]: class a(object) : > ....: x=property(lambda s: 0, doc='my doc string') > ....: > ....: > > In [54]: b=a() > > In [55]: help(b) I agree it works, but for a class with tens of attributes, this is not very practical. > Also you can do something like that (put it in some startup script) : > > > In [27]: __IPYTHON__.old_pinfo = __IPYTHON__.magic_pinfo > > In [28]: def new_pinfo(obj) : > ....: return __IPYTHON__.old_pinfo('modified_version_of_obj') > ....: > > In [29]: __IPYTHON__.magic_pinfo = new_pinfo > > But you can also send a bug report to Ipython maintainer :) I looked into the internals of IPython and I can't say I understood much... I think I'll follow your advice. Has this problem come up before ? It seems that with the new classes, this kind of wish will generalize, or is it a bad coding habit to embed objects inside classes ? Thanks David From max at alcyone.com Sun Jun 11 03:55:34 2006 From: max at alcyone.com (Erik Max Francis) Date: Sun, 11 Jun 2006 00:55:34 -0700 Subject: Xah Lee network abuse In-Reply-To: References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148495974.975395.12920@i40g2000cwc.googlegroups.com> <1149998343.493200.144990@h76g2000cwa.googlegroups.com> Message-ID: <5smdnb3j67LkURbZnZ2dnUVZ_qydnZ2d@speakeasy.net> Philippa Cowderoy wrote: > Hrmm, does that one differ in Scotland? I don't believe so. > Wrong pronoun, then. Well, your comment was challenged, and I offered a reasonable interpretation of what you might have meant (which indicated a more general point in any case, namely that libel law is not quite as simple as the original poster was making it out to be). If you don't wish to defend your position, that's fine, but pointing fingers is kind of weird at this stage. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis To perceive is to suffer. -- Aristotle From maric at aristote.info Sat Jun 24 08:42:02 2006 From: maric at aristote.info (Maric Michaud) Date: Sat, 24 Jun 2006 14:42:02 +0200 Subject: module docstring, documentation, anything? please note is the module type/object NOT some module In-Reply-To: <32822fe60606231941l156051e7m806c23b2b02d0be8@mail.gmail.com> References: <32822fe60606231917r495b166i47ee7f19a6c873fb@mail.gmail.com> <32822fe60606231941l156051e7m806c23b2b02d0be8@mail.gmail.com> Message-ID: <200606241442.04567.maric@aristote.info> Le Samedi 24 Juin 2006 04:41, Jorge Vargas a ?crit?: > On 6/23/06, Jorge Vargas wrote: > > Hi everyone I have wasted 2 hours trying to figure out how to get a > > reference to the module object. that is the one returned by > > > > __import__ or when you call a module for name like > > > > >>> import sys > > >>> sys > > > > In [16]: from types import ModuleType In [17]: print ModuleType.__doc__ module(name[, doc]) Create a module object. The name must be a string; the optional doc argument can have any type. In [18]: ModuleType is type(sys) Out[18]: True > > > > the reason I want this is that I want to introspec my module > > > > so I need some way to indentify what elements are inside the module, to > > execute something like: > > > > ""for all the classes defined in this module do " > Like for any other object, use the __dict__ attribute : In [19]: sys.__dict__.items()[:3] Out[19]: [('setrecursionlimit', ), ('getfilesystemencoding', ), ('stdout', ', mode 'w' at 0xa7ddc068>)] Also, you''ll need these : In [59]: from types import ClassType In [60]: import subprocess In [61]: subprocess.__dict__['Popen'] Out[61]: In [62]: isinstance(subprocess.__dict__['Popen'], type) Out[62]: True In [63]: isinstance(subprocess.__dict__['Popen'], ClassType) Out[63]: False In [64]: ClassType # old-style class Out[64]: putting all togetther : In [75]: def find_classes(mod) : ....: for k, v in mod.__dict__.iteritems() : ....: if isinstance(v, type) : print 'new style class : ', k ....: elif isinstance(v, ClassType) : print 'old style class : ', k ....: ....: In [76]: find_classes(subprocess) new style class : Popen In [77]: find_classes(sys) In [78]: find_classes(os) old style class : _Environ new style class : stat_result old style class : error new style class : statvfs_result > I found an ugly hack to the docs help(type(sys)) This is not ugly, people used to do "type('')" rather than "import types; types.StringType", in prior versions of python (2.1). -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From s99999999s2003 at yahoo.com Tue Jun 27 05:41:58 2006 From: s99999999s2003 at yahoo.com (s99999999s2003 at yahoo.com) Date: 27 Jun 2006 02:41:58 -0700 Subject: classes and interfaces Message-ID: <1151401318.703216.288850@x69g2000cwx.googlegroups.com> hi i come from a non OO environment. now i am learning about classes. can i ask, in JAva, there are things like interface. eg public interface someinterface { public somemethod (); .... ... } In python , how to implement interface like the above? is it just define a class?? class someinterface: def somemethod: blah.... thanks From robert.thorpe at antenova.com Wed Jun 21 12:04:35 2006 From: robert.thorpe at antenova.com (Rob Thorpe) Date: 21 Jun 2006 09:04:35 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <7zpshbsvjy.fsf@app-1.diku.dk><7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <1150809118.677124.142230@u72g2000cwu.googlegroups.com> <1150815461.210286.53120@r2g2000cwb.googlegroups.com> <1150822150.701434.296460@u72g2000cwu.googlegroups.com> <1150883442.498308.226730@b68g2000cwa.googlegroups.com> Message-ID: <1150905875.552388.44170@y41g2000cwy.googlegroups.com> David Hopwood wrote: > Rob Thorpe wrote: > > Matthias Blume wrote: > >>"Rob Thorpe" writes: > >> > >>>I think we're discussing this at cross-purposes. In a language like C > >>>or another statically typed language there is no information passed > >>>with values indicating their type. > >> > >>You seem to be confusing "does not have a type" with "no type > >>information is passed at runtime". > >> > >>>Have a look in a C compiler if you don't believe me. > >> > >>Believe me, I have. > > > > In a C compiler the compiler has no idea what the values are in the program. > > It knows only their type in that it knows the type of the variable they > > are contained within. > > Would you agree with that? > > No. In any language, it may be possible to statically infer that the > value of an expression will belong to a set of values smaller than that > allowed by the expression's type in that language's type system. For > example, all constants have a known value, but most constants have a > type which allows more than one value. > > (This is an essential point, not just nitpicking.) Yes, I agree. That does not apply in general though. In general the value of the variable could be, for example, read from a file, in which case the compiler may know it's type, but not any more. I was talking about the general case. From onurb at xiludom.gro Wed Jun 14 10:05:54 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 14 Jun 2006 16:05:54 +0200 Subject: Quacker In-Reply-To: <1150281416.125684.301290@p79g2000cwp.googlegroups.com> References: <1150281416.125684.301290@p79g2000cwp.googlegroups.com> Message-ID: <449017c2$0$1949$626a54ce@news.free.fr> Quacker wrote: > Very interesting! > indeed. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From michele.simionato at gmail.com Tue Jun 27 02:57:39 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 26 Jun 2006 23:57:39 -0700 Subject: TypeError: Cannot create a consistent method resolution order (MRO) for bases object In-Reply-To: <1151345197.691600.200060@y41g2000cwy.googlegroups.com> References: <1151345197.691600.200060@y41g2000cwy.googlegroups.com> Message-ID: <1151391459.155117.20900@i40g2000cwc.googlegroups.com> digitalorganics at gmail.com wrote: > What are the reason one would get this error: TypeError: Cannot create > a consistent method resolution order (MRO) for bases object ?? See http://www.python.org/download/releases/2.3/mro/ Michele Simionato From jo at durchholz.org Sun Jun 25 09:21:56 2006 From: jo at durchholz.org (Joachim Durchholz) Date: Sun, 25 Jun 2006 15:21:56 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150908952.804184.218990@r2g2000cwb.googlegroups.com> <1150991074.705803.211570@m73g2000cwd.googlegroups.com> Message-ID: Andreas Rossberg schrieb: > > Luca Cardelli has given the most convincing one in his seminal tutorial > "Type Systems", where he identifies "typed" and "safe" as two orthogonal > dimensions and gives the following matrix: > > | typed | untyped > -------+-------+---------- > safe | ML | Lisp > unsafe | C | Assembler > > Now, jargon "dynamically typed" is simply untyped safe, while "weakly > typed" is typed unsafe. Here's a matrix how most people that I know would fill in with terminology: | Statically | Not | | typed | statically | | | typed | ---------+--------------+-------------+ typesafe | "strongly | Dynamically | | typed" | typed | | (ML, Pascal) | (Lisp) | ---------+--------------+-------------+ not | (no common | "untyped" | typesafe | terminology) | | | (C) | (Assembly) | ---------+--------------+-------------+ (Terms in quotes are challenged on a regular basis, or rarely if ever applied.) With the above terminology, it becomes clear that the opposite if "(statically) typed" isn't "statically untyped", but "not statically typed". "Statically typed" and "dynamically typed" aren't even opposites, they just don't overlap. Another observation: type safeness is more of a spectrum than a clearcut distinction. Even ML and Pascal have ways to circumvent the type system, and even C is typesafe unless you use unsafe constructs. IOW from a type-theoretic point of view, there is no real difference between their typesafe and not typesafe languages in the "statically typed" column; the difference is in the amount of unsafe construct usage in practial programs. Regards, Jo From elbertlev at hotmail.com Mon Jun 12 17:17:17 2006 From: elbertlev at hotmail.com (elbertlev at hotmail.com) Date: 12 Jun 2006 14:17:17 -0700 Subject: PIL show moves focus Message-ID: <1150147037.584482.120180@y43g2000cwc.googlegroups.com> Hi! I have an application where images (jpeg) have to be annotated by an operator. I use PIL like: import Image im = Image.open(Path) im.show() raw_input(Path + ':') .... Python runs in a console window. Then show starts some application (in my case "Windows picture and FAX viewer") and the picture goes to this application window. Then operator enteres the annotation as prompted by raw_input. So far so good. I understand, that the approach is very minilalistic, but suffisient for what has to be done. Unfortunatelly after im.show focus moves to thw "Windows picture ..." and stays there until I move it back using the mouse. Question: is there any way of returning the input focus to the console window? From greg.kujawa at gmail.com Wed Jun 7 12:59:48 2006 From: greg.kujawa at gmail.com (gregarican) Date: 7 Jun 2006 09:59:48 -0700 Subject: 10GB XML Blows out Memory, Suggestions? References: <1149594519.098115.8980@u72g2000cwu.googlegroups.com> <4eleh3F1eguosU1@uni-berlin.de> <1149648187.891942.258300@i40g2000cwc.googlegroups.com> <1149694031.712812.304940@u72g2000cwu.googlegroups.com> Message-ID: <1149699588.742309.24180@j55g2000cwa.googlegroups.com> Point for Fredrik. If someone doesn't recognize the inherent performance differences between different XML parsers they haven't experienced the pain (and eventual victory) of trying to optimize their techniques for working with the albatross that XML can be :-) Fredrik Lundh wrote: > fuzzylollipop wrote: > > > dependes on the CODE and the SIZE of the file, in this case > > processing 10GB of file, unless that file is heavly encrypted or > > compressed will, the process will be IO bound PERIOD! > > so the fact that > > for token, node in pulldom.parse(file): > pass > > is 50-200% slower than > > for event, elem in ET.iterparse(file): > if elem.tag == "item": > elem.clear() > > when reading a gigabyte-sized XML file, is due to an unexpected slowdown > in the I/O subsystem after importing xml.dom? > > > I work with TeraBytes of files, and all our Python code is just as fast > > as equivelent C code for IO bound processes. > > so how large are the things that you're actually *processing* in your > Python code? megabyte blobs or 100-1000 byte records? or even smaller > things? > > From steve at holdenweb.com Mon Jun 12 19:39:55 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 13 Jun 2006 00:39:55 +0100 Subject: Writing PNG with pure Python In-Reply-To: <1150152913.315502.16840@u72g2000cwu.googlegroups.com> References: <1149853401.521169.112530@i39g2000cwa.googlegroups.com> <1149889778.182865.181600@f6g2000cwb.googlegroups.com> <1149910872.025017.60160@i40g2000cwc.googlegroups.com> <1150152913.315502.16840@u72g2000cwu.googlegroups.com> Message-ID: Paul Boddie wrote: > Johann C. Rocholl wrote: > >>The MIT license is enticingly short and simple, thank you for the tip. >> >>I have now decided to license my project (including the pure python PNG >>library) under the Apache License 2.0 which is less restrictive than >>the GPL in terms of sublicensing. > > > But it is also incompatible with the GPL: > > http://www.fsf.org/licensing/licenses/index_html#GPLIncompatibleLicenses > > It's obviously your decision about how you license your own code, but > I'd advise you to disregard the "Pythonic license" rhetoric, whatever > that means: Python's original licence was regarded as not being enough > of a licence by some lawyers (that's what some people refer to as the > original Python licence); subsequent licences aren't recommended for > application to any other works (like various licences of the Python > code over the years); despite advocacy for permissive licences by some > parties, there exist numerous successful GPL'd and LGPL'd Python > projects (meaning that projects licensed in such a way are not lesser > members of the community). Moreover, any licensing gymnastics > undertaken by the PSF did involve various extra somersaults to remain > GPL-compatible, meaning that even people who favour permissive licences > regard "licence interoperability" positively. > > If you're convinced that a permissive licence suits your code best, > please consider something whose side-effects you understand. If the > additional patent grant or licence termination clauses (which the FSF > don't regard as a bad thing, just something incompatible with the > current GPL/LGPL) are specifically what you want, then the Apache > Licence may be what you're after; otherwise, you should choose > something less baroque and better understood, perhaps from this list: > > http://www.fsf.org/licensing/licenses/index_html#GPLCompatibleLicenses > > Yes, one of the best places to find out about non-FSF licences is > actually the FSF themselves, undermining various myths some people like > to put forward. > Also remember that it's perfectly possible to release the same code under several different licenses. This can happen, for example, with contributions to Python. The PSF doesn't care how you license it to anyone else, only that you license it to the PSF under the Free Academic Licence or v2 of the Apache License. We then re-license it to Python users (under the Python license, naturally). If the contributor then wants to license the same code under the GPL to other people there's no problem with that. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From alanalan at newsgroup.nospam Thu Jun 1 23:44:10 2006 From: alanalan at newsgroup.nospam (A.M) Date: Thu, 1 Jun 2006 23:44:10 -0400 Subject: New to Python: Do we have the concept of Hash in Python? References: <1149206685.768210.71990@i39g2000cwa.googlegroups.com> <1149212030.851030.257180@c74g2000cwc.googlegroups.com> Message-ID: <_qOfg.1685$Su3.148290@news20.bellglobal.com> Well the work is done now. I arrived home at 10:30 PM. The application takes data from Oracle 10g stored procedures and renders data to both HTML and CSV formats. The HTML reports have summary and grouping sections and the HTML files are Excel friendly. The application is modular and consists of reusable modules. The application is called every night by scheduled task. The CSV and HTML files are being deployed to Apache for internal employee access. This isn't a complex and big system. Tomorrow, I'll add the email functionality to the application and re-use it's components for more reports. Now that I finished the 1st part of the application, I have to admit that choosing Python was an excellent decision. Python is an awesome programming language with comprehensive library and great community support. I am not that new to Python anymore.. I had a productive day. Thanks everybody for help. "gregarican" wrote in message news:1149212030.851030.257180 at c74g2000cwc.googlegroups.com... > Dear A.M., > > The day is complete. My TPS reports still aren't on my desk. Either > with or without cover sheets. Not a good time to try to teach yourself > a new language. Please gather your belongings and move down to basement > storage C. > > That'd be great, > Bill Lumberg > > John Machin wrote: >> A.M wrote: >> >> > The application is not mission critical system. It is just a simple >> > reporting tool. >> >> Famous last words. > From gdamjan at gmail.com Tue Jun 27 12:37:49 2006 From: gdamjan at gmail.com (Damjan) Date: Tue, 27 Jun 2006 18:37:49 +0200 Subject: Python database access References: <1151295558.067744.91470@b68g2000cwa.googlegroups.com> <1151331311.172035.178060@y41g2000cwy.googlegroups.com> <1151335288.099526.207890@m73g2000cwd.googlegroups.com> Message-ID: <44a15ede$0$15784$14726298@news.sunsite.dk> > The odbc module is part of the Python Standard Library. Since when? -- damjan From jarausch at skynet.be Wed Jun 28 14:06:34 2006 From: jarausch at skynet.be (Helmut Jarausch) Date: Wed, 28 Jun 2006 20:06:34 +0200 Subject: Python in a nutshell - new edition ? Message-ID: <44A2C52A.6040807@skynet.be> Hi, is there a new edition of "Python in a Nutshell" covering Python 2.5 coming soon? Many thanks, Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From russandheather at gmail.com Thu Jun 22 16:32:54 2006 From: russandheather at gmail.com (Russell Warren) Date: 22 Jun 2006 13:32:54 -0700 Subject: Is Queue.Queue.queue.clear() thread-safe? Message-ID: <1151008374.303940.251300@c74g2000cwc.googlegroups.com> I'm guessing no, since it skips down through any Lock semantics, but I'm wondering what the best way to clear a Queue is then. Esentially I want to do a "get all" and ignore what pops out, but I don't want to loop through a .get until empty because that could potentially end up racing another thread that is more-or-less blindly filling it asynchronously. Worst case I think I can just borrow the locking logic from Queue.get and clear the deque inside this logic, but would prefer to not have to write wrapper code that uses mechanisms inside the object that might change in the future. Also - I can of course come up with some surrounding architecture to avoid this concern altogether, but a thread-safe Queue clear would do the trick and be a nice and short path to solution. If QueueInstance.queue.clear() isn't thread safe... what would be the best way to do it? Also, if not, why is the queue deque not called _queue to warn us away from it? Any other comments appreciated! Russ From dadapapa at googlemail.com Mon Jun 12 09:20:45 2006 From: dadapapa at googlemail.com (Harold Fellermann) Date: 12 Jun 2006 06:20:45 -0700 Subject: Searching and manipulating lists of tuples In-Reply-To: <1150117632.693617.45310@c74g2000cwc.googlegroups.com> References: <1150117632.693617.45310@c74g2000cwc.googlegroups.com> Message-ID: <1150118445.128516.189840@f14g2000cwb.googlegroups.com> MTD wrote: > Hello, > > I'm wondering if there's a quick way of resolving this problem. > > In a program, I have a list of tuples of form (str,int), where int is a > count of how often str occurs > > e.g. L = [ ("X",1),("Y",2)] would mean "X" occurs once and "Y" occurs > twice > > If I am given a string, I want to search L to see if it occurs already. > If it does, I find the corresponding tuple and increment the integer > part. If not, I append the new element with int = 1. > > e.g. > > algorithm(L, "X") would produce output L = [("X",2),("Y",2)] > algorithm(L,"Z") would produce L = [("X",1),("Y",2),("Z",1)] > > I tried to create an algorithm of the following form: > >>> def algorith(list,str): > ... flag = True > ... for l in list: > ... if l[0] == str: > ... l[1] += 1 > ... flag = False > ... if flag: > ... list.append((str,1)) > ... > > > But: > > >>> algorith(L,"X") > > gives: > > Traceback (most recent call last): > File "", line 1, in ? > File "", line 5, in algorith > TypeError: object does not support item assignment Your approach does not work because the tuples in the list a imutable. The problem occurs in the line l[1] += 1. You could solve the problem by using lists of lists, rather than lists of tuples. However, if you only want to know the frequency of items in the list (i.e. want to build a histogram) and you are not interested in the original order of items in the list, a dictionary is suited better for this task, because you avoid the linear time behavior of: def histogram(liste) : result = {} for item in liste : result[item] = result.get(item,0) + 1 return result.items() From edreamleo at charter.net Fri Jun 2 12:14:52 2006 From: edreamleo at charter.net (Edward K. Ream) Date: Fri, 2 Jun 2006 11:14:52 -0500 Subject: Best Python Editor References: Message-ID: <7uZfg.4$5t3.2@fe07.lga> I like scite for small tasks, Leo for larger tasks and python scripting. Leo's script buttons are something probably no other tool has: http://webpages.charter.net/edreamleo/customizing.html#creating-script-buttons Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From micklee74 at hotmail.com Tue Jun 13 10:37:15 2006 From: micklee74 at hotmail.com (micklee74 at hotmail.com) Date: 13 Jun 2006 07:37:15 -0700 Subject: a string problem In-Reply-To: References: <1150206140.912224.113420@p79g2000cwp.googlegroups.com> <1150207549.429623.231830@f14g2000cwb.googlegroups.com> Message-ID: <1150209435.260097.294790@i40g2000cwc.googlegroups.com> John Salerno wrote: > micklee74 at hotmail.com wrote: > > > just curious , if RE has the \b and it works, can we look into the > > source of re and see how its done for \b ? > > I had a look in the sre module (which re seems to import), but I > couldn't find much. I'm not the best at analyzing source code, though. :) > > What is it you want to know about \b? It searches for the empty string > before and after a word (word being an alphanumeric character that can > include underscores). > > A little more specific info is in the docs: > > Matches the empty string, but only at the beginning or end of a word. A > word is defined as a sequence of alphanumeric or underscore characters, > so the end of a word is indicated by whitespace or a non-alphanumeric, > non-underscore character. Note that \b is defined as the boundary > between \w and \ W, so the precise set of characters deemed to be > alphanumeric depends on the values of the UNICODE and LOCALE flags. > Inside a character range, \b represents the backspace character, for > compatibility with Python's string literals. thanks..actually i had seen \b in the docs before, just that it slipped my mind when i was doing the coding. was even meddling with look aheads ..which is not the answer anyway. well, since re has the \b, was wondering why there is no implementation of it in strings. So the idea of looking at the source or re on how it's done came to my mine..i suppose we have to go down to viewing the C source then..:-) From python.list at tim.thechases.com Tue Jun 6 11:58:37 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 06 Jun 2006 10:58:37 -0500 Subject: what are you using python language for? In-Reply-To: <128b8cg1d0p7uce@corp.supernews.com> References: <128b8cg1d0p7uce@corp.supernews.com> Message-ID: <4485A62D.6070900@tim.thechases.com> > 4) Miscellaneous other stuff like grabbing all of the comic > strips I like every day and putting them on a local web > page so I can read them all in one place I wonder how many other folks have done this too. It was my first pet Python project, converting a Java rendition of the same app into Python. Shorter, clearer, faster, better... Mine uses my older Java config file (which, while tinkering with Java's XML libraries, ended up being XML), supports Referrer/Referer spoofing, searches pages for regexps so that I can find image URLs that have been munged with random numbers (like dilbert.com does). It then builds a local HTML file that points at all the locally-saved images. I wonder what other sorts of features folks have added in their comic-snatchers... I tried a multi-threaded version in Java, but had problems with it saturating my dialup connection, and returning some sort of errors (perhaps in violation of HTTP's suggestion that one only have, IIRC, 2 connections to a server at a given time). I might try it again with Python. I saw some function-call fly by recently that looked like it took a function reference and an array of parameter-arrays, and spawned a thread for each function. I foolishly deleted that message, but it shouldn't be too hard to scare up again. I think it involved importing something from the future. A nice little status-GUI would be a nice addition, but I'm too lazy to go that far, leaving it with just a TUI. Might be a good way to learn Python GUI programming... -tkc From rossberg at ps.uni-sb.de Tue Jun 20 05:29:58 2006 From: rossberg at ps.uni-sb.de (Andreas Rossberg) Date: Tue, 20 Jun 2006 11:29:58 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150749670.053433.242210@p79g2000cwp.googlegroups.com> <1150754918.338770.89870@i40g2000cwc.googlegroups.com> Message-ID: Chris F Clark wrote: > > A static > type system eliminates some set of tags on values by syntactic > analysis of annotations (types) written with or as part of the program > and detects some of the disallowed compuatations (staticly) at compile > time. Explicit annotations are not a necessary ingredient of a type system, nor is "eliminating tags" very relevant to its function. - Andreas From fredrik at pythonware.com Tue Jun 27 05:58:56 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 27 Jun 2006 11:58:56 +0200 Subject: Replace Whole Object Through Object Method References: <1151337453.804750.293180@b68g2000cwa.googlegroups.com><44a041a6$0$17612$636a55ce@news.free.fr><1151354259.082966.25820@p79g2000cwp.googlegroups.com><1151376052.727979.71470@c74g2000cwc.googlegroups.com> <44a0f4d9$0$9022$626a54ce@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > As a matter of fact, in Python, the class is an attribute of an object. except when it isn't. >> def add_role(self, role_class): >> self.roles.append(role_class(self)) > > And here you create a circular reference between object and roles... and ? Python has a garbage collector, you know... From yan at NsOeSiPnAeMr.com Thu Jun 1 19:08:43 2006 From: yan at NsOeSiPnAeMr.com (Captain Dondo) Date: Thu, 01 Jun 2006 16:08:43 -0700 Subject: Replace one element of a tuple (LONG) In-Reply-To: <1149202416.959127.71620@i39g2000cwa.googlegroups.com> References: <127ulhn6h7hvj22@corp.supernews.com> <1149198946.567904.260480@f6g2000cwb.googlegroups.com> <127upu8k63qnu10@corp.supernews.com> <1149202416.959127.71620@i39g2000cwa.googlegroups.com> Message-ID: <127usq9lrqavm3d@corp.supernews.com> Brian wrote: > Captain Dondo wrote: > >>What I'd like to do is build the correct selectlist in the first place, >>rather than build the wrong one and then rebuild a correct one. > > > This is sounding more like a SQL/DB problem and less like a Python one. > If you have a field that is being pulled from the database that you > would like to do a substitution on, I'm fairly sure MySQL includes a > CASE statement in their flavor of SQL. Instead of performing a SELECT > * in your script you could select the individual fields you want, and > instead of just pulling the problematic column as is, you could pull it > as something like "select case when sourcehost = x then y else > sourcehost end case, ...". Naturally if an entire column needs to be > replaced with a static value, you won't even need to use CASE. > AFAICT, that one column is always the same, the name of the host that the database resides on. As myth can use multiple backends , it sort of makes sense, but it seems redunandant to me. Even with mutliple backends, I would hope you have a single database.... I thought about just picking all the other fields via the SQL query, but this seemed simpler to me.... Anyway, here's the code I came up with: for listing in itemlist: (rectitle, recdate) = listing.split('|',1) c.execute("""SELECT * FROM recorded WHERE title=%s AND starttime=%s""",(rectitle,recdate)) for listitem in c.fetchall(): if 'tooth.seiner.lan' in listitem: selectlist.append(listitem[:7] + ('hermes.seiner.lan',) + listitem[9:]) else: selectlist.append(listitem) From gdr at integrable-solutions.net Sun Jun 25 18:24:38 2006 From: gdr at integrable-solutions.net (Gabriel Dos Reis) Date: 26 Jun 2006 00:24:38 +0200 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150908952.804184.218990@r2g2000cwb.googlegroups.com> <1150991074.705803.211570@m73g2000cwd.googlegroups.com> <1151244628.566060.40500@p79g2000cwp.googlegroups.com> <1151252226.104247.62960@b68g2000cwa.googlegroups.com> Message-ID: Joachim Durchholz writes: [...] | (Yes, I'm being silly. But the point is very serious. Even with less | silly examples, whether a language or subset is "safe" entirely | depends on what you define to be "safe", and these definitions tend to | vary vastly across language communities.) Yes, I know. I hoped we would escape sillyland for the sake of productive conversation. -- Gaby From anton at appsolutions.com Wed Jun 21 03:33:55 2006 From: anton at appsolutions.com (Anton van Straaten) Date: Wed, 21 Jun 2006 07:33:55 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: <1150765102.867144.12590@h76g2000cwa.googlegroups.com> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> Message-ID: Marshall wrote: > Joe Marshall wrote: > >>They *do* have a related meaning. Consider this code fragment: >>(car "a string") >>[...] >>Both `static typing' and `dynamic typing' (in the colloquial sense) are >>strategies to detect this sort of error. > > > The thing is though, that putting it that way makes it seems as > if the two approaches are doing the same exact thing, but > just at different times: runtime vs. compile time. But they're > not the same thing. Passing the static check at compile > time is universally quantifying the absence of the class > of error; passing the dynamic check at runtime is existentially > quantifying the absence of the error. A further difference is > the fact that in the dynamically typed language, the error is > found during the evaluation of the expression; in a statically > typed language, errors are found without attempting to evaluate > the expression. > > I find everything about the differences between static and > dynamic to be frustratingly complex and subtle. Let me add another complex subtlety, then: the above description misses an important point, which is that *automated* type checking is not the whole story. I.e. that compile time/runtime distinction is a kind of red herring. In fact, automated type checking is orthogonal to the question of the existence of types. It's perfectly possible to write fully typed programs in a (good) dynamically-checked language. In a statically-checked language, people tend to confuse automated static checking with the existence of types, because they're thinking in a strictly formal sense: they're restricting their world view to what they see "within" the language. Then they look at programs in a dynamically-checked language, and see checks happening at runtime, and they assume that this means that the program is "untyped". It's certainly close enough to say that the *language* is untyped. One could also say that a program, as seen by the language, is untyped. But a program as seen by the programmer has types: the programmer performs (static) type inference when reasoning about the program, and debugs those inferences when debugging the program, finally ending up with a program which has a perfectly good type scheme. It's may be messy compared to say an HM type scheme, and it's usually not proved to be perfect, but that again is an orthogonal issue. Mathematicians operated for thousands of years without automated checking of proofs, so you can't argue that because a dynamically-checked program hasn't had its type scheme proved correct, that it somehow doesn't have types. That would be a bit like arguing that we didn't have Math until automated theorem provers came along. These observations affect the battle over terminology in various ways. I'll enumerate a few. 1. "Untyped" is really quite a misleading term, unless you're talking about something like the untyped lambda calculus. That, I will agree, can reasonably be called untyped. 2. "Type-free" as suggested by Chris Smith is equally misleading. It's only correct in a relative sense, in a narrow formal domain which ignores the process of reasoning about types which is inevitably performed by human programmers, in any language. 3. A really natural term to refer to types which programmers reason about, even if they are not statically checked, is "latent types". It captures the situation very well intuitively, and it has plenty of precedent -- e.g. it's mentioned in the Scheme reports, R5RS and its predecessors, going back at least a decade or so (haven't dug to check when it first appeared). 4. Type theorists like to say that "universal" types can be used in a statically-typed language to subsume "dynamic types". Those theorists are right, the term "dynamic type", with its inextricable association with runtime checks, definitely gets in the way here. It might be enlightening to rephrase this: what's really happening is that universal types allow you to embed a latently-typed program in a statically-checked language. The latent types don't go anywhere, they're still latent in the program with universal types. The program's statically-checked type scheme doesn't capture the latent types. Describing it in these terms clarifies what's actually happening. 5. Dynamic checks are only part of the mechanism used to verify latent types. They shouldn't be focused on as being the primary equivalent to static checks. The closest equivalent to the static checks is a combination of human reasoning and testing, in which dynamic checks play an important but ultimately not a fundamental part. You could debug a program and get the type scheme correct without dynamic checks, it would just be more difficult. So, will y'all just switch from using "dynamically typed" to "latently typed", and stop talking about any real programs in real programming languages as being "untyped" or "type-free", unless you really are talking about situations in which human reasoning doesn't come into play? I think you'll find it'll help to reason more clearly about this whole issue. Thanks for your cooperation!! Anton From wblock at wonkity.com Sun Jun 4 14:05:14 2006 From: wblock at wonkity.com (Warren Block) Date: Sun, 04 Jun 2006 18:05:14 -0000 Subject: Installation Problem References: <44830900.155C7297@king-cart.com> <44831694.A022913A@king-cart.com> Message-ID: Marshall Dudley wrote: > Sorry, this is a FreeBSD system 4.8-RELEASE > > I found another set of documents that say to use the following to > install:: > > python setup.py install > > but after running it, I still have the same problem. [top-posting trimmed, please don't do that] Doesn't the port work for 4.8? It does work on FreeBSD 4.11, but there may have been changes to the ports system since 4.8. (You should consider updating to 4.11.) There are several patch files in the FreeBSD port, including one to setup.py. The easiest way is to cvsup your ports tree and then cd /usr/ports/lang/python make make install make clean -- Warren Block * Rapid City, South Dakota * USA From rvtol+news at isolution.nl Fri Jun 23 15:30:18 2006 From: rvtol+news at isolution.nl (Dr.Ruud) Date: Fri, 23 Jun 2006 21:30:18 +0200 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> Message-ID: Chris Smith schreef: > Static types are not fuzzy Static types can be fuzzy as well. For example: a language can define that extra accuracy and bits may be used for the implementation of calculations: d = a * b / c Often some minimum is guaranteed. > I see it as quite reasonable when there's an effort by several > participants in this thread to either imply or say outright that > static type systems and dynamic type systems are variations of > something generally called a "type system", and given that static > type systems are quite formally defined, that we'd want to see a > formal definition for a dynamic type system before accepting the > proposition that they are of a kind with each other. The 'dynamic type' is just another type. -- Affijn, Ruud "Gewoon is een tijger." From onurb at xiludom.gro Fri Jun 2 13:11:24 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 02 Jun 2006 19:11:24 +0200 Subject: Package In-Reply-To: References: Message-ID: <448071b0$0$11225$636a55ce@news.free.fr> Matthieu Pichaud wrote: > I have a problem organizing my programs in packages and subpackages. > > I use python.2.3.3 > I built a test structure to try to understand how it worked: > > /test > /test/__init__.py (containing: __all__=['test1']) > /test/test1/ > /test/test1/__init__.py (containing: __all__=['test2']) > /test/test1/test2/ > /test/test1/test2/__init__.py (containing: __all__=['test3']) > /test/test1/test2/test3.py (containing: print 'test3') > > Then I run: >>>> from test import * >>>> test1 > >>>> test2 > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'test2' is not defined > So it seems that I am very limited in the number of subpackages I can > create. Not at all. > Is it normal? Yes : when you have nested namespaces, it won't magically become a flat namespace. There's a mostly clear documention on this in the official Python tutorial. > Am I silly organizing my programs like that? Dunno - it depends on the program. But still: python -c "import this" | grep nested HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From jhefferon at smcvt.edu Fri Jun 16 16:50:59 2006 From: jhefferon at smcvt.edu (Jim) Date: 16 Jun 2006 13:50:59 -0700 Subject: Cross-site scripting (XSS) defense In-Reply-To: <1150480621.563312.134500@c74g2000cwc.googlegroups.com> References: <1150480621.563312.134500@c74g2000cwc.googlegroups.com> Message-ID: <1150491059.000644.133240@u72g2000cwu.googlegroups.com> Have a look at http://feedparser.org/docs/html-sanitization.html . Jim From rune.strand at gmail.com Sun Jun 11 11:21:22 2006 From: rune.strand at gmail.com (Rune Strand) Date: 11 Jun 2006 08:21:22 -0700 Subject: import hook In-Reply-To: References: Message-ID: <1150039282.759696.321600@f6g2000cwb.googlegroups.com> Jeremy Sanders wrote: > Hi - Is it possible to override the import process so that if in my program > I do (...) > > Any ideas? Why not handle the foo.bar/version string separately and just append the resulting path to sys.path? From olsongt at verizon.net Wed Jun 28 15:01:47 2006 From: olsongt at verizon.net (olsongt at verizon.net) Date: 28 Jun 2006 12:01:47 -0700 Subject: Psyco tagging the same function multiple times In-Reply-To: References: Message-ID: <1151521307.573299.190830@y41g2000cwy.googlegroups.com> skip at pobox.com wrote: > I'm trying some stuff with Psyco and am confused about its apparent desire > to compile the same function (or method) multiple times). Here's an > abstract from a recent run: > > 12:45:15.99 tag function: __main__.Watcher.processUpdate % > 12:45:24.95 tag function: __main__.Watcher.processUpdate % > 12:45:55.12 tag function: __main__.Watcher.processUpdate % > 12:46:12.29 tag function: __main__.Watcher.processUpdate % > 12:46:28.09 tag function: __main__.Watcher.processUpdate % > 12:47:05.32 tag function: __main__.Watcher.processUpdate % > 12:47:48.62 tag function: __main__.Watcher.processUpdate % > 12:48:09.63 tag function: __main__.Watcher.processUpdate % > 12:48:43.20 tag function: __main__.Watcher.processUpdate % > 12:49:58.80 tag function: __main__.Watcher.processUpdate % > 12:50:32.20 tag function: __main__.Watcher.processUpdate % > 12:51:07.91 tag function: __main__.Watcher.processUpdate % > 12:52:17.14 tag function: __main__.Watcher.processUpdate % > 12:52:33.67 tag function: __main__.Watcher.processUpdate % > > What (if anything) does it mean that it tagged Watcher.processUpdate more > than once? > > Thanks, > > Skip I think that's what Armin means by a *specializing* compiler. I believe it will compile multiple versions based on the arguments going into a block of code. From g.brandl-nospam at gmx.net Fri Jun 30 15:31:17 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Fri, 30 Jun 2006 21:31:17 +0200 Subject: Way for see if dict has a key In-Reply-To: <44a542bc$0$25491$626a54ce@news.free.fr> References: <6V6pg.21624$_J1.271925@twister2.libero.it> <44a5041f$0$29637$636a55ce@news.free.fr> <4F7pg.21676$_J1.272665@twister2.libero.it> <1151667333.569664.152670@h44g2000cwa.googlegroups.com> <44a50e5c$0$11383$626a54ce@news.free.fr> <44a542bc$0$25491$626a54ce@news.free.fr> Message-ID: Bruno Desthuilliers wrote: >>> value = dict.get(key, None) >> >> >> value = dict.get(key) > > Yes - but : > 1/ not everybody knows that dict.get() takes a second optional param. > Note that, while it happens that the default return value of dict.get() > is the same as in the above example, but it may not have been the case. > > 2/ Since dict.get() implicitely returns None while getattr() defaults to > raising an AttributeError unless you provide a default, I prefer to be > very explicit when using dict.get(). You're right, and I would write that with explicit None too. Just wanted to continue the shortening ;) Georg From kent at kentsjohnson.com Thu Jun 1 14:36:45 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Thu, 01 Jun 2006 14:36:45 -0400 Subject: os.walk trouble In-Reply-To: <1149173920.903876.68370@c74g2000cwc.googlegroups.com> References: <1149173920.903876.68370@c74g2000cwc.googlegroups.com> Message-ID: <447f32c4_2@newspeer2.tds.net> The Prophet wrote: > As my first Python script, I am trying to make a program that recurses > a directory searching for files whose names match a pattern. If your patterns are simple (supported by fnmatch), the path module makes this very easy: import path for f in path.path(dirname).walkfiles('*.foo'): # process a .foo file here http://www.jorendorff.com/articles/python/path/index.html Kent From johnjsal at NOSPAMgmail.com Thu Jun 8 09:52:38 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 08 Jun 2006 13:52:38 GMT Subject: what are you using python language for? In-Reply-To: <1149719891.761757.263650@c74g2000cwc.googlegroups.com> References: <1149719891.761757.263650@c74g2000cwc.googlegroups.com> Message-ID: Jason wrote: > I've been working on an RPG character generator for consistent (yet > varied) set of role-playing systems. Nothing like a pen-and-pencil RPG > to throw in tons of special cases and strange rulesets. Sounds interesting. Something I've thought about as a project, but I'm not good enough yet! :) From a at tempinbox.com Thu Jun 29 00:02:32 2006 From: a at tempinbox.com (a) Date: 28 Jun 2006 21:02:32 -0700 Subject: cheetah - how do i use .refreshcaceh() in cheetah Message-ID: <1151553752.082474.180370@y41g2000cwy.googlegroups.com> cheetah - how do i use .refreshcaceh() in cheetah the doc is skimpy and doesnt tell more than you can use refreshcache with id to refresh a cache my code in html has #cache 30m, id =cachei #end cache From joncle at googlemail.com Thu Jun 1 17:33:21 2006 From: joncle at googlemail.com (Jon Clements) Date: 1 Jun 2006 14:33:21 -0700 Subject: Using print instead of file.write(str) In-Reply-To: <447f4c9a$0$6174$626a54ce@news.free.fr> References: <447f4c9a$0$6174$626a54ce@news.free.fr> Message-ID: <1149197601.238826.151200@f6g2000cwb.googlegroups.com> Didn't know of the >> syntax: lovely to know about it Bruno - thank you. To the OP - I find the print statement useful for something like: print 'this','is','a','test' >>> 'this is a test' (with implicit newline and implicit spacing between parameters) If you want more control (more flexibility, perhaps?) over the formatting of the output: be it spacing between parameters or newline control, use the methods Bruno describes below. I'm not sure if you can suppress the spacing between elements (would love to be corrected though); to stop the implicit newline use something like print 'testing', >>> 'testing' (but - with the leading comma, the newline is suppressed) I personally find that print is convenient for sentences (or writing 'lines'). Thought it worth pointing this out in case, like some I know, you come across a cropper with certain output streams. All the best, Jon. Bruno Desthuilliers wrote: > A.M a ?crit : > > Hi, > > > > > > I found print much more flexible that write method. Can I use print instead > > of file.write method? > > > > f = open("/path/to/file") > print >> f, "this is my %s message" % "first" > f.close() > > To print to stderr: > > import sys > print >> sys.stderr, "oops" > > FWIW, you and use string formating anywhere, not only in print statements: > > s = "some %s and % formating" % ("nice", "cool") > print s > > You can also use "dict formating": > > names = {"other": "A.M.", "me" : "bruno"} > s = "hello %(other)s, my name is %(me)s" % names From bijsterblokit at hccnet.nl Tue Jun 13 09:01:43 2006 From: bijsterblokit at hccnet.nl (Jan Bijsterbosch) Date: Tue, 13 Jun 2006 15:01:43 +0200 Subject: Very nice python IDE (windows only) References: <1149694235.741274.325200@u72g2000cwu.googlegroups.com> <1149701880.540109.10100@y43g2000cwc.googlegroups.com> <1149704292.676501.138530@h76g2000cwa.googlegroups.com> <448d5f3d$0$815$3a628fcd@textreader.nntp.hccnet.nl> <1150123984.819338.84330@u72g2000cwu.googlegroups.com> <1150175414.784581.35420@c74g2000cwc.googlegroups.com> Message-ID: <448eb72c$0$10503$3a628fcd@textreader.nntp.hccnet.nl> Hello Luis, "Luis M. Gonz?lez" schreef in bericht news:1150175414.784581.35420 at c74g2000cwc.googlegroups.com... > > digitalorganics at gmail.com wrote: >> I happen to have delphi, so if someone wants me to make small changes, >> just let me know, I'll try to help.... > > Hmm... now that you offer, would it be possible to have the colors of > text just like in IDLE? > I tried configuring the colors, but some of them don't exist as options > in this IDE (for example "orange"). Hmm, it's a little bit hidden, but if you go to Options / Editor / Syntax Colors and be sure to select Python language as editor syntax then select 'reserved words' and after that from the color dropdown box select Custom... (the topmost option) a color dialog pops up and you can select any color You want...;-)) > I like how text looks in IDLE, with orange for reserved words, green > for strings, etc... With the above, no problem at all...;-)) Greetings from sunny Amsterdam, Jan From fredrik at pythonware.com Fri Jun 9 09:48:59 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 09 Jun 2006 15:48:59 +0200 Subject: Where is the ucs-32 codec? In-Reply-To: <1149860078.334793.308420@y43g2000cwc.googlegroups.com> References: <1149459785.331497.203920@c74g2000cwc.googlegroups.com> <4483EB71.9090509@v.loewis.de> <4483FD63.2080502@v.loewis.de> <1149860078.334793.308420@y43g2000cwc.googlegroups.com> Message-ID: cben at users.sf.net wrote: > Somebody asked me about generating UTF-32 (he didn't have choice of the > output format). I was about to propose the obvious ``u.encode('utf-32')`` > but discovered it's missing. hint 1: >>> u = u"Hello" >>> a = array.array("I", map(ord, u)) >>> a.tostring() 'H\x00\x00\x00e\x00\x00\x00l\x00\x00\x00l\x00\x00\x00o\x00\x00\x00' >>> a.byteswap() >>> a.tostring() '\x00\x00\x00H\x00\x00\x00e\x00\x00\x00l\x00\x00\x00l\x00\x00\x00o' hint 2: >>> import sys >>> sys.byteorder 'little' From fredrik at pythonware.com Fri Jun 30 15:59:54 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 30 Jun 2006 21:59:54 +0200 Subject: Reddit broke - should have remained on Lisp? In-Reply-To: <1151680670.764245.18520@m73g2000cwd.googlegroups.com> References: <1151626961.232761.255550@d56g2000cwd.googlegroups.com> <1151680670.764245.18520@m73g2000cwd.googlegroups.com> Message-ID: Alok wrote: > Their site was more responsive last year. http://tinyurl.com/zhary From test at test.test Sat Jun 24 14:56:17 2006 From: test at test.test (test at test.test) Date: Sat, 24 Jun 2006 13:56:17 -0500 Subject: Python to PHP Login System (HTTP Post) References: <1151018390.792574.102920@b68g2000cwa.googlegroups.com> <87mzc3fikh.fsf@reportlab.com> Message-ID: On Sat, 24 Jun 2006 01:28:29 GMT, jjlee at reportlab.com (John J. Lee) wrote: >test at test.test writes: > >> On 22 Jun 2006 16:19:50 -0700, "Justin Azoff" >> wrote: >> >> >Jeethu Rao wrote: >> >> You need to use httplib. >> >> http://docs.python.org/lib/httplib-examples.html >> >> >> >> Jeethu Rao >> > >> >Not at all. They need to read the documentation for urrlib: >> > >> >http://docs.python.org/lib/module-urllib.html >> >http://docs.python.org/lib/node483.html >> >"The following example uses the "POST" method instead:".... >> > >> >Additionally, they probably need to use cookielib, otherwise the logged >> >in state will not be persistant. > >Or you may not be able to log in at all, for an everyday meaning of >"log in". > > >> Here's what's strange... I tried using urllib like this: >> ---------------------------------------------------------------------------------- >> try: >> msparams = urllib.urlencode({'user': >> self.components.User.text, 'pass': >> self.components.MagnetSharePassword.text, 'sublogin': 1}) >> f = urllib.urlopen("http://www.magnetshare.com/process.php", >> msparams) >> fc = f.read() >> fc.close() >> print fc >> except: >> self.statusBar.text = "Disconnected" >> result = dialog.alertDialog(self, 'Couldn\'t connect to >> MagnetShare.com! Please check your Internet connection, and then try >> again.') >> else: >> print fc >> ----------------------------------------------------------------------------------- >> ...and then I visited http://www.magnetshare.com/main.php to see if I >> was logged in. Sure enough I was logged in, but the exception was > >That's not how it works (assuming you visited that URL in a browser, >not using Python). The "logged-in-ness" comes from a "session ID" >cookie that is stored in your browser (or in your Python code). The >server sends a cookie when you log in (and usually stores your cookie >in a database). The browser keeps the cookie. When you come back >later using the same browser (maybe even after you've closed the >browser, if it's the right kind of cookie), your browser sends the >cookie back and the server looks up the session ID from that cookie in >the database, and sees it's you. > >If you come back using a different browser (and your Python program is >effectively just a different browser than your copy of Firefox or IE >or whatever), then the server won't remember who you are, so you're >not logged in *in that browser session*, even if the server has you >recorded in its database as logged in from a different browser >session. > >So, the fact that you saw yourself as logged in when you looked using >your web browser doesn't really help your Python program -- it's still >out in the cold. > > >> thrown anyway. I commented out the urlopen, f, and fc lines and >> tested it again. This time I made it to "else:" >> >> I'm stumped. I'm glad that the user can log in; however, the >> MagnetShare application needs to read in the response from the server, >> and then decide what to do with the information. > >Here's one way: > >easy_install mechanize > >(install easy_install first if you don't have that: > >http://peak.telecommunity.com/DevCenter/EasyInstall#installing-easy-install > >) > >#------------------------------- >import mechanize > >SHOW_COOKIES = True > >br = mechanize.Browser() >if SHOW_COOKIES: > cj = mechanize.CookieJar() > br.set_cookiejar(cj) >br.open("http://www.magnetshare.com/main.php") >br.select_form(nr=0) >br["user"] = "joe" >br["pass"] = "password" >r = br.submit() >assert "Logged In" in r.get_data() >if SHOW_COOKIES: > for cookie in cj: > print cj >#------------------------------- > > >(note the cookiejar is always there; you only need to create one and >pass it in in order to get at it to e.g. print out the cookies you've >collected) > > >John Thanks a lot John! This "mechanize" was exactly what I was looking for. There are some key improvements over urllib2 and also, cookies are turned on by default. Just an FYI for others, PHP can set $SESSIONID when the user refuses cookies. I haven't decided whether the application will use cookies or not, but luckily I got the login page response I was looking for. Now, I just parse the HTML using Python, and then go to the next screen in the MagnetShare application. Here's the test code I used. --------------------------------------------------------------------------------------- import mechanize br = mechanize.Browser() br.open("http://www.magnetshare.com/main.php") br.select_form(nr=0) br["user"] = "test2" br["pass"] = "test2" response1 = br.submit() fc = response1.read() print fc ---------------------------------------------------------------------------------------- Cheers! Ben From nmm1 at cus.cam.ac.uk Fri Jun 30 07:32:02 2006 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 30 Jun 2006 11:32:02 GMT Subject: Interprocess communication on multi-user machine References: <44a41cae$0$29145$9b4e6d93@newsread4.arcor-online.net> Message-ID: In article , Lawrence D'Oliveiro writes: |> > |> >Sockets are often accessed via special files, but are not files. |> |> They are files. They are not _regular_ files. Sigh. Firstly, look at something like: http://www.opengroup.org/onlinepubs/009695399/toc.htm Start at the entry 'socket' and work from there. Yes, I know about UNIX-domain sockets, but even when they give the appearance of being files, 90% of the time that is the API only, and the underlying facility is very different. Dammit, processes are not files just because they happen to have a /proc entry under many systems! |> >They may also be accessed by port numbers, for example. |> |> UNIX sockets have no ports. You mean "UNIX-domain", not "UNIX". So? Many sockets do. Internet- domain ones always do. |> I wasn't talking about FIFOs. Even if I was, they _are_ still subject to |> regular file permissions (on Linux, at least). They aren't on most Unices - Linux is not UNIX, you know :-) I shall not respond further on this. Regards, Nick Maclaren. From serge.orlov at gmail.com Tue Jun 27 22:42:39 2006 From: serge.orlov at gmail.com (Serge Orlov) Date: Tue, 27 Jun 2006 19:42:39 -0700 Subject: Function to prune dictionary keys not working In-Reply-To: <44A1E9AB.6060206@lexicon.net> References: <44A1E9AB.6060206@lexicon.net> Message-ID: On 6/27/06, John Machin wrote: > |>> '1.00' >= 0.5 > True > |>> '0.33' >= 0.5 > True > > Python (correctly) does very little (guesswork-based) implicit type > conversion. At the same time, Python (incorrectly :) compares incomparable objects. From cdsmith at twu.net Fri Jun 23 11:59:34 2006 From: cdsmith at twu.net (Chris Smith) Date: Fri, 23 Jun 2006 09:59:34 -0600 Subject: Saying "latently-typed language" is making a category mistake References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> Message-ID: Vesa Karvonen wrote: > I think that we're finally getting to the bottom of things. While reading > your reponses something became very clear to me: latent-typing and latent- > types are not a property of languages. Latent-typing, also known as > informal reasoning, is something that all programmers do as a normal part > of programming. To say that a language is latently-typed is to make a > category mistake, because latent-typing is not a property of languages. It's pretty clear to me that there are two different things here. There is the set of reasoning that is done about programs by programmers. This may or may not have some subset called "type reasoning", depending on whether there's a real difference between type reasoning and any other reasoning about program behavior, or it's just a word that we've learned from early experience to use in certain rather arbitrary contexts. In either case, then there are language features that look sort of type-like which can support that same reasoning about program behavior. It is, to me, an interesting question whether those language features are really intrinsically connected to that form of reasoning about program behavior, or whether they are just one way of doing it where others would suffice as well. Clearly, there is some variation in these supporting language features between languages that have them... for example, whether there are only a fixed set of type tags, or an infinite (or logically infinite, anyway) set, or whether the type tags may have other type tags as parameters, or whether they even exist as tags at all or as sets of possible behaviors. Across all these varieties, the phrase "latently typed language" seems to be a reasonable shorthand for "language that supports the programmer in doing latent-type reasoning". Of course, there are still problems here, but really only if you share my skepticism that there's any difference between type reasoning and any other reasoning that's done by programmers on their programs. Perhaps, if you wanted to be quite careful about your distinctions, you may want to choose different words for the two. However, then you run into that same pesky "you can't choose other people's terminology" block again. > A programmer, working in any language, whether typed or not, performs > informal reasoning. I think that is fair to say that there is a > correspondence between type theory and such informal reasoning. The > correspondence is like the correspondence between informal and formal > math. I'd be more careful in the analogy, there. Since type theory (as applied to programming languages, anyway) is really just a set of methods of proving arbitrary statements about program behaviors, a corresponding "informal type theory" would just be the entire set of informal reasoning by programmers about their programs. That would agree with my skepticism, but probably not with too many other people. > An example of a form of informal reasoning that (practically) every > programmer does daily is termination analysis. Or perhaps you agree with my skepticism, here. This last paragraph sounds like you're even more convinced of it than I am. -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation From marshall.spight at gmail.com Mon Jun 26 22:20:01 2006 From: marshall.spight at gmail.com (Marshall) Date: 26 Jun 2006 19:20:01 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <34aj92h0g7tqi9amhh7k3ieq5n568t0e6f@4ax.com> Message-ID: <1151374801.003139.68680@u72g2000cwu.googlegroups.com> George Neuner wrote: > > I can know that my conversion of floating point to integer is going to > produce a value within a certain range ... but, in general, the > compiler can't determine what that range will be. All it knows is > that a floating point value is being truncated and the stupid > programmer wants to stick the result into some type too narrow to > represent the range of possible values. > > Like I said to Ben, I haven't seen any _practical_ static type system > that can deal with things like this. Writing a generic function is > impossible under the circumstances, and writing a separate function > for each narrow type is ridiculous and a maintenance nightmare even if > they can share the bulk of the code. This is the partial function question again, in a different guise. Marshall From onurb at xiludom.gro Wed Jun 28 06:32:19 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Wed, 28 Jun 2006 12:32:19 +0200 Subject: how do i make an array global In-Reply-To: <1151472238.400461.42350@p79g2000cwp.googlegroups.com> References: <1151472238.400461.42350@p79g2000cwp.googlegroups.com> Message-ID: <44a25ab4$0$1017$626a54ce@news.free.fr> a wrote: > def fn(): > for i in range(l) l is not defined - you should have an error here. > global count > count[i]= .... > > how do i declare count to be global if it is an array Just like it was an integer > subsequently i should access or define count as an array You need to define count before. > error: > global name 'count' is not defined He... *but* You probably should not do that anyway. Globals are *evil*. And functions modifying globals is the worst possible thing. There are very few chances you *need* a global here. Also, and FWIW: - Python has lists, not arrays (there's an array type in some numerical package, but that's another beast) - 'l' is a very bad name - 'count' is a bad name for a list - 'counts' would be better (when I see the name 'count', I think of an integer) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From jo at durchholz.org Mon Jun 26 17:31:49 2006 From: jo at durchholz.org (Joachim Durchholz) Date: Mon, 26 Jun 2006 23:31:49 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <7zpshbsvjy.fsf@app-1.diku.dk><4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150904134.520639.71070@b68g2000cwa.googlegroups.com> <1151030140.202720.245140@y41g2000cwy.googlegroups.com> <1151255749.436492.70680@m73g2000cwd.googlegroups.com> Message-ID: Darren New schrieb: > Marshall wrote: >> Also: has subtyping polymorphism or not, has parametric polymorphism or >> not. > > And covariant or contravariant. That's actually not a design choice - if you wish to have a sound type system, all input parameters *must* be contravariant, all output parameters *must* be covariant, and all in/out parameters must be novariant. (Eiffel got this one wrong in almost all cases.) Regards, Jo From fcorreia at gmail.com Fri Jun 30 12:14:55 2006 From: fcorreia at gmail.com (Filipe) Date: 30 Jun 2006 09:14:55 -0700 Subject: handling unicode data In-Reply-To: <44A4339D.8040303@v.loewis.de> References: <1151506510.391856.207460@y41g2000cwy.googlegroups.com> <44a2af7d$0$7205$9b622d9e@news.freenet.de> <1151515932.365483.311890@m73g2000cwd.googlegroups.com> <44A4339D.8040303@v.loewis.de> Message-ID: <1151684095.322994.270690@b68g2000cwa.googlegroups.com> Martin v. L?wis wrote: > > What do you mean by "ANSI-to-OEM conversion is enabled"? > > See AutoAnsiToOem in > http://support.microsoft.com/default.aspx?scid=KB;EN-US;199819 > I checked the registry key "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSSQLServer\Client\DB-Lib", and verified AutoAnsiToOem was 'ON'. I also tried assuming mbcs as the encoding but didn't got very far (please see my other post). From aleax at mac.com Thu Jun 1 22:16:16 2006 From: aleax at mac.com (Alex Martelli) Date: Thu, 1 Jun 2006 19:16:16 -0700 Subject: An oddity in list comparison and element assignment References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> <1149199942.955228.281950@u72g2000cwu.googlegroups.com> Message-ID: <1hg9pbo.1oem3vh1ryksipN%aleax@mac.com> Slawomir Nowaczyk wrote: > On Thu, 01 Jun 2006 15:12:23 -0700 > michael.f.ellis at gmail.com wrote: > > #> I believe that 'is' tests equality of reference, such that > #> > #> >>> a = range(1,3) > #> >>> b = range(1,3) > #> >>> a is b > #> False > #> > #> The 'is' operator tells you whether a and b refer to the same object. > #> What I've been discussing is whether == should test for "structural" > #> equality so that a and b remain equivalent under parallel mutations > #> (and also under single mutations to common references) > > What does "parallel mutations" mean? In particular, what should be the > results of each of the following three comparisons: > > x, y, z = [1],[1],[1] > a, b = [x,y], [y,z] > c, d = [[1],[1]], [[1],[1]] > a == b > c == d > a[0].remove(1) > b[0].remove(1) > a == b > > So, do I understand correctly that you would like first comparison > (a==b) to return "False" and second comparison (c==d) to return > "True"? I sure hope not, since, e.g.: ridiculous = c[0] is not a "mutation" (so equality should still hold, right?), and then it becomes weird to claim that ridiculous.append('bah, humbug!') is a "nonparallel mutation to" c and/or d. In fact, I'm starting to wonder if by Michaels' requirement ANY non-*IDENTICAL* containers (with non-identical mutable items) could EVER be deemed "equal". If he's arguing that "==" should mean exactly the same as "is", that's even crazier than I had gauged so far. But of course, since Michaels still refuses to provide simple, straightforward operational definitions of what it IS that he wants, all of this remains vague and ill-defined. See *WHY* it's so important to provide precision rather than just the handwaving he's given so far? Alex From *firstname*nlsnews at georgea*lastname*.com Thu Jun 15 15:34:07 2006 From: *firstname*nlsnews at georgea*lastname*.com (Tony Nelson) Date: Thu, 15 Jun 2006 19:34:07 GMT Subject: socket and Ctl-C workaround? Message-ID: <*firstname*nlsnews-5BA2B7.15342215062006@news.verizon.net> I've been trying to figure out why Ctl-C sometimes doesn't interrupt yum. It appears to be unresolved Python bug 926423, unresolved proposed patch 1102879, don't know if anything ever came of it. Note that I cannot ask all yum users to apply the patch. I'm not sure I should be getting rid of the timeout, either. When a Ctl-C is lost, sometimes it is silently eaten, and other times it becomes socket.error(11,...) (EWOULDBLOCK). As (AFAICT) the socket in question is a blocking socket, I could use that nonsense exception to detect at least some of the lost Ctl-Cs (eww). The socket does have a timeout. Note that I am using FC5 Linux, Python 2.4.2. ________________________________________________________________________ TonyN.:' *firstname*nlsnews at georgea*lastname*.com ' From rossberg at ps.uni-sb.de Wed Jun 21 13:24:15 2006 From: rossberg at ps.uni-sb.de (Andreas Rossberg) Date: Wed, 21 Jun 2006 19:24:15 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <0%Wlg.3521$MF6.947@tornado.socal.rr.com> <44992e6c$0$664$bed64819@news.gradwell.net> Message-ID: Darren New wrote: > >> Maybe I don't understand what you mean with ADT here, but all >> languages with a decent module system support ADTs in the sense it is >> usually understood, see ML for a primary example. > > OK. Maybe some things like ML and Haskell and such that I'm not > intimately familiar with do, now that you mention it, yes. Well, Modula and CLU already had this, albeit in restricted form. >> Classes in most OOPLs are essentially beefed-up ADTs as well. > > Err, no. There's nothing really abstract about them. And their values > are mutable. So while one can think about them as an ADT, one actually > has to write code to (for example) calculate or keep track of how many > entries are on a stack, if you want that information. Now you lost me completely. What has mutability to do with it? And the stack? AFAICT, ADT describes a type whose values can only be accessed by a certain fixed set of operations. Classes qualify for that, as long as they provide proper encapsulation. >> Not counting C/C++, I don't know when I last worked with a typed >> language that does *not* have this ability... (which is slightly >> different from ADTs, btw) > > Java? C#? Icon? Perl? (Hmmm... Pascal does, IIRC.) I guess you just work > with better languages than I do. :-) OK, I admit that I exaggerated slightly. Although currently I'm indeed able to mostly work with the more pleasant among languages. :-) (Btw, Pascal did not have it either, AFAIK) - Andreas From dananrg at yahoo.com Thu Jun 29 17:09:45 2006 From: dananrg at yahoo.com (dananrg at yahoo.com) Date: 29 Jun 2006 14:09:45 -0700 Subject: pyGoogle - restrict by country doesn't seem to work In-Reply-To: <1151614342.293952.294630@75g2000cwc.googlegroups.com> References: <1151614342.293952.294630@75g2000cwc.googlegroups.com> Message-ID: <1151615385.579434.159200@i40g2000cwc.googlegroups.com> This worked for me: data = google.doGoogleSearch(searchTerm, restrict = 'countryUS') How does restrict results by country at Google.com? From max at alcyone.com Wed Jun 7 14:12:52 2006 From: max at alcyone.com (Erik Max Francis) Date: Wed, 07 Jun 2006 11:12:52 -0700 Subject: CENSORSHIP - Django Project (Schema Evolution Support) In-Reply-To: <1mbzvhr7j0x99.qlcv3kw259m6.dlg@40tude.net> References: <4486B9FB.9030804@lazaridis.com> <1mbzvhr7j0x99.qlcv3kw259m6.dlg@40tude.net> Message-ID: Thorsten Kampe wrote: > I think I have a deja-vu... Did someone say "Xah"?! With a hint of Brandon. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Too much agreement kills a chat. -- Eldridge Cleaver From chris.uppal at metagnostic.REMOVE-THIS.org Fri Jun 23 08:03:13 2006 From: chris.uppal at metagnostic.REMOVE-THIS.org (Chris Uppal) Date: Fri, 23 Jun 2006 13:03:13 +0100 Subject: What is a type error? References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <7i3mg.204167$8W1.155367@fe1.news.blueyonder.co.uk> <44992e6c$2$664$bed64819@news.gradwell.net> <%Igmg.464974$xt.353729@fe3.news.blueyonder.co.uk> <449aaea0$2$656$bed64819@news.gradwell.net> Message-ID: <449bde5f$0$663$bed64819@news.gradwell.net> Eliot Miranda wrote: [me:] > > Taking Smalltalk /specifically/, there is a definite sense in which it > > is typeless -- or trivially typed -- in that in that language there are > > no[*] operations which are forbidden[**], > > Come one Chris U. One has to distinguish an attempt to invoke an > operation with it being carried out. There is nothing in Smalltalk to > stop one attempting to invoke any "operation" on any object. But one > can only actually carry-out operations on objects that implement them. > So, apart from the argument about inadvertent operation name overloading > (which is important, but avoidable), Smalltalk is in fact > strongly-typed, but not statically strongly-typed. What are you doing /here/, Eliot, this is Javaland ? Smalltalk is thatta way -> ;-) But this discussion has been all about /whether/ it is ok to apply the notion of (strong) typing to what runtime-checked languages do. We all agree that the checks happen, but the question is whether it is reasonable/helpful/legitimate to extend the language of static checking to the dynamic case. (I'm on the side which says yes, but good points have been made against it). The paragraph you quoted doesn't represent most of what I have been saying -- it was just a side-note looking at one small aspect of the issue from a different angle. -- chris From Dennis.Benzinger at gmx.net Thu Jun 29 14:38:00 2006 From: Dennis.Benzinger at gmx.net (Dennis Benzinger) Date: Thu, 29 Jun 2006 20:38:00 +0200 Subject: Problem with sets and Unicode strings In-Reply-To: <4gfr58F1mijo5U2@uni-berlin.de> References: <44a17d05$1@news.uni-ulm.de> <44a19d55$2@news.uni-ulm.de> <44a2b2cc$2@news.uni-ulm.de> <4gfr58F1mijo5U2@uni-berlin.de> Message-ID: <44a41e06$1@news.uni-ulm.de> Diez B. Roggisch wrote: >> But I'd say that it's not intuitive that for sets x in y can be false >> (without raising an exception!) while the doing the same with a tuple >> raises an exception. Where is this difference documented? > > 2.3.7 Set Types -- set, frozenset > > ... > > Set elements are like dictionary keys; they need to define both __hash__ and > __eq__ methods. > ... > > And it has to hold that > > a == b => hash(a) == hash(b) > > but NOT > > hash(a) == hash(b) => a == b > > Thus if the hashes vary, the set doesn't bother to actually compare the > values. > [...] Ok, I understand. But isn't it a (minor) problem that using a set like this: # -*- coding: UTF-8 -*- FIELDS_SET = set(("F?cher", )) print u"F?cher" in FIELDS_SET print u"F?cher" == "F?cher" shadows the error of not setting sys.defaultencoding()? Dennis From iainws at gmail.com Tue Jun 13 13:38:44 2006 From: iainws at gmail.com (iainws at gmail.com) Date: 13 Jun 2006 10:38:44 -0700 Subject: DispatchEx('.Application') Message-ID: <1150220324.353472.253180@h76g2000cwa.googlegroups.com> When using win32com and DispatchEx to work with a webbrowser, eg: from win32com.client import DispatchEx ie = DispatchEx('InternetExplorer.Application') can anyone suggest the right answer to this? mf = DispatchEx('MozillaFirefox.Application') It is an invalid class string, but I don't know how to find the right class string for Mozilla (or any other window for that matter)? Can somebody suggest to me an easy way to 'get' this information. After that I intend to do this: mf.Navigate('www.groups.google.com.au/etc'') Will all of these functions work with Firefox or is it only Internet Explorer(I can use either but I prefer Firefox?) From Serge.Orlov at gmail.com Mon Jun 5 10:34:42 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 5 Jun 2006 07:34:42 -0700 Subject: is it possible to find which process dumped core References: <1149514829.032643.193890@h76g2000cwa.googlegroups.com> Message-ID: <1149518081.968730.122220@i40g2000cwc.googlegroups.com> su wrote: > to find which process dumped core at the promt we give > > $ file core.28424 > > core.28424: ELF 32-bit LSB core file of 'soffice.bin' (signal 11), > Intel 80386, version 1 (SYSV), from 'soffice.bin' > > from this command we know 'soffice.bin' process dumped core. Now can i > do the same using python i.e. finding which process dumped core? if so > how can i do it? Parse a core file like the file command does? From fredrik at pythonware.com Mon Jun 19 06:56:43 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 19 Jun 2006 12:56:43 +0200 Subject: Simple script to make .png thumbnails from .zip archive... In-Reply-To: <1150713530.440037.54650@y41g2000cwy.googlegroups.com> References: <1150660266.413889.217280@c74g2000cwc.googlegroups.com> <1150664094.345764.280030@u72g2000cwu.googlegroups.com> <1150713530.440037.54650@y41g2000cwy.googlegroups.com> Message-ID: K P S wrote: > I'm able to read a .jpg from a .zip archive, but can't seem to > manipulate it. If I do this: > > zip=zipfile.ZipFile(inURL,mode="r") > picture=zip.read("00.jpg") > > I get the image, but it is of "type" ZipFile. string, more likely (zip is a ZipFile object, picture is a string of bytes). PIL expects a file name or a file object, so you need to use the StringIO adapter: picture = zip.read(name) # returns a string file = StringIO.StringIO(picture) # wrap string in file-like object image = Image.open(file) # create image object from file-like object From fabiofz at gmail.com Thu Jun 29 11:17:35 2006 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Thu, 29 Jun 2006 12:17:35 -0300 Subject: Pydev 1.2.1 Released Message-ID: Hi All, Pydev and Pydev Extensions 1.2.1 have been released Details on Pydev Extensions: http://www.fabioz.com/pydev Details on Pydev: http://pydev.sf.net Details on its development: http://pydev.blogspot.com Important ---------------- 1. This release is still not available in the sourceforge downloads session because of some problems at sourceforge, but it is already placed in the update sites (and should be added to the sourceforge downloads as soon as the sourceforge release works again. 2. Eclipse 3.2: The final Eclipse 3.2 should be available (according to http://eclipse.org) in 1 day. Release Highlights in Pydev Extensions: ----------------------------------------------------------------- - Bug-Fixes Release Highlights in Pydev: ---------------------------------------------- - The user is asked for which paths should be added to the system pythonpath - Go to previous method now works with decorators - Stack-trace link now opens in correct line for external files - Variables now show in the variables view while debugging - If an invalid interpreter is selected to run a file (old interpreter or wrong project type), a warning is given to the user - Ctrl+w is removed as the default for select word (the action is still there, but its keybinding is removed, so, users have to configure themselves which keybinding they want for it) - Assign to local or field variable now enters in linked mode - Added dependency to Eclipse 3.2 features, as version 1.2.0 of pydev and newer are only Eclipse 3.2 compatible. What is PyDev? --------------------------- PyDev is a plugin that enables users to use Eclipse for Python and Jython development -- making Eclipse a first class Python IDE -- It comes with many goodies such as code completion, syntax highlighting, syntax analysis, refactor, debug and many others. Cheers, -- Fabio Zadrozny ------------------------------------------------------ Software Developer ESSS - Engineering Simulation and Scientific Software http://www.esss.com.br Pydev Extensions http://www.fabioz.com/pydev Pydev - Python Development Enviroment for Eclipse http://pydev.sf.net http://pydev.blogspot.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From juergen.huber at kirchnersoft.com Fri Jun 30 09:07:48 2006 From: juergen.huber at kirchnersoft.com (Juergen Huber) Date: Fri, 30 Jun 2006 15:07:48 +0200 Subject: delete first line in a file References: <44a4f854$0$12942$91cee783@newsreader02.highway.telekom.at><44a50151$0$12935$91cee783@newsreader02.highway.telekom.at> <44a50825$0$3888$91cee783@newsreader01.highway.telekom.at> Message-ID: <44a52219$0$12934$91cee783@newsreader02.highway.telekom.at> this helps me! thank you very much!!!!! greetings, juergen JH> Fredrik Lundh wrote: >> Juergen Huber wrote: >> >>> ok...i thought as much, that i have to copy this file! >>> >>> how will i do that?! >>> how will i fix this file => delete the first line?! >>> >>> with which commands could i do that?! >> >> start here: >> >> http://docs.python.org/tut/node9.html#SECTION009200000000000000000 >> >> JH> that documentation i have already read, but it wouldn`t help me for my JH> problem! JH> i know, how i can read the first line an print them on the screen! JH> but...how can i say python, delete the first line?! JH> thats my problem! as Fredrik told you, you can not delete the first line directly!!! JH> in the entry of my posting i wrote, that i am a newbie and so please JH> understand me, that i ask so questions?! :-) We are trying to understand that, but it is expected some effort on your side as well :) You didn't read the documentation properly! try to experiment with the code by yourself as well! Try: 1) open your file 2) use readlines() method which returns the list of ALL rows from the file and store them to some variable. it can be done for example like: all_lines = f.readlines() (if you do not know, what the list is, start here: http://docs.python.org/tut/node5.html#SECTION005140000000000000000) 4) save the list members without its first member to the file for example: for line in all_lines[1:]: f.write(line) 5) close the file Good luck Petr Jakes JH> thanks for your help! From timothy.williams at nvl.army.mil Thu Jun 22 15:24:40 2006 From: timothy.williams at nvl.army.mil (timw.google) Date: 22 Jun 2006 12:24:40 -0700 Subject: Help req: Problems with MySQLdb References: <1150968147.565850.156870@u72g2000cwu.googlegroups.com> Message-ID: <1151004280.845498.302500@u72g2000cwu.googlegroups.com> Do you have a MySQL acccount set up on the localhost? I usually create two users with the same privs. One for the localhost where the server is, another to connect from somewhere else. Something like mysql> grant usage on *.* to 'user'@'localhost' identitfied by 'some_pass'; mysql> grant usage on *.* to 'user'@'%' to identified by 'some_pass'; Check out http://dev.mysql.com/doc/refman/4.1/en/adding-users.html Hope this helps. rodmc wrote: > I have written an application that connects to a database on a remote > machine which uses MySQLdb 1.2.0. The application works perfectly when > connecting to the database from a remote machine, however when it > attempts to connect to a database on the same machine a connection > error is generated. I have attached what little info I can below. > > DBSERVERIP = "1.2.3.4" > db = MySQLdb.connect(host=DBSERVERIP, user="user", passwd="password", > db="nuke") > --- it refuses to connect on the above line and the exception is caught > and a message displayed. > From nyamatongwe+thunder at gmail.com Wed Jun 14 05:28:48 2006 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Wed, 14 Jun 2006 09:28:48 GMT Subject: python-dev Summary for 2006-05-01 through 2006-05-15 In-Reply-To: References: Message-ID: Radovan: > This summary is tagged as being in ISO-8859-1 encoding: > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > However, it really is in UTF-8, which results in this mojibake: > >> Martin v. L??wis and Marc-Andre Lemburg discussed how to include both Its a good thing we have Martin to highlight these manglings although he must be quite sore from the repeated identity breakage. Neil From girish at cse.iitb.ac.in Fri Jun 9 02:31:03 2006 From: girish at cse.iitb.ac.in (Girish Sahani) Date: Fri, 9 Jun 2006 12:01:03 +0530 (IST) Subject: Error in Chain of Function calls Message-ID: <53637.10.209.4.2.1149834663.squirrel@10.105.1.3> Hi, There is a code in my main function which is something like: while prunedFinal != []: prunedNew = genColocations(prunedK) *** tableInstancesNew = genTableInstances(prunedNew,tableInstancesK) tiCountDict = tiCount(tableInstancesNew) tiDict = findPI(tableInstancesNew) prunedFinal = pruneTI(tiDict,pi) rulesDict = genRules(prunedFinal) cpDict = findCP(rulesDict) prunedRulesList = pruneCP(cpDict,cp) prunedK = prunedFinal tableInstancesK = tableInstancesNew else: return prunedRulesList prunedK and tableInstancesK are defined in the main function. Before the main function, i have defined the other functions such as genColocations,genTableInstances,etc. Output of genColocations is to be given to the next function genTableInstances,output of this function to tiCount and findPI, and so on. However i am getting an error at the line marked with ***. Also,i am getting a ValueError in the code below: for s in prunedNew: substrings = [s[:i]+s[i+1:] for i in range(len(s))] for string in substrings: if string not in prunedK: prunedNew.remove(s) continue continue The error is: prunedNew.remove(s) ValueError: list.remove(x): x not in list Could anyone enlighten me as to why i'm getting these two errors?? Thanks a lot, girish From skip at pobox.com Tue Jun 6 09:04:35 2006 From: skip at pobox.com (skip at pobox.com) Date: Tue, 6 Jun 2006 08:04:35 -0500 Subject: Reading from a file and converting it into a list of lines: code not working In-Reply-To: <54688.10.209.4.1.1149567048.squirrel@10.105.1.3> References: <1149534126.129714.131860@f6g2000cwb.googlegroups.com> <1149535195.763340.220010@y43g2000cwc.googlegroups.com> <54688.10.209.4.1.1149567048.squirrel@10.105.1.3> Message-ID: <17541.32099.915753.631037@montanaro.dyndns.org> Girish> I have a text file in the following format: Girish> 1,'a',2,'b' Girish> 3,'a',5,'c' Girish> 3,'a',6,'c' Girish> 3,'a',7,'b' Girish> 8,'a',7,'b' Girish> . Girish> . Girish> . Girish> Now i need to generate 2 things by reading the file: Girish> 1) A dictionary with the numbers as keys and the letters as values. Girish> e.g the above would give me a dictionary like Girish> {1:'a', 2:'b', 3:'a', 5:'c', 6:'c' ........} Girish> 2) A list containing pairs of numbers from each line. Girish> The above formmat would give me the list as Girish> [[1,2],[3,5],[3,6][3,7][8,7]......] Running this: open("some.text.file", "w").write("""\ 1,'a',2,'b' 3,'a',5,'c' 3,'a',6,'c' 3,'a',7,'b' 8,'a',7,'b' """) import csv class dialect(csv.excel): quotechar = "'" reader = csv.reader(open("some.text.file", "rb"), dialect=dialect) mydict = {} mylist = [] for row in reader: numbers = [int(n) for n in row[::2]] letters = row[1::2] mydict.update(dict(zip(numbers, letters))) mylist.append(numbers) print mydict print mylist import os os.unlink("some.text.file") displays this: {1: 'a', 2: 'b', 3: 'a', 5: 'c', 6: 'c', 7: 'b', 8: 'a'} [[1, 2], [3, 5], [3, 6], [3, 7], [8, 7]] That seems to be approximately what you're looking for. Skip From webraviteja at gmail.com Sun Jun 18 13:14:12 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 18 Jun 2006 10:14:12 -0700 Subject: code is data In-Reply-To: <1150626424.563673.175060@c74g2000cwc.googlegroups.com> References: <1150574111.415068.255900@p79g2000cwp.googlegroups.com> <1150606118.456390.262620@y41g2000cwy.googlegroups.com> <1150626424.563673.175060@c74g2000cwc.googlegroups.com> Message-ID: <1150650852.275956.249340@p79g2000cwp.googlegroups.com> Paddy wrote: > Ravi Teja wrote: > > BJ?rn Lindqvist wrote: > > > > Personally, I would like to see macros in Python (actually Logix > > > > succeeding is good enough). But I am no language designer and the > > > > community has no interest in it. When I absolutely need macros, I will > > > > go elsewhere. > > > > > > One must wonder, when is that? When do you absolutely need macros? > > > > Whenever there is significant boiler plate code that functions and > > classes cannot eliminate alone. > > Whenever there is a more elegant way to express your code. > > > > Me, I am torn. I should now better. I have listened to the arguments > against Macros in Python and the ones that struck home were the > argument for maintainability: > Without macros, Python is Python. Statements do what you expect. Yes! I heard those arguments too. And I am not convinced. Static language programmer: Lack of static typing removes the necessary safeguards. The code is more error prone. Objects have behavior that is not obvious. Dynamic language programmer: Really? I don't seem to have any more bugs than in my statically typed code. And my code is compact and reads better. I don't want to go back. No to macros proponent: Macros introduce a lot of potential for abuse. Code will be worse to read than Perl. Macros proponent: Really? We have been doing macros for decades. We all think our code is better for macros, not worse. We are not going back. I just don't get it. Don't we often invoke the "We are all adults here" argument. Writing a macro is not as simple as writing a function. Sort of like metaclasses. Many will stay off them. Those that really need them will walk that extra mile. Don't we all believe that "Simple should be possible. Complex should be doable" > And the argument against DSLs altogether: > Make Python your DSL! If you design your own DSL before long you start > to embellish it with more statements or data types and before long it > becomes complex. If you used Python from the beginning then you would > have a community for support. Python has a low cognitive overhead. But it not a DSL by definition. No language can be. The idea is that when the domain changes, a DSL should be driven by the new domain as warranted. In other words, driven "by the problem, not the tool". I don't want "a DSL". I want a language that allows me to make "my DSL" based on it. That means I don't loose the community connection. I can still use all the rich libraries in my DSL. I like Python for its indentation syntax, sensible semantics and readability. I invested a lot of time in Python. After much language hopping, I settled with Python. I like the community and the code base available for it. The libraries just seem to be designed at the right level of abstraction for me (as opposed to say, Java). When I need to do something, I know where to go. But all this ties me to the language tightly that I cannot change. > I know the arguments, but every once in a while I think if only I could > craft my own ??? statement or .... My thoughts exactly. Web frameworks, which seem to be the rage now in Python community could have benefited tremendously from Macro capabilities since they have a lot of boiler plate. From deets at nospam.web.de Tue Jun 27 03:54:02 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 27 Jun 2006 09:54:02 +0200 Subject: How do I limit access to objects in Python? In-Reply-To: References: Message-ID: <4gc6gjF1mcg9rU1@uni-berlin.de> Tommytrojan schrieb: > Hi, > > I have an application that embeds the Python interpreter. My users have > access to the interpreter through a console like window and they can run > Python scripts. For my application I use some Python modules (say module > Restricted) that I don't want to give my users access to. However, the > modules that I make public to my users and that I want my users to be > able to use themselves use the Restricted module. Any suggestions on how > to solve this? I was thinking of instantiating a separate interpreter > but I don't think this will solve my problem. I don't think that is possible - how is one to distinguish your code from the code written by a user that calls one method in the restricted module? What you _can_ do is to spawn an interpreter, and expose the allowed objects via Pyro. The question is though: why cripple your users? If someone could reach an otherwise unreachable goal why do yoou hinder him? What is the reasoning behind that? Diez From pjb at informatimago.com Thu Jun 22 13:21:55 2006 From: pjb at informatimago.com (Pascal Bourguignon) Date: Thu, 22 Jun 2006 19:21:55 +0200 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150902275.129780.50260@p79g2000cwp.googlegroups.com> <1150918629.818145.143220@y41g2000cwy.googlegroups.com> <4fv081F1jh4ifU1@individual.net> <1150967543.947096.72840@g10g2000cwb.googlegroups.com> <4fv84rF1kp06kU1@individual.net> <4fvfuiF1kncqtU1@individual.net> <87ejxh9xoq.fsf@thalassa.informatimago.com> <87ac859m1p.fsf@thalassa.informatimago.com> Message-ID: <87y7vp85sc.fsf@thalassa.informatimago.com> Matthias Blume writes: > Pascal Bourguignon writes: > >> Matthias Blume writes: >> >>> Pascal Bourguignon writes: >>> >>>> Moreover, a good proportion of the program and a good number of >>>> algorithms don't even need to know the type of the objects they >>>> manipulate. >>>> >>>> For example, sort doesn't need to know what type the objects it sorts >>>> are. It only needs to be given a function that is able to compare the >>>> objects. >>> >>> Of course, some statically typed languages handle this sort of thing >>> routinely. >>> >>>> Only a few "primitive" functions need specific types. >>> >>> Your sort function from above also has a specific type -- a type which >>> represents the fact that the objects to be sorted must be acceptable >>> input to the comparison function. >> >> Well, not exactly. > > What do you mean by "not exactly". > >> sort is a higher level function. The type of its >> arguments is an implicit parameter of the sort function. > > What do you mean by "higher-level"? Maybe you meant "higher-order" or > "polymorphic"? Yes, that's what I wanted to say. > [ rest snipped ] > > You might want to look up "System F". > [...] >>> ...or you type-check your "black box" and make sure that no matter how >>> you will ever change the type of the inputs (in accordance with the >>> interface type of the box) you get a valid program. >> >> When? > > When what? When will you type-check the "black box"? A function such as: (defun f (x y) (if (g x) (h x y) (i y x))) in the context of a given program could be type-infered statically as taking an integer and a string as argument. If the compiler did this inference, it could perhaps generate code specific to these types. But it's always possible at run-time that new functions and new function calls be generated such as: (let ((x "two")) (eval `(defmethod g ((self ,(type-of x))) t)) (eval `(defmethod h ((x ,(type-of x)) (y string)) (,(intern (format nil "DO-SOMETHING-WITH-A-~A" (type-of x))) x) (do-something-with-a-string y))) (funcall (compile nil `(let ((x ,x)) (lambda () (f x "Hi!")))))) Will you execute the whole type-inference on the whole program "black box" everytime you define a new function? Will you recompile all the "black box" functions to take into account the new type the arguments can be now? This wouldn't be too efficient. Let's just say that by default, all arguments and variable are of type T, so the type checking is trivial, and the generated code is, by default, totally generic. Only the few concrete, low-level functions need to know the types of their arguments and variables. In these functions, either the lisp compiler will do the type inference (starting from the predefined primitives), or the programmer will declare the types to inform the compiler what to expect. (defun do-something-with-a-string (x) (declare (string x)) ...) (defun do-something-with-a-integer (x) (declare (integer x)) ...) ... -- __Pascal Bourguignon__ http://www.informatimago.com/ PUBLIC NOTICE AS REQUIRED BY LAW: Any use of this product, in any manner whatsoever, will increase the amount of disorder in the universe. Although no liability is implied herein, the consumer is warned that this process will ultimately lead to the heat death of the universe. From jo at durchholz.org Sun Jun 25 13:33:02 2006 From: jo at durchholz.org (Joachim Durchholz) Date: Sun, 25 Jun 2006 19:33:02 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <0%Wlg.3521$MF6.947@tornado.socal.rr.com> <44992e6c$0$664$bed64819@news.gradwell.net> <1151010139.960608.122470@b68g2000cwa.googlegroups.com> Message-ID: Chris Smith schrieb: > Joachim Durchholz wrote: >> Sorry, I have to insist that it's not me who's stretching terms here. >> >> All textbook definitions that I have seen define a type as the >> set/operations/axioms triple I mentioned above. >> No mention of immutability, at least not in the definitions. > > The immutability comes from the fact (perhaps implicit in these > textbooks, or perhaps they are not really texts on formal type theory) > that types are assigned to expressions, That doesn't *define* what's a type or what isn't! If it's impossible to assign types to all expressions of a program in a language, that does mean that there's no useful type theory for the program, but it most definitely does not mean that there are no types in the program. I can still sensibly talk about sets of values, sets of allowable operations over each value, and about relationships between inputs and outputs of these operations. So programs have types, even if they don't have a static type system. Q.E.D. Regards, Jo From manuelg at gmail.com Fri Jun 16 17:47:30 2006 From: manuelg at gmail.com (manuelg at gmail.com) Date: 16 Jun 2006 14:47:30 -0700 Subject: copyfile avoiding overwrites and race conditions Message-ID: <1150494450.684069.104490@h76g2000cwa.googlegroups.com> Here is a code fragment, where I am trying to copy a file, avoiding overwrites and race conditions. The filename gets a '02','03','04' etc appended to the end if a file with that name already exists. I know the writing of the single space is overkill, but I am surprised I cannot find an example of this floating around the web and newsgroups my understanding of 'os.open' and 'os.fdopen' is minimal ## start fragment i = 0 while True: if i >= 100: raise RanOutFileNamesError(fullpath) i += 1 if i > 1: name0 = '%s_%02i%s' % (suggested_name, i, file_extension) else: assert i == 1 name0 = '%s%s' % (suggested_name, file_extension) fullpath = os.path.join(path0, name0) # create dummy file, force overwrite try: fd = os.open( fullpath, os.O_CREAT | os.O_EXCL | os.O_WRONLY) except OSError: continue # is this really necessary? file = os.fdopen(fd, "w") file.write(' ') file.close() shutil.copyfile(original_filepath, fullpath) return fullpath ## end fragment From martin.witte at gmail.com Sat Jun 10 06:00:58 2006 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 10 Jun 2006 03:00:58 -0700 Subject: os.link makes a copy, not a link In-Reply-To: References: Message-ID: <1149933658.725754.27520@m38g2000cwc.googlegroups.com> I had good results with os.symlink on Solaris, see http://docs.python.org/lib/os-file-dir.html Dan M wrote: > I'm a little bit confused. According to the sources I've looked at on the > net, > os.link('file1', 'file2') > should make a hard link from file1 to file2. But what I'm finding is that > it's actually making a copy. Am I forgetting a step or something? > > Python 2.3.4 running on CentOS 4.3

> PythonPerl 0.9 - simple module to allow the use of Perl inside > Python. (16-Jun-06) > -- > http://mail.python.org/mailman/listinfo/python-announce-list > > Support the Python Software Foundation: > http://www.python.org/psf/donations.html -- Jim Fulton mailto:jim at zope.com Python Powered! CTO (540) 361-1714 http://www.python.org Zope Corporation http://www.zope.com http://www.zope.org From reply.in.the.newsgroup at my.address.is.invalid Mon Jun 5 07:52:00 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Mon, 05 Jun 2006 13:52:00 +0200 Subject: Python to C converter References: <1149506038.843016.298470@c74g2000cwc.googlegroups.com> Message-ID: praveenkumar.117 at gmail.com: >I have an application return in python. I want this to be >converted to C. http://www.python.org/doc/faq/general/#can-python-be-compiled-to-machine-code-c-or-some-other-language -- Ren? Pijlman From alisonken1 at gmail.com Fri Jun 16 12:41:36 2006 From: alisonken1 at gmail.com (alisonken1) Date: 16 Jun 2006 09:41:36 -0700 Subject: Duplex communication with pipes - is possible ? In-Reply-To: References: Message-ID: <1150476096.873581.96560@g10g2000cwb.googlegroups.com> > readlines () will try to read until the stream/socket is closed. Try to > read only one line. This of course means that you cannot sent \n as part > of the data, you have to escape them somehow. > If I remember correctly, if you want to pass '\n' so readline won't stop, you should be able to escape the escape '\\n', then remove the extra '\' when actually processing. Of course, readline will continue to read until buffer filled or a real '\n' is passed (g). From ibr at radix50.net Sat Jun 3 07:04:10 2006 From: ibr at radix50.net (Baurzhan Ismagulov) Date: Sat, 3 Jun 2006 13:04:10 +0200 Subject: logging In-Reply-To: <1149113113.083677.235570@i39g2000cwa.googlegroups.com> References: <1148426018.334087.124160@i40g2000cwc.googlegroups.com> <1148577240.250304.116360@j55g2000cwa.googlegroups.com> <1149005605.819519.242350@j55g2000cwa.googlegroups.com> <1149113113.083677.235570@i39g2000cwa.googlegroups.com> Message-ID: <20060603110410.GA30398@radix50.net> Hello Vinay, On Wed, May 31, 2006 at 03:05:13PM -0700, Vinay Sajip wrote: > > Hmm, log1 decides once whether to print an event, and after that it gets > > printed in log1 and all its ancestors, regardless of their level? I find > > this quite counter-intuitive. I'd instead expect that each logger > > decides whether to print an event according to its own level. Could you > > give an example why one would want the python behavior? > > Loggers are hierarchical for a reason - not just randomly named > channels. ... Thanks for the explanation! Please note that I am not questioning the usefulness of hierarchical logging -- I think it's a Good Thing. What I can't understand is the motivation for the single place of decision whether a message should be printed ("is enabled" in log4j terms) or not. Consider the following scenario: root is CRITICAL, l01 is DEBUG, a debug message is logged on l01. l01 decides that the message should be printed, and _both_ root and l01 print it. Now, it is good that the message is propagated to root, but why doesn't root decide for itself whether to print it or not? For instance, I log root to syslog and have only critical messages there. I log l01 to console to debug. I want that my message to l01 is not printed by root since its level is CRITICAL. This is why I want that each logger re-evaluates the message level for itself. Could you perhaps give a useful example why one could want loggers to decide once? And another thing I couldn't find how to do: I want to have several debug levels. I can log messages without problems, but numeric values in the configuration file cause error messages during logging.config.fileConfig. Can I specify numeric values in the config file? With kind regards, Baurzhan. From chris.uppal at metagnostic.REMOVE-THIS.org Fri Jun 23 16:03:58 2006 From: chris.uppal at metagnostic.REMOVE-THIS.org (Chris Uppal) Date: Fri, 23 Jun 2006 21:03:58 +0100 Subject: What is a type error? References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <7i3mg.204167$8W1.155367@fe1.news.blueyonder.co.uk> <44992e6c$2$664$bed64819@news.gradwell.net> <%Igmg.464974$xt.353729@fe3.news.blueyonder.co.uk> <449aaea0$2$656$bed64819@news.gradwell.net> <449bde60$0$663$bed64819@news.gradwell.net> Message-ID: <449c4826$1$657$bed64819@news.gradwell.net> Chris Smith wrote: > But then, I > dislike discussion of strong/weak type systems in the first place. It > doesn't make any sense to me to say that we verify something and then > don't do anything if the verification fails. In those cases, I'd just > say that verification doesn't really exist or is incorrectly > implemented. Hmm, that seems to make what we are doing when we run some tests dependent on what we do when we get the results. If I run a type inference algorithm on some of my Smalltalk code, and it tells me that something is type-incorrect, then I think I'd like to be able to use the same words for the checking regardless of whether, after due consideration, I decide to change my code, or that it is OK as-is. Minor point, though... Anyway: > if (x != 0) y = 1 / x; > else y = 999999999; > > is not all that much different from (now restricting to Java): > > try { y = 1 / x; } > catch (ArithmeticException e) { y = 999999999; } > > So is one of them a use of a dynamic type system, where the other is > not? My immediate thought is that the same question is equally applicable (and equally interesting -- i.e. no simple answer ;-) for static typing. Assuming Java's current runtime semantics, but positing different type checkers, we can get several answers. A] Trivial: neither involves the type system at all. What we are seeing is a runtime check (not type check) correctly applied, or made unnecessary by conditional code. And, obviously we can take the same line for the "dynamic type checking" -- i.e. that no type checking is involved. B] More interesting, we could extend Java's type system with a NotZero numeric type (or rather, about half a dozen such), and decree that 1 / x was only legal if x : NotZero Under that type system, neither of the above would be type legal, assuming x is declared int. Or both would be legal if it was declared NotZero -- but in both cases there'd be a provably unnecessary runtime check. The nearest "dynamic type system" equivalent would be quite happy with x : int. For the first example, the runtime checks would never fire (though they would execute). For the second the runtime "type" might come into play, and if it did, then the assignment of 999999999 would take place /because/ the illegal operation (which can be thought of as casting 0 to NotZero) had been replaced by a specific legal one (throwing an ArithmeticException in this case). C] A different approach would be to type the execution, instead of the value, so we extend Java's type system so that: 1 / x had type (in part) . The first example as a whole then would also have (in part) that type, and the static type system would deem that illegal. The second example, however, would be type-legal. I hope I don't seem to be fudging the issue, but I don't really think this version has a natural "dynamic type system" equivalent -- what could the checker check ? It would see an attempt to throw an exception from a place where that's not legal, but it wouldn't make a lot of sense to replace it with an IllegalExceptionException ;-) D] Another possibility would be a static type checker after the style of [B] but extended so that it recognised the x != 0 guard as implicitly giving x : NonZero. In that case, again, the first example is static type-correct but the second is not. In this case the corresponding "dynamic type system" could, in principle, avoid testing x for zero the second time. I don't know whether that would be worth the effort to implement. In the second example, just as in [B], the reason the program doesn't crash when x == 0 is that the "dynamic type system" has required that the division be replaced with a throw. One could go further (merge [B] and [C], or [C] and [D] perhaps), but I don't think it adds much, and anyway I'm getting a bit bored.... (And also getting sick of putting scare quotes around "dynamic type system" every time ;-) Personally, of the above, I find [B] most appealing. -- chris From Bulkan at gmail.com Mon Jun 19 21:43:21 2006 From: Bulkan at gmail.com (placid) Date: 19 Jun 2006 18:43:21 -0700 Subject: Newbie Question In-Reply-To: <1150767309.831092.188530@h76g2000cwa.googlegroups.com> References: <1150750938.973049.114780@y41g2000cwy.googlegroups.com> <129e55eahc35f00@corp.supernews.com> <1150753085.332654.283270@f6g2000cwb.googlegroups.com> <1150767309.831092.188530@h76g2000cwa.googlegroups.com> Message-ID: <1150767801.754519.165440@y41g2000cwy.googlegroups.com> BartlebyScrivener wrote: > Saint Malo wrote: > > If the program searches for blue, i just want it to print blue > > Huh? Tell it to print whatever you want. > > for line in file: > if 'blue' in line: > print 'blue' > > for line in file: > if 'brown' in line: > print 'brown' > > for line in file: > if 'red' in line: > print 'weasels rip my flesh' wow Dude, this is not efficient at all! You only need to read the file once not as many times as there are words in your looking for in the lines of the file From meyer at mesw.de Thu Jun 15 19:35:09 2006 From: meyer at mesw.de (meyer at mesw.de) Date: 15 Jun 2006 16:35:09 -0700 Subject: Which compiler will Python 2.5 / Windows (Intel) be built with? In-Reply-To: References: <1150367139.495114.148550@g10g2000cwb.googlegroups.com> <44917535$1@nntp0.pdx.net> <1150391891.130185.4640@f6g2000cwb.googlegroups.com> <4491b9e1$1@nntp0.pdx.net> <1150406005.948538.188950@h76g2000cwa.googlegroups.com> <4491d3c0$1@nntp0.pdx.net> <1150410921.201231.277880@c74g2000cwc.googlegroups.com> Message-ID: <1150414509.020482.249110@g10g2000cwb.googlegroups.com> > This is the .NET 11 SDK, I belive it includes the 2003 compiler (*): Last time I checked the .NET SDK they had the C# compiler in there, but not the C++ optimizing 2003 compiler. Might be wrong though.... From martin.witte at gmail.com Fri Jun 16 07:52:32 2006 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 16 Jun 2006 04:52:32 -0700 Subject: Pycrypto In-Reply-To: <1150446904.527285.255170@g10g2000cwb.googlegroups.com> References: <1150446904.527285.255170@g10g2000cwb.googlegroups.com> Message-ID: <1150458752.342042.189650@h76g2000cwa.googlegroups.com> luca72 wrote: > Hello > I have to make an easy operation but reading the pycrypto doc. a never > see AES example > I have to cript this key 'ea523a664dabaa4476d31226a1e3bab0' with the > AES. > Can you help me for make it with pycrypto > > Regards Luca You can do this as follows: py> from Crypto.Cipher import AES py> # key has to be 16, 24 or 32 bytes for AES py> crypt = AES.new('abcdefghijklmnop', AES.MODE_ECB) # we're lucky, the string to encrypt is a multiple of 16 in length py> txt = 'ea523a664dabaa4476d31226a1e3bab0' py> c = crypt.encrypt(txt) py> c 'w\x81\xe3\xdd\x066\x9eY\xc7\xce~O\x9e\xfb\xef\xfa\xb5\x8a\xac\x7f\xca\x9fl{\xe5\xfd6\x80\xe3\x81%\xb9' py> crypt.decrypt(c) 'ea523a664dabaa4476d31226a1e3bab0' see http://www.amk.ca/python/writing/pycrypt for the docs. if you have to encrypt data which has not a multiple of length 16 you have to pad it e.g. with spaces, and then strip the decrypt() result. From alanalan at newsgroup.nospam Thu Jun 1 19:04:10 2006 From: alanalan at newsgroup.nospam (A.M) Date: Thu, 1 Jun 2006 19:04:10 -0400 Subject: Conditional Expressions in Python 2.4 Message-ID: Hi, I am using Python 2.4. I read the PEP 308 at: http://www.python.org/dev/peps/pep-0308/ I tried the statement: a= "Yes" if 1==1 else "No" but the interpreter doesn't accept it. Do we have the conditional expressions in Python 2.4? Thank you, Alan From edgrsprj at ix.netcom.com Wed Jun 14 18:17:43 2006 From: edgrsprj at ix.netcom.com (edgrsprj) Date: Wed, 14 Jun 2006 22:17:43 GMT Subject: Earthquake and Tornado Forecasting Programs June 13, 2006 References: <448eef76$0$30713$ec3e2dad@news.usenetmonster.com> <448EFE0D.3B2D968B@yahoo.com> Message-ID: > > Oh for a newsreader that can eliminate all such ugly excessively > cross-posted articles lacking follow-ups. PLONK thread is the only > remaining answer. > Posted by E.D.G. June 14, 2006 In my opinion, even moderated Internet Newsgroups cannot provide the necessary control for adequately protected scientific communications. I have in mind the development of a sophisticated Web site based Internet Bulletin Board which past experiences indicate to me should work. The Web site running that bulletin board should be of interest to computer programmers around the globe regardless of what programming language they are using. From praveenkumar.117 at gmail.com Thu Jun 29 03:34:28 2006 From: praveenkumar.117 at gmail.com (praveenkumar.117 at gmail.com) Date: 29 Jun 2006 00:34:28 -0700 Subject: Import Issue Message-ID: <1151566468.352032.24560@j72g2000cwa.googlegroups.com> Hi All, What is the difference between import string and from string import * Regards, Praveen From simon at xiano.co.uk Wed Jun 28 10:50:44 2006 From: simon at xiano.co.uk (Bowen) Date: 28 Jun 2006 07:50:44 -0700 Subject: MySQLdb not updating rows In-Reply-To: References: <1151500514.817456.65510@d56g2000cwd.googlegroups.com> Message-ID: <1151506244.690864.252850@d56g2000cwd.googlegroups.com> Thanks for that tip, it's a simple script that I am experimenting on, planning to build a custon gui for my database. It is definately something for me to note in the future. Thanks again. From cowie.rob at gmail.com Fri Jun 9 17:49:44 2006 From: cowie.rob at gmail.com (Rob Cowie) Date: 9 Jun 2006 14:49:44 -0700 Subject: Most elegant way to generate 3-char sequence Message-ID: <1149889784.391965.271570@h76g2000cwa.googlegroups.com> Hi all, I wish to generate a sequence of the form 'aaa', 'aab', aac'.... 'aba', 'abb', 'abc' etc. all the way to 'zzz'. How would you construct a generator to acheive this? A simple, working but somewhat inelegant solution is... alpha = ['a','b','c','d'] #shortened for brevity alpha2 = ['a','b','c','d'] alpha3 = ['a','b','c','d'] def generator(): for char in alpha: for char2 in alpha2: for char3 in alpha3: yield char + char2 + char3 x = generate() x.next() # etc, etc, etc, From sreeram at tachyontech.net Sun Jun 11 15:57:37 2006 From: sreeram at tachyontech.net (K.S.Sreeram) Date: Mon, 12 Jun 2006 01:27:37 +0530 Subject: math.pow(x,y) In-Reply-To: References: <1150049976.916474.186580@j55g2000cwa.googlegroups.com> Message-ID: <448C75B1.4080307@tachyontech.net> Raymond L. Buvel wrote: > I just tried this and it is taking an extremely long time even on a fast > machine with 4 Gb of RAM. Killed it after a couple of minutes. You probably tried printing the value. a = 34564323**456356 (takes just 28 seconds) whereas b = str(a) takes forever! Regards Sreeram -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 260 bytes Desc: OpenPGP digital signature URL: From bearophileHUGS at lycos.com Fri Jun 9 10:23:41 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 9 Jun 2006 07:23:41 -0700 Subject: removing dictionary key-pair In-Reply-To: <128j0r7tla1qi12@corp.supernews.com> References: <128j0r7tla1qi12@corp.supernews.com> Message-ID: <1149863021.752799.249680@y43g2000cwc.googlegroups.com> JD>I try to remove a dictionary key-pair (remove an entry), >>> d = {1:2, 3:4} >>> d {1: 2, 3: 4} >>> del d[1] >>> d {3: 4} Bye, bearophile From johnjsal at NOSPAMgmail.com Tue Jun 13 14:27:28 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 13 Jun 2006 18:27:28 GMT Subject: wxpython: how do i write this without the id parameter? In-Reply-To: <448e430d$1@nntp0.pdx.net> References: <448e430d$1@nntp0.pdx.net> Message-ID: Scott David Daniels wrote: > class InputForm(wx.Frame): > def __init__(self, parent=None, id=-1, title=__file__): Also, is there a way to define parent and id with defaults, but not title? Is it good to change the order around to do this? From python.list at tim.thechases.com Wed Jun 7 12:11:45 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 07 Jun 2006 11:11:45 -0500 Subject: help to install MySQL-python module In-Reply-To: References: <1149687465.4486d6a9e5c5e@webmail.unical.it> Message-ID: <4486FAC1.9040505@tim.thechases.com> >> error: invalid Python installation: unable to open >> /usr/local/lib/python2.3/config/Makefile (No such file or >> directory) > > Ernesto, Where did the install put Python - the obvious > situation is that the Makefile is not where the install of > MySQL-Python thinks it is. Some binary distros of Python omit this piece of the package. I had a similar problem with the installation of WebStack on Debian Linux. Alexis Roda's solution of apt-get install python2.3-dev got matters working for me. Likely there's a "python development" package you can install for your version of Python that should provide this header. You omit details regarding what platform you're using, though you hint at something *nix-ish given the path (/usr/local/lib/python...). If it's Debian, the same solution may work for you too. -tkc From bignose+hates-spam at benfinney.id.au Wed Jun 14 19:58:12 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 15 Jun 2006 09:58:12 +1000 Subject: Bundling an application with third-party modules References: <1150285229.237626.36440@y41g2000cwy.googlegroups.com> Message-ID: <87ver3mgrv.fsf@benfinney.id.au> "utabintarbo" writes: > 1. py2exe/csFreeze-type thing. This would even relieve the customer > of installing python Not really what I need. I only want to have installation control over *some* of the modules, and leave Python and other dependencies up to the administrator to manage. The application consists of many programs, so bundling Python-and-many-modules with *each* one makes no sense. > 2. An Installshield-type installer can place files (essentially) > wherever you want them That's a large part of my question. How can I lay out these modules sensibly during installation so they'll be easily available to, but specific to, my application? -- \ "Know what I hate most? Rhetorical questions." -- Henry N. Camp | `\ | _o__) | Ben Finney From pink at odahoda.de Wed Jun 28 10:15:38 2006 From: pink at odahoda.de (Benjamin Niemann) Date: Wed, 28 Jun 2006 16:15:38 +0200 Subject: MySQLdb not updating rows References: <1151500514.817456.65510@d56g2000cwd.googlegroups.com> Message-ID: Bowen wrote: > import md5 > import string > import MySQLdb > > tc = raw_input("Teacher Code: ") > p = raw_input("New Password: ") > > print tc > hash = md5.new() > hash.update(p) > print p > print hash.hexdigest() > h = hash.hexdigest() > > boo = raw_input("Sure you want to update password with above details? Y > or N: ") > > if boo == 'y': > db = MySQLdb.connect("copweb2", "******", "******", "*******") > cursor = db.cursor() > if cursor.execute("UPDATE teachers SET password = '%s' WHERE > teacher_code = '%s'" % (h, tc)): > print "Done" > else: > print "Error" > else: > print "cancelled" > > cursor.close() > db.close() > > > This code doesn't seem to update my database, anyone any idea why? Is > it me being stupid? It doesn't kick out an error at all. Another side note: don't build your queries using (dumb) string formatting, let the MySQLdb module do it for you. More specifically use: cursor.execute( "UPDATE teachers SET password = %s WHERE teacher_code = %s", (h, tc) ) instead of cursor.execute( "UPDATE teachers SET password = '%s' WHERE teacher_code = '%s'" % (h, tc) ) The former form takes care of quoting and escaping, your version did not escape potentially harmful characters in tc, resulting in a possibly opened door for SQL injection attacks. -- Benjamin Niemann Email: pink at odahoda dot de WWW: http://pink.odahoda.de/ From kent at kentsjohnson.com Wed Jun 21 21:42:14 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Wed, 21 Jun 2006 21:42:14 -0400 Subject: Standard Yes / No Windows Dialog box creation In-Reply-To: <1150581640.385143.83410@y41g2000cwy.googlegroups.com> References: <1150581640.385143.83410@y41g2000cwy.googlegroups.com> Message-ID: <4499f413$1_2@newspeer2.tds.net> flaus.a at wanadoo.fr wrote: > I found a way to create "Open File" or "Open Folder" windows dialog > boxes, but not to create an easier Yes / No dialog box... > Maybe someone has a solution for this? Maybe you would like EasyGui http://www.ferg.org/easygui/ Kent From cvanarsdall at mvista.com Tue Jun 27 16:51:07 2006 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Tue, 27 Jun 2006 13:51:07 -0700 Subject: to py or not to py ? In-Reply-To: References: Message-ID: <44A19A3B.7010503@mvista.com> Serge Orlov wrote: > On 6/27/06, Chandrashekhar kaushik wrote: > >> HI all >> I have the following prob. >> I am to write a parallel vis application . >> I wud have by default used C++ for the same but somehow >> thought if py cud help me .. >> It does as in many things that i would otherwise have written down >> already exists ... ( like built in classes for sockets , threading etc ) >> >> I would be doin the following type of tasks .. >> >> 1. sending data across the network >> the data is going to be huge >> >> 2. once data has been sent i will run some vis >> algos parallely on them and get the results >> >> now one thing that i wud req. is serializing my data structures so that >> they can be sent across the net. >> >> pyton does allow this using cPickle , but it bloats the data like anythin >> !!! >> for example a class containing 2 integers which i expect will be 8 bytes >> long .. >> cPickle.dumps returns a string thats 86 bytes wide !!!! ( this is the binary >> version protocol 1 ) >> >> anyway to improve serialization ?? >> > > Do it yourself using struct module. > > >> also is it actually a good idea to write high perf applications in python ? >> > > Take a look at Mercurial sources. > It's a high performance python application. Or watch Bryan > O'Sullivan's Mercurial presentation > he > talks briefly how they made it work fast. > > But writing high performance application in python requires > self-discipline and attention to details, looking at the way you spell > I think it will be a challenge ;) > One more comment would be that running parallel applications on python can be problematic because of the way python does threading (and i'm not presently aware of other threading libraries). Parallelizing in python doesn't do much good unless you spend a lot of time blocking on IO because of the GIL. -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From webraviteja at gmail.com Fri Jun 2 17:22:44 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 2 Jun 2006 14:22:44 -0700 Subject: New to Python: Do we have the concept of Hash in Python? In-Reply-To: <%aIfg.3027$EF1.232063@news20.bellglobal.com> References: <%aIfg.3027$EF1.232063@news20.bellglobal.com> Message-ID: <1149283364.026729.155370@h76g2000cwa.googlegroups.com> A.M wrote: > "Fredrik Lundh" wrote in message > news:mailman.6424.1149190330.27775.python-list at python.org... > > A.M wrote: > > > >> This is my 1st day that I am seriously diving into Python and I have to > >> finish this application by the end of today. Maybe it wasn't a good idea > >> to choose the language that I don't know when I have to deliver my work > >> in such short time. > > > > are your boss aware of this ? > > > > > > > > > > are your boss aware of this ? > > In fact my boss is quite impressed with my progress so far. > > > > I am a little confused about the fact that you got frustrated with my posts > today. I am not asking for a big tutorial or > > deepest philosophy behind the concepts. The answer to this post could be > just the word "Dictionary" which is 10 key stroke ! > > Does this hurt? IRC is a better place to request 10 key stroke answers. And it is faster for you to get answers there too. Usenet is archived these days and it adds value to all of us that it is filled with discussions of questions that are more intellectual than those which can be looked up at a glance at the documentation. From sudheerb at netapp.com Thu Jun 8 07:51:11 2006 From: sudheerb at netapp.com (Sudheer Gupta) Date: Thu, 08 Jun 2006 07:51:11 -0400 Subject: Using C struct in Python In-Reply-To: References: Message-ID: <44880F2F.5070205@netapp.com> Dennis Lee Bieber wrote: > On Wed, 07 Jun 2006 17:35:58 -0400, Sudheer Gupta > declaimed the following in comp.lang.python: > > > >> print cp >> print cp.next >> >> There is a typo in this. Second statement was suppose to be cp = cp.next. I corrected it latter with the second email. > What happens if you keep adding > print cp.next > statements (say 50 or more of them). > > Your error message might indicate that you ran out of "cp.next" > /values/ (ie: the last valid item in the chain of cp's does not have a > next link at all, rather than a next link that contains null) > From mirandacascade at yahoo.com Mon Jun 19 08:23:08 2006 From: mirandacascade at yahoo.com (mirandacascade at yahoo.com) Date: 19 Jun 2006 05:23:08 -0700 Subject: Amara installation Message-ID: <1150719788.482305.9560@r2g2000cwb.googlegroups.com> O/S WinXP Home Vsn of Python: 2.4 Wish to install Amara. Using amara-allinone-1.0.win32-py2.4.exe (2965KB) Forder structure before installation: c: python24 DLLs Doc Include Lib site-packages [previously installed stuff] libs scripts tcl tools When I run install, the install program indicates: Python directory: c:\python24\ Installation directory: c:\python24\lib\site-packages\ After install, folder structrue is: Vsn of Python: 2.4 Wish to install Amara. Using amara-allinone-1.0.win32-py2.4.exe (2965KB) Forder structure after installation: c: python24 DLLs Doc Include Lib site-packages [previously installed stuff] libs python24 <<<-- lib <<<-- site-packages <<<-- new amara files/folders appear amara <<<-- to be installed here ft <<<-- scripts <<<-- share <<<-- scripts tcl tools I was expecting the new amara files/folders to be installed within the existing c:\python24\ folder structure...wasn't expecting it to create a new ...\python24\ folder within the parent ...\python24\ folder. My questions: 1) has anyone else observed this when installing? 2) should I move the newly installed files/folders into the previously-existing folder structure? as long as I don't remove files/folders, is there any risk of causing a previously installed site package that worked to no longer work? From DustanGroups at gmail.com Thu Jun 8 16:32:36 2006 From: DustanGroups at gmail.com (Dustan) Date: 8 Jun 2006 13:32:36 -0700 Subject: Importing again and again In-Reply-To: <1149796920.757115.290840@h76g2000cwa.googlegroups.com> References: <1149796920.757115.290840@h76g2000cwa.googlegroups.com> Message-ID: <1149798756.111737.204770@h76g2000cwa.googlegroups.com> abcd wrote: > If I have code which imports a module over and over again...say each > time a function is called, does that cause Python to actually re-import > it...or will it skip it once the module has been imported?? > > for example: > > def foo(): > import bar > bar.printStuff() > > foo() > foo() > foo() > foo() > > ...will that re-import bar 4 times...or just import it once? is this a > big performance hit? > > thanks I don't really know, but I do know that the right way to re-import a module is: reload(bar) From dieter at handshake.de Sun Jun 25 16:30:31 2006 From: dieter at handshake.de (Dieter Maurer) Date: 25 Jun 2006 22:30:31 +0200 Subject: Program slowing down with greater memory use References: Message-ID: Dan Stromberg writes on Thu, 22 Jun 2006 23:36:00 GMT: > I have two different python programs that are slowing down quite a bit as > their memory use goes up. I have seen this too with Zope. I do not know where it comes from -- maybe from degraded locality. Dieter From irmen.NOSPAM at xs4all.nl Wed Jun 28 19:48:09 2006 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Thu, 29 Jun 2006 01:48:09 +0200 Subject: socket close problems with Python 2.5b1 Message-ID: <44a3153d$0$31638$e4fe514c@news.xs4all.nl> I'm having some troubles with closing sockets using Python 2.5b1 Simply closing a client socket (on the server side) doesn't seem to actually shutdown the socket anymore. A connected client simply hangs, while with older Pythons it aborted with a socket close error. Can someone confirm this for me? Or shed some light on it? More info and a test program is available in the following but report: http://sourceforge.net/tracker/index.php?func=detail&aid=1513223&group_id=5470&atid=105470 Thanks, --Irmen. From find at my.address.elsewhere Wed Jun 28 10:53:01 2006 From: find at my.address.elsewhere (Matthias Blume) Date: Wed, 28 Jun 2006 09:53:01 -0500 Subject: What is Expressiveness in a Computer Language References: <7zy7vt1mz2.fsf@app-3.diku.dk> <1151384511.223582.305760@m73g2000cwd.googlegroups.com> <4gdkmiF1ldalhU3@individual.net> <4gfcclF1mpbg7U1@individual.net> <6gwog.488405$xt.80841@fe3.news.blueyonder.co.uk> <4gfiufF1mg6h9U1@individual.net> Message-ID: Pascal Costanza writes: > Whether you consider something you cannot do with statically typed > languages a bad idea or not is irrelevant. You were asking for things > that you cannot do with statically typed languages. The whole point of static type systems is to make sure that there are things that one cannot do. So the fact that there are such things are not an argument per se against static types. [ ... ] > Beyond that, I am convinced that the ability to update a running > system without the need to shut it down can be an important asset. And I am convinced that updating a running system in the style of, e.g., Erlang, can be statically typed. >> Note that prohibiting directly self-modifying code does not prevent a >> program from specifying another program to *replace* it. > > ...and this creates problems with moving data from one version of a > program to the next. How does this "create" such a problem? The problem is there in either approach. In fact, I believe that the best chance we have of addressing the problem is by adopting the "replace the code" model along with a "translate the data where necessary at the time of replacement". Translating the data, i.e., re-establishing the invariants expected by the updated/replaced code, seems much harder (to me) in the case of self-modifying code. Erlang got this one right. From fredrik at pythonware.com Tue Jun 20 04:27:41 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 20 Jun 2006 10:27:41 +0200 Subject: difference between import from mod.func() and x=mod.func() References: <4497ACB9.4020905@gmail.com> Message-ID: Hari Sekhon wrote: > What is the difference in terms of efficiency and speed between > > from os import path > > and > > import os > path=os.path the only difference is that the former only sets the "path" variable, while the latter leaves both "os" and "path" in your namespace. > I would think that the import from would be better, just curious since I > read somewhere on the web, some guy's code tutorial where he did the > latter and said it was for efficiency/speed. sounds like "uneducated premature optimization" to me. From jeethu at tachyontech.net Mon Jun 26 15:47:29 2006 From: jeethu at tachyontech.net (Jeethu Rao) Date: Tue, 27 Jun 2006 01:17:29 +0530 Subject: PEP thought experiment: Unix style exec for function/method calls In-Reply-To: <449e72ec$0$3530$ed2619ec@ptn-nntp-reader01.plus.net> References: <449e72ec$0$3530$ed2619ec@ptn-nntp-reader01.plus.net> Message-ID: <44A039D1.50001@tachyontech.net> This reminds me of an silly little optimization I used to use all the times when coding in assembler on PIC MCUs. A call followed by a return can be turned into jump. Saves one instruction and one level on the call stack. I think most optimizing compilers already do something of this sort, at least in the embedded world :) Jeethu Rao Michael wrote: > Hi, > > > [ I'm calling this PEP thought experiment because I'm discussing language > ideas for python which if implemented would probably be quite powerful > and useful, but the increased risk of obfuscation when the ideas are > used outside my expected/desired problem domain probably massively > outweigh the benefits. (if you're wondering why, it's akin to adding > a structured goto with context) > > However I think as a thought experiment it's quite useful, since any > language feature can be implemented in different ways, and I'm wondering > if anyone's tried this, or if it's come up before (I can't find either > if they have...). ] > > I'm having difficulty finding any previous discussion on this -- I > keep finding people either having problems calling os.exec(lepev), or > with using python's exec statement. Neither of which I mean here. > > Just for a moment, let's just take one definition for one of the > os.exec* commands: > > execv(...) > execv(path, args) > > Execute an executable path with arguments, replacing current > process. > path: path of executable file > args: tuple or list of strings > > Also: Note that execv inherits the system environment. > > Suppose we could do the same for a python function - suppose we could > call the python function but either /without/ creating a new stack > frame or /replacing/ the current stack frame with the new one. > > Anyway, I've been thinking recently that the same capability in python > would be useful. However, almost any possible language feature: > * Has probably already been discussed to death in the past > * There's often a nice idiom working around the lack of said feature. > > So I'm more on an exploratory forage than asking for a language change > here ;) > > Since os.exec* exists and "exec" already exists in python, I need to > differentiate what I mean by a unix style exec from python. So for > convenience I'll call it "cexe". > > Now, suppose I have: > ---------- > def set_name(): > name = raw_input("Enter your name! > ") > cexe greet() > > def greet(): > print "hello", name > > cexe set_name() > print "We don't reach here" > ---------- > > This would execute, ask for the user's name, say hello to them and then > exit - not reaching the final print "We don't reach here" statement. > > Let's ignore for the moment that this example sucks (and is a good example > of the danger of this as a language feature), what I want to do here is > use this to explain the meaning of "cexe". > > There's two cases to consider: > cexe some_func_noargs() > > This transfers execution to the function that would normally be called > if I simply called without using "cexe" some_func_noargs() . However, > unlike a function call, we're /replacing/ the current thread of > execution with the thread of execution in some_func_noargs(), rather > than stacking the current location, in order to come back to later. > > ie, in the above this could also be viewed as "call without creating a > new return point" or "call without bothering to create a new stack > frame". > > It's this last point why in the above example "name" leaks between the > two function calls - due to it being used as a cexe call. > > Case 2: > given... > def some_func_withargs(colour,tone, *listopts, **dictopts) > > consider... > cexe some_func_withargs(foo,bar, *argv, **argd) > > This would be much the same as the previous case, except in the new > execution point, the name colour & tone map to the values foo & bar had > in the original context, whilst listopts and dictopts map the values > that argv & argd had in the original content) > > One consequence here though is that in actual practice the final print > statement of the code above never actually gets executed. (Much like if > that was inside a function, writing something after "return foo", wouldn't > be executed) > > The reason I'm curious here about previous discussion is because > conceptually there's obviously other semantics you can apply - such as > the current stack frame is /replaced/ by the new stack frame. This is > perhaps a more accurate mapping to the Unix exec call. > > If that was the case, it would mean that locals would not "leak" between > functions (which is desirable), and our example above could be rewritten > as follows: > > ---------- > def get_and_use_value_from_user(tag, callforward): > somevalue = raw_input(tag) > cexe callforward(name) > > def greet(name): > print "hello", name > > cexe get_and_use_value_from_user("Enter your name! > ", greet) > print "We don't reach here" > ---------- > > OK, so this probably seems pretty pointless to many people, but I'm > curious about improving the tools to deal with state machines. Often > people use switch statements in other languages to deal with them, and > for certain classes of state machines you can use replace them with > generators. But that's not appropriate for everything... > > My particular thought that started all this off actually stems from this: > > Essentially by doing a cexe we're actually creating a composite function > out of disparate functions (perhaps shared or not shared local context). > ie ... > ---------- > def count(): > print "Counting to 3!" > cexe one() > > def one(): > print "one!" > cexe two() > > def two(): > print "two!" > cexe three() > > def three(): > print "three!" > > count() # Note I'm not doing cexe count() here > ---------- > ... essentially dynamically constructs an execution context similar to a > single function, ie the above collapses to something like: > > ---------- > def count(): > print "Counting to 3!" > print "one!" > print "two!" > print "three!" > > count() # Note I'm not doing cexe count() here > ---------- > It's this recognition that made me wonder this: > > This works well for state machines, and generators are a nice model for > dealing with resumable things (and a state machine can be viewed as a > resumable "thing"). > > Now suppose we take all that one stage further and provide said > composite generator, with some additional context in the way we do > with Kamaelia - cf http://kamaelia.sf.net/MiniAxon/ , we could > potentially do this: > > (choosing something relatively substantial to show I'm not just > being whimsical, and to provide somthing perhaps more "real") > > class TCP_StateMachine(Axon.Component.component): > def CLOSED(self): > if not self.anyReady(): yield self.pause() > event = self.recv("inbox") > if "appl passive open" == event.type: cexe self.LISTEN() > if "active open" == event.type: > self.send(SYN(event.payload), "network") > cexe self.SYN_SENT() > > def LISTEN(self): > if not self.anyReady(): yield self.pause() > event = self.recv("inbox") > if "recv syn" == event.type: > self.send( , "network") > cexe self.SYN_RCVD() > if "appl send data" == event.type: > self.send( , "network") > cexe self.SYN_SENT() > > def SYN_RCVD(self): > if not self.anyReady(): yield self.pause() > event = self.recv("inbox") > if "recv rst" == event.type: cexe self.LISTEN() > if "recv ack" == event.type: cexe self.ESTABLISHED() > if "appl close" == event.type: > self.send(FIN(event.payload), "network") > cexe self.FIN_WAIT1() > > def SYN_SENT(self): > if not self.anyReady(): yield self.pause() > event = self.recv("inbox") > if "appl close" == event.type: cexe self.CLOSED() > if "timeout" == event.type: cexe self.CLOSED() > if "recv syn-ack" == event.type: > self.send(ACK(event.payload), "network") > cexe self.ESTABLISHED() > > def ESTABLISHED(self): > # more complex than others, so skipped, has its own data transfer > # state etc, so would make more sense to model as a subcomponent. > > def FIN_WAIT_1(self): > if not self.anyReady(): yield self.pause() > event = self.recv("inbox") > if "recv ack" == event.type: cexe self.FIN_WAIT_2() > > if "recv fin" == event.type: > self.send(ACK(event.payload), "network") > cexe self.CLOSING() > > if "recv fin, ack" == event.type: > self.send(ACK(event.payload), "network") > cexe self.TIME_WAIT() > > def FIN_WAIT_2(self): > if not self.anyReady(): yield self.pause() > event = self.recv("inbox") > if "recv fin" == event.type: > self.send(ACK(event.payload), "network") > cexe self.TIME_WAIT() > > def CLOSING(self): > if not self.anyReady(): yield self.pause() > event = self.recv("inbox") > if "recv ack" == event.type: cexe self.TIME_WAIT() > > def TIME_WAIT(self): > if not self.anyReady(): yield self.pause() > event = self.recv("inbox") > if "timeout 2MSL" == event.type: cexe self.CLOSED() > > Now obviously that's not particularly pretty, but the clear definition > of states as methods, and clear transitions between states via the cexe > calls, is relatively easy to follow through. ie it's fairly clear it's > implementing the standard TCP state machine. > > (Incidentally if you're wondering what relevance this has outside of > just TCP, this sort of thing could be useful in games for modelling > complex behaviours) > > What is less clear about this is that I'm working on the assumption that > as well as the language change making "cexe" work, is that this also > allows the above set of methods to be treated as if it's one large > generator that's split over multiple function definitions. This is > conceptually very similar to the idea that cexe would effectively > "join" functions together, as alluded to above. > > This has a number of downsides for the main part of the language, so > I wouldn't suggest that these changes actually happen - consider it a > thought experiment if you like. (I think the single function/no wrapping > of yield IS actually a good thing) > > However, I feel the above example is quite a compelling example of how > a unix style exec for python method calls could be useful, especially > when combined with generators. (note this is a thought experiment ;) > > It also struck me that any sufficiently interesting idea is likely to > have already been implemented, though perhaps not looking quite like the > above, so I thought I'd ask the questions: > > * Has anyone tried this sort of thing? > > * Has anyone tried simply not creating a new stack frame when doing > a function call in python? (or perhaps replacing the current one with > a new one) > > * Has anyone else tried modelling the unix system exec function in > python? If so what did you find? > > * Since I can't find anything in the archives, I'm presuming my > searching abilities are bust today - can anyone suggest any better > search terms or threads to look at? > > * Am I mad? :) > > BTW, I'm aware that this has similarities to call with continuation, > and that you can use statesaver.c & generators to achieve something > vaguely similar to continuations, but I'm more after this specific > approach, rather than that general approach. (After all, even ruby > notes that their most common use for call/cc is to obfuscate code - > often accidentally - and I'm not particularly interested in that :) > > Whereas the unix style exec is well understood by many people, and > when it's appropriate can be extremely useful. My suspicion is that > my ideasabove actually maps to a common idiom, but I'm curious to > find that commonidiom. > > I'm fairly certain something like this could be implemented using > greenlets, and also fairly certain that Stackless has been down this > route in the past, but I'm not able to find something like this exec > style call there. (Which is after all more constrained than your usual > call with continuation approach) > > So, sorry for the length of this, but if anyone has any thoughts, I'd be > very interested. If they don't, I hope it was interesting :) > > Regards, > > > Michael. > > From girish at cse.iitb.ac.in Mon Jun 12 05:34:59 2006 From: girish at cse.iitb.ac.in (Girish Sahani) Date: Mon, 12 Jun 2006 15:04:59 +0530 (IST) Subject: Function to remove elements from a list not working (corrected) In-Reply-To: <1150102280.505268.174420@u72g2000cwu.googlegroups.com> References: <1150102280.505268.174420@u72g2000cwu.googlegroups.com> Message-ID: <43266.10.209.4.2.1150104899.squirrel@10.105.1.3> Thank you Mark....this works too... Btw going slightly off-topic, when i try to run a code like below with around 50 elements (pairs) in l4,python just hangs. Any ideas why this is happening...the data is not that large :(( > > Girish Sahani wrote: >> Hi, >> I am trying to modify a list of pairs (l4) by removing those >> pairs which are not present in a third list called pairList. >> The following is a simplified part of the routine i have written. >> However >> it does not give the correct output. Please help! >> Its possible i have made a trivial mistke since i am a newbie. >> >> def getl5(): >> l5 = [] >> pairList = [[1,2],[3,4],[3,5],[3,6],[9,7],[8,9],[8,7],[7,9],[11,10]] >> l4 = >> [[4,2],[4,7],[4,10],[4,12],[9,2],[9,7],[9,10],[9,12],[11,2],[11,7]] >> for pair in l4: >> if pair not in pairList: >> l4.remove(pair) >> print "l4 is",l4 >> >> The output given is: >> l4 is [[4, 7], [4, 12], [9, 7], [9, 12], [11, 7]] > > It is better to iterate over a copy, e.g. like this: > > pairList = [[1,2],[3,4],[3,5],[3,6],[9,7],[8,9],[8,7],[7,9],[11,10]] > l4 = > [[4,2],[4,7],[4,10],[4,12],[9,2],[9,7],[9,10],[9,12],[11,2],[11,7]] > for pair in l4[:]: > if pair not in pairList: > l4.remove(pair) > print "l4 is",l4 > > -- > http://mail.python.org/mailman/listinfo/python-list > From tim.leeuwvander at nl.unisys.com Sat Jun 24 05:35:48 2006 From: tim.leeuwvander at nl.unisys.com (Tim N. van der Leeuw) Date: 24 Jun 2006 02:35:48 -0700 Subject: PyGTK and Py2Exe troubles Message-ID: <1151141748.172141.285890@p79g2000cwp.googlegroups.com> I tried to create a windows executable of a pygtk program. My first attempt worked, kinda, except that no themes were applied and no readable fonts were found by pango; so all letters where just empty squares. But the program worked. I looked up some docs, found the following recipe on the PyGTK Wiki site: http://starship.python.net/crew/theller/moin.cgi/Py2exeAndPyGTK I followed those instructions to convert my setup.py file; everything still worked the same as before. Then I copied GTK's 'etc', 'share' and 'lib' directories into the directory of my executable, as per instructions. That's when it all went wrong... (See errors below) Apart from the errors below, there were also multiple windows error-reporting popup boxes telling me that the program crashed; do I want to send info to Microsoft. If anyone can help me getting a PyGTK GUI running as standalone executable, that would be very much appreciated! I know it's possible, BitTorrent had a PyGTK GUI on windows. (I'm not that attached to PyGTK as such, but I'm somewhat familiar with it and it has a good multi-column TreeView widget with inline editing. That's what I need for my program, and wxPython didn't seem to have a very workable solution for multicolumn treeviews...) $ ./CBGui.exe (CBGui.exe:1320): GLib-GObject-CRITICAL **: gtype.c:2215: initialization assertion failed, use g_type_init() prior to this function (CBGui.exe:1320): GLib-GObject-CRITICAL **: gtype.c:2255: initialization assertion failed, use g_type_init() prior to this function (CBGui.exe:1320): GLib-GObject-CRITICAL **: gtype.c:2215: initialization assertion failed, use g_type_init() prior to this function (CBGui.exe:1320): GLib-GObject-CRITICAL **: gtype.c:2255: initialization assertion failed, use g_type_init() prior to this function (CBGui.exe:1320): GLib-GObject-CRITICAL **: gtype.c:2215: initialization assertion failed, use g_type_init() prior to this function (CBGui.exe:1320): GLib-GObject-CRITICAL **: gtype.c:2215: initialization assertion failed, use g_type_init() prior to this function (CBGui.exe:1320): Gdk-CRITICAL **: gdk_window_new_internal: assertion `GDK_IS_WINDOW (parent)' failed (CBGui.exe:1320): GLib-GObject-CRITICAL **: g_object_new: assertion `G_TYPE_IS_OBJECT (object_type)' failed (CBGui.exe:1320): Gdk-CRITICAL **: _gdk_window_destroy_hierarchy: assertion `window != NULL' failed (CBGui.exe:1320): GLib-GObject-CRITICAL **: g_object_unref: assertion `G_IS_OBJECT (object)' failed (CBGui.exe:916): GLib-GObject-CRITICAL **: gtype.c:2215: initialization assertion failed, use g_type_init() prior to this function (CBGui.exe:916): GLib-GObject-CRITICAL **: gtype.c:2255: initialization assertion failed, use g_type_init() prior to this function (CBGui.exe:916): GLib-GObject-CRITICAL **: gtype.c:2215: initialization assertion failed, use g_type_init() prior to this function (CBGui.exe:916): GLib-GObject-CRITICAL **: gtype.c:2255: initialization assertion failed, use g_type_init() prior to this function (CBGui.exe:916): GLib-GObject-CRITICAL **: gtype.c:2215: initialization assertion failed, use g_type_init() prior to this function (CBGui.exe:916): GLib-GObject-CRITICAL **: gtype.c:2215: initialization assertion failed, use g_type_init() prior to this function (CBGui.exe:916): Gdk-CRITICAL **: gdk_window_new_internal: assertion `GDK_IS_WINDOW (parent)' failed (CBGui.exe:916): GLib-GObject-CRITICAL **: g_object_new: assertion `G_TYPE_IS_OBJECT (object_type)' failed (CBGui.exe:916): Gdk-CRITICAL **: _gdk_window_destroy_hierarchy: assertion `window != NULL' failed (CBGui.exe:916): GLib-GObject-CRITICAL **: g_object_unref: assertion `G_IS_OBJECT (object)' failed (CBGui.exe:5020): GLib-GObject-CRITICAL **: gtype.c:2215: initialization assertion failed, use g_type_init() prior to this function (CBGui.exe:5020): GLib-GObject-CRITICAL **: gtype.c:2255: initialization assertion failed, use g_type_init() prior to this function (CBGui.exe:5020): GLib-GObject-CRITICAL **: gtype.c:2215: initialization assertion failed, use g_type_init() prior to this function (CBGui.exe:5020): GLib-GObject-CRITICAL **: gtype.c:2255: initialization assertion failed, use g_type_init() prior to this function (CBGui.exe:5020): GLib-GObject-CRITICAL **: gtype.c:2215: initialization assertion failed, use g_type_init() prior to this function (CBGui.exe:5020): GLib-GObject-CRITICAL **: gtype.c:2215: initialization assertion failed, use g_type_init() prior to this function (CBGui.exe:5020): Gdk-CRITICAL **: gdk_window_new_internal: assertion `GDK_IS_WINDOW (parent)' failed (CBGui.exe:5020): GLib-GObject-CRITICAL **: g_object_new: assertion `G_TYPE_IS_OBJECT (object_type)' failed (CBGui.exe:5020): Gdk-CRITICAL **: _gdk_window_destroy_hierarchy: assertion `window != NULL' failed (CBGui.exe:5020): GLib-GObject-CRITICAL **: g_object_unref: assertion `G_IS_OBJECT (object)' failed (CBGui.exe:5936): GLib-GObject-CRITICAL **: gtype.c:2215: initialization assertion failed, use g_type_init() prior to this function (CBGui.exe:5936): GLib-GObject-CRITICAL **: gtype.c:2255: initialization assertion failed, use g_type_init() prior to this function (CBGui.exe:5936): GLib-GObject-CRITICAL **: gtype.c:2215: initialization assertion failed, use g_type_init() prior to this function (CBGui.exe:5936): GLib-GObject-CRITICAL **: gtype.c:2255: initialization assertion failed, use g_type_init() prior to this function (CBGui.exe:5936): GLib-GObject-CRITICAL **: gtype.c:2215: initialization assertion failed, use g_type_init() prior to this function (CBGui.exe:5936): GLib-GObject-CRITICAL **: gtype.c:2215: initialization assertion failed, use g_type_init() prior to this function (CBGui.exe:5936): Gdk-CRITICAL **: gdk_window_new_internal: assertion `GDK_IS_WINDOW (parent)' failed (CBGui.exe:5936): GLib-GObject-CRITICAL **: g_object_new: assertion `G_TYPE_IS_OBJECT (object_type)' failed (CBGui.exe:5936): Gdk-CRITICAL **: _gdk_window_destroy_hierarchy: assertion `window != NULL' failed (CBGui.exe:5936): GLib-GObject-CRITICAL **: g_object_unref: assertion `G_IS_OBJECT (object)' failed (CBGui.exe:4552): GLib-GObject-CRITICAL **: gtype.c:2215: initialization assertion failed, use g_type_init() prior to this function (CBGui.exe:4552): GLib-GObject-CRITICAL **: gtype.c:2255: initialization assertion failed, use g_type_init() prior to this function (CBGui.exe:4552): GLib-GObject-CRITICAL **: gtype.c:2215: initialization assertion failed, use g_type_init() prior to this function (CBGui.exe:4552): GLib-GObject-CRITICAL **: gtype.c:2255: initialization assertion failed, use g_type_init() prior to this function (CBGui.exe:4552): GLib-GObject-CRITICAL **: gtype.c:2215: initialization assertion failed, use g_type_init() prior to this function (CBGui.exe:4552): GLib-GObject-CRITICAL **: gtype.c:2215: initialization assertion failed, use g_type_init() prior to this function (CBGui.exe:4552): Gdk-CRITICAL **: gdk_window_new_internal: assertion `GDK_IS_WINDOW (parent)' failed (CBGui.exe:4552): GLib-GObject-CRITICAL **: g_object_new: assertion `G_TYPE_IS_OBJECT (object_type)' failed (CBGui.exe:4552): Gdk-CRITICAL **: _gdk_window_destroy_hierarchy: assertion `window != NULL' failed (CBGui.exe:4552): GLib-GObject-CRITICAL **: g_object_unref: assertion `G_IS_OBJECT (object)' failed (CBGui.exe:4428): GLib-GObject-CRITICAL **: gtype.c:2215: initialization assertion failed, use g_type_init() prior to this function (CBGui.exe:4428): GLib-GObject-CRITICAL **: gtype.c:2255: initialization assertion failed, use g_type_init() prior to this function (CBGui.exe:4428): GLib-GObject-CRITICAL **: gtype.c:2215: initialization assertion failed, use g_type_init() prior to this function (CBGui.exe:4428): GLib-GObject-CRITICAL **: gtype.c:2255: initialization assertion failed, use g_type_init() prior to this function (CBGui.exe:4428): GLib-GObject-CRITICAL **: gtype.c:2215: initialization assertion failed, use g_type_init() prior to this function (CBGui.exe:4428): GLib-GObject-CRITICAL **: gtype.c:2215: initialization assertion failed, use g_type_init() prior to this function (CBGui.exe:4428): Gdk-CRITICAL **: gdk_window_new_internal: assertion `GDK_IS_WINDOW (parent)' failed (CBGui.exe:4428): GLib-GObject-CRITICAL **: g_object_new: assertion `G_TYPE_IS_OBJECT (object_type)' failed (CBGui.exe:4428): Gdk-CRITICAL **: _gdk_window_destroy_hierarchy: assertion `window != NULL' failed (CBGui.exe:4428): GLib-GObject-CRITICAL **: g_object_unref: assertion `G_IS_OBJECT (object)' failed From ullrich at math.okstate.edu Thu Jun 1 06:16:33 2006 From: ullrich at math.okstate.edu (David C. Ullrich) Date: Thu, 01 Jun 2006 05:16:33 -0500 Subject: shuffling elements of a list References: <1149045499.212967.13120@f6g2000cwb.googlegroups.com> <1149051212.139046.155340@c74g2000cwc.googlegroups.com> <1149105576.321676.131600@j55g2000cwa.googlegroups.com> Message-ID: <69ft72516amvri3up8fop5rf543s6en1lg@4ax.com> On Wed, 31 May 2006 23:05:14 +0200, Fredrik Lundh wrote: >Roger Miller wrote: > >> DSU seems like a lot of trouble to go through in order to use an O(n >> log n) sorting algorithm to do what can be done in O(N) with a few >> lines of code. The core code of random.shuffle() shows how easy it is >> to do it right: >> >> for i in reversed(xrange(1, len(x))): >> # pick an element in x[:i+1] with which to exchange x[i] >> j = int(random() * (i+1)) >> x[i], x[j] = x[j], x[i] > >easy to do it right? you know, the main reason for adding shuffle to >the standard library was that its way too easy to get it wrong. Heh. And I thought it was just me. _I_ find it easy to get the "limits" wrong, even though I have the idea of the algorithm perfectly straight. Better yet is the number of times I've seen a simply wrong algorithm posted online: >see e.g. this thread: http://tinyurl.com/ppgzq Good example, because we know that EMF is not dumb. I've seen the same algorithm many times - the best example is http://www.cigital.com/papers/download/developer_gambling.php Some poker site posted the simply-wrong algorithm in an effort to convince people that their decks were properly shuffled! ************************ David C. Ullrich From danb_83 at yahoo.com Tue Jun 20 12:09:18 2006 From: danb_83 at yahoo.com (Dan Bishop) Date: 20 Jun 2006 09:09:18 -0700 Subject: How to truncate/round-off decimal numbers? In-Reply-To: <1150795607.818914.186950@h76g2000cwa.googlegroups.com> References: <1150795481.361532.310790@b68g2000cwa.googlegroups.com> <1150795607.818914.186950@h76g2000cwa.googlegroups.com> Message-ID: <1150819758.883242.47280@b68g2000cwa.googlegroups.com> MTD wrote: > > The system cannot > > accurately represent some integers, > > Er, I meant FLOATS. Doh. You were also right the first time. But it only applies to integers with more than 53 bits. From slawomir.nowaczyk.847 at student.lu.se Thu Jun 8 15:30:10 2006 From: slawomir.nowaczyk.847 at student.lu.se (Slawomir Nowaczyk) Date: Thu, 08 Jun 2006 21:30:10 +0200 Subject: CONSTRUCT - Python's way of Ruby's "alias_method" In-Reply-To: <1149771935.391193.147360@h76g2000cwa.googlegroups.com> References: <1149771935.391193.147360@h76g2000cwa.googlegroups.com> Message-ID: <20060608210529.FC85.SLAWOMIR.NOWACZYK.847@student.lu.se> On Thu, 08 Jun 2006 06:05:35 -0700 "Tim N. van der Leeuw" wrote: #> Since your question is so much about Django, you might want to ask #> on Django groups. Now *that*, and the rest of your post, was uncalled for. This thread is perfectly on topic for this list and the question asked concerns *Python*, with django being only a use case. -- Best wishes, Slawomir Nowaczyk ( Slawomir.Nowaczyk at cs.lth.se ) Some drink at the fountain of knowledge. Others just gargle. From nothingcanfulfill at gmail.com Tue Jun 6 20:50:03 2006 From: nothingcanfulfill at gmail.com (Ws) Date: 6 Jun 2006 17:50:03 -0700 Subject: Function Verification Message-ID: <1149641403.078295.231730@h76g2000cwa.googlegroups.com> Hi all I'm trying to write up a module that *safely* sets sys.stderr and sys.stdout, and am currently having troubles with the function verification. I need to assure that the function can indeed be called as the Python manual specifies that sys.stdout and sys.stderr should be defined (standard file-like objects, only requiring a function named "write"). For an example output wrapper class, it could look something so simple as this: class OutputWrapper: def __init__(self,CallBack,*args,**kwargs): self.cb = CallBack def write(self,str): self.cb(str,*args,**kwargs) My problem is in verifying the class we're trying to redirect output to. This is what I have so far: def _VerifyOutputStream(fh): if 'write' not in dir(fh): raise AttributeError, "The Output Stream should have a write method." if not callable(fh.write): raise TypeError, "The Output Stream's write method is not callable." ((( On a side note, I have derived the above exception names to use via. experimentation in an interactive shell: >>> class SomeClass:pass ... >>> w = SomeClass() >>> w.write Traceback (most recent call last): File "", line 1, in ? AttributeError: w instance has no attribute 'write' >>> w.write = "Hurr, strings are not callable!" >>> w.write() Traceback (most recent call last): File "", line 1, in ? TypeError: 'str' object is not callable >>> ))) In the above _VerifyOutputStream function, how would I verify that the fh.write method requires only one argument, as the built-in file objects do? Thanks in advance -Wes PS: As a point of reference, to make your lives easier, the links to the Python manual pages: http://docs.python.org/lib/module-sys.html http://docs.python.org/lib/bltin-file-objects.html ((( My experimentation in IDLE yielded no results, really, either. >>> class C: def write(self, str, noreq=None): pass >>> c=C() >>> dir(c.write.func_code) ['__class__', '__cmp__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'co_argcount', 'co_cellvars', 'co_code', 'co_consts', 'co_filename', 'co_firstlineno', 'co_flags', 'co_freevars', 'co_lnotab', 'co_name', 'co_names', 'co_nlocals', 'co_stacksize', 'co_varnames'] >>> c.write.func_code.co_argcount 3 >>> c.write.func_code.co_varnames ('self', 'str', 'noreq') ))) From robert.thorpe at antenova.com Wed Jun 14 11:12:12 2006 From: robert.thorpe at antenova.com (Rob Thorpe) Date: 14 Jun 2006 08:12:12 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: <7zpshbsvjy.fsf@app-1.diku.dk> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> Message-ID: <1150297932.458202.227360@c74g2000cwc.googlegroups.com> Torben ?gidius Mogensen wrote: > On a similar note, is a statically typed langauge more or less > expressive than a dynamically typed language? Some would say less, as > you can write programs in a dynamically typed language that you can't > compile in a statically typed language (without a lot of encoding), > whereas the converse isn't true. However, I think this is misleading, > as it ignores the feedback issue: It takes longer for the average > programmer to get the program working in the dynamically typed > language. >From the point of view purely of expressiveness I'd say it's rather different. If a language can express constraints of one kind that is an increase in expressiveness. If a language requires constraint to be in one particular way thats a decrease in expressiveness. So I would say languages that can be statically typed and can be dynamically typed are the most expressive. Languages that require static typing or are dynamic but cannot express static typing are less expressive. This meets my experience of what useful in practice too, static typing for everything is painful for writing simple code. Pure dynamic typing is painful when writing complex code because it makes impossible a layer of error checking that could otherwise be useful. From overly.crazy.steve at gmail.com Thu Jun 29 17:07:45 2006 From: overly.crazy.steve at gmail.com (overly.crazy.steve at gmail.com) Date: 29 Jun 2006 14:07:45 -0700 Subject: Is it safe to shre a reg exp object among threads? Message-ID: <1151615265.014791.307200@p79g2000cwp.googlegroups.com> Let's say I construct a regular expression object r by: r = re.compile("some pattern") Is it safe to let multiple threads to use r concurrently (use r.search on different strings, etc.)? Thanks. From steve at holdenweb.com Tue Jun 27 02:49:57 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 27 Jun 2006 07:49:57 +0100 Subject: TypeError: Cannot create a consistent method resolution order (MRO) for bases object In-Reply-To: <1151376918.242180.301210@m73g2000cwd.googlegroups.com> References: <1151345197.691600.200060@y41g2000cwy.googlegroups.com> <1151376918.242180.301210@m73g2000cwd.googlegroups.com> Message-ID: digitalorganics at gmail.com wrote: > Maric Michaud wrote: > >>Le lundi 26 juin 2006 20:06, digitalorganics at gmail.com a ?crit : >> >>>What are the reason one would get this error: TypeError: Cannot create >>>a consistent method resolution order (MRO) for bases object ?? >>> >>>I can provide the code if needed.... >> >>This is the python solution to the diamond problem (cf. wikipedia). >> >>In [61]: class a(object) : pass >> ....: >>In [62]: class b(a) : pass >> ....: >>In [63]: class c(object, a) : pass >> ....: >>--------------------------------------------------------------------------- >>exceptions.TypeError Traceback (most recent >>call last) >> >>/home/maric/ >> >>TypeError: Error when calling the metaclass bases >> Cannot create a consistent method resolution >>order (MRO) for bases object, a >> >>In [64]: b.mro() >>Out[64]: [, , ] >> >>In [65]: class c(a, object) : pass >> ....: >> >>In [66]: c.mro() >>Out[66]: [, , ] >> >>In [67]: class d(b, c) : pass >> ....: >> >>In [69]: d.mro() >>Out[69]: >>[, >> , >> , >> , >> ] >> >>mro means "method resolution order", this is the path the interpreter will >>look for attributes for a given class. You cannot introduce inconsistency in >>this path, for example duplicate the type object before another type (or any >>type wich appear to be the ancestor of another). >> >>-- > > > Ah, thank you Maric, I see the problem. I diagrammed the flow of class > inheritance and I can see the problem clearly. Ruby doesn't have this > problem because it uses a single inheritance model complemented by the > power of mixins (modules of functionality mixed into classes as > needed). So what's the Pythonic solution to this problem? > Technically, wait until Python 3.0. Until then, just make sure all your classes inherit from (something that inherits from ...) object. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From iny+news at iki.fi Mon Jun 5 00:49:52 2006 From: iny+news at iki.fi (Ilpo =?iso-8859-1?Q?Nyyss=F6nen?=) Date: Mon, 05 Jun 2006 07:49:52 +0300 Subject: Python less error-prone than Java References: <1149408824.174844.178010@u72g2000cwu.googlegroups.com> Message-ID: "Kaz Kylheku" writes: > Buggy library code is what prompted that article. Yes, but it is an error type that happens very rarely still. And so it seems that very few programs even notice that bug in that library. > Except when you feed those programs inputs which are converted to > integers which are then fed as domain values into some operation that > doesn't fit into the range type. If the input value range is limited, you want to get an error, if out of range value is given. If you want to handle unlimited values, you really need to take a look that you can do it. Think for example storing such value to a database. >> 1. null pointer errors >> 2. wrong type (class cast in Java, some weird missing attribute in python) >> 3. array/list index out of bounds >> >> First and third ones are the same in about every language. > > ... other than C and C++, where their equivalents just crash or stomp > over memory, but never mind; who uses those? ;) It is not different. Your crash can tell you that it was a null pointer. Your crash can tell you that you stomped over memory. You just get the information about the error in different way. > Instead of this stupid idea of pointers or references having a null > value, you can make a null value which has its own type, and banish > null pointers. Yes and I actually think that as bad thing. It is nice to be able to tell the difference between null pointer and wrong type. Of course if the error message tells you that you had null there, it is not a problem, but what if you somehow lose the error message and get only the exception class name? (Yes, you should always keep the message too, but it does happen.) -- Ilpo Nyyss?nen # biny # /* :-) */ From iainking at gmail.com Fri Jun 2 07:30:55 2006 From: iainking at gmail.com (Iain King) Date: 2 Jun 2006 04:30:55 -0700 Subject: shuffling elements of a list In-Reply-To: References: <1149045499.212967.13120@f6g2000cwb.googlegroups.com> <1149051212.139046.155340@c74g2000cwc.googlegroups.com> Message-ID: <1149247855.487864.124540@i39g2000cwa.googlegroups.com> David C. Ullrich wrote: > On 30 May 2006 21:53:32 -0700, "greenflame" > wrote: > > That's DSU for _sorting_ a list. I read about this, thought > it was pretty neat. I thought that the fact that you > could use the same trick for _shuffling_ a list was > my idea, gonna make me rich and famous. I guess I'm > not the only one who thought of it. Anyway, you can > use DSU to _shuffle_ a list by decorating the list > with random numbers. > > In fairly old-fashioned Python: > > from random import random > > def shuffle(data): > decorated = map(lambda x: (random(), x), data) > decorated.sort() > return map(lambda x: x[1], decorated) > > print shuffle(range(10)) > > This prints > > [4, 2, 7, 8, 9, 3, 5, 1, 6, 0] > > . Seems kinda neat - I have no idea how the efficiency > compares with the standard sort of "bubble shuffle" > you were trying to use in your OP, but the point is > that various off-by-one errors simply don't come up. > > (The same thing in extremely awful Python, in case > you're mystified by map and lambda: > > from random import random > > def shuffle(data): > decorated = [] > for x in data: > decorated.append((random(), x)) > decorated.sort() > res = [] > for x in decorated: > res.append(x[1]) > return res > > .) or in nicer python, but still when you're mysitified by map and lambda (like me): def shuffle(data): decorated = [(random(), x) for x in data] decorated.sort() return [x[1] for x in decorated] or shorter but possible less readable (and only in 2.4+): def shuffle(data): return [y[1] for y in sorted([(random(), x) for x in data])] Iain From benboals at gmail.com Mon Jun 19 15:06:24 2006 From: benboals at gmail.com (benboals at gmail.com) Date: 19 Jun 2006 12:06:24 -0700 Subject: Overriding a function... References: <1150742558.198061.239660@p79g2000cwp.googlegroups.com> Message-ID: <1150743984.330994.113410@y41g2000cwy.googlegroups.com> programmer.py at gmail.com wrote: > Suppose I have this module `mymodule.py' - > > # mymodule.py - begin > def test(): > print "original" > # mymodule.py - end > > Now assume that I do this in some arbitrary module -> > > def override(): > print "test is overridden" > > import mymodule > mymodule.test = override > > Two questions - > > 1) If mymodule is subsequently imported, will my `override' function be > used, or will python magically `fix' (or break depending on your > perspective) mymodule and use the original mymodule.test function? > > 2) Once I assign mymodule.test with override, will modules that > imported my module *PRIOR* to the assignment get override, or will they > keep the original function test()? > > I hope that makes sense. > > Thanks! > jw iirc, python only imports modules once, so for future imports should be ok with the override. There is a reload() function that wipes and reloads a module(though not, I believe, recursively, that is, not modules that it imported) I've done someting similar to your overwriting in the past, anyway, and it worked. However, you should find this easy to test yourself, in case the revision makes a difference. How i'd test it: file: original def afunction(): print 'Hi' file: changer import original def otherFunc(): print "Bye" original.afunction()=otherFunc file: final1 import original original.afunction() ##should say hi import changer original.afunction() ##should say bye changer.original.afunction() ##should still say bye. file: final2 import changer changer.original.afunction() ##should say bye import original changer.original.afunction() ##should say bye original.afunction() ##should say bye cmd prompt: python final1.py Expect: Hi Bye Bye python final2.py Expect: Bye Bye Bye From onurb at xiludom.gro Tue Jun 27 12:23:27 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Tue, 27 Jun 2006 18:23:27 +0200 Subject: file writing question In-Reply-To: <1151423998.492022.269810@m73g2000cwd.googlegroups.com> References: <1151423998.492022.269810@m73g2000cwd.googlegroups.com> Message-ID: <44a15b80$0$16556$636a55ce@news.free.fr> diffuser78 at gmail.com wrote: > Hi, I am a newbie so not very confident in file handling. > > I want to write to a file atrributes in this fashion > #NameOfComputer:MAC_Address:IP_Address > > ------computer_details.txt > begins----------------------------------------- > IG1:8f00142a123c:192.168.2.101 > IG2:8f00142a124d:192.168.2.102 > IG3:8f00142a124e:192.168.2.103 > IG4:8f00142a124f:192.168.2.104 > IG5:8f00142a124a:192.168.2.105 > IG6:8f00142a124b:192.168.2.106 > ------computer_details.txt > ends------------------------------------------- > > While writing this file I insert "\n" after every line so that details > of every new computer goes into next line for readibility. > > > After I have to read this file. While reading this file "\n" remains > which I dont want. Then strip it: for line in open('computer_details.txt'): name, mac, ip = line.strip().split(':') # ... > Is there a neat way of writing to a file and not having "\n" ? Yes : don't add the newline after every line. But note that this may make the file a bit more difficult to read and parse for both your program and you !-) Also, may I suggest that you read the doc for the CSV module ? -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From rpdooling at gmail.com Sat Jun 10 15:56:24 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 10 Jun 2006 12:56:24 -0700 Subject: Get my airlines boarding pass In-Reply-To: <1149954923.868806.87270@m38g2000cwc.googlegroups.com> References: <1hgotbh.1vd74fb1qhzdziN%aleax@mac.com> <1149954923.868806.87270@m38g2000cwc.googlegroups.com> Message-ID: <1149969384.065683.224810@f6g2000cwb.googlegroups.com> >> SW air script Post it here, first, and these geniuses will improve it; then post it on ActiveState. Besides, if you post it here first, I can use it. That would be handy! Thanks, rpd From sjmachin at lexicon.net Sun Jun 4 08:17:41 2006 From: sjmachin at lexicon.net (John Machin) Date: Sun, 04 Jun 2006 22:17:41 +1000 Subject: Pyrex list/array In-Reply-To: <1149415140.458073.65310@c74g2000cwc.googlegroups.com> References: <1149360983.373137.200740@i39g2000cwa.googlegroups.com> <448239EB.6010706@lexicon.net> <1149415140.458073.65310@c74g2000cwc.googlegroups.com> Message-ID: <4482CF65.1070506@lexicon.net> On 4/06/2006 7:59 PM, Jim Lewis wrote: > Thanks for your comments. > >> You probably didn't expect the Inquisition... > > Correct ;-) Nobody does :-) > >> The question might be better asked on the Pyrex mailing list. > > I did not find it - where is it? Evidently somewhere near the Hall of the Mountain King. A reference to it is cunningly concealed in the last place one would think of finding it: under the heading "Mailing List" on the Pyrex home page :-) Here: http://lists.copyleft.no/mailman/listinfo/pyrex ... get in quick before the pirate moves it again. > >> Almost any Python code is also valid Pyrex code. For a start, just compile your function with Pyrex and compare the speed. > > It's slower. > >> What you do next is going to depend very much on what operations you are performing on the list and the objects it contains. > > Simple list of ints. Comparing sections of lists between each other. Do you mean alist[x:x+n] == alist[y:y+n] ? If so, that's creating two new lists each of size n, and then comparing those two lists. I doubt that psyco would recognize that it didn't need to copy the two slices. The first step might be to write functions to compare without copying, e.g.: def py_slices_cmp_eq(py_list, start1, start2, size): """Return 1 if py_list[start1+size] == py_list[start2+size] else 0""" offset = start2 - start1 for i in xrange(start1, start1+size): if py_list[i] != py_list[i+offset]: return 0 return 1 See what psyco makes of that. Then turn that into a cdef function for Pyrex. If that's still not fast enough, then you might be in for some harder work: Allocate memory for a C array, unpack your list into it, write comparison functions c_slices_cmp_* that operate on your array of ints. There should be no Python stuff in there, only C constructs. You can even use memcmp() for the cmp_eq function. Which brings us back to your original question "Do I need to convert to array or something so pyrex can generate tight code?" ... 1. Some of the above may help you to determine whether you need to. 2. Without any knowledge of the size of your list or what you are doing, we can't help you much more on whether you need to. 3. AFAICT, Pyrex doesn't do much in the way of optimisation, leaving that up to the C compiler. Generating tight code would depend more on you replacing appropriately-chosen Pythonisms with C-isms. As for *how* to make your C array, something like this: cdef extern from "Python.h": void PyMem_Free(void *p) void* PyMem_Malloc(int n) except NULL # untested -- compiles OK :-) cdef int * int_array_from_list(object ilist): cdef int n, i cdef int * arrayp n = len(ilist) arrayp = PyMem_Malloc(n * sizeof(int)) for i from 0 <= i < n: arrayp[i] = ilist[i] return &arrayp[0] Hoping some of this helps, John From deets at nospam.web.de Sat Jun 10 16:35:55 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 10 Jun 2006 22:35:55 +0200 Subject: Killing a thread In-Reply-To: <4evk2jF1h5v0dU1@uni-berlin.de> References: <7c8a9a970606091338t174fbcb0wc73cdb8b385f8ccd@mail.gmail.com> <7c8a9a970606091354u73308bf8o2758eea5ef690c39@mail.gmail.com> <1149889827.2754.6.camel@kenshin.CASA> <4evk2jF1h5v0dU1@uni-berlin.de> Message-ID: <4f0opbF1ghoqoU1@uni-berlin.de> > Python uses the underlying OS thread implementation. It does _not_ spawn > new threads. Obviously that was meant to be "spawn processes" Diez From johnjsal at NOSPAMgmail.com Tue Jun 6 15:56:38 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 06 Jun 2006 19:56:38 GMT Subject: tkinter: making widgets instance or not? In-Reply-To: References: Message-ID: John Salerno wrote: > 2. Related to your comment, the obvious problem here is that it doesn't > save references to the text box names, so I can't access them later. Is > there still a way to automate the process like I've done, but have each > entry field have a separate name? A thought about this: maybe I can pass in the name of what I'd like the entry field to be called as another parameter, then after the entry object is created I can say something like: self. = self.entry Of course, I'm not sure how to write the left side, because I assume I'd have to pass in my new name as a string, but a string wouldn't work as an instance variable. Also, would there be any problems with this kind of assignment? Any weird reference problems that makes this not really work? From cdsmith at twu.net Mon Jun 19 11:20:20 2006 From: cdsmith at twu.net (Chris Smith) Date: Mon, 19 Jun 2006 09:20:20 -0600 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> Message-ID: Torben ?gidius Mogensen wrote: > That's not really the difference between static and dynamic typing. > Static typing means that there exist a typing at compile-time that > guarantess against run-time type violations. Dynamic typing means > that such violations are detected at run-time. This is orthogonal to > strong versus weak typing, which is about whether such violations are > detected at all. The archetypal weakly typed language is machine code > -- you can happily load a floating point value from memory, add it to > a string pointer and jump to the resulting value. ML and Scheme are > both strongly typed, but one is statically typed and the other > dynamically typed. Knowing that it'll cause a lot of strenuous objection, I'll nevertheless interject my plea not to abuse the word "type" with a phrase like "dynamically typed". If anyone considers "untyped" to be perjorative, as some people apparently do, then I'll note that another common term is "type-free," which is marketing-approved but doesn't carry the misleading connotations of "dynamically typed." We are quickly losing any rational meaning whatsoever to the word "type," and that's quite a shame. By way of extending the point, let me mention that there is no such thing as a universal class of things that are called "run-time type violations". At runtime, there is merely correct code and incorrect code. To the extent that anything is called a "type" at runtime, this is a different usage of the word from the usage by which we may define languages as being statically typed (which means just "typed"). In typed OO languages, this runtime usage is often called the "class", for example, to distinguish it from type. This cleaner terminology eliminates a lot of confusion. For example, it clarifies that there is no binary division between strongly typed languages and weakly typed languages, since the division between a "type error" and any other kind of error is arbitrary, depending only on whether the type system in a particular language happens to catch that error. For example, type systems have been defined to try to catch unit errors in scientific programming, or to catch out-of-bounds array indices... yet these are not commonly called "type errors" only because such systems are not in common use. This also leads us to define something like "language safety" to encapsulate what we previously would have meant by the phrase "strongly dynamically typed language". This also is a more general concept than we had before. Language safety refers to a language having well-defined behavior for as many operations as feasible, so that it's less likely that someone will do something spectacularly bad. Language safety may be achieved either by a type system or by runtime checks. Again, it's not absolute... I'm aware of no language that is completely determinate, at least if it supports any kind of concurrency. This isn't just a matter of preference in terminology. The definitions above (which are, in my experience, used widely by most non-academic language design discussions) actually limit our understanding of language design by pretending that certain delicate trade-offs such as the extent of the type system, or which language behavior is allowed to be non-deterministic or undefined, are etched in stone. This is simply not so. If types DON'T mean a compile-time method for proving the absence of certain program behaviors, then they don't mean anything at all. Pretending that there's a distinction at runtime between "type errors" and "other errors" serves only to confuse things and artificially limit which problems we are willing to concieve as being solvable by types. > Anyway, type inference for statically typed langauges don't make them > any more dynamically typed. Indeed it does not. Unless it weakens the ability of a compiler to prove the absence of certain program behaviors (which type inference does not), it doesn't move anything on the scale toward a type-free language. That being said, though, it is considered a feature of some programming languages that the programmer is asked to repeat type information in a few places. The compiler may not need the information, but for precisely the reason that the information is redundant, the compiler is then able to check the consistency of the programmer in applying the type. I won't get into precisely how useful this is, but it is nevertheless present as an advantage to outweigh the wordiness. -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation From broek at cc.umanitoba.ca Tue Jun 13 06:07:15 2006 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Tue, 13 Jun 2006 12:07:15 +0200 Subject: Python 411. In-Reply-To: <1150188399.809316.172840@f14g2000cwb.googlegroups.com> References: <1150152755.474292.39010@j55g2000cwa.googlegroups.com> <1150188399.809316.172840@f14g2000cwb.googlegroups.com> Message-ID: <448E8E53.90200@cc.umanitoba.ca> Mike T said unto the world upon 13/06/06 10:46 AM: > What exactly is 411 in this context? A reference to higher education > perhaps? Or perhaps part of the American constitution? What exactly? > Also for that matter what is 101? > > Cheers, > Mike > Hi Mike, 411 is the number one dials in North America to reach directory assistance (getting telephone numbers). So, it has a slang usage meaning something like information. Introductory university course in a field are often numbered 101 (i.e. Computer Science 101). So, that number has acquired a slang meaning of basic and introductory information. Where I did my undergrad studies, a few Departments had 001 classes. Somehow that felt more honest ;-) Best to all, Brian vdB From sjmachin at lexicon.net Thu Jun 15 21:43:01 2006 From: sjmachin at lexicon.net (John Machin) Date: Fri, 16 Jun 2006 11:43:01 +1000 Subject: Need Help comparing dates In-Reply-To: References: <1150419503.224684.320550@c74g2000cwc.googlegroups.com> Message-ID: <44920ca4$1@news.eftel.com> On 16/06/2006 11:23 AM, Ben Finney wrote: > colincolehour at gmail.com writes: > >> I am new to Python and am working on my first program. I am trying >> to compare a date I found on a website to todays date. The problem I >> have is the website only shows 3 letter month name and the date. >> Example: Jun 15 > > The 'datetime' module in the standard library will do the job of > creating date objects that can be compared. > > > > Construct a date from arbitrary values with datetime.date(), get the > current date with datetime.date.today(). The objects returned by those > functions can be compared directly. > > As for how to get from a string representation to a date object, > you're now talking about parsing strings to extract date/time > information. This isn't provided in the standard library, time.strptime() doesn't do "parsing strings to extract date/time information"? It appears to me to do a reasonably tolerant job on the OP's spec i.e. month abbreviation and a day number: |>> import time |>> time.strptime('Jun 15', '%b %d') (1900, 6, 15, 0, 0, 0, 4, 166, -1) |>> time.strptime('dec 9', '%b %d') (1900, 12, 9, 0, 0, 0, 4, 152, -1) The OP should be able to use that to get the month and the day. The year of the web page date will need some guessing (e.g. is within the last year) and not even Python has a crystal ball :-) BTW, datetime has grown a strptime in version 2.5. [snip] > > That module predates (and was largely an inspiration for) the standard > library 'datetime' module; however, I don't know if the egenix module > uses objects that can be used with those from the standard library. It doesn't. From fredrik at pythonware.com Fri Jun 30 07:30:28 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 30 Jun 2006 13:30:28 +0200 Subject: delete first line in a file References: <44a4f854$0$12942$91cee783@newsreader02.highway.telekom.at><44a50151$0$12935$91cee783@newsreader02.highway.telekom.at> <44a50825$0$3888$91cee783@newsreader01.highway.telekom.at> Message-ID: Juergen Huber wrote: >> start here: >> >> http://docs.python.org/tut/node9.html#SECTION009200000000000000000 > > that documentation i have already read, but it wouldn`t help me for my > problem! that documentation and a little experimentation should be all you need. > i know, how i can read the first line an print them on the screen! > but...how can i say python, delete the first line?! > thats my problem! read the first line, and ignore it. then read all the other lines, and write them to a new file. From Bulkan at gmail.com Mon Jun 19 21:39:07 2006 From: Bulkan at gmail.com (placid) Date: 19 Jun 2006 18:39:07 -0700 Subject: Newbie Question In-Reply-To: <1150753085.332654.283270@f6g2000cwb.googlegroups.com> References: <1150750938.973049.114780@y41g2000cwy.googlegroups.com> <129e55eahc35f00@corp.supernews.com> <1150753085.332654.283270@f6g2000cwb.googlegroups.com> Message-ID: <1150767547.252901.163870@r2g2000cwb.googlegroups.com> Saint Malo wrote: > Thanks! That helped a lot! Now, lets say that I just want to display > one or just a few of the items and not the whole line. For example, > the text file contains the following: > > red blue yello > green purple brown > > > If the program searches for blue, i just want it to print blue, not the > whole line. If i ask it to find blue and brown, i just want it to > return those two values. > > search_words = ["red", "brown"] # Open a file for read file=open(r'test.txt','r') # Read each line in file for line in file #Search each line for words in search_words: if words in line: print words file.close() * create a list containing search words * open file for reading * iterate through each line in the text file * iterate though each word in search words * check if the line contains the word your searching for * print the word if it does * close file Cheers > > > > Andrew Robert wrote: > > Saint Malo wrote: > > > I am new to programming, and I've chosen python to start with. I wrote > > > a simple program that asks several questions and assings each one of > > > them a variable via raw_input command. I then combined all the > > > variables into one like this a = b + c + d. After this I wrote these > > > values to a file. What I want to do now is be able to search through > > > the file for any data in there. Is this possible? > > > > > Most certainly. > > > > It depends on how you want to treat the read data. > > > > for example > > > > > > # Open a file for read > > file=open(r'test.txt','r') > > > > # Read each line in file > > for line in file > > > > #Search each line > > if "A" in line: > > > > print "I found A" > > > > file.close() From warpcat at sbcglobal.net Wed Jun 14 15:37:04 2006 From: warpcat at sbcglobal.net (warpcat) Date: 14 Jun 2006 12:37:04 -0700 Subject: better Python IDE? Mimics Maya's script editor? In-Reply-To: References: <1149810048.765664.107820@i40g2000cwc.googlegroups.com> Message-ID: <1150313824.937532.22780@g10g2000cwb.googlegroups.com> I'm not sure where you got "pythonwin sucks" from my text (none of those words are there). Saying one aspect of a piece of software is clunky to "me" (if that's what you're refering too?) or saying the whole software "sucks" are pretty different IMO. All I stated is that it's very different from how I'm used to working. I didn't mean any disrespect, but I do appreciate your info! Steve Holden wrote: > You might also wish to reconsider your approach to the Python community. > "PythonWin sucks" isn't my idea of how to win friends and influence > people in a first posting to a usenet newsgroup. By and large we are a > friendly bunch here, but you don't want to start off on the wrong foot :-) > > regards > Steve > -- > Steve Holden +44 150 684 7255 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Love me, love my blog http://holdenweb.blogspot.com > Recent Ramblings http://del.icio.us/steve.holden From llosee at gmail.com Tue Jun 6 12:09:38 2006 From: llosee at gmail.com (Lou Losee) Date: Tue, 6 Jun 2006 12:09:38 -0400 Subject: Expanding Search to Subfolders In-Reply-To: References: <1149526866.681348.273590@c74g2000cwc.googlegroups.com> Message-ID: On 6/6/06, Fredrik Lundh wrote: > Lou Losee wrote: > > > How about something like: > > > import os, stat > > > > class DirectoryWalker: > > # a forward iterator that traverses a directory tree, and > > # returns the filename > > ... > > > not tested > > speak for yourself ;-) > > (the code is taken from http://effbot.org/librarybook/os-path.htm ) > > > Well that is good to know :) I know I did not get it from there but I had it in my snippits directory. Lou -- Artificial Intelligence is no match for Natural Stupidity From thorley at gmail.com Fri Jun 30 12:40:30 2006 From: thorley at gmail.com (thorley at gmail.com) Date: 30 Jun 2006 09:40:30 -0700 Subject: fcgi server in python? Message-ID: <1151685630.563705.212610@d30g2000cwa.googlegroups.com> Does any one know of a fcgi SEVER implementation for python? I've seen lots of great stuff for the client/application side, but not a server. By server, I mean the program that accepts requests from the browser and passes them to the web app over fcgi. Usaually this is done by Apace or Lightttpd, but I'm trying to reduce dependancies, so a (pure) python implementation would be really great! thanks -- matthew From scott.daniels at acm.org Sun Jun 18 19:48:04 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Sun, 18 Jun 2006 16:48:04 -0700 Subject: Simple script to make .png thumbnails from .zip archive... In-Reply-To: <1150664094.345764.280030@u72g2000cwu.googlegroups.com> References: <1150660266.413889.217280@c74g2000cwc.googlegroups.com> <1150664094.345764.280030@u72g2000cwu.googlegroups.com> Message-ID: <4495e151$1@nntp0.pdx.net> hdante wrote: > .... there are too many ways to create a thumbnail from an > image. I'll cite one, using the "python image" external module, that > I've found to be very easy: > > import Image > def process(file): > try: > image = Image.open(file) > image.thumbnail ((128,128), Image.ANTIALIAS) > image.save (file + '.thumb.png') > except: > print 'Skipping file', file > > Links: > http://docs.python.org/lib/lib.html - Python Library Reference > http://www.pythonware.com/library/pil/handbook/image.htm - The Image > Module That, by the way, is the "PIL" library that you'll see a lot about -- The Python Imaging Library that the effbot is justly proud of. You won't do better than that. --Scott David Daniels scott.daniels at acm.org From onurb at xiludom.gro Mon Jun 12 04:32:51 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Mon, 12 Jun 2006 10:32:51 +0200 Subject: Python or Ajax? In-Reply-To: References: Message-ID: <448d26b5$0$25184$626a54ce@news.free.fr> Redefined Horizons wrote: > I've been hearing a ot about AJAX lately. I may have to build a web > application in the near future, and I was curoius: > > How does a web application that uses Python compare with one that uses > AJAX? How does a car that has a diesel motor compare with one that is red ? > I've done some basic web page design with HTML and CSS, but never any > web applications. Obviously !-) So the first steps would be to learn what is AJAX (hint: it's not a lnaguage), and what is the difference between client-side scripting and server-side scripting. HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From diffuser78 at gmail.com Thu Jun 15 16:29:13 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 15 Jun 2006 13:29:13 -0700 Subject: GUI in Python using wxGlade References: <1150380251.279150.73620@u72g2000cwu.googlegroups.com> <1150386216.365531.157690@g10g2000cwb.googlegroups.com> Message-ID: <1150403353.755218.292100@c74g2000cwc.googlegroups.com> I am a newbie. I was looking for some code where I could a list of different items from a file and display it in a list box. Then give a user the capability to select some. Basically, reading and writing to a file and displaying them in different widgets...thats something I am looking for. If anybody can point me to some good example tutorials...I will be greatly helped. Thanks, Every help is appreciated From gandalf at designaproduct.biz Tue Jun 13 05:09:39 2006 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Tue, 13 Jun 2006 11:09:39 +0200 Subject: Decimals In-Reply-To: <1150188516.739925.102810@h76g2000cwa.googlegroups.com> References: <1150188516.739925.102810@h76g2000cwa.googlegroups.com> Message-ID: <448E80D3.2030008@designaproduct.biz> Tgone ?rta: > Hello, > > I have a price column in a MySQL table: price decimal(5,2) > > When I access them in Python with SQLObject, prices display as 15.0 > instead of 15.00. Why is this happening? I can't figure out why Python > is trimming off the hundredth place. I'm not doing any formatting... > What do you mean by 'displays as 15.0'? Do you print in with the print statement? If your DB access module returns decimal.Decimal instances, then you are right. It should print as 15.00 instead of 15.0. Try to determine the type of the returned value. Maybe your DB module uses float instead of Decimal? Best, Laszlo From kst-u at mib.org Wed Jun 7 22:21:42 2006 From: kst-u at mib.org (Keith Thompson) Date: Thu, 08 Jun 2006 02:21:42 GMT Subject: The Nature of the =?utf-8?q?=E2=80=9CUnix_Philosophy=E2=80=9D?= References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1149080931.582431.95560@j55g2000cwa.googlegroups.com> <1149730552.161534.121350@i40g2000cwc.googlegroups.com> Message-ID: "Xah Lee" writes: > The Nature of the ?Unix Philosophy? > > Xah Lee, 2006-05 ___________________ /| /| | | ||__|| | Please do | / O O\__ NOT | / \ feed the | / \ \ trolls | / _ \ \ ______________| / |\____\ \ || / | | | |\____/ || / \|_|_|/ \ __|| / / \ |____| || / | | /| | --| | | |// |____ --| * _ | |_|_|_| | \-/ *-- _--\ _ \ // | / _ \\ _ // | / * / \_ /- | - | | * ___ c_c_c_C/ \C_c_c_c____________ (If you *must* post followups, please drop comp.lang.c from the Newsgroups: header -- which doesn't imply that this is topical in any of the other newsgroups to which it's posted.) Xah: please consider creating your own newsgroup under alt.*. You can post your long essays there and (if you absolutely insist on doing so) post pointers to them elsewhere. -- Keith Thompson (The_Other_Keith) kst-u at mib.org San Diego Supercomputer Center <*> We must do something. This is something. Therefore, we must do this. From onurb at xiludom.gro Fri Jun 23 05:31:00 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Fri, 23 Jun 2006 11:31:00 +0200 Subject: Using metaclassed to dynamically generate a class based on a parameter to the objects init function. In-Reply-To: <1151018669.849641.265990@g10g2000cwb.googlegroups.com> References: <1151018669.849641.265990@g10g2000cwb.googlegroups.com> Message-ID: <449bb4d6$0$32258$626a54ce@news.free.fr> sashang at gmail.com wrote: > Hi > > I'd like to use metaclasses to dynamically generate a class based on a > parameter to the objects init function. Do you really need a metaclass for this ? > For example: > > class MetaThing(type): > def __init__(cls, name, bases, dict, extra_information): > super(MetaThing, cls).__init__(name, bases, dict) > #setup the class based on the parameter extra_information > > class Thing: > __metaclass__ = MetaThing > def __init__(self, extra_information): > #Somehow pass extra_information to the MetaThing > > extra_information = 1 > t = Thing(extra_information) Why would you want a new *class* here ? > The above sample won't work but I hope it demonstrates what I'm trying > to do. Not enough, I'm afraid - unless it's just me being dumb. From what I see here, you just can add the extra informations on the object in the initializer. What's your *real* use case ? -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From kay.schluehr at gmx.net Tue Jun 20 01:35:34 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 19 Jun 2006 22:35:34 -0700 Subject: Seeking regex optimizer In-Reply-To: <1150750294.232093.304230@p79g2000cwp.googlegroups.com> References: <1150650439.651839.38180@y41g2000cwy.googlegroups.com> <1150750294.232093.304230@p79g2000cwp.googlegroups.com> Message-ID: <1150781734.524970.272390@u72g2000cwu.googlegroups.com> andrewdalke at gmail.com wrote: > Kay Schluehr wrote: > > I have a list of strings ls = [s_1,s_2,...,s_n] and want to create a > > regular expression sx from it, such that sx.match(s) yields a SRE_Match > > object when s starts with an s_i for one i in [0,...,n]. > > Why do you want to use a regex for this? Because it is part of a tokenizer that already uses regexps and I do not intend to rewrite / replace it. Certain groups of token ( operators, braces and special characters ) should be user extensible. All others will stay as they are. I found that certain groups of token might be represented in a more compact mannerr: for matching ['+', '++'] one might generate '\+|\+\+' or '\+\+?' and I wanted to know if there is some generic approach to solve the "inverse regexp" problem in a non-trivial fashion. Regards, Kay From sjmachin at lexicon.net Fri Jun 2 23:56:35 2006 From: sjmachin at lexicon.net (John Machin) Date: Sat, 03 Jun 2006 13:56:35 +1000 Subject: Seg fault in python extension module In-Reply-To: <1149305921.145967.248740@i39g2000cwa.googlegroups.com> References: <4480F004.7000602@lexicon.net> <1149305921.145967.248740@i39g2000cwa.googlegroups.com> Message-ID: <44810873.3050200@lexicon.net> On 3/06/2006 1:38 PM, sam wrote: > I recommend that you also replace the NULL after the METH_VARARGS with > a valid documentations string such as: > > static PyMethodDef modglMethods[] = > { > { (char *)"glVertex4f", _wrap_glVertex4f, METH_VARARGS, "My > Doc String"}, > { NULL, NULL, 0, NULL } > > }; > Lack of one is unlikely to have anything to do with the OP's segfault. |>>> repr(modgl.glVertex4f.__doc__) 'None' |>>> As to style, etiquette, and good citizenship in module extension writing, it might be better to give him some references, rather than mention just one point. Cheers, John From gh at ghaering.de Tue Jun 20 17:59:06 2006 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 20 Jun 2006 23:59:06 +0200 Subject: [ANN] pysqlite 2.3.1 released Message-ID: <44986FAA.10209@ghaering.de> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 pysqlite 2.3.1 released ======================= I'm pleased to announce the availability of pysqlite 2.3.1. This is a bugfix release, but it includes important fixes. Users of pysqlite 2.2.1 to 2.3.0 should definitely upgrade. Go to http://pysqlite.org/ for downloads, online documentation and reporting bugs. What is pysqlite? pysqlite is a DB-API 2.0-compliant database interface for SQLite. SQLite is a relational database management system contained in a relatively small C library. It is a public domain project created by D. Richard Hipp. Unlike the usual client-server paradigm, the SQLite engine is not a standalone process with which the program communicates, but is linked in and thus becomes an integral part of the program. The library implements most of SQL-92 standard, including transactions, triggers and most of complex queries. pysqlite makes this powerful embedded SQL engine available to Python programmers. It stays compatible with the Python database API specification 2.0 as much as possible, but also exposes most of SQLite's native API, so that it is for example possible to create user-defined SQL functions and aggregates in Python. If you need a relational database for your applications, or even small tools or helper scripts, pysqlite is often a good fit. It's easy to use, easy to deploy, and does not depend on any other Python libraries or platform libraries, except SQLite. SQLite itself is ported to most platforms you'd ever care about. It's often a good alternative to MySQL, the Microsoft JET engine or the MSDE, without having any of their license and deployment issues. pysqlite can be downloaded from http://pysqlite.org/ - Sources and Windows binaries for Python 2.4 and Python 2.3 are available. ======= CHANGES ======= - - Implemented a workaround for SQLite versions < 3.3.3: they are buggy and cannot use sqlite3_result_error from certain callbacks. So we cannot abort queries from callbacks. For these SQLite versions we set the Python exception and catch it later on when sqlite3_step is finished. - - Plugged a memory leak that affects pysqlite versions 2.2.1, 2.2.2 and 2.3.0: due to wrong usage of weak references, an internal list of weak references was always growing with each new statement text executed on the same connection. - - Removed a call to enable_callback_tracebacks that slipped in the test suite. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2.2 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFEmG+qdIO4ozGCH14RAhP1AKC28KMKzup8JuBnAnXSXwG7BdZzvgCfYDMm 5aCJ/bhuAZLCRFK7Nauj9Gs= =7o3U -----END PGP SIGNATURE----- From randhol+valid_for_reply_from_news at pvv.org Sat Jun 17 17:25:43 2006 From: randhol+valid_for_reply_from_news at pvv.org (Preben Randhol) Date: Sat, 17 Jun 2006 23:25:43 +0200 Subject: Extracting values from text file References: Message-ID: <20060617232543.9a0338fb.randhol+valid_for_reply_from_news@pvv.org> On Sat, 17 Jun 2006 14:20:44 +0200 Mirco Wahab wrote: > Thus spoke Mirco Wahab (on 2006-06-16 21:21): > > > I used your example just to try that in python > > (i have to improve my python skills), but waved > > the white flag after realizing that there's no > > easy string/var-into-string interpolation. > > I did another try on it, using all my Python > resources available (and several cups of coffee) > ;-) > > This scans your text for rules provided > and extracts values and variable names > and prints them at the end. > > I had some issues with python then: > - no comment # after line continuation \\ > - regular expressions **** **** (as I said before) Thanks! The code is a very good starting point for me! I already managed to change it and I see I need to make it a bit more robust. And the next challange I have is to extract n values from one line. I mean: 23 Apples 234 Lemons 4 Eggs for example. Again thanks. And thanks to all others for the suggestions. I have looked at all and learned a lot of python. I probably will end up with a mixture of several approaches. Preben From fredrik at pythonware.com Fri Jun 16 15:11:59 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 16 Jun 2006 21:11:59 +0200 Subject: Opening an editor for interactive use In-Reply-To: <1150480516.803469.275820@y41g2000cwy.googlegroups.com> References: <1150480516.803469.275820@y41g2000cwy.googlegroups.com> Message-ID: "Webb" wrote: > (I am sure there is a recipe somewhere, but I can't find it.) How does > one open an editor while in the middle of an interactive program, let > the user do some editing and closing, and then capture the text that > was edited? I am reminded of subversion or CVS when they open an > $EDITOR session for the check-in log entry. > > I tried os.popen, but it fired off vim in the background--not useful. > Then I tried os.system, but that only returns the return code (126 in > my case) after you close the editor. Perhaps I need to write to a file > and read it that's exactly how it's done in subversion and cvs, of course. From diffuser78 at gmail.com Fri Jun 23 01:06:41 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 22 Jun 2006 22:06:41 -0700 Subject: Network Programming in Python In-Reply-To: <449af860$0$31645$e4fe514c@news.xs4all.nl> References: <1151002934.586359.174540@m73g2000cwd.googlegroups.com> <1151005542.852613.115870@r2g2000cwb.googlegroups.com> <449af860$0$31645$e4fe514c@news.xs4all.nl> Message-ID: <1151039201.316003.263360@m73g2000cwd.googlegroups.com> I just realized that you are the author of Pyro. Will it be of any help to me ?? Irmen de Jong wrote: > tactics40 at gmail.com wrote: > > > > Really, was that so hard? > > > > Python makes sockets a total breeze. You can write an 80's style HTTP > > server in less than a page of code. > > But making a *good* 80's style http/socket server is a lot of work. > Better pick one of the high level protocols built on top of it, > to shield you from the gory details of raw socket programming. > > --Irmen From aleax at mac.com Fri Jun 23 11:08:45 2006 From: aleax at mac.com (Alex Martelli) Date: Fri, 23 Jun 2006 08:08:45 -0700 Subject: Using metaclassed to dynamically generate a class based on a parameter to the objects init function. References: <1151018669.849641.265990@g10g2000cwb.googlegroups.com> <449bb4d6$0$32258$626a54ce@news.free.fr> <1151061557.682689.189440@c74g2000cwc.googlegroups.com> <1151072013.327497.257110@g10g2000cwb.googlegroups.com> Message-ID: <1hhdl3h.1i7uyj51eqqqqxN%aleax@mac.com> Carl Banks wrote: > sashang at gmail.com wrote: > > The extra_information is used in MetaThing to tell it what attributes > > to add to the class. For example: > > > > class MetaThing(type): > > def __init__(cls, name, bases, dict, extra_information): > > super(MetaThing, cls).__init__(name, bases, dict) > > #setup the class based on the parameter extra_information > > setattr(cls, make_name(extra_information), > > make_object(extra_information)) > > > > Does that clarify things? > > Why do the extra attributes need to be part of the class? ISTM each > instance has its own class; therefore there it doesn't matter whether a > member is a class member or an instance member. It matters for a "member" that is actually a special-method: Python's automatic search for special methods (except on old-style classes) does NOT look at per-instance members, only at per-class ones. But, as many have already said, a custom metaclass is probably not the optimal tool for this task (and it's definitely wrong to alter a metaclass's __init__'s signature in incompatible ways -- you would never be able to make classes with metaclass MetaThing with a normal class statement, since the intrinsic call to the metaclass's __init__ fails!). Alex From marshall.spight at gmail.com Wed Jun 21 11:12:11 2006 From: marshall.spight at gmail.com (Marshall) Date: 21 Jun 2006 08:12:11 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <4fo19aF1jsudeU1@individual.net> Message-ID: <1150902731.828394.175560@m73g2000cwd.googlegroups.com> David Hopwood wrote: > > Oh, but it *does* make sense to talk about dynamic tagging in a statically > typed language. > > That's part of what makes the term "dynamically typed" harmful: it implies > a dichotomy between "dynamically typed" and "statically typed" languages, > when in fact dynamic tagging and static typing are (mostly) independent > features. That's really coming home to me in this thread: the terminology is *so* bad. I have noticed this previously in the differences between structural and nominal typing; many typing issues associated with this distinction are falsely labeled as a static-vs-dynamic issues, since so many statically type languages are nominally typed. We need entirely new, finer grained terminology. Marshall From christoph.hieronymus at geo.uu.se Sun Jun 18 14:55:58 2006 From: christoph.hieronymus at geo.uu.se (Chris Hieronymus) Date: Sun, 18 Jun 2006 20:55:58 +0200 Subject: Passing data to system command Message-ID: <66160C9F-803F-4EB6-B021-D905515B9247@geo.uu.se> Hi, I have a bunch of x-y data contained in an array. I would like to plot the data using an external program (psxy in GMT). The plotting program takes x-y couples as standard input. How do I get the data into the system call? I used to do things in csh and awk, i.e., something like awk '{; print $1, $2}' filename | psxy >! output.ps The reason I'm trying to use python is because the manipulations are getting too cumbersome in awk. Now I have all the manipulations done in python, but I'm missing that last step. I've tried various things with os.system, popen, and subprocess, but so far without success. Does anyone know how to do this? chris ------------------------------------------------------------------------ ------------------------------------------- Christoph Hieronymus christoph.hieronymus at geo.uu.se Associate Professor phone: (+46) 18-471 2383 Uppsala University fax: (+46) 18-501 110 Dept. of Earth Sciences (Geophysics) Villav?gen 16 SE-752 36 Uppsala, Sweden From jean.moser at neuf.fr Sun Jun 25 07:27:19 2006 From: jean.moser at neuf.fr (jean-jeanot) Date: 25 Jun 2006 04:27:19 -0700 Subject: sum fonction in gadfly References: <1151137825.177814.217180@u72g2000cwu.googlegroups.com> <449d253d$1@nntp0.pdx.net> Message-ID: <1151234839.665889.258660@b68g2000cwa.googlegroups.com> Thank you for your help. I have changed StringVar in IntVar and it works! I didn't know that IntVar (as StringVa) were Tkinter Widget variables! (It is important to read the doc!) I made another mistake in the value definition. I'have changed '%s' in %d and it goes perfectly well. It could be useful for me to change of DB ? Which one ? Postgresql or another ? Jean Moser Scott David Daniels a ?crit : > jean-jeanot wrote: > > After creating the table I create the variables with > > varAmount = StringVar() > Maybe you want to use DoubleVar or IntVar here? > > > With a function > > def treatment (): > > requete = "insert into transactions ( date,amount,,....) > > values(......) "% (varDate.get(), > > varAmount.get > Or float(varAmount.get()) | > int(round(100 * float(varAmount.get()))) here > > > cur.execute ("select sum(amount) from transactions").I get > > Sum.amout.transaction > > ================= > > 100-10.5....... > > > > instead of 110.5 > > > > It means that the select command does not add but concatenates the > > different amounts. Why ? > Sounds like you selected columns are strings, not numbers. > Remember '123.5' + '-23' is '123.5-23', while 123.5 + -23 is 100.5 > You need the amount column of the transactions table in the gadfly > database to be a numeric type, not a string type. > > --Scott David Daniels > scott.daniels at acm.org From Greg_Aumann at sil.org Wed Jun 28 01:45:19 2006 From: Greg_Aumann at sil.org (Greg Aumann) Date: Wed, 28 Jun 2006 14:45:19 +0900 Subject: using TreeBuilder in an ElementTree like way Message-ID: <44A2176F.6080305@sil.org> I am trying to write some python code for a library that reads an XML-like language from a file into elementtree data structures. Then I want to be able to read and/or modify the structure and then be able to write it out either as XML or in the original format. I really want the api for the XML-like language to be the same as the elementtree api to reduce confusion, ease of learning etc. In reading the elementtree documentation I found the ElementTree.TreeBuilder class which it says can be used to create parsers for XML-like languages. So I wrote the code below. The code is working but I am not sure that this is really the intended way to use the ElementTree.TreeBuilder class. Essentially I was trying to implement the following advice from Frederik Lundh (Wed, Sep 8 2004 12:54 am): > by the way, it's trivial to build trees from arbitrary SAX-style sources. > just create an instance of the ElementTree.TreeBuilder class, and call > the "start", "end", and "data" methods as appropriate. > > builder = ElementTree.TreeBuilder() > builder.start("tag", {}) > builder.data("text") > builder.end("tag") > elem = builder.close() but in another post he wrote (Wed, May 21 2003 2:56 am): > usage: > > from elementtree import ElementTree, HTMLTreeBuilder > > # file is either a filename or an open stream > tree = ElementTree.parse(file, parser=HTMLTreeBuilder.TreeBuilder()) > root = tree.getroot() > > or > > from elementtree import HTMLTreeBuilder > > parser = HTMLTreeBuilder.TreeBuilder() > parser.feed(data) > root = parser.close() This second one makes me think I should have implemented a parser class using Treebuilder. Also when I used return builder.close() in the code below it didn't return an ElementTree structure but an _ElementInterface. So my question is really about how I should structure the code so that it is as similar to use this XML format as to use XML itself in elementtree. from elementtree import ElementTree from nltk_lite.corpora.shoebox import ShoeboxFile class Settings(ShoeboxFile): def __init__(self): super(Settings, self).__init__() def parse(self, encoding=None): builder = ElementTree.TreeBuilder() for mkr, value in self.fields(encoding, unwrap=False): block=mkr[0] if block in ("+", "-"): mkr=mkr[1:] else: block=None if block == "+": builder.start(mkr, {}) builder.data(value) elif block == '-': builder.end(mkr) else: builder.start(mkr, {}) builder.data(value) builder.end(mkr) return ElementTree.ElementTree(builder.close()) From duane at franz.com Fri Jun 23 18:36:45 2006 From: duane at franz.com (Duane Rettig) Date: Fri, 23 Jun 2006 15:36:45 -0700 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150902275.129780.50260@p79g2000cwp.googlegroups.com> <1150918629.818145.143220@y41g2000cwy.googlegroups.com> <4fv081F1jh4ifU1@individual.net> <1150967543.947096.72840@g10g2000cwb.googlegroups.com> <4fv84rF1kp06kU1@individual.net> <1150988625.527780.148710@c74g2000cwc.googlegroups.com> <4g22l7F1j8p4mU1@individual.net> <1151081129.290382.297530@r2g2000cwb.googlegroups.com> Message-ID: "Marshall" writes: > Pascal Costanza wrote: >> Marshall wrote: >> > Pascal Costanza wrote: >> >> Consider a simple expression like 'a + b': In a dynamically typed >> >> language, all I need to have in mind is that the program will attempt to >> >> add two numbers. In a statically typed language, I additionally need to >> >> know that there must a guarantee that a and b will always hold numbers. >> > >> > I still don't really see the difference. >> > >> > I would not expect that the dynamic programmer will be >> > thinking that this code will have two numbers most of the >> > time but sometimes not, and fail. I would expect that in both >> > static and dynamic, the thought is that that code is adding >> > two numbers, with the difference being the static context >> > gives one a proof that this is so. >> >> There is a third option: it may be that at the point where I am writing >> this code, I simply don't bother yet whether a and b will always be >> numbers. In case something other than numbers pop up, I can then >> make a decision how to proceed from there. > > Ouch; I have a really hard time understanding this. > > I can't see how you'd call + on a and b if you think they might > not be numbers. If they could be something other than numbers, > and you're treating them as if they are, is that sort of like > doing a case analysis and only filling in one of the cases? > If so, wouldn't you want to record that fact somehow? But suppose + were polymorphic and someone (dynamically) added a method on + to handle strings? If the type error were that a and b happened to be strings, there would be at least two courses of action in the development of the program: limit a and b so that they are never strings at this point, or define a method on + to add correct functionality for the + operator. Note that I use the term "correct", because the correctness of the subprogram (including any added methods on +) depends both on the correctness of usage within the language, and also correctness of extensibilities allowed by the language for the purpose of satisfying goals of the program. In the many cases where the eventual goals of the program are not known at the beginning of the design, this extensibility is a good thing to have. Note that the above paragraph explicitly leaves out Common Lisp, because + is not extensible in CL. CL does, however, allow for methods to be defined on functions not already defined by the standard, so the argument could still apply to some generic function named my-+, or even on my-package::+ where the CL defined + operator is shadowed. -- Duane Rettig duane at franz.com Franz Inc. http://www.franz.com/ 555 12th St., Suite 1450 http://www.555citycenter.com/ Oakland, Ca. 94607 Phone: (510) 452-2000; Fax: (510) 452-0182 From solisgb at gmail.com Fri Jun 30 02:50:08 2006 From: solisgb at gmail.com (luis) Date: 29 Jun 2006 23:50:08 -0700 Subject: conecting with a MsAcces DB by dao Message-ID: <1151650208.783778.186690@d56g2000cwd.googlegroups.com> Hi I'm using activestate python 2.4 on win xp 2 ed. and Ms Access 2002 (reading first http://starship.python.net/crew/bwilk/access.html) I have writed the following code def append_from_Access(self): try: import ... conn = win32com.client.Dispatch(r'ADODB.Connection') DSN = "PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=C:/Afile.mdb;" conn.Open(DSN) except Exception, inst: ... try: sql_statement='SELECT * FROM Mytable' rs = win32com.client.Dispatch(r'ADODB.Recordset') rs.Open(sql_statement, conn, 1, 3) while not rs.EOF: id=rs.Fields(colName.Value) #colName, valid column name ... rs.MoveNext() rs.Close() conn.Close() except Exception, inst: ... I'm using it for reading tables or queries in a mdb file. With some mdb it works fine and return a no empty recordset, but with others mdb files, the recordsets are void (opening the tables or recorsets with Ms Access are not void). Some help is welcome, Thanks in advance Luis From jcb at iteris.com Thu Jun 1 15:01:43 2006 From: jcb at iteris.com (Metalone) Date: 1 Jun 2006 12:01:43 -0700 Subject: Python for Visual Basic or C# programmers In-Reply-To: <1149184981.184143.63160@f6g2000cwb.googlegroups.com> References: <1149184981.184143.63160@f6g2000cwb.googlegroups.com> Message-ID: <1149188503.783262.132870@h76g2000cwa.googlegroups.com> Slight correction. " %d" % 123 is not quite equivalent to str(123) as it does not handle negative numbers the same way. I am not sure there is a simple direct equivalent. "%+d" % 123 --> "+123" always gives a sign. "%4d" % 123 --> " 123" "%4d" % -123 --> "-123" so this works if you you know how wide the number is. This might be a little too tricky. [" %d", "%d][n < 0] % n --> selects list[0] or list[1] based upon sign of number From mhellwig at xs4all.nl Wed Jun 7 09:17:26 2006 From: mhellwig at xs4all.nl (Martin P. Hellwig) Date: Wed, 07 Jun 2006 15:17:26 +0200 Subject: secure xmlrpc server? In-Reply-To: References: <4486c6ee$0$31647$e4fe514c@news.xs4all.nl> Message-ID: <4486d1e9$0$31646$e4fe514c@news.xs4all.nl> Laszlo Nagy wrote: > Martin P. Hellwig wrote: >> Laszlo Nagy wrote: >> >> Have a look at: >> http://trevp.net/tlslite/ >> > C:\temp\ccc>python setup.py install > running install > running build > running build_py > running build_ext > error: The .NET Framework SDK needs to be installed before building > extensions f > or Python. > > C:\temp\ccc> > In the installers directory is exe for windows installation. > > Does it mean that .NET framework is required for tlslite on Windows? > > Also can you please provide an example for tlslite/xmlrpc integration? > The documentation of tlslite is very detailed, but it has many options > and I could not find an example. SimpleXMLRPCServer uses SimpleHTTPServer for its transfer stuff, so you might want to look more in that direction. > > Thanks, > > Laszlo > -- mph From chris.uppal at metagnostic.REMOVE-THIS.org Thu Jun 22 10:53:50 2006 From: chris.uppal at metagnostic.REMOVE-THIS.org (Chris Uppal) Date: Thu, 22 Jun 2006 15:53:50 +0100 Subject: What is a type error? References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <7i3mg.204167$8W1.155367@fe1.news.blueyonder.co.uk> <44992e6c$2$664$bed64819@news.gradwell.net> <%Igmg.464974$xt.353729@fe3.news.blueyonder.co.uk> Message-ID: <449aaea0$2$656$bed64819@news.gradwell.net> Chris Smith wrote: > Some people here seem to be > saying that there is a universal concept of "type error" in dynamic > typing, but I've still yet to see a good precise definition (nor a good > precise definition of dynamic typing at all). How about this, at least as a strawman: I think we're agreed (you and I anyway, if not everyone in this thread) that we don't want to talk of "the" type system for a given language. We want to allow a variety of verification logics. So a static type system is a logic which can be implemented based purely on the program text without making assumptions about runtime events (or making maximally pessimistic assumptions -- which comes to the same thing really). I suggest that a "dynamic type system" is a verification logic which (in principle) has available as input not only the program text, but also the entire history of the program execution up to the moment when the to-be-checked operation is invoked. I don't mean to imply that an operation /must/ not be checked until it is invoked (although a particular logic/implementation might not do so). For instance an out-of-bound array access might be rejected: When the attempt was made to read that slot. When, in the surrounding code, it first became unavoidable that the about read /would/ be reached. When the array was first passed to a function which /might/ read that slot. ...and so on... Note that not all errors that I would want to call type errors are necessarily caught by the runtime -- it might go happily ahead never realising that it had just allowed one of the constraints of one of the logics I use to reason about the program. What's known as an undetected bug -- but just because the runtime doesn't see it, doesn't mean that I wouldn't say I'd made a type error. (The same applies to any specific static type system too, of course.) But the checks the runtime does perform (whatever they are, and whenever they happen), do between them constitute /a/ logic of correctness. In many highly dynamic languages that logic is very close to being maximally optimistic, but it doesn't have to be (e.g. the runtime type checking in the JMV is pretty pessimistic in many cases). Anyway, that's more or less what I mean when I talk of dynamically typed language and their dynamic type systems. > I suspect you'll see the Smalltalk version of the objections raised in > response to my post earlier. In other words, whatever terminology you > think is consistent, you'll probably have a tough time convincing > Smalltalkers to stop saying "type" if they did before. If you exclude > "message not understood" as a type error, then I think you're excluding > type errors from Smalltalk entirely, which contradicts the psychological > understanding again. Taking Smalltalk /specifically/, there is a definite sense in which it is typeless -- or trivially typed -- in that in that language there are no[*] operations which are forbidden[**], and none which might not be invoked deliberately (e.g. I have code which deliberately reads off the end of a container object -- just to make sure I raise the "right" error for that container, rather than raising my own error). But, on the other hand, I do still want to talk of type, and type system, and type errors even when I program Smalltalk, and when I do I'm thinking about "type" in something like the above sense. -- chris [*] I can't think of any offhand -- there may be a few. [**] Although there are operations which are not possible, reading another object's instvars directly for instance, which I suppose could be taken to induce a non-trivial (and static) type logic. From marshall.spight at gmail.com Fri Jun 23 16:36:06 2006 From: marshall.spight at gmail.com (Marshall) Date: 23 Jun 2006 13:36:06 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: <449bde5f$2$663$bed64819@news.gradwell.net> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150908952.804184.218990@r2g2000cwb.googlegroups.com> <1150991074.705803.211570@m73g2000cwd.googlegroups.com> <449bde5f$2$663$bed64819@news.gradwell.net> Message-ID: <1151094966.249077.284610@m73g2000cwd.googlegroups.com> Chris Uppal wrote: > David Hopwood wrote: > > > > But some of the advocates of statically > > > typed languages wish to lump these languages together with assembly > > > language a "untyped" in an attempt to label them as unsafe. > > > > A common term for languages which have defined behaviour at run-time is > > "memory safe". For example, "Smalltalk is untyped and memory safe." > > That's not too objectionable, is it? > > I find it too weak, as if to say: "well, ok, it can't actually corrupt memory > as such, but the program logic is still apt go all over the shop"... It is impossible to evaluate your claim without a specific definition of "go all over the shop." If it means subject to Method Not Understood, then we would have to say that Smalltalk can in fact go all over the shop. If it means subject to memory corruption, then it can't. In any event, the denotation is quite clear: Smalltalk does not formally assign types to expressions during a static analysis phase, and Smalltalk is not subject to memory corruption. I have a problem with the whole line of reasoning that goes "someone might think term x means something bad, so we can't use it." It's unfalsifiable. It also optimizes for malicious use of the terms. Both are bad properties to have as design principles, at least in this context. Marshall From rossberg at ps.uni-sb.de Tue Jun 20 10:42:14 2006 From: rossberg at ps.uni-sb.de (Andreas Rossberg) Date: Tue, 20 Jun 2006 16:42:14 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <1150809118.677124.142230@u72g2000cwu.googlegroups.com> Message-ID: David Squire wrote: > Andreas Rossberg wrote: > >> Rob Thorpe wrote: >> >>>> >>>>> No, that isn't what I said. What I said was: >>>>> "A language is latently typed if a value has a property - called it's >>>>> type - attached to it, and given it's type it can only represent >>>>> values >>>>> defined by a certain class." >>>> >>>> >>>> "it [= a value] [...] can [...] represent values"? >>> >>> >>> ??? >> >> I just quoted, in condensed form, what you said above: namely, that a >> value represents values - which I find a strange and circular definition. > > But you left out the most significant part: "given it's type it can only > represent values *defined by a certain class*" (my emphasis). That qualification does not remove the circularity from the definition. > In C-ish notation: > > unsigned int x; > > means that x can only represent elements that are integers elements of > the set (class) of values [0, MAX_INT]. Negative numbers and non-integer > numbers are excluded, as are all sorts of other things. I don't see how that example is relevant, since the above definition does not mention variables. - Andreas From python.list at tim.thechases.com Mon Jun 26 10:55:41 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 26 Jun 2006 09:55:41 -0500 Subject: Search String for Word In-Reply-To: <1151332947.985001.226510@r2g2000cwb.googlegroups.com> References: <1151332947.985001.226510@r2g2000cwb.googlegroups.com> Message-ID: <449FF56D.5020103@tim.thechases.com> > What's the best way to search a string for a particular word and get a > booleen value indicating whether it exists in the string or not? >>> substring = 'foo' >>> targetstring = 'blah foo bar' >>> substring in targetstring True >>> if substring in targetstring: print 'yup' yup http://docs.python.org/lib/typesseq.html -tkc From aisaac0 at verizon.net Fri Jun 9 18:13:12 2006 From: aisaac0 at verizon.net (David Isaac) Date: Fri, 09 Jun 2006 22:13:12 GMT Subject: Writing PNG with pure Python References: <1149853401.521169.112530@i39g2000cwa.googlegroups.com> <1149889778.182865.181600@f6g2000cwb.googlegroups.com> Message-ID: "Johann C. Rocholl" wrote in message news:1149889778.182865.181600 at f6g2000cwb.googlegroups.com... > What license would you suggest? I recommend that you choose the license that will best achieve your long run goals for the code. As I understand them, and as I understand your application and software development, this implies something like the MIT license: http://www.opensource.org/licenses/mit-license.php I believe that the MIT license maximizes the likelihood that a small scale application will receive useful patches, as long as you actively incorporate patches. You may reach other conclusions for many reasons ... Cheers, Alan Isaac From azadi232 at gmail.com Thu Jun 15 08:04:06 2006 From: azadi232 at gmail.com (azadi232 at gmail.com) Date: 15 Jun 2006 05:04:06 -0700 Subject: how you get Python files on websites? Message-ID: <1150373046.038502.307850@i40g2000cwc.googlegroups.com> i downloaded Python 2.4 and did a bit of playing with it (iam using Windows platform) ................................................................................ i have a few questions about Python 1. Can Python work with databases like MySql,Oracle? (i think it sounds silly) 2.the Python files have .py extension and i used Windows Command Prompt(DOS) to execute the file,how can i use the programs written in Python on the web? (for large-scale search engines) From dax5 at ax5.com Tue Jun 13 06:50:43 2006 From: dax5 at ax5.com (Antonio Arauzo Azofra) Date: Tue, 13 Jun 2006 12:50:43 +0200 Subject: Unimporting modules, memory leak? Message-ID: <448E9883.70408@ax5.com> Hello everybody, Probably, this is being too demanding for Python, but it may be useful to unimport modules to work with dynamic code (though not the best, one example is [2]). In fact, it is supposed to be possible[1], but I have detected it usually leaks memory. When unimported in Linux, the simple C module attached (has no functions, just the structure) leaks two memory pages To see the test you can just put the attached files in a directory and: python setupmod1.py install --install-lib . python testMemory.py Its output follows. First, the memory used before import. Second memory used after the import. Third the number of references to that object is checked before using del. Finally the memory used after unimporting. -- Testing mod1 -- Mem. used: 1242 (gc: 0 ) Mem. used: 1244 (gc: 0 ) Check refs (should be = 2): 2 Mem. used: 1244 (gc: 0 ) -- Testing bigModule -- Mem. used: 1244 (gc: 0 ) Mem. used: 2686 (gc: 0 ) Check refs (should be = 2): 2 Mem. used: 1244 (gc: 0 ) -- Testing random -- Mem. used: 1244 (gc: 0 ) Mem. used: 1256 (gc: 0 ) Check refs (should be = 2): 2 Mem. used: 1256 (gc: 57 ) Unimporting attached "bigmodule.py" there are no memory leaks. Unimporting python's random module it leaks some pages, but garbage collector admit it can not free them. If a module with the same name that the unimported module is imported, the pages are reused. While, if this same module is loaded with another name, they are not freed, and the program grows with each module imported/unimported Is this a Python bug? A Linux bug? Am i missing some way of freeing that memory used by C module? [1] http://mail.python.org/pipermail/python-list/1999-May/002669.html [2] http://ax5.com/antonio/orangesnns PD. If I attach the files the message does not reach to the list :-? Code follows: bigModule.py-------------------------------- def funcion_de_prueba(a,b): print a,b big_list = [] for i in xrange(1000): big_list.append(1000 * 'biiiig') -------------------------------------------- setupmod1.py-------------------------------- from distutils.core import setup, Extension module1 = Extension('mod1', sources = ['srcmod1.c']) setup (name = 'OrangeSNNStmp', version = '1.0', description = 'Function that calls a trained NN', ext_modules = [module1]) -------------------------------------------- srcmod1.c----------------------------------- #include static PyMethodDef orangeSnnsTmpMethods[] = { {NULL, NULL, 0, NULL} /* Sentinel */ }; PyMODINIT_FUNC initmod1(void) { (void) Py_InitModule("mod1", orangeSnnsTmpMethods); } -------------------------------------------- testMemory.py------------------------------- # # Test memory comsumption importing and unimporting modules # import gc, os, sys def printMemoryUse(): rgc = gc.collect() f = open("/proc/" + str(os.getpid()) + "/statm") totalMemorySize = f.readline().split()[0] f.close() print "Mem. used:", totalMemorySize, "(gc:", rgc, ")" def testImport(moduleName): print "-- Testing", moduleName, "--" printMemoryUse() module = __import__(moduleName, globals(), locals()) printMemoryUse() del sys.modules[moduleName] print "Check refs (should be = 2):", sys.getrefcount(module) del module printMemoryUse() testImport("mod1") testImport("bigModule") testImport("random") -------------------------------------------- -- Regards, Antonio Arauzo Azofra From ms at cerenity.org Wed Jun 21 18:37:46 2006 From: ms at cerenity.org (Michael) Date: Wed, 21 Jun 2006 23:37:46 +0100 Subject: Kamaelia 0.4.0 RELEASED - Faster! More Tools! More Examples! More Docs! ; -) Message-ID: <4499c9de$0$69378$ed2619ec@ptn-nntp-reader01.plus.net> Hi! (OK, slightly silly subject line :) I'm extremely pleased to say - Kamaelia 0.4.0 has been released! What's New & Changed? ===================== Kamaelia 0.4.0 is a consolidation, documentation and optimisation enhanced release. Whilst there are a wide variety of new components, existing functionality has been consolidated, and is now in use in a handful of (beta) production systems. Notable New Components * Tools for Timeshifting Digital TV (DVB-T handling to be precise) (These tools are only intended for use as legal under UK law, you need to check locally if you can use them.) * A software data backplane - http://kamaelia.sourceforge.net/Introduction.html has an example using this. * Tools for piping data easily/trivially through external processes * Tools for taking advantage of system optimisations allowing quiescent behaviour. (both in terms of pygame & network based systems) * Tools for using UDP *** Kamaelia 0.4.0 requires the use of Axon 1.5 *** *** (released at the same time as this release). *** Also, virtually all components now have highly detailed documentation inside their sourcefiles. A (large) subset of this is available here: * http://kamaelia.sourceforge.net/Components.html The examples have been duplicated onto the website, and are here: * http://kamaelia.sourceforge.net/Cookbook.html Our tutorial for helping getting started is here: * http://kamaelia.sourceforge.net/MiniAxon/ This has now been battle tested by a good few dozen people, and we feel is a good introduction to Kamaelia's approach, and others have also stated they find it a good way of understanding generators too. (even if they're not interested in Kamaelia) New Examples * Tools for using UDP & SingleServer * A collaborative whiteboard "sketcher" which is both a server to other whiteboards and/or a client to other whiteboards. (Due to changes, when not in use CPU usage for these is as close to zero as it can be for any software) This is also a good example of usage of the backplane component. This application is particularly nice to use in conjunction with a tablet PC! An overview of the sketcher can be found on our systems page: * http://kamaelia.sourceforge.net/Systems.html (see Collaborative Whiteboarding) * Examples for using the tools for timeshifting including: * Tuning into a TV channel on Freeview and recording it to disk * Dumping a DVB multiplex transport stream * Demultiplexing a prestored DVB multiplex A system for grabbing a TV channel and it's now & next information, such that this can allow the programmes to be captured and transcoding as individual programmes for watching later. This is the core of the BBC Macro system (an internal prototype) that can be seen here: * http://bbc.kamaelia.org/cgi-bin/blog/blog.cgi An overview of the architecture can be found here: * http://kamaelia.sourceforge.net/KamaeliaMacro.html Essentially, this allows you to build your own space efficient PVR. General overview of other large scale changes Massively improved documentation across the board (no file left untouched). This is all largely in the form of pydoc based documentation, a fair chunk of it is available at * http://kamaelia.sourceforge.net/Components.html However the documentation in those files goes further than that, including many, many more examples than are even at: * http://kamaelia.sourceforge.net/Cookbook.html *NOTE* Kamaelia 0.4.0 requires Axon-1.5.0 to run due to a number of system optimisations which Kamaelia 0.4.0 takes advantage of. Full release notes and change log: * http://kamaelia.sourceforge.net/Kamaelia-0.4.0-ReleaseNotes.html What Is Kamaelia? ================= See also: http://kamaelia.sourceforge.net/Introduction.html GOAL: Kamaelia is a general component framework for all programmers and maintainable development. Write clear and simple snap-together components using Unix Pipes for the 21st Century. Kamaelia is a library of networking/communications components for innovative multimedia systems. The component architecture is designed to simplify creation and testing of systems, protocols and large scale media delivery systems. A subset of the system has been tested on series 60 mobile phones. It is optimised for simplicity, such that people can get started very rapidly, and such that maintainers can pick up the code of others without misunderstandings. It is designed as a /practical/ toolkit, such that you can build systems such as: * Collaborative whiteboards * Transcoding PVRs for timeshifting TV * Ogg Vorbis streaming server/client systems (via vorbissimple) * Create Video players & streaming systems (for dirac). * With subtitles. * Simple network aware games (via pygame) * Quickly build TCP & Multicast based network servers and clients * Presentation tools * A networked audio mixer matrix (think multiple audio sources over network connections mixed and sent on to multiple locations with different mixes) * Look at graph topologies & customise the rules of display & particle types. .... Mix and match all of the above. These are all real examples you can do today. You can also do a lot of this *visually* using the new PipeBuilder application in Tools. Essentially if the system you want to build involves audio or moving pictures, and you want to be able to make the system network aware, then this should be quick and easy to do using Kamaelia. (If it isn't, then a) it's a bug b) needs improving :-) Oh, and due to things like the visual editor, the use of pygame in a lot of examples, the use of dirac & vorbis, it's a lot of fun too :-) It runs on Linux, Windows, Mac OS X with a subset running on Series 60 phones. (Linux is the primary development system) Requirements ============ * Python 2.3 or higher recommended, though please do report any bugs with 2.2. * Axon (1.5 required) Optional extras: (all available via the Kamaelia download page) * vorbissimple (if you want to use the vorbis decode component/examples) * dirac bindings (again from kamaelia site) if you want to use the dirac encode/decode components & examples). (And dirac of course :-) * python-dvb bindings Axon, vorbissimple and python-dirac are separate parts of the Kamaelia project, and available at the same download location - see below) Platforms ========= Kamaelia has been used successfully under both Linux, Windows and Mac OS X (panther). A subset of Kamaelia has been successfully tested on Series 60 Nokia mobiles when used with the Axon SERIES 60 branch. Where can I get it? =================== Sourceforge Download: http://sourceforge.net/project/showfiles.php?group_id=122494&package_id=133714 Web pages are here: http://kamaelia.sourceforge.net/Docs/ http://kamaelia.sourceforge.net/ (includes info on mailing lists) ViewCVS access is available here: http://cvs.sourceforge.net/viewcvs.py/kamaelia/ Tutorial for the core component/concurrency system: * http://kamaelia.sourceforge.net/MiniAxon/ Project Motivations: * http://kamaelia.sourceforge.net/Challenges/ Licensing ========= Kamaelia is released under the Mozilla tri-license scheme (MPL1.1/GPL2.0/LGPL2.1). See http://kamaelia.sourceforge.net/Licensing.html Best Regards, Michael. -- Michael Sparks, Senior Research Engineer, BBC Research, Technology Group michael.sparks at rd.bbc.co.uk, Kamaelia Project Lead, http://kamaelia.sf.net/ This message (and any attachments) may contain personal views which are not the views of the BBC unless specifically stated. From onurb at xiludom.gro Fri Jun 9 10:24:37 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 09 Jun 2006 16:24:37 +0200 Subject: removing dictionary key-pair In-Reply-To: <128j0r7tla1qi12@corp.supernews.com> References: <128j0r7tla1qi12@corp.supernews.com> Message-ID: <448984a9$0$14889$626a54ce@news.free.fr> JD wrote: > Hello, > > I try to remove a dictionary key-pair (remove an entry), > but I'm unsuccessful. Does anyone know how to achieve this? > > Thanks mydict = {"key" : "value"} del mydict(key) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From iant at the-wire.com Thu Jun 8 10:38:19 2006 From: iant at the-wire.com (moonman) Date: 8 Jun 2006 07:38:19 -0700 Subject: cos: "Integer Required"?!?!?!? Message-ID: <1149777499.262577.318070@u72g2000cwu.googlegroups.com> Hello all, I've just jumped into Python trying to develop X-Plane plugins. All was chugging along well until I tried to use math.cos() snippet: import math .... cos_phi = math.cos(math.radians(XPLMGetDataf(self.ACphi))) # Error occurs here Now XPLMGetDataf should be returning float. Is there something that I'm completely missing about how Python does tyonig or something? Thanks in advance, Moonman From steve at holdenweb.com Wed Jun 28 03:19:23 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 28 Jun 2006 08:19:23 +0100 Subject: [W2k, wxPython 2.6.1.0] - MDISashDemo bug? In-Reply-To: References: Message-ID: w.p. wrote: > Steve Holden wrote: > > >>Well done! Do you know how to feed this information on to the developers >>(probably Robin Dunn)? All such changes are valuable. >> > > > Hmm... i dont know. wxpython.org -> "submit a patch" or "Report a bug" ? > > w.p. Either of those would do, since it's not a huge fix and so won't require a formal patch file. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From jo at durchholz.org Mon Jun 26 16:54:53 2006 From: jo at durchholz.org (Joachim Durchholz) Date: Mon, 26 Jun 2006 22:54:53 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <0%Wlg.3521$MF6.947@tornado.socal.rr.com> <44992e6c$0$664$bed64819@news.gradwell.net> <1151010139.960608.122470@b68g2000cwa.googlegroups.com> Message-ID: Andrew McDonagh schrieb: > Joachim Durchholz wrote: >> Chris Smith schrieb: >>> Joachim Durchholz wrote: >>>> Sorry, I have to insist that it's not me who's stretching terms here. >>>> >>>> All textbook definitions that I have seen define a type as the >>>> set/operations/axioms triple I mentioned above. >>>> No mention of immutability, at least not in the definitions. >>> >>> The immutability comes from the fact (perhaps implicit in these >>> textbooks, or perhaps they are not really texts on formal type >>> theory) that types are assigned to expressions, >> >> That doesn't *define* what's a type or what isn't! >> >> If it's impossible to assign types to all expressions of a program in >> a language, that does mean that there's no useful type theory for the >> program, but it most definitely does not mean that there are no types >> in the program. >> I can still sensibly talk about sets of values, sets of allowable >> operations over each value, and about relationships between inputs and >> outputs of these operations. >> >> So programs have types, even if they don't have a static type system. >> Q.E.D. > > Of course not. Otherwise programs using dynamically typed systems > wouldnt exist. I don't understand. Do you mean dynamic typing (aka runtime types)? > I haven't read all of this thread, I wonder, is the problem to do with > Class being mistaken for Type? (which is usually the issue) No, not at all. I have seen quite a lot beyond OO ;-) Regards, Jo From timr at probo.com Wed Jun 14 03:08:47 2006 From: timr at probo.com (Tim Roberts) Date: Wed, 14 Jun 2006 07:08:47 GMT Subject: Decimals References: <1150188516.739925.102810@h76g2000cwa.googlegroups.com> <1150190908.231517.314040@h76g2000cwa.googlegroups.com> <1150191995.559582.140270@p79g2000cwp.googlegroups.com> Message-ID: "Tgone" wrote: >Sybren Stuvel wrote: >> Tgone enlightened us with: >> > Sorry, when I print out the variable it displays as '15.0'. The >> > price is '15.00' in the database though. >> >> That's the same thing, isn't it? 15.0 == 15.000000000 > >Yes, they're both mathematically the same. I never said they weren't... > >> > Here's my code: >> > >> > product = Product.get(2) >> > print product.price # 15.0 >> >> Try string formatting: >> >> print '%.2f' % product.price > >That works. I expected Python to display the data exactly as it is in >the database, like most languages. "Like most languages?" Name one. C and C++ certainly will not display this with two decimal places, unless you print it out with a %.2f format. DECIMAL is an SQL thing. Unless the language has a native decimal type, it cannot possibly know how to display it in the same format as your SQL. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From fredrik at pythonware.com Thu Jun 15 11:35:12 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 15 Jun 2006 17:35:12 +0200 Subject: Numerics, NaNs, IEEE 754 and C99 In-Reply-To: <1292tvei30ahhd4@corp.supernews.com> References: <12904mjhl493t49@corp.supernews.com> <1290aik50hmk94a@corp.supernews.com> <4490329e$0$12356$636a55ce@news.free.fr> <12917f6jp7u90f8@corp.supernews.com> <44912058$0$29674$636a55ce@news.free.fr> <1292p7s46ef5off@corp.supernews.com> <1292tvei30ahhd4@corp.supernews.com> Message-ID: Grant Edwards wrote: >> Firstly, a FAR more common assumption is that integers wrap in twos' >> complement - Python does not do that. > > It used to for integers ? what version was that ? From fredrik at pythonware.com Tue Jun 6 06:13:47 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 06 Jun 2006 12:13:47 +0200 Subject: Checking var is a number? In-Reply-To: <1149587868.671013.31550@h76g2000cwa.googlegroups.com> References: <1149583700.145737.170720@j55g2000cwa.googlegroups.com> <1149587868.671013.31550@h76g2000cwa.googlegroups.com> Message-ID: dav.phillips at ntlworld.com wrote: > I took a variable to mean a container for diffirent kinds of > information either strings or integers etc, as i am mainly a > asp, php, asp.net developer. in python, a variable is a name that refers to a specific object. it's the object that has a type and a value, not the variable. this article might be somewhat helpful: http://effbot.org/zone/python-objects.htm From robert.thorpe at antenova.com Wed Jun 21 13:29:36 2006 From: robert.thorpe at antenova.com (Rob Thorpe) Date: 21 Jun 2006 10:29:36 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <1150902019.850531.204740@g10g2000cwb.googlegroups.com> Message-ID: <1150910976.455179.55870@r2g2000cwb.googlegroups.com> Dr.Ruud wrote: > Marshall schreef: > > > "dynamic types." I don't have a firm definition for > > that term, but my working model is runtime type tags. In which > > case, I would say that among statically typed languages, > > Java does have dynamic types, but C does not. C++ is > > somewhere in the middle. > > C has union. That's not the same thing. The value of a union in C can be any of a set of specified types. But the program cannot find out which, and the language doesn't know either. With C++ and Java dynamic types the program can test to find the type. From slawomir.nowaczyk.847 at student.lu.se Mon Jun 5 05:48:05 2006 From: slawomir.nowaczyk.847 at student.lu.se (Slawomir Nowaczyk) Date: Mon, 05 Jun 2006 11:48:05 +0200 Subject: An oddity in list comparison and element assignment In-Reply-To: <1hgd7ry.1lrs9rqnn77ayN%aleax@mac.com> References: <1hgd7ry.1lrs9rqnn77ayN%aleax@mac.com> Message-ID: <20060605114741.FC69.SLAWOMIR.NOWACZYK.847@student.lu.se> On Sat, 03 Jun 2006 17:03:00 -0700 aleax at mac.com (Alex Martelli) wrote: #> Terry Reedy wrote: #> #> > Depends what one means by 'copy'. See below for your alternate wording. #> #> Please give me a reasonable definition of the unadorned word "copy" #> which would make this statement false. (And, just to forestall one #> possible attempt: no, I cannot agree that a ``deepcopy'' is a reasonable #> definition of the _unadorned_ word "copy"). Actually, when *I* think about the word "copy", I have in mind what happens with files... and I to me semantics of []*3 is more like symbolic linking, not copying. While I, personally, understand the sentence in question "The result of S*n or n*S is the concatenation of n copies of S" correctly, I *do* see how it might be misunderstood by others. Not that I know how to express it better :-( -- Best wishes, Slawomir Nowaczyk ( Slawomir.Nowaczyk at cs.lth.se ) Don't wake me for the end of the world unless it has very good special effects -- Roger Zelazny From peter-gsellmann at eunet.at Thu Jun 1 17:16:17 2006 From: peter-gsellmann at eunet.at (Peter Gsellmann) Date: Thu, 01 Jun 2006 23:16:17 +0200 Subject: WinPops References: <1149132789_5889@sp6iad.superfeed.net> Message-ID: <447f5781$0$15793$14726298@news.sunsite.dk> Roger Upole wrote: > > "Hari Sekhon" wrote in message > news:mailman.6230.1148640634.27775.python-list at python.org... >> Hi, >> Is there a way of sending winpops (Windows Pop-Up / Net Send messages) >> in python? >> >> Perhaps some library or something that I can use under both Windows and >> Linux? >> >> Hari > > On Windows, you can use win32net.NetMessageBufferSend. > > Roger > On Linux, i use the smbclient binary: from subprocess import * q=Popen(['smbclient','-M','maggy'],stdin=PIPE) q.stdin.write('hello!') q.stdin.close() q.wait() Peter From jo at durchholz.org Tue Jun 20 18:27:29 2006 From: jo at durchholz.org (Joachim Durchholz) Date: Wed, 21 Jun 2006 00:27:29 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150749670.053433.242210@p79g2000cwp.googlegroups.com> <1150754918.338770.89870@i40g2000cwc.googlegroups.com> Message-ID: Chris F Clark schrieb: > In that sense, a static type system is eliminating tags, because the > information is pre-computed and not explicitly stored as a part of the > computation. Now, you may not view the tag as being there, but in my > mind if there exists a way of perfoming the computation that requires > tags, the tag was there and that tag has been eliminated. On a semantic level, the tag is always there - it's the type (and definitely part of an axiomatic definition of the language). Tag elimination is "just" an optimization. > To put it another way, I consider the tags to be axiomatic. Most > computations involve some decision logic that is driven by distinct > values that have previously been computed. The separation of the > values which drive the compuation one-way versus another is a tag. > That tag can potentially be eliminated by some apriori computation. Um... just as precomputing constants, I'd say. Are the constants that went into a precomputed constant eliminated? On the implementation level, yes. On the semantic/axiomatic level, no. Or, well, maybe - since that's just an optimization, the compiler may have decided to no precompute the constant at all. (Agreeing with the snipped parts.) Regards, Jo From rogue_pedro at yahoo.com Sat Jun 24 11:25:32 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 24 Jun 2006 08:25:32 -0700 Subject: HTTP server In-Reply-To: <1151134073.393065.187500@c74g2000cwc.googlegroups.com> References: <1151134073.393065.187500@c74g2000cwc.googlegroups.com> Message-ID: <1151162732.819264.190560@i40g2000cwc.googlegroups.com> placid wrote: > Hi all, > > Ive been reading about creating a HTTP server like the one pydoc > creates (and studying pydoc source code). What i want to know, is it > possible to create server that creates a webpage with hyperlinks that > communicate back to the HTTP server, where each link accessed tells the > server to execute some arbitrary command on local machine its running > on? > > Cheers Yes. It is possible. Ok, seriously, I don't know how pydoc does it, but when I need a quick-and-dirty http server [written in python] I use something like this: from BaseHTTPServer import HTTPServer from SimpleHTTPServer import SimpleHTTPRequestHandler HTTPServer(('', 8000), SimpleHTTPRequestHandler).serve_forever() For what you're asking about you'd probably want to use the CGIHTTPRequestHandler from the CGIHTTPServer module instead. Check out http://docs.python.org/lib/module-CGIHTTPServer.html Then you'd just write one or more cgi scripts (they can be in python IIRC) to run the commands you want. HTH, ~Simon From hdante at gmail.com Tue Jun 20 04:59:26 2006 From: hdante at gmail.com (hdante at gmail.com) Date: 20 Jun 2006 01:59:26 -0700 Subject: Simple script to make .png thumbnails from .zip archive... References: <1150660266.413889.217280@c74g2000cwc.googlegroups.com> <1150769193.295701.246330@g10g2000cwb.googlegroups.com> Message-ID: <1150793966.121556.169590@g10g2000cwb.googlegroups.com> K P S wrote: > Thanks everyone. > routines to list all the files in a zip archive, but I don't see any to > list only the first, or only the second, etc. It doesn't look like If you can list all the files, then you can list only the first. :-) Don't worry about python internal allocation procedures. It will try to make things in an efficient way. Just make sure your code looks cool. ;-) > > zip=zipfile.ZipFile("text.zip",mode="r") > picture=zip.read(zip.namelist(0)) That's because you're using the wrong syntax. -> zip.namelist()[0] However, I bet that your first file in the zip is not a jpeg file. Do this, instead: zip = zipfile.ZipFile('text.zip') jpeglist = [x for x in zip.namelist() if '.jp' in x] try: picture = zip.read(jpeglist[0]) except IndexError: print 'No jpeg found' From andrew.arobert at gmail.com Wed Jun 21 18:58:57 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Wed, 21 Jun 2006 18:58:57 -0400 Subject: Question regarding commit/backout of a message using the pymqi module Message-ID: <129jjq06n1ddh46@corp.supernews.com> Hi everyone, Could someone help explain what I am doing wrong in this code block? This code block is an excerpt from a larger file that receives transmitted files via IBM WebSphere MQSeries an drops it to the local file system. Transmission of the file works as designed but it has a flaw. If the file cannot be created for whatever reason, the transmitted message is lost. What I am trying to do is ensure that a file transmit is considered successful only after the created file's checksum matches. If not, the code should treat it as an error and roll back the message to MQSeries without a commit. The basis for this should be around the pymqi.QueueManager class which is named mq in the block listed below. On execution, I get the traceback of: Traceback (most recent call last): File "M:\MQ\MQ\Scripts\receiver.py", line 269, in ? receiver.run() File "M:\MQ\MQ\Scripts\receiver.py", line 109, in run self.connect() File "M:\MQ\MQ\Scripts\receiver.py", line 118, in connect self.qm.begin() File "c:\python24\lib\site-packages\pymqi.py", line 738, in begin raise MQMIError(rv[0], rv[1]) pymqi.MQMIError: MQI Error. Comp: 1, Reason 2121: WARNING: MQRC_NO_EXTERNAL_PARTICIPANTS Do you have any idea why this might be occurring? class Receiver(object): def __init__(self,qm_name,queue_name): self.qm_name = qm_name self.queue_name = queue_name # Will be set later self.qm = None self.message = None def run(self): self.connect() self.get() def connect(self): """ Connect to queue manager """ try: self.qm = mq.QueueManager(options.qmanager.upper() ) self.qm.begin() except mq.PYIFError, err: mqevlog.event("error",err) sys.exit(1) def get(self): """ Get a message from queue. """ queue = mq.Queue(self.qm, self.queue_name) pmo = mq.pmo(Options = CMQC.MQPMO_SYNCPOINT) md = mq.md() while True: try: var = queue.get(self.message, md, pmo ) except mq.MQMIError,e: if e.reason != CMQC.MQRC_NO_MSG_AVAILABLE: mqevlog.event("error",e) sys.exit(1) break else: buff = StringIO(var) tree = ElementTree(file=buff) # Extract required elements and assign to local variables key = "this should be a well-kept secret" file_name = tree.find("dest").text creation_time = tree.find("creation_time").text contents = tree.find("contents").text check = tree.find("checksum").text #Decode temp file original = file_encoder.decode(contents) # Drop file to disk if os.path.exists(file_name) is False: open(file_name,"wb").write(original) else: mqevlog.event(sys.argv[0],"error","Output file path/name already exists") sys.exit(1) # Get checksum of newly created file sum=csums.getsum(file_name) # Compare checksum of created file with value transmitted if csums.checksum_compare(sys.argv[0],sum,check,file_name) == True: queue.commit() sys.exit(0) else: queue.backout() mqevlog.event("error","CheckSums of received/transmitted files do not match") sys.exit(1) Any help/insight you can provide on this would be greatly appreciated. From matt.good at gmail.com Tue Jun 27 22:57:01 2006 From: matt.good at gmail.com (Matt Good) Date: 27 Jun 2006 19:57:01 -0700 Subject: what is pygtk.require("2.0") for? In-Reply-To: <1151462520.184570.309240@p79g2000cwp.googlegroups.com> References: <1151462520.184570.309240@p79g2000cwp.googlegroups.com> Message-ID: <1151463421.545961.121920@d56g2000cwd.googlegroups.com> yaru22 wrote: > when I read a book, it just said we need to do > > import pygtk > pygtk.require("2.0") > import gtk > > in order to import gtk modules > > What is that pygtk.require("2.0") command for? It enables you to install multiple versions of pygtk in parallel and makes sure when you do "import gtk" you get the version you're expecting. See the FAQ for more info: http://www.async.com.br/faq/pygtk/index.py?req=show&file=faq02.004.htp From aleax at mac.com Sun Jun 25 12:23:07 2006 From: aleax at mac.com (Alex Martelli) Date: Sun, 25 Jun 2006 09:23:07 -0700 Subject: Python taught in schools? References: <1151220913.406987.162420@u72g2000cwu.googlegroups.com> Message-ID: <1hhhbmb.qcvbcn14uox59N%aleax@mac.com> MilkmanDan wrote: > I'll be a college freshman this fall, attending Florida Institute of > Tech studying electrical engineering. > > I was considering taking some classes in programming and computer > science, and I happened to notice that everything taught is using C++. > After further research, it seems to me that C++ seems to be the > dominating language in universities. Must be a weird local phenomenon -- my impression (based on non-scientific but widespread observations) is that _Java_ has come to dominate the programming-language scene in universities. One such observation struck me intensely last year, for example, as Tim O'Reilly was showing (at Euro OSCON 2005) his rich graphical environment for looking at book sales (by category, time, etc etc): Java book sales display an obvious, strong "cyclic" seasonality with a yearly cycle, in a perfect correlation with the times at which students would be likely to buy books. No other language whose book-sales data Tim displayed had anything like that obvious an effect (C, C++, Basic, Perl, Python, Ruby, ...); funny enough, Tim himself, while obviously "seeing" the seasonality (the UK-sales diagram in particular looked almost like a sine wave!-), hadn't thought of the "student purchases" explanation. For some reason, the effect, while obvious already in US data, was even more pronounced in UK data; perhaps UK universities have less flexible timing &c for courses (I don't know much about UK universities -- I do know, however, that in Italy for example summer courses for undergrads are rare to non-existent, while I see there's quite an offer of those in the US). Many others have remarked on Java's ascendancy as a language in universities in many different contexts. Joel Spolski, for example, has bemoaned that ascendancy's effect on how well he can evaluate a new grad in a hiring interview: when undegrads typically learned C or Lisp, he says, he had sure-fire ways to probe if a candidate "has what it takes" to be a top programmer, by asking hard questions respectively on pointers and on recursion; with "everybody" learning Java, he's lost that chance, because a candidate may never have seen pointers and be quite unfamiliar with recursion (supported in Java, of course, but hardly the staple it is in Lisp!-), so poor performance on such questions does not really indicate much:-). Paul Graham, a paladin of Lisp, created quite a stir by stating that you're likely to get better programmers if you look for ones experienced in Python rather than ones experienced in Java; in the midst of the resulting flamefest, he clarified that the issue is not so much about the specific nature of the languages (although, like many Lisp'ers, he finds Python a lesser evil than Java, technically) -- rather, he says that a programmer who's only experienced in Java may have merely "fallen" into it because that's what universities teach and he or she had no motivation to "look elsewhere" and thus probably no deep passion for programming, while somebody experienced in Python (which is not as widely taught) must have taked that path by choice, evidencing a real passion for programming (by looking around and choosing reasonably well -- of course, for Graham, only Lisp would be the "perfect" choice;-). A similar line of reasoning has been used to explain the empirical findings of Software Development magazine's yearly survey on programmers' salaries, which, for years, has shown Python programmers at the top of the heap and Visual Basic programmers at the bottom (I do not recall where Java programmers place, but I think it's closer to the bottom than to the top): VB programmers, goes the reasoning, are closer to have "stumbled" into it and to have no real experience of other languages, while Python programmers typically have strong experience in more languages and use Python _by choice_ -- so, again (the reasoning goes), it's not so much about the languages "per se", but the sociology and psychology around them. ((in terms of the emerging economics discipline of "asymmetric information markets", this would make Python expertise a "signal" of a strong programmer in a way that VB or to a lesser extent Java would not)). > By comparison, our local community college teaches a few classes in VB, > Java, Javascript, C++, and for some reason, PASCAL. Interestingly, Mission College (Santa Clara, CA) offers C (I know because my wife's been studying there to accumulate some credits while Stanford considered her application -- it's now been accepted, so she'll be starting Symbolic Systems there in the fall); Bologna University (I know the details because of the recent study there of my son [Financial Economics], daughter [Telecom Engineering] and daughter's boyfriend [started with Civil Engineering, switched to Political Science] offers: a first course in C, and a second one in Java, for Telecom; Fortran, for Civil engineers (all of these are mandatory for these majors); no mandatory programming for either economics or political scientists, but the suggested optional courses are respectively focused on Advanced Excel (with some VBA for advanced macros) and SPSS (a well-known package for statistics, rather than a "real" programming language). > I'm certianly not against any of this, but out of curiousity does > anyone know of a school that teaches Python? A brief Google search (discarding the flurry of news about Burmese pythons in the Everglades...;-) shows for example that the UWF (for a GIS certificate) requires among others a "UWF Programming Course (Java/SQL/Python/etc.)" for 3 semester hours; UMD's page on professor Einstein's course "Introduction to programming in the physical sciences", entirely focusing on Python, has among the recommended "references" an entry for "Advanced topics from U. Central Florida python class" (which is unfortunately a dead link); the Course Syllabus page for the graduate course "Simulation Analysis of Forest Ecosystems" at ufl.edu includes three Python programming books (and none on other languages); "University of Florida" is also listed at but with no usable link or details. So, yes, Python _is_ used in some Florida universities, but it sure looks like it just occupies some minor niches. To get some indication of the popularity of languages in universities, let's try some google searches and see the number of million hits...: python programming 66.9 M java programming 219 M c++ programming 98.9 M and python university 11.9 M java university 110 M c++ university 26 M so, besides the general indication of relative popularity of the three languages, we can't fail to notice: *OVER HALF* of the java hits also mention university, as compared to *JUST ABOVE 1/4* for C++ and *JUST ABOVE 1/5* for Python -- a rough but interesting confirmation that Java dominates University uses far more than other fields... Alex From fredrik at pythonware.com Wed Jun 21 13:08:15 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 21 Jun 2006 19:08:15 +0200 Subject: [newbie] Iterating a list in reverse ? In-Reply-To: <1150909005.604896.122290@m73g2000cwd.googlegroups.com> References: <1150909005.604896.122290@m73g2000cwd.googlegroups.com> Message-ID: Andy Dingley wrote: > Python newbie: I've got this simple task working (in about ten > different ways), but I'm looking for the "favoured" and "most Python > like" way. > > Forwards I can do this > for t in listOfThings: > print t > > Now how do I do it in reverse? In particular, how might I do it if I > only wanted to iterate part-way through (with a conditional test and a > break), or if I had a large list ? > > reverse( listOfThings ) > for t in listOfThings: > print t for item in reversed(listOfThings): ... >>> help(reversed) Help on class reversed in module __builtin__: class reversed(object) | reversed(sequence) -> reverse iterator over values of the sequence | | Return a reverse iterator ... > As reverse() operates in-place I often can't do this. given that lists only hold references to objects, reversing a *copy* of the list is a lot more efficient than you may think... From shekhar.kaushik at gmail.com Wed Jun 28 03:28:36 2006 From: shekhar.kaushik at gmail.com (Chandrashekhar kaushik) Date: Wed, 28 Jun 2006 12:58:36 +0530 Subject: to py or not to py ? In-Reply-To: References: Message-ID: okay so much for a few spelling errors and abbreviations used by me !! we are losing the main point ! i had a look at mercurial . It deals with SCM . I am typically looking at an application thats to deal with geometry data ( tetras ) , process millions of them and may be process them repeatedly ( iterative ). It would basically involve client-server operations to first distribute data over a computing network and then send requests to process the data at the various nodes that contain the data. it is going to be multi-threaded. Carl , what are the problems that could arise with threading ?? On 6/28/06, Steve Holden wrote: > > Serge Orlov wrote: > > On 6/27/06, Chandrashekhar kaushik wrote: > [...] > >>also is it actually a good idea to write high perf applications in > python ? > > > > > > Take a look at Mercurial sources. > > It's a high performance python application. Or watch Bryan > > O'Sullivan's Mercurial presentation > > he > > talks briefly how they made it work fast. > > > > But writing high performance application in python requires > > self-discipline and attention to details, looking at the way you spell > > I think it will be a challenge ;) > > This doesn't distinguish Python: are there any languages that you can > write high-performance applications in *without* self-discipline and > attention to details? > > regards > Steve > -- > Steve Holden +44 150 684 7255 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Love me, love my blog http://holdenweb.blogspot.com > Recent Ramblings http://del.icio.us/steve.holden > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- shekhar -------------- next part -------------- An HTML attachment was scrubbed... URL: From python.list at tim.thechases.com Thu Jun 15 13:49:47 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 15 Jun 2006 12:49:47 -0500 Subject: a good programming text editor (not IDE) In-Reply-To: <_xgkg.2317$No6.48542@news.tufts.edu> References: <_xgkg.2317$No6.48542@news.tufts.edu> Message-ID: <44919DBB.7080306@tim.thechases.com> I recommend Vim. > I'm looking for suggestions for a good cross-platform text > editor Check. > (which the features for coding, such as syntax > highlighting, etc.) Check. > but not a full IDE with all the fancy jazz > (GUI developer, UML diagrams, etc.). Check. > Ideally, it would be something I could even put on a flash > drive and move from computer to computer, but this isn't > necessary. Check http://72.14.203.104/search?q=cache%3Ahttp%3A//blog.gmane.org/gmane.editors.vim/day%3D20050923 > I do it doesn't seem to remember the window size and position, in your gvimrc, use set lines=50 columns=80 winpos 300 0 > or any options I choose (like showing line numbers). to enable line numbering :set number to disable line numbering :set nonumber to gottle line numbering :set number! > It seems to always reset itself each time I open it. Options can be saved in your vimrc/gvimrc file to preserve settings. Additionally, the viminfo file can be used to preserve registers, etc across editing sessions. On top of that, you can use the ":mksession" command to take a snapshot of a session with all its window positionings, manual folds, etc. > And naturally there are Emacs and Vim, > but I just don't know if I need to invest > *that* much time into learning one of them > (probably Vim, since I hear it's lighter and faster). Excellent idea... :) I invested a bit of time up front to learn vim, but it was well worth every moment I spent on it. I'll be the first to admit that it has a learning curve like a brick wall. But once you get the basics and force yourself to use it until you get comfortable with it, it pays massive dividends. > to free, Check. > open-source Check. > cross-platform Check. In addition, it has folding, both console versions and GUI versions, and a host of plugins for making various files easier to edit. Oh, and a rather helpful mailing list! Just some answers to your questions... -tkc From rtw at freenet.co.uk Sat Jun 3 05:19:07 2006 From: rtw at freenet.co.uk (Rob Williscroft) Date: Sat, 03 Jun 2006 04:19:07 -0500 Subject: Making a second window with Tkinter References: <1149282184.587252.59160@y43g2000cwc.googlegroups.com> <1149305472.893535.67770@h76g2000cwa.googlegroups.com> Message-ID: greenflame wrote in news:1149305472.893535.67770 @h76g2000cwa.googlegroups.com in comp.lang.python: > Ok so I played with your script. Here is a script that more closely > mimics what I would like to do except that the way I make the variable > deckstr will be different. The only thing I am confused about is that > it opens the second window in the beginning and when I click on the > button, it does nothing even after I have closed the other window. > > from Tkinter import * > from string import join > > root = Tk() > > def showdeck(deck): > deckwin = Toplevel() > deckstr = join(deck, "\n") > Label(deckwin, text=deckstr, justify=LEFT, anchor=W, > font="Courier").pack(fill=X) > > L = Button(root, text="Show Deck", font="Courier", > command=showdeck(list('zxcvbnm'))) You made the buttons command option None (which is what showdeck() returns), you need to make command a function that calls showdeck(list('zxcvbnm')). L = Button(root, text="Show Deck", font="Courier", command= lambda : showdeck(list('zxcvbnm'))) > L.pack() > > root.mainloop() > lambda's docs online: http://docs.python.org/ref/lambdas.html Rob. -- http://www.victim-prime.dsl.pipex.com/ From apavluck at gmail.com Mon Jun 26 13:44:20 2006 From: apavluck at gmail.com (Alex Pavluck) Date: 26 Jun 2006 10:44:20 -0700 Subject: break the loop in one object and then return Message-ID: <1151343860.239200.179270@c74g2000cwc.googlegroups.com> I am trying to write the following code to block up evaluation and prompting for entering new information. However, when I break the loop in one object and then return it does not start at the beginning again but rather at the point where it exited. Can someone look at the following code and give me some feedback. yournum = input("I am thinking of a number between 1 and 100.\n Guess which number: ") mynum = (yournum-5) def eval(): if yournum == mynum: print "Wow! You got it!" elif yournum < mynum: print "Nope. Too low" again() elif yournum > mynum: print "Oh, your too high" again() def again(): global yournum yournum = input("guess again: ") eval() eval() From maric at aristote.info Thu Jun 22 10:52:45 2006 From: maric at aristote.info (Maric Michaud) Date: Thu, 22 Jun 2006 16:52:45 +0200 Subject: Registry of Methods via Decorators In-Reply-To: <1150983145.387222.5600@c74g2000cwc.googlegroups.com> References: <1150983145.387222.5600@c74g2000cwc.googlegroups.com> Message-ID: <200606221652.46869.maric@aristote.info> Hi, Le Jeudi 22 Juin 2006 15:32, bayerj a ?crit?: > I want to make a registry of methods of a class during creation. Why ? you already have them in dec2.__dict__ : In [42]: import types In [43]: class a : ....: def b(self) : return ....: @classmethod ....: def c(self) : return ....: ....: In [44]: [ k for k, v in a.__dict__.items() if isinstance(v, types.FunctionType) ] Out[44]: ['b'] In [45]: [ k for k, v in a.__dict__.items() if isinstance(v, classmethod) ] Out[45]: ['c'] Warning : In [46]: list(isinstance(i, types.MethodType) for i in (a.b, a().b, a.__dict__['b'])) Out[46]: [True, True, False] In [47]: list(isinstance(i, types.FunctionType) for i in (a.b, a().b, a.__dict__['b'])) Out[47]: [False, False, True] I would prefer write some inspection method that retrieve all these infos. > My > attempt was this And that can't work, > > """ classdecorators.py > > Author: Justin Bayer > Creation Date: 2006-06-22 > Copyright (c) 2006 Chess Pattern Soft, > All rights reserved. """ > > class decorated(object): > > methods = [] > > @classmethod > def collect_methods(cls, method): > cls.methods.append(method.__name__) > return method > > class dec2(decorated): > > @collect_methods > def first_func(self): > pass > > @collect_methods > def second_func(self): > pass > This is trying to do : first_func = collect_methods(first_fun) but collect_methods doesn't exists in the global namespace (indeed you got a NameError exception). You can't reference it as decorated.collect_methods because the methods will be appended to the decorated.methods list and not one list specific to dec2. You neither can refer it as dec2.collect_methods because dec2 is still undefined. > > def main(): > print dec2.methods > > if __name__ == '__main__': > main() > > This does not work and exits with "NameError: ("name 'collect_methods' > is not defined",)". Which is understandable due to the fact that the > class dec2 is not complete. Not exactly. At any moment in a python program, there are two and only two scope, global and local, global is usually the module level scope (where no 'collect_methods' exists), and, in the case of a class definition, local is the class __dict__ (the local namespace is not same the class and its method). But I'm not sure of what you really want : a list of all decorated methods of all subclasses of a class, or a list of marked method in each class ? -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From ldo at geek-central.gen.new_zealand Tue Jun 27 01:12:54 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 27 Jun 2006 17:12:54 +1200 Subject: Having problems with strings in HTML References: Message-ID: In article , Kiana Toufighi wrote: >print ''' > href="http://bbc.botany.utoronto.ca/ntools/cgi-bin/ntools_treeview_word.cgi?inp >ut=&max=2&values_off=no&remove_bracket=no&show_line_nr=yes&show_link_out=yes&de >cimal_places=10&show_classification=yes&db=arabidopsis&selection=any%20term&mod >e=&mode_nos=&yellow_blue=yes&local_file_name=%(OUT_FILE_NAME)s&show_instruction >s=no&expt_link=NASCArrays&max_adjust=2&view_size=large&highlight=%(HI_LITE_FILE >_NAME)s">GraphicalOutput > ''' % {'OUT_FILE_NAME': OUT_FILE_NAME, 'HI_LITE_FILE_NAME': >HI_LITE_FILE_NAME} By the way, you _do_ realize that your "&" characters should be escaped as "&", don't you? From mcPas.De.Spam at mclaveauPas.De.Spam.com Fri Jun 2 02:12:34 2006 From: mcPas.De.Spam at mclaveauPas.De.Spam.com (Michel Claveau) Date: Fri, 02 Jun 2006 08:12:34 +0200 Subject: C# equivalent to range() References: <1149214153.359809.288610@i39g2000cwa.googlegroups.com> <1149214491.034665.29030@j55g2000cwa.googlegroups.com> <1149217547.618703.209770@i39g2000cwa.googlegroups.com> <1149226573.446484.17340@c74g2000cwc.googlegroups.com> Message-ID: Hi! > There are thousands of threads to choose from in this forum. > If they didn't like this question, they could have picked any other one > to discuss. > There's no need to be disagreeable :-) I think the same thing. -- @-salutations Michel Claveau From robert.kern at gmail.com Tue Jun 20 02:04:44 2006 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 20 Jun 2006 01:04:44 -0500 Subject: OS specific command in Python In-Reply-To: <1150781429.090359.148560@c74g2000cwc.googlegroups.com> References: <1150781429.090359.148560@c74g2000cwc.googlegroups.com> Message-ID: diffuser78 at gmail.com wrote: > I want to write a python program and call OS specific commands in it. > So basically, instead of typing in on the command line argument I want > to have it in a python program and let it do the action. > > for example. in my program I would want to call the ssh feature like > one does on the command line > > ssh Admin at 192.168.2.10 .....etc > > How can I do this easily ? http://www.python.org/doc/current/lib/module-subprocess.html -- 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 From digitalorganics at gmail.com Mon Jun 26 10:06:11 2006 From: digitalorganics at gmail.com (digitalorganics at gmail.com) Date: 26 Jun 2006 07:06:11 -0700 Subject: DictProxy? What is this? In-Reply-To: References: <1151328077.677523.57820@b68g2000cwa.googlegroups.com> Message-ID: <1151330771.142051.312380@b68g2000cwa.googlegroups.com> Fredrik Lundh wrote: > digitalorganics at gmail.com wrote: > > > When I tried to update a class's __dict__, I got an error saying that > > there is no 'update' attribute for dictproxy object. What is a > > dictproxy object? > > a CPython implementation detail, used to protect an internal data structure used > by new-style objects from unexpected modifications. > > Ah, so I'm not suppose to be able to change a class's __dict__? Thanks Fredrik. From anton.vredegoor at gmail.com Wed Jun 21 10:21:23 2006 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Wed, 21 Jun 2006 16:21:23 +0200 Subject: [OT] code is data In-Reply-To: <44982637$0$29812$626a54ce@news.free.fr> References: <44965f53$0$12743$636a55ce@news.free.fr> <4496b29f$0$27412$626a54ce@news.free.fr> <4496e9c9$0$14868$626a54ce@news.free.fr> <4fokj4F1ihat3U1@uni-berlin.de> <4497c20e$0$29656$636a55ce@news.free.fr> <4fpuh5F1i9bl1U1@uni-berlin.de> <4497d72d$0$30964$636a55ce@news.free.fr> <4fq5fkF1k346bU1@uni-berlin.de> <44982637$0$29812$626a54ce@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > You mean like 'converting' javascript to python or python to ruby (or > converting any home-grown DSL to Python, etc) ? Yes, but also what some other posters mentioned, making Pythons internal parsing tree available to other programs (and to Python itself) by using a widely used standard like XML as its datatype. >> Then there are some people who keep insisting they don't understand what >> I'm talking about until I simplify things enough to get them on-board, > > count me in then :( Sorry about that. >> but then simply dismiss my ideas with 'you can already do that easily >> with this standard python construct'. This strategy was also eloquently >> refuted by some other poster, so I don't need to repeat it :-) >> >> I've gotten a lot of things to think about, so thanks all for your >> thoughts, but since this is getting way above my head I'll just wimp out >> and leave the rest of the thread to the experts! > > No way you will escape from your responsabilities so easily !-) Ok, count me back in then too :-) Of course I will be available for further discussion. If more than ten people demand a PEP and no better champion is available (very unlikely) I'll even write a proposal. Anton From jmdeschamps at gmail.com Mon Jun 19 22:31:38 2006 From: jmdeschamps at gmail.com (jmdeschamps at gmail.com) Date: 19 Jun 2006 19:31:38 -0700 Subject: Newbie Question In-Reply-To: <1150767801.754519.165440@y41g2000cwy.googlegroups.com> References: <1150750938.973049.114780@y41g2000cwy.googlegroups.com> <129e55eahc35f00@corp.supernews.com> <1150753085.332654.283270@f6g2000cwb.googlegroups.com> <1150767309.831092.188530@h76g2000cwa.googlegroups.com> <1150767801.754519.165440@y41g2000cwy.googlegroups.com> Message-ID: <1150770698.928563.55530@y41g2000cwy.googlegroups.com> placid wrote: > BartlebyScrivener wrote: > > Saint Malo wrote: > > > If the program searches for blue, i just want it to print blue > > > > Huh? Tell it to print whatever you want. > > > > for line in file: > > if 'blue' in line: > > print 'blue' > > > > for line in file: > > if 'brown' in line: > > print 'brown' > > > > for line in file: > > if 'red' in line: > > print 'weasels rip my flesh' > A little rewrite of the precedent code to make it just a bit closer to a program (since the OP is a so-called newbie) myWords=['blue','red','brown'] # you might use a list myFile=open('mytextfile.txt').readlines() for line in myFile: for word in myWords: if word in line: if word != "red": print 'weasels rip my flesh' else: print "i found",word > wow Dude, this is not efficient at all! You only need to read the file > once not as many times as there are words in your looking for in the > lines of the file FWIW, I'm pretty sure the example of BartleByScrivener didn't entail a new read each time but that it was written for readabilityt purposes only of the "print what you want" idea... ;-) Jean-Marc From bdesth.quelquechose at free.quelquepart.fr Mon Jun 12 21:40:52 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 13 Jun 2006 03:40:52 +0200 Subject: Most elegant way to generate 3-char sequence In-Reply-To: References: <1149889784.391965.271570@h76g2000cwa.googlegroups.com> Message-ID: <448de7ce$0$1612$636a55ce@news.free.fr> James Stroud a ?crit : > SuperHik wrote: > >> and the winner is... :D >> David Isaac wrote: >> >>> alpha = string.lowercase >>> x=(a+b+c for a in alpha for b in alpha for c in alpha) >> >> >> >> > > Not necessarily vying for winner, but David's solution is highly > specific as it doesn't do so well for something like > > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab > . > . > . > zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzy > zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz > And ? Was it asked for ? I'd personaly start with David's solution - IOW : simplest thing that could possibly work -, and only bother making it more generic if/when I have a use case for a more generic solution. Premature generalisation is the root of all evil !-) From jmbc at nospam.fr Mon Jun 19 04:01:28 2006 From: jmbc at nospam.fr (jean-michel bain-cornu) Date: Mon, 19 Jun 2006 10:01:28 +0200 Subject: wxPython GUI designer In-Reply-To: <1150661348.837969.46870@r2g2000cwb.googlegroups.com> References: <1150661348.837969.46870@r2g2000cwb.googlegroups.com> Message-ID: <44965a22$0$7767$7a628cd7@news.club-internet.fr> diffuser78 at gmail.com a ?crit : > I am newbie learning wxPython. I tried using GUI designer called > wxGlade. When it generated code I couldnt get the same level of > flexibility as writing the code by oneself. > > Any view on what you think about using GUI designer tools. > > Every help is appreciated. > Boa is excellent if you stay at a primary level. It's a visual design tool, and it can help you to learn how to manage wx classes. It works on windows and linux as well. My understanding of wxglade is that you need skills about sizers to be confident with it. So if you know how to use sizers, you don't really need a tool. Regards, jm From martin at v.loewis.de Thu Jun 29 16:10:05 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 29 Jun 2006 22:10:05 +0200 Subject: handling unicode data In-Reply-To: <1151515932.365483.311890@m73g2000cwd.googlegroups.com> References: <1151506510.391856.207460@y41g2000cwy.googlegroups.com> <44a2af7d$0$7205$9b622d9e@news.freenet.de> <1151515932.365483.311890@m73g2000cwd.googlegroups.com> Message-ID: <44A4339D.8040303@v.loewis.de> Filipe wrote: >> Also, it appears that DB-Library (the API used by pymssql) always >> returns CP_ACP characters (unless ANSI-to-OEM conversion is enabled); >> so the "right" encoding to use is "mbcs". > > do you mean using something like the following line? > term = unicode(row[1], "mbcs") Correct. > What do you mean by "ANSI-to-OEM conversion is enabled"? (sorry, I'm > quite a newbie to python) It's an SQL server thing more than a Python thing. See AutoAnsiToOem in http://support.microsoft.com/default.aspx?scid=KB;EN-US;199819 Regards, Martin From digitalorganics at gmail.com Mon Jun 26 13:45:04 2006 From: digitalorganics at gmail.com (digitalorganics at gmail.com) Date: 26 Jun 2006 10:45:04 -0700 Subject: Mix-In Class Methods At Run-Time In-Reply-To: <44a00cf0$0$19040$636a55ce@news.free.fr> References: <1151191406.755252.210300@i40g2000cwc.googlegroups.com> <1151193767.589325.158820@m73g2000cwd.googlegroups.com> <1151269186.710343.41210@c74g2000cwc.googlegroups.com> <1151270770.030282.237050@u72g2000cwu.googlegroups.com> <449fa027$0$24929$626a54ce@news.free.fr> <1151327819.320233.305400@i40g2000cwc.googlegroups.com> <44a00cf0$0$19040$636a55ce@news.free.fr> Message-ID: <1151343904.217820.253360@b68g2000cwa.googlegroups.com> Bruno Desthuilliers wrote: > digitalorganics at gmail.com wrote: > > Bruno Desthuilliers wrote: > > > >>digitalorganics at gmail.com wrote: > (snip) > > >>>and 2) what's the reason to use newstyle classes > >>>versus the old? > >> > >>All this is explained on python.org (there's a menu entry for this in > >>the documentation menu). AFAICT, newstyle classes can do whatever > >>oldstyle classes did, *and much more* (descriptors and usable > >>metaclasses) - and they are somewhat faster too. So - compatibility with > >>older Python versions (< 2.2 IIRC) set aside -, there's just no reason > >>to use oldstyle classes. > >> > >> > >>> In order to create the dynamic class "NewClass" in the > >>>code above I called type() but that requires at least one new style > >>>class as a base. Thus, I had to have at least one of my animals inherit > >>>from "object" and this seemed a nuisance since > >> > >>OMG, eight more keystrokes - talk about a nuisance... > > > > > > Like, Oh My God! *claps hand to mouth* lol You humor me. Yes, eight > > more keystrokes. I follow the general rule of, if I'm going to put in > > extra effort, > > OMG, eight more keystrokes - talk about extra effort !-) As I said, its not the effort, its the personal need to know why the effort, however small, is being put in. > > > I'd like to know why. > > The only reason for *not* doing it would be compat issues with pre 2.2.x > versions. > > > So you see, it's not so much an > > adversion to the eight keystrokes (multiplied by however many classes I > > have mind you), > > Strange enough, I do write my share of Python code, and don't even > notice typing the EightKeystrokes. > > > but to not knowing why I should use them. > > Because they are kind of the standard Python object model since 2.2.x ?-) What kind of answer is that? What does that actually mean to me? I'm talking practical reasons here.... > > Did you at least take time to read the doc on newstyle classes on > python.org ? > > FWIW, with 2.5, even exceptions are now newstyle classes. No more > oldstyle classes in the builtins. And AFAICT, no more oldstyle classes > in the standard lib neither. Does that ring a bell ? Yes yes, but I've been able to use all that without declaring a single new-style class. So my question was, what penalty do I actually pay... > > > If I don't > > care for descriptors or metaclasses, > > You *do* care for descriptors. Without descriptors, no properties, no > classmethods, no staticmethods... What a desolation :( > > More seriously, given what you're into actually, not caring about what > one can do with newstyle classes seems really strange to me - like > digging a swimming-pool with a pick and a shovel when you have an > excavator... (disclaimer : google translation, not sure it makes sens in > english...) You have it backwards. Of course I care what can be done with new-style classes. That was precisely the basis for my original question. I wanted to know what those eight keystrokes * #ofclasses gets me, and if its necessary versus just a key to unlock features that I may or may not need. From avelldiroll at yahoo.fr Tue Jun 20 02:52:40 2006 From: avelldiroll at yahoo.fr (Avell Diroll) Date: Tue, 20 Jun 2006 08:52:40 +0200 Subject: OS specific command in Python In-Reply-To: <1150781429.090359.148560@c74g2000cwc.googlegroups.com> References: <1150781429.090359.148560@c74g2000cwc.googlegroups.com> Message-ID: <44979b35$0$8390$626a54ce@news.free.fr> diffuser78 at gmail.com wrote: > I want to write a python program and call OS specific commands in it. > So basically, instead of typing in on the command line argument I want > to have it in a python program and let it do the action. There are several ways to do so : * os.system() if you just want to launch a command (kind of fire-and-forget) * the subprocess module if you want to access stdin, stdout and stderr of the launched command > > for example. in my program I would want to call the ssh feature like > one does on the command line > > ssh Admin at 192.168.2.10 .....etc To interact with an ssh process , there is a great module called pexpect (featuring some examples of how to handle ssh process in python) http://pexpect.sourceforge.net/ OT : paramiko is a module to handle the SSH2 protocol in python http://www.lag.net/paramiko/ From certo at comeno.it Sun Jun 18 08:40:28 2006 From: certo at comeno.it (imho) Date: Sun, 18 Jun 2006 12:40:28 GMT Subject: mapping None values to '' In-Reply-To: <1150632320.443681.42640@r2g2000cwb.googlegroups.com> References: <1150632320.443681.42640@r2g2000cwb.googlegroups.com> Message-ID: <0Rblg.5940$zy5.141663@twister1.libero.it> micklee74 at hotmail.com ha scritto: > hi > i wish to map None or "None" values to "". > eg > a = None > b = None > c = "None" > > map( , [i for i in [a,b,c] if i in ("None",None) ]) > > I can't seem to find a way to put all values to "". Can anyone help? > thanks > You already filtered [a,b,c] in the comprehension list, so you just have to map all its values to "": map(lambda x:"" , [i for i in [a,b,c] if i in ("None",None) ]) From meyer at mesw.de Thu Jun 15 13:18:11 2006 From: meyer at mesw.de (meyer at mesw.de) Date: 15 Jun 2006 10:18:11 -0700 Subject: Which compiler will Python 2.5 / Windows (Intel) be built with? In-Reply-To: <44917535$1@nntp0.pdx.net> References: <1150367139.495114.148550@g10g2000cwb.googlegroups.com> <44917535$1@nntp0.pdx.net> Message-ID: <1150391891.130185.4640@f6g2000cwb.googlegroups.com> Scott, Scott David Daniels wrote: > meyer at mesw.de wrote: > > Hi everyone, > > > > which compiler will Python 2.5 on Windows (Intel) be built with? > > Same as for Python 2.4 (the decision was taken a while ago). > Intel sells a compatible compiler, I believe. the problem is not the ABI, but the runtime libraries. From what you're saying, it looks like we will have to standardize on VS2003. As I said, we need to buy VS anyway because of the MFC support. On the other hand, I really worry about all those people that want to build open source extensions for Python 2.5. It is really possible that there will be no legal, free way to do that soon if you don't have an old installation of the 2003 toolkit lying around somewhere... So I'd like to ask you: why was the decision taken a while ago (and is not subject to reconsideration) and what are the reasons for using VS2003? I mean there must be a real good reason why you're doing this, as I only see disadvantages in it. Markus From maric at aristote.info Thu Jun 15 04:37:18 2006 From: maric at aristote.info (Maric Michaud) Date: Thu, 15 Jun 2006 10:37:18 +0200 Subject: Correctly reading stdout/stderr from subprocess In-Reply-To: <20060614175617.GB5018@workaround.org> References: <20060613222002.GB5153@workaround.org> <200606141556.16856.maric@aristote.info> <20060614175617.GB5018@workaround.org> Message-ID: <200606151037.18563.maric@aristote.info> Le Mercredi 14 Juin 2006 19:56, Christoph Haas a ?crit?: > > Quite interesting. I dived into /usr/lib/python2.4/subprocess.py and > found out that the "communicate()" method actually works similarly. I > might even prefer your version You should'nt IMO, the former 'run2' was quite short compared to this one. Also Popen.communicate is maintained by experienced folks, your function (mine in this case :) ) is not. This is just more job. > because I get the returncode from > run.wait() what "communicate()" does not. > What the problem with getting it from an attribute (returncode) ? -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From michael at araneidae.co.uk.invalid Fri Jun 30 14:13:00 2006 From: michael at araneidae.co.uk.invalid (Michael Abbott) Date: Fri, 30 Jun 2006 19:13:00 +0100 Subject: Import bug: Module executed twice when imported! References: Message-ID: Bump In article , Michael Abbott wrote: > --- test.py --- > import imptest > execfile('subtest.py', dict(__name__ = 'subtest.py')) > --- imptest.py --- > print 'Imptest imported' > --- subtest.py --- > import imptest > --- > > $ python test.py > Imptest imported > Imptest imported > $ I claim this as an unreported (and highly obscure) Python bug. From mcPas.De.Spam at mclaveauPas.De.Spam.com Mon Jun 12 12:07:15 2006 From: mcPas.De.Spam at mclaveauPas.De.Spam.com (Michel Claveau) Date: Mon, 12 Jun 2006 18:07:15 +0200 Subject: Bridge: Ruby to Python communication References: <1150126134.802843.122890@h76g2000cwa.googlegroups.com> Message-ID: Hi! For me, like PHP (message of 11h.35) : Only in Windows, I can call Ruby (more exactly Ruby-script) from Python. I can, also, call, from Python, Ruby-defined-functions, like a method of a Python-class. It's a combination of Active-scripting & dynamic method add to a class. It's run OK with : Ruby-script, Perl-script, PHPscript, VBscript, Jscript. -- @-salutations Michel Claveau -- @-salutations Michel Claveau From g.brandl-nospam at gmx.net Wed Jun 28 09:52:13 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Wed, 28 Jun 2006 15:52:13 +0200 Subject: how do i make an array global In-Reply-To: References: <1151472238.400461.42350@p79g2000cwp.googlegroups.com> Message-ID: Erik Max Francis wrote: > a wrote: > >> def fn(): >> for i in range(l) >> global count >> count[i]= .... >> >> how do i declare count to be global if it is an array > > count = [...] > > def fn(): > global count > for i in range(l): > count[i] = ... > No need for "global" here. Georg From faulkner612 at comcast.net Mon Jun 19 19:16:15 2006 From: faulkner612 at comcast.net (faulkner) Date: 19 Jun 2006 16:16:15 -0700 Subject: Function definition In-Reply-To: <1150758338.302466.102040@r2g2000cwb.googlegroups.com> References: <1150758338.302466.102040@r2g2000cwb.googlegroups.com> Message-ID: <1150758975.376255.67480@p79g2000cwp.googlegroups.com> no. python is not C. python is interpreted, not compiled, so if you want a function to exist when you call it, you need to define it before you call it. it isn't clunky, it's just how it's done. if you want to define a 'main' function at the top of your script/module, go for it. then you can use this: if __name__ == '__main__': sys.exit(main(*sys.argv[1:])) aarondesk wrote: > I have a little .py file that has the format: > > > def fxn(a): > do stuff > > other stuff > ... > r = fxn(a) > .... > > > Now I've tried putting the function declaration after the call but the > program wouldn't work. Is there anyway to put function declarations at > the end of the program, rather than putting them at the beginning, > which is rather clunky? > > Thanks. > Aaron From felipe.lessa at gmail.com Fri Jun 2 17:04:59 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Fri, 02 Jun 2006 18:04:59 -0300 Subject: Open Source Charting Tool In-Reply-To: References: <1L0gg.1841$Su3.159041@news20.bellglobal.com> Message-ID: <1149282299.4189.2.camel@kenshin.CASA> Em Sex, 2006-06-02 ?s 15:42 -0500, Larry Bates escreveu: > ReportLab Graphics can do 2D and pie charts, but I don't think it does > 3D charts yet. > > www.reporlab.org It does, but I'm not sure if the PNG backend is as good as the PDF one. -- Felipe. From beni.cherniavsky at gmail.com Fri Jun 9 12:25:03 2006 From: beni.cherniavsky at gmail.com (cben@users.sf.net) Date: 9 Jun 2006 09:25:03 -0700 Subject: Newbie question about updating multiple objects ... In-Reply-To: <1149753137.498806.314640@c74g2000cwc.googlegroups.com> References: <1149753137.498806.314640@c74g2000cwc.googlegroups.com> Message-ID: <1149870303.338369.294360@c74g2000cwc.googlegroups.com> fivenastydisco at hotmail.com wrote: > All, > Hello and welcome to Python. > Apologies in advance: I'm new to Python and OO, and I'm sure this is a > really simple question, but I just can't seem to crack it on my own, or > through looking at examples. I'm playing around with VPython > (http://www.vypthon.org) to try and teach myself about objects: I've > got a box that I've put some balls in, and I'm trying to get said balls > to move around and bounce off the walls of the box -- that's literally > it. I can put multiple balls in the box, but I can't get them to update > their position -- it works when I have one ball, but now that I have a > list of balls, I can't get them to move. > > I've copied in the code I'm using below, as it's not very long -- can > anyone help me? > Below is your code with the many impovements (including other suggestions in this thread). I've used double (``##``) comments to indicate all changes. Stylistic improvements aside, the biggest issue was that your code didn't bounce the balls off the walls but just wrapped them to the opposite wall. The simplest example of bouncing appears in http://vpython.org/vpythonprog.htm Bouncing requires a separate velocity per ball (when one bounces, the others keep direction). Note that `b.velocity` has no signifacance to the sphere object -- in Python you can add attributes to most objects whenever you want. OOP purists would say this is dirty but "practicality beats purity". You could also use a separate `velocities[b]` dictionary if you prefer. # <--START--> ## Say this at the top if you use division. This fixes 3/2 to equal 1.5. ## (3//2 == 1 if you really want the floor of the ratio.) from __future__ import division from visual import * from random import uniform ## why limit to integral [a,b) values? # set up a box to collide with side_length = 100 minx = side_length * -10 maxx = side_length * 10 miny = side_length * -4 maxy = side_length * 4 numballs = 5 # number of balls ## List comprehensions simplify the ``b=[]; for...: b.append(...)`` idiom balls = [sphere(pos=(uniform(minx, maxx), uniform(miny, maxy)), radius=50, color=color.red) for i in range(numballs)] # create a wireframe of space ## Common spacing conventions: space after commas and around = in ## assignements but not = in keyword arguments left = curve(pos=[(minx, miny), (minx, maxy)], color=color.white) top = curve(pos=[(minx, maxy), (maxx, maxy)], color=color.white) right = curve(pos=[(maxx, maxy), (maxx, miny)], color=color.white) bottom = curve(pos=[(maxx, miny), (minx,miny)], color=color.white) ## Note that your `dt` was not equal to 1/rate, so you were not simulating ## in real time. I'll assume your velocity is correct but will increase ## the simulation speedup to make it less boring. fps = 50 ## this should not be touched once you match it to your computer speedup = 40.0 ## tune this to watch the process at different speeds dt = speedup/fps ## note that a big `dt` will increase simulation errors ## bouncing requires separate velocity per ball for b in balls: ## removed z component since you want a 2D simulation (right?) b.velocity = vector(2, 0.2) while True: ## the idiomatic way to say forever ... rate(fps) ## see comment above for b in balls: ## usually you don't need the indexes, only the items ## First update, then bounce - this way you never display ## a ball outside the box. b.pos += (b.velocity * dt) ## += avoids repeating yourself # check it hasn't overrun a boundary ## if it has, reflect velocity, not wrap around the position if b.x - b.radius < minx: b.velocity.x *= -1 if b.x + b.radius > maxx: b.velocity.x *= -1 if b.y - b.radius < miny: b.velocity.y *= -1 if b.y + b.radius > maxy: b.velocity.y *= -1 # <--END--> The above is an approximation: when the ball has already penetrated the wall to some depth, it only reverses the speed but leaves the ball in the wall. We are simulating a continious process by discrete steps. If the ball is inside the wall it means the collision occured earlier and the ball has already moved away for that distance. (I'm ingnoring ball and wall deformation here. This penetration depends randomly on `dt` so it's not the proper way to simulate deformation anyway.) So we shoud do:: if b.x - b.radius < minx: b.velocity.x *= -1 #b.x = minx - (b.x - b.radius - minx) + b.radius b.x = (minx + b.radius)*2 - b.x and similarly for other cases... From hancock at anansispaceworks.com Wed Jun 21 02:24:17 2006 From: hancock at anansispaceworks.com (Terry Hancock) Date: Wed, 21 Jun 2006 06:24:17 +0000 Subject: Python is fun (useless social thread) ;-) In-Reply-To: References: Message-ID: <4498E611.7040702@anansispaceworks.com> John Salerno wrote: > Did you have to learn it for a job? No, for me, programming is primarily a hobby. I worked on scientific programming in Fortran in the 1980s and in C in the 1990s. Later I did some sys admin work, and managed to use a bit of Python in that. > Or did you just like what you saw and decided to learn it for fun? I became interested in creating a free software graphic adventure game, and we needed a scripting language. A collaborator heavily favored Python, and so I checked it out. I was a stay-at-home Dad at the time, so I had time to work on projects. But I also had to juggle kids. So a programming language like C that required me to "hold a lot of state in my head" was unworkable. When you're watching kids, you have maybe 5-10 minutes between interruptions, so you need to be able to recover your place in seconds. Python makes that more possible than any other language I've seen. At first I was suspicious of the significant whitespace. But I quickly realized the brilliance of it -- it makes the computer queue on the same thing my eyes use to recognize code-blocks, so it's virtually impossible to have an ambiguous code-block bug. In fact, I was stunned at how many common bugs you just can't have happen in Python (of course, later on I discovered a few that it specifically enables, but well, there's no such thing as a perfect solution). > Also, how did you go about learning it? (i.e., like I described > above, I started with the main stuff then moved on to the different > available frameworks) I picked up a copy of Learning Python from O'Reilly books. I went through it in three days -- easily record-breaking time for me to learn a new computer language. Of course, I didn't learn *everything* in that time, but I learned enough to write useful stuff in it. That sold me on it -- it was obviously the right language for me to be using. > Was there any necessity in the specifics you learned, or did you just > dabble in something (e.g. wxPython) for fun? Well, as I said, I started on a game project. Later on, I spent a lot of time using Zope and working on a big-concept CMS design. I think I was way out of my depth actually. I'm considering extending Plone to do what I need, now, but I haven't really had a chance to look at it. > Are there still some things you feel you need to learn or improve? Of course! * I am working on combining auto-generated documentation with pre-written overview documentation to get the 'best of both worlds' documentation for the code. * I am trying to better understand and use testing methodologies. Testing is hard to get in the habit of doing, because it requires forethought -- testing is work you do now, during early development, that saves you tons of time later on, when you are supporting and improving the software. So it's requires some discipline to spend that extra up-front time (even though you know it's going to save you later). * There will always be modules you don't know yet (and more are being written). In particular, I'm looking into installing and extending Plone. I also need to learn more about XML processing and other stuff I'm going to need for processing vector graphics. * I still haven't totally gotten my head around GUIs, nor PyGame (which is back to the game project) though I'm getting closer to my goals. Regrettably, though, it's still a hobby, and I have less time even than I used to. Even though I still stay at home, I have a full time writing workload now, and it's become a little difficult to find enough time for programming. Once again, though, Python's ease of readability really helps me to pick up where I left off when I have to do that (which is a lot). Cheers, Terry -- Terry Hancock (hancock at AnansiSpaceworks.com) Anansi Spaceworks http://www.AnansiSpaceworks.com From robert.kern at gmail.com Wed Jun 21 14:57:11 2006 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 21 Jun 2006 13:57:11 -0500 Subject: Update on Memory problem with NumPy arrays In-Reply-To: <1150907922.908497.120310@u72g2000cwu.googlegroups.com> References: <1150907922.908497.120310@u72g2000cwu.googlegroups.com> Message-ID: sonjaa wrote: > Hi > > last week I posted a problem with running out of memory when changing > values in NumPy arrays. Since then I have tried many different > approaches and > work-arounds but to no avail. > > I was able to reduce the code (see below) to its smallest size and > still > have the problem, albeit at a slower rate. Please post this to numpy-discussion instead of here. Also, please create a ticket in our Trac: http://projects.scipy.org/scipy/numpy > The problem appears to come > from changing values in the array. Does this create another reference > to the > array, which can't be released? Since the array shouldn't be going away and no new arrays should be created that wouldn't cause a problem. It's possible that there is a bug with the scalar objects that are being created when indexing into the arrays. I can reproduce abnormal memory consumption even when I remove the line where you are setting value in the if: clause. > Also, are there other python methods/extensions that can create > multi-deminsional > arrays? A few. numpy's predecessors, Numeric and numarray are still usable, but aren't being actively developed. There's a pure-Python array package somewhere, but I forget the name. -- 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 From bdesth.quelquechose at free.quelquepart.fr Fri Jun 2 20:26:03 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 03 Jun 2006 02:26:03 +0200 Subject: after del list , when I use it again, prompt 'not defined'.how could i delete its element,but not itself? In-Reply-To: <1149235087.256704.309360@g10g2000cwb.googlegroups.com> References: <1149235087.256704.309360@g10g2000cwb.googlegroups.com> Message-ID: <4480a78d$0$3767$636a55ce@news.free.fr> python a ?crit : > after del list , when I use it again, prompt 'not defined'.how could i > delete its element,but not itself? FWIW, del don't delete an object (not directly at least), it just delete the name<->object association. If (and only if) it was the only name referencing that object, then the object will be disposed too. >>> list1 = [1, 2] >>> list2 = list1 >>> id(list1) 1078043852 >>> id(list2) 1078043852 >>> del list2 >>> list1 [1, 2] >>> list2 Traceback (most recent call last): File "", line 1, in ? NameError: name 'list2' is not defined >>> From ptmcg at austin.rr._bogus_.com Fri Jun 30 13:58:12 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 30 Jun 2006 17:58:12 GMT Subject: Regular Expression - old regex module vs. re module References: <1151607229.548737.145800@d56g2000cwd.googlegroups.com> <12aaigaohtou291@corp.supernews.com> Message-ID: "Jim Segrave" wrote in message news:12aaigaohtou291 at corp.supernews.com... > In article , > Paul McGuire wrote: > > >Not an re solution, but pyparsing makes for an easy-to-follow program. > >TransformString only needs to scan through the string once - the > >"reals-before-ints" testing is factored into the definition of the > >formatters variable. > > > >Pyparsing's project wiki is at http://pyparsing.wikispaces.com. > > If fails for floats specified as ###. or .###, it outputs an integer > format and the decimal point separately. It also ignores \# which > should prevent the '#' from being included in a format. > Ah! This may be making some sense to me now. Here are the OP's original re's for matching. exponentPattern = regex.compile('\(^\|[^\\#]\)\(#+\.#+\*\*\*\*\)') floatPattern = regex.compile('\(^\|[^\\#]\)\(#+\.#+\)') integerPattern = regex.compile('\(^\|[^\\#]\)\(##+\)') leftJustifiedStringPattern = regex.compile('\(^\|[^\\<]\)\(<<+\)') rightJustifiedStringPattern = regex.compile('\(^\|[^\\>]\)\(>>+\)') Each re seems to have two parts to it. The leading parts appear to be guards against escaped #, <, or > characters, yes? The second part of each re shows the actual pattern to be matched. If so: It seems that we *don't* want "###." or ".###" to be recognized as floats, floatPattern requires at least one "#" character on either side of the ".". Also note that single #, <, and > characters don't seem to be desired, but at least two or more are required for matching. Pyparsing's Word class accepts an optional min=2 constructor argument if this really is the case. And it also seems that the pattern is supposed to be enclosed in ()'s. This seems especially odd to me, since one of the main points of this funky format seems to be to set up formatting that preserves column alignment of text, as if creating a tabular output - enclosing ()'s just junks this up. My example also omitted the exponent pattern. This can be handled with another expression like realFormat, but with the trailing "****" characters. Be sure to insert this expression before realFormat in the list of formatters. I may be completely off in my re interpretation. Perhaps one of the re experts here can explain better what the OP's re's are all about. Can anybody locate/cite the actual spec for this formatting, um, format? -- Paul From feel.energetic at gmail.com Fri Jun 2 05:07:01 2006 From: feel.energetic at gmail.com (feel_energetic) Date: 2 Jun 2006 02:07:01 -0700 Subject: how to define a static field of a given class Message-ID: <1149239221.045268.6170@g10g2000cwb.googlegroups.com> Hi, I already knew how to define a static method of a class( using staticmethod() ),but I find there isn't a built-in func to build a static field ( something like staticfield() ) can anyone help me on this? thanks very much for your help :) From sjmachin at lexicon.net Thu Jun 29 19:37:14 2006 From: sjmachin at lexicon.net (John Machin) Date: Fri, 30 Jun 2006 09:37:14 +1000 Subject: locating strings approximately In-Reply-To: References: <1151537334.900487.322980@75g2000cwc.googlegroups.com> <44A31824.8000504@lexicon.net> <6e8360ad0606281707w10d7f0ch9636c9e80a9cbe3@mail.gmail.com> Message-ID: <44A4642A.70208@lexicon.net> On 29/06/2006 10:52 AM, John Machin wrote: > On 29/06/2006 10:07 AM, BBands wrote: >> On 6/28/06, John Machin wrote: >>> On 29/06/2006 9:28 AM, BBands wrote: >>> > I'd like to see if a string exists, even approximately, in another. >>> For >>> > example if "black" exists in "blakbird" or if "beatles" exists in >>> > "beatlemania". The application is to look though a long list of songs >>> > and return any approximate matches along with a confidence factor. I >>> > have looked at edit distance, but that isn't a good choice for finding >>> > a short string in a longer one. >>> >>> There is a trivial difference between the traditional >>> distance-matrix-based Levenshtein algorithm for edit distance and the >>> corresponding one for approximate string searching. Ditto between >>> finite-state-machine approaches. Ditto between modern bit-bashing >>> approaches. The trivial difference is that in the searching case one edge of the dynamic programming matrix is initialised (in theory) to [0] * (len(text)+1) whereas in the distance case it is set to range(len(text)+1). >>> >>> > I have also explored >>> > difflib.SequenceMatcher and .get_close_matches, but what I'd really >>> > like is something like: >>> > >>> > a = FindApprox("beatles", "beatlemania") >>> > print a >>> > 0.857 >>> > >>> > Any ideas? >>> >>> You got no ideas from googling "approximate string search python"??? >> >> Yes, many including agrepy and soundex in addition to those I >> mentioned already, but none seem really handy at approximately looking >> up smaller strings in larger ones. I also note that this has been the >> topic of prior discussion without resolutiuon. >> >> jab > > It helps if you tell all that you've done. Otherwise people will tell > you to do what you've done already :-) > > It helps if you reply on-list so that others can see. You may get better > answers sooner. I have to vanish now. Will check back tonight. > Here's a possibly better answer: def approx_search(pattern, text, max_dist): """ Return a generator which yields tuples (endpos, dist) for each possible endpos such that (1) Levenshtein_distance(pattern, text[startpos:endpos]) = dist (2) 0 <= dist <= max_dist for some (undetermined) startpos. Not restricted to strings: (a) pattern must support pattern[i] and len(pattern). (b) text needs only to support enumerate(text). (c) contents of pattern and text need only support the != operator. Example: list(approx_search('Beatles', 'beetles Beat leverage Betelguese', 3)) -> [(6, 3), (7, 2), (8, 3), (12, 3), (13, 3), (14, 3), (15, 2), (16, 2), (17, 3), (26, 3), (27, 3)] """ plen = len(pattern) prange = range(plen) dprev = range(plen+1) dcurr = [0] * (plen+1) dist = plen for tx, tc in enumerate(text): # dcurr[0] = 0 # not needed, never changes for px in prange: dist = dprev[px] + (tc != pattern[px]) temp = dcurr[px] + 1 if temp < dist: dist = temp temp = dprev[px+1] + 1 if temp < dist: dist = temp dcurr[px+1] = dist if dist <= max_dist: yield tx+1, dist dprev, dcurr = dcurr, dprev If you need/want to poke around discovering "startpos", then you need something like the following, which is similar to the function by Magnus Lie Hetland which you'll find on the web, but appears to be about twice as fast without destroying legibility completely :-) def Levenshtein_SJM(aseq, bseq): """ Calculate Levenshtein distance between aseq and bseq. Space O(min(m,n)) Time O(mn) """ alen = len(aseq) blen = len(bseq) if alen > blen: aseq, bseq = bseq, aseq alen, blen = blen, alen if not alen: return blen arange = range(alen) dprev = range(alen+1) dcurr = [0] * (alen+1) for bx in xrange(blen): bc = bseq[bx] dcurr[0] = bx + 1 for ax in arange: dist = dprev[ax] + (bc != aseq[ax]) temp = dcurr[ax] + 1 if temp < dist: dist = temp temp = dprev[ax+1] + 1 if temp < dist: dist = temp dcurr[ax+1] = dist dprev, dcurr = dcurr, dprev return dist Note that both of the above functions use the ancient original algorithm, which takes O(mn) time. For heavy lifting a modern algorithm and use of Pyrex or C are indicated. HTH, John From jim at trainplayer.com Mon Jun 19 21:11:02 2006 From: jim at trainplayer.com (Jim) Date: 19 Jun 2006 18:11:02 -0700 Subject: can't find win32api from embedded pyrun call Message-ID: <1150765862.185334.53290@u72g2000cwu.googlegroups.com> I am trying to figure out how to embed Python in a little C++ Windows console app. Here's the code: // Py_Initialize(); Py_InitializeEx(0); PyRun_SimpleString("from win32com.client import *"); Here's what it does on the last line: File "D:\Python\Lib\site-packages\win32com\__init__.py", line 5, in ? import win32api, sys, ok ImportError: No module named win32api The same line runs fine in IDLE or at the command prompt. It also runs without complaint if I run a release version of the app. To build the debug version I had to build python42_d.lib/dll myself. The reason I can't call PyInitialize is that it crashes with an "invalid signal" error. I don't think it's a path issue -- I've checked system path, sys.path, pythonpath env var, and the pythonpath entry in the registry, all of them loaded with directories including the one with win32api.pyd. Besides, if it were an install or path problem, why would it work at the command prompt? Could it be a problem with the debug lib I built? Any suggestions are welcome. -- Jim From bdesth.quelquechose at free.quelquepart.fr Fri Jun 2 19:38:55 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 03 Jun 2006 01:38:55 +0200 Subject: Conditional Expressions in Python 2.4 In-Reply-To: <7OidneazQ9UJHB3ZnZ2dnUVZ_sGdnZ2d@comcast.com> References: <4480042b$0$29879$636a55ce@news.free.fr> <7OidneazQ9UJHB3ZnZ2dnUVZ_sGdnZ2d@comcast.com> Message-ID: <44809c81$0$14874$626a54ce@news.free.fr> Steven Bethard a ?crit : > A.M wrote: > > Do we have the conditional expressions in Python 2.4? > > bruno at modulix wrote: > (snip) > >> In the meanwhile, there are (sometime tricky? ways to get the same >> result: >> >> a = 1 == 1 and "Yes" or "No" >> a = ("No", "Yes")[1 == 1] > > And just to give some examples where the conditional expression will > show a difference:: > > >>> True and 0 or [] > [] Yes, this is one of the tricky part !-) Always make sure the second term doesn't eval to False. > > >>> def f(): > ... print "don't evaluate me" > ... return 'f' > ... > >>> def g(): > ... return 'g' > ... > >>> (f(), g())[True] Why on earth are you calling the callables *before* testing ? Should be: (f, g)[True]() of course. From python.list at tim.thechases.com Thu Jun 1 12:23:09 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 01 Jun 2006 11:23:09 -0500 Subject: An oddity in list comparison and element assignment In-Reply-To: <1149177617.985251.74560@c74g2000cwc.googlegroups.com> References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> Message-ID: <447F146D.9070903@tim.thechases.com> > As to containers, would you say that envelope containing five $100 > bills is the same as an envelope containing a single $100 bill and 4 > xerox copies of it? If so, I'd like to engage in some envelope > exchanges with you :-) if len(set([bill.serialnumber for bill in envelope])) != len(envelope): refuseMichaelsExchange() Though the way references work, you would have an envelope containing only 5 slips of paper that all say "I have a $100 bill"... :) -tkc From luismgz at gmail.com Thu Jun 29 20:59:14 2006 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 29 Jun 2006 17:59:14 -0700 Subject: Reddit broke - should have remained on Lisp? In-Reply-To: References: <1151626961.232761.255550@d56g2000cwd.googlegroups.com> <1151627462.297352.205150@i40g2000cwc.googlegroups.com> Message-ID: <1151629154.628979.119920@y41g2000cwy.googlegroups.com> K.S.Sreeram wrote: > Have people lost all sense of humor?? Its just reddit's attempt at > humor! I've rarely seen any server errors on reddit, but even when I do > see one.. its funny! > > Here's another one: > http://www.flickr.com/photos/pvera/sets/72057594050280833/ > > Check out their testimonials, its hilarious! > http://reddit.com/static/spreddit/testimonials.html Sure, it looks like a joke! And I don't find it offensive at all. It's just the comment he added below (their site appears to be 3 times slower ...), which seemed to be looking for an argument :-) From rpdooling at gmail.com Fri Jun 2 02:17:35 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 1 Jun 2006 23:17:35 -0700 Subject: Are there something like "Effective Python"? References: <1149224468.481470.74580@i39g2000cwa.googlegroups.com> Message-ID: <1149229055.088793.89010@i39g2000cwa.googlegroups.com> >> I just finished reading Learning Python 3rd ed, For real? I thought there was only a 2nd edition. http://www.oreilly.com/catalog/lpython2/ From onurb at xiludom.gro Fri Jun 9 12:02:23 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 09 Jun 2006 18:02:23 +0200 Subject: [noob question] References and copying In-Reply-To: References: Message-ID: <44899b92$0$19170$626a54ce@news.free.fr> zefciu wrote: > Hello! > > Where can I find a good explanation when does an interpreter copy the > value, and when does it create the reference. Unless you explicitely ask for a copy (either using the copy module or a specific function or method), you'll get a reference. > I thought I understand > it, but I have just typed in following commands: > > >>>>a=[[1,2],[3,4]] - creates a list object containing 2 list objects, the first one containing 2 integer objects with respective values 1 and 2, the second one containing 2 integer objects with respective values 3 and 4 - associates ('binds') the name 'a' with the list object. Now in the current namespace, 'a' refers to this list. >>>>b=a[1] - binds the name 'b' with the second element of [the list bound to] 'a' >>>>b=[5,6] - *re*binds 'b' to a new list containing two integer objects with respective values 5 and 6. >>>>a > > [[1, 2], [3, 4]] > >>>>b > > [5, 6] Which is exactly what you asked for (while not being what you thought you asked for...). > And I don't understand it. I thought, that b will be a reference to a, It was - before you rebind it to another object. > so changing b should change a as well. To be pedantic, you don't change 'b'. You can either modify the object bound to 'b' (which you did not) or rebind 'b' to another object (which you did). > What do I do wrong. confusing rebinding a name and modifying an object. Try this to better see what happens NB : - id() returns the unique identifier of an object - actually, in CPython, it's memory address, - 'is' test for identity ( a is b <=> id(a) == id(b) >>> a = [[1, 2], [3, 4]] >>> id(a) 46912496884192 >>> id(a[1]) 46912496914656 >>> b = a[1] >>> id(b) 46912496914656 >>> b is a[1] True >>> b = [5, 6] >>> id(b) 46912496915520 >>> b is a[1] False >>> Now to modify a[1] thru b : >>> b = a[1] >>> id(b) 46912496914656 >>> b is a[1] True >>> # add an item >>> b.append(5) >>> b [3, 4, 5] >>> b is a[1] True >>> a[1] [3, 4, 5] >>> # remove the first item >>> del b[0] >>> a[1] [4, 5] >>> # replace actual content with something else >>> b[:] = [5, 6] >>> b [5, 6] >>> b is a[1] True >>> a [[1, 2], [5, 6]] >>> > And a > second question - can I create a reference to element of a list of > floating points and use this reference to change that element? Not directly - but this has nothing to do with a reference-or-value problem. It's just that floats (like ints, strings and tuples) are immutable. You'll need either to work with indices or to wrap your floats in mutable objects. I'd recommand the first solution. > Greets to all PyFans > zefciu -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From jeff_barish at earthlink.net Thu Jun 8 09:06:16 2006 From: jeff_barish at earthlink.net (Jeffrey Barish) Date: Thu, 08 Jun 2006 07:06:16 -0600 Subject: Debugging a pickle References: <44878970.8080704@holdenweb.com> Message-ID: Steve Holden wrote: > First of all, verify that you are opening the file in binary mode. Not > doing this is the biggest cause of problems for Windows users, which the > intermittent failure makes me suspect you may be. > > regards > Steve Right on all counts. I am on Windows and I was not opening the file in binary mode either for input or output. I am amazed that it worked at all. Thanks for the suggestion. -- Jeffrey Barish From efuzzyone at netscape.net Tue Jun 13 03:16:49 2006 From: efuzzyone at netscape.net (Surendra Singhi) Date: Tue, 13 Jun 2006 12:46:49 +0530 Subject: Xah Lee network abuse References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148495974.975395.12920@i40g2000cwc.googlegroups.com> <1149998343.493200.144990@h76g2000cwa.googlegroups.com> Message-ID: Its not Xah Lee, who abuses the system. But people like "Erik Max Francis" and "Philippa Cowderoy" who carry on nonsense discussions across mailing lists. -- Surendra Singhi http://ssinghi.kreeti.com ,---- | WHY SHOULD WE SAVE TIGER? | Ans: Saving the tiger means saving mankind.. | | Help http://pudang.tripod.com/ | or https://secure.worldwildlife.org/forms/tiger_appeal_1.cfm `---- From ilias at lazaridis.com Tue Jun 13 12:59:23 2006 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Tue, 13 Jun 2006 19:59:23 +0300 Subject: ANN: Dao 1.0.0-alpha is released In-Reply-To: <1150043255.902842.277460@g10g2000cwb.googlegroups.com> References: <1150043255.902842.277460@g10g2000cwb.googlegroups.com> Message-ID: phoolimin at gmail.com wrote: > Hello, > > It is a pleasure to announce in this mailing list the newly released > Dao. This is the first release after the Dao interpreter being ... > Two modules are also released along with the virtual machine: DaoMySQL > and DaoPyhon. DaoPython is particularly interesting, because it allows > Python modules to be loaded by Dao, then Python variables, functions > and classes can be used conviniently in Dao scripts. ... > For more detail about this release: please visit http://www.xdao.org, > and http://xdao.org/dokuwiki/. the documentation looks nice! hope you've implemented most of my suggestions subjecting reflection. Whenever I have the time, I will take a closer look and check dao against this one: http://lazaridis.com/case/lang/ > Your suggestions and comments are extremely welcome! > Limin FU . -- http://lazaridis.com From johnjsal at NOSPAMgmail.com Wed Jun 14 10:13:27 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 14 Jun 2006 14:13:27 GMT Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jun 12) In-Reply-To: <1150256003.535950.157580@u72g2000cwu.googlegroups.com> References: <1150256003.535950.157580@u72g2000cwu.googlegroups.com> Message-ID: and-google at doxdesk.com wrote: > John Salerno wrote: > >> I love the new 'folder' icon, but how can I access it as an icon? > > I've just given these are proper home, so here: > > http://doxdesk.com/software/py/pyicons.html > > cheers! > Thanks! From nogradi at gmail.com Fri Jun 23 13:47:39 2006 From: nogradi at gmail.com (Daniel Nogradi) Date: Fri, 23 Jun 2006 19:47:39 +0200 Subject: Getting Python scripts to execute in RedHat In-Reply-To: <1151081154.003234.299170@r2g2000cwb.googlegroups.com> References: <1151081154.003234.299170@r2g2000cwb.googlegroups.com> Message-ID: <5f56302b0606231047m18402467iaf2c2f1d196b5db1@mail.gmail.com> > I apologise if this is a stupid newbie error, but I've been googling > "hash bang" and "shebang" all morning. I've added the shebang to my > scripts: > > #!/usr/bin/python > > I've added execute permissions: > > chmod +rx shebang.py > > But I still can't execute my scripts by themselves > > shebang.py ## produces error > > python shebang.py ## runs correctly > > I found one site that mentioned adding "./" to the beginning, and that > works. > > ./shebang.py ## runs correctly. > > I gather that there's a path problem then. My script is in > ~/pyscripts/. How do I get my scripts to run without using "./"? Add ~/pyscripts to your path for example by putting this into your .bash_profile if you are using bash: PATH=$PATH:$HOME/pyscripts export PATH HTH, Daniel From onurb at xiludom.gro Tue Jun 20 04:25:56 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 20 Jun 2006 10:25:56 +0200 Subject: Function definition In-Reply-To: <1150758975.376255.67480@p79g2000cwp.googlegroups.com> References: <1150758338.302466.102040@r2g2000cwb.googlegroups.com> <1150758975.376255.67480@p79g2000cwp.googlegroups.com> Message-ID: <4497b116$0$1604$636a55ce@news.free.fr> faulkner wrote: (pelase don't top-post - fixed) > aarondesk wrote: > (snip) >>Now I've tried putting the function declaration after the call but the >>program wouldn't work. Is there anyway to put function declarations at >>the end of the program, rather than putting them at the beginning, >>which is rather clunky? > no. > python is not C. python is interpreted, not compiled, Please verify your assertions... FWIW, being "compiled" or "interpreted" is not a feature of a language, but of an implementation of a language. And FWIW also, CPython *is* compiled (to byte-code, like Java). -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From padraigkitterick at gmail.com Mon Jun 19 14:07:01 2006 From: padraigkitterick at gmail.com (Padraig) Date: 19 Jun 2006 11:07:01 -0700 Subject: Installing Python on Windows Vista In-Reply-To: <1150732391.956521.125310@r2g2000cwb.googlegroups.com> References: <1150731053.741522.190010@p79g2000cwp.googlegroups.com> <1150732391.956521.125310@r2g2000cwb.googlegroups.com> Message-ID: <1150740421.825972.181940@r2g2000cwb.googlegroups.com> dakman at gmail.com wrote: > Padraig wrote: > > Hi all, > > > > Just a quick question... when I try to install Python on Windows Vista > > Beta 2 the installer seems to hang after I select the destination > > folder, saying that it will "return when it has finished calculating > > disk space requirements". I just can't seem to get past that step. I've > > also tried installing both 2.4.3 and 2.4.2 with no luck. > > > > Any help would be very much appreciated. > > > > Many thanks > > > > P > > I've heard that Windows Vista has many restrictions on reading/writing > to the disk, perhaps you do not have an admin account? I've managed to install it by using the msiexec command to manipulate windows installer directly. Running the installer in any mode that requires user input makes the installer hang when you choose the installation dir. I did an automated install with the following command: msiexec /i python-2.4.3.msi TARGETDIR="C:\Program Files\Python24" ALLUSERS=1 /qb The '/qb' only displays a progress bar and cancel button. This seems to bypass the installer problem. Wierd! I was going to try compatibility mode but it doesn't work for msi packages. From onurb at xiludom.gro Mon Jun 19 04:28:23 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Mon, 19 Jun 2006 10:28:23 +0200 Subject: code is data In-Reply-To: References: <1150574111.415068.255900@p79g2000cwp.googlegroups.com> Message-ID: <44966029$0$12743$636a55ce@news.free.fr> BJ?rn Lindqvist wrote: >> Personally, I would like to see macros in Python (actually Logix >> succeeding is good enough). But I am no language designer and the >> community has no interest in it. When I absolutely need macros, I will >> go elsewhere. > > > One must wonder, when is that? When do you absolutely need macros? > One must wonder, when do you absolutely need HOFs, closures, OO, functions, or even structured programming. All we 'absolutely' need is tests and gotos... (and love, of course !-). -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From max at alcyone.com Mon Jun 5 04:51:58 2006 From: max at alcyone.com (Erik Max Francis) Date: Mon, 05 Jun 2006 01:51:58 -0700 Subject: Where is the ucs-32 codec? In-Reply-To: <4483EB71.9090509@v.loewis.de> References: <1149459785.331497.203920@c74g2000cwc.googlegroups.com> <4483EB71.9090509@v.loewis.de> Message-ID: Martin v. L?wis wrote: > The only reason is that nobody has needed one so far, and because > it is quite some work to do if done correctly. Why do you need it? Why would it be "quite some work"? Converting from UTF-16 to UTF-32 is pretty straightforward, and UTF-16 is already supported. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Democritus may have come from Abdera, but he was no dummy. -- Carl Sagan From aleax at mac.com Sat Jun 17 01:59:36 2006 From: aleax at mac.com (Alex Martelli) Date: Fri, 16 Jun 2006 22:59:36 -0700 Subject: Python is fun (useless social thread) ;-) References: <1150381872.958342.180420@p79g2000cwp.googlegroups.com> Message-ID: <1hh1rsw.kmbbd21vuu9akN%aleax@mac.com> BartlebyScrivener wrote: ... > Especially the Python Cookbook, as I don't normally 'get it' when > someone just describes theory or an abstraction, I also must see an > example. The examples in the Cookbook are useful and also come with > explanations about how they work. Same goes for this group. Nine times Yes, I agree that the Cookbook is particularly advisable for readers who learn best from/via examples. Other very example-rich books include Mark Pilgrim's and Magnus Lie Hetlands', by the way. Alex From sekhon.hari at googlemail.com Mon Jun 26 05:07:59 2006 From: sekhon.hari at googlemail.com (Hari Sekhon) Date: Mon, 26 Jun 2006 10:07:59 +0100 Subject: style question Message-ID: <449FA3EF.7010508@gmail.com> Is it better to do: message = """This is line1. This is line2 This is line3\n""" or message = "This is line1.\n message = message + "This is line2\n" message = message + "This is line3\n" Since the first method does not follow python's clean and easy looking indentation structure but the second just looks crude and ugly anyway. If I indent the first version so the text is lined up to match code indentation then this comes out in the input and isn't aligned there. From bdesth.quelquechose at free.quelquepart.fr Mon Jun 5 10:16:50 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 05 Jun 2006 16:16:50 +0200 Subject: re beginner In-Reply-To: References: <44834d62$0$6192$626a54ce@news.free.fr> <4483665A.206@lexicon.net> Message-ID: <44840d31$0$3870$626a54ce@news.free.fr> Fredrik Lundh a ?crit : > John Machin wrote: > >> Fantastic -- at least for the OP's carefully copied-and-pasted input. >> Meanwhile back in the real world, there might be problems with >> multiple tabs used for 'prettiness' instead of 1 tab, non-integer >> values, etc etc. > > > yeah, that's probably why the OP stated "which always has the same format". Lol. > and the "trying to understand regex for the first time, and it would be > very helpful to get an example" part Yeps, I missed that part when answering yesterday. My bad. From rod at sudden.net Tue Jun 20 18:40:18 2006 From: rod at sudden.net (Sudden Disruption) Date: 20 Jun 2006 15:40:18 -0700 Subject: Iteration over recursion? In-Reply-To: References: <1150808045.539887.291180@i40g2000cwc.googlegroups.com> <1150816827.826028.114740@h76g2000cwa.googlegroups.com> <4498211b$0$8390$626a54ce@news.free.fr> <1150828012.837354.160110@u72g2000cwu.googlegroups.com> <449846e0$0$4793$636a55ce@news.free.fr> Message-ID: <1150843218.307571.9690@c74g2000cwc.googlegroups.com> Nick, > you will have cursed the concept to hell and back again. Been there - done that :-( My point exactly. Years ago with Pascal I took the recursive approach way too often with much distress. I began to learn that if I move enough stuff out of the loop and set up a context that could easily see what was getting "re-cursed" (great term), iteration was often much easier to debug and FAR more effective to execute. Since those times I can count on one hand the times I've used recursion - and then only because I was late for lunch and I knew "i" wouldn't get away from me. > As someone who was in this area when the Algol versus Fortran wars were I'll take your word for it. My start with recursion was Pascal. > Agreed. Recursion should be used when it is the right technology to > clarify the code, and not as a gimmicky, obfuscatory and often dogmatic > substitute for iteration! Well put. > There are algorithms that become almost incomprehensible without recursion, and I > have implemented a recursion layer in both assembler AND Fortran just to enable me > to write them without going bonkers. With a reasonable exception. Sudden Disruption -- Sudden View... the radical option for editing text http://www.sudden.net/ http://suddendisruption.blogspot.com From beliavsky at aol.com Wed Jun 21 18:59:52 2006 From: beliavsky at aol.com (beliavsky at aol.com) Date: 21 Jun 2006 15:59:52 -0700 Subject: source reduction using Python Message-ID: <1150930792.758470.315110@b68g2000cwa.googlegroups.com> Intel has introduced something called CESR, written in Python, to aid C, C++, and Fortran programmers in reducing the sizes of programs included in bug reports. Here is a brief description from http://cache-www.intel.com/cd/00/00/21/93/219320_relnotes_10.pdf : "Compiler Error Source Reducer (CESR) is a set of utilities which are useful individually or collectively in gathering, reducing, pinpointing, protecting, documenting, and bundling test cases comprised of C/C++ or Fortran source code. It can be helpful if you have a large application for which you want to extract a small test case for submission to Intel? Premier Support. CESR can be downloaded from Intel? Premier Support File Downloads - search for text CESR in the file description. CESR is unsupported and should be considered experimental, but we welcome your feedback on it through Intel? Premier Support. CESR requires prior installation of Python 2.2 or newer." I think one needs to qualify for "Intel Premier Support" to get CESR. I wonder if a similar open-source Python program exists. From ptmcg at austin.rr._bogus_.com Thu Jun 8 00:49:34 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Thu, 08 Jun 2006 04:49:34 GMT Subject: Regular Expression question References: <1149714949.542234.148800@y43g2000cwc.googlegroups.com> Message-ID: "Frank Potter" wrote in message news:mailman.6720.1149730752.27775.python-list at python.org... > pyparsing is cool. > but use only re is also OK > # -*- coding: UTF-8 -*- > import urllib2 > html=urllib2.urlopen(ur"http://www.yahoo.com/").read() > > import re > r=re.compile('[^"]+)"[^>]*>',re.IGNORECASE) > for m in r.finditer(html): > print m.group('image') > Ouch - this fails to match any tag that has some other attribute, such as "height" or "width", before the "src" attribute. www.yahoo.com has several such tags. On the other hand, pyparsing's makeHTMLTags defines a starting tag expression that looks for (conceptually): < tagname ZeroOrMore(attrname '=' value) Optional('/') > and does not assume that the first tag is "src", or anything else for that matter. The returned results make the tag attributes accessible as object attributes or dictionary keys. -- Paul From axwack at gmail.com Tue Jun 6 15:53:58 2006 From: axwack at gmail.com (axwack at gmail.com) Date: 6 Jun 2006 12:53:58 -0700 Subject: 10GB XML Blows out Memory, Suggestions? In-Reply-To: <2Qfhg.18186$0v4.787@tornado.texas.rr.com> References: <1149594519.098115.8980@u72g2000cwu.googlegroups.com> <2Qfhg.18186$0v4.787@tornado.texas.rr.com> Message-ID: <1149623638.736338.185320@h76g2000cwa.googlegroups.com> Paul, This is interesting. Unfortunately, I have no control over the XML output. The file is from Goldmine. However, you have given me an idea... Is it possible to read an XML document in compressed format? Paul McGuire wrote: > wrote in message > news:1149594519.098115.8980 at u72g2000cwu.googlegroups.com... > > I wrote a program that takes an XML file into memory using Minidom. I > > found out that the XML document is 10gb. > > > > I clearly need SAX or something else? > > > > You clearly need something instead of XML. > > This sounds like a case where a prototype, which worked for the developer's > simple test data set, blows up in the face of real user/production data. > XML adds lots of overhead for nested structures, when in fact, the actual > meat of the data can be relatively small. Note also that this XML overhead > is directly related to the verbosity of the XML designer's choice of tag > names, and whether the designer was predisposed to using XML elements over > attributes. Imagine a record structure for a 3D coordinate point (described > here in no particular coding language): > > struct ThreeDimPoint: > xValue : integer, > yValue : integer, > zValue : integer > > Directly translated to XML gives: > > > 4 > 5 > 6 > > > This expands 3 integers to a whopping 101 characters. Throw in namespaces > for good measure, and you inflate the data even more. > > Many Java folks treat XML attributes as anathema, but look how this cuts > down the data inflation: > > > > This is only 50 characters, or *only* 4 times the size of the contained data > (assuming 4-byte integers). > > Try zipping your 10Gb file, and see what kind of compression you get - I'll > bet it's close to 30:1. If so, convert the data to a real data storage > medium. Even a SQLite database table should do better, and you can ship it > around just like a file (just can't open it up like a text file). > > -- Paul From maric at aristote.info Mon Jun 5 13:40:24 2006 From: maric at aristote.info (Maric Michaud) Date: Mon, 5 Jun 2006 19:40:24 +0200 Subject: Storing nothing in a dictionary and passing it to a function In-Reply-To: <1149527899.364138.312150@j55g2000cwa.googlegroups.com> References: <1149527899.364138.312150@j55g2000cwa.googlegroups.com> Message-ID: <200606051940.25765.maric@aristote.info> Le Lundi 05 Juin 2006 19:18, 63q2o4i02 at sneakemail.com a ?crit?: > Any thoughts? In [24]: a, b = (lambda : 'works like this'), (lambda a, b : (a,b)) In [25]: a(*()) Out[25]: 'works like this' In [26]: b(4,3) Out[26]: (4, 3) -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From jmbc at nospam.fr Thu Jun 8 02:15:47 2006 From: jmbc at nospam.fr (jean-michel bain-cornu) Date: Thu, 08 Jun 2006 08:15:47 +0200 Subject: what are you using python language for? In-Reply-To: References: Message-ID: <4487c0cd$0$7763$7a628cd7@news.club-internet.fr> This is my main development tool. I use it for business specific applications (with wx, cherrypy and mysql), mail server administration (in console mode and with cherrypy), and utilities. Regards jm From DustanGroups at gmail.com Mon Jun 5 20:59:57 2006 From: DustanGroups at gmail.com (Dustan) Date: 5 Jun 2006 17:59:57 -0700 Subject: Again, Downloading and Displaying an Image from the Internet in Tkinter Message-ID: <1149555597.559051.162590@i39g2000cwa.googlegroups.com> Nobody answered last time. I guess they wanted me to give it a shot. Well, here is how I download the image (it's a class method): def download_image(self): web_download=self.opener.open(self.url) save=open("image.jpg","w") save.writelines(web_download.readlines()) save.close() web_download.close() self.opener is urllib.URLopener(), self.url is the url for the image. I display the image as follows: self.image=t.Label(self.frame,image=path+"\\image.jpg") t is Tkinter, path is sys.path[0]. (if sys.path[0] is not the proper way of getting the program's path, inform me; I hunted it down without any reference to look to) But the image won't display, using any application (including Tkinter, paint, Firefox, etc.). I'm assuming the reason it can't be read is because the image is protected from downloading. So, once again, is there a better way to download and display an image using Tkinter? Did I try hard enough for you? Are you going to help me this time? From johnjsal at NOSPAMgmail.com Mon Jun 12 12:55:12 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 12 Jun 2006 16:55:12 GMT Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jun 12) In-Reply-To: References: Message-ID: Cameron Laird wrote: > Andrew Clover provides new Python icons: > http://doxdesk.com/img/software/py/icons2.png > http://mail.python.org/pipermail/python-dev/2006-March/063235.html > http://mail.python.org/pipermail/python-dev/2006-April/063517.html I love the new 'folder' icon, but how can I access it as an icon? The first link above seems to be just one big image with all four icons in it. The other links only lead to the old zip file that doesn't include the new icon. Thanks. From scott.daniels at acm.org Sat Jun 24 08:04:24 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Sat, 24 Jun 2006 05:04:24 -0700 Subject: sum fonction in gadfly In-Reply-To: <1151137825.177814.217180@u72g2000cwu.googlegroups.com> References: <1151137825.177814.217180@u72g2000cwu.googlegroups.com> Message-ID: <449d253d$1@nntp0.pdx.net> jean-jeanot wrote: > After creating the table I create the variables with > varAmount = StringVar() Maybe you want to use DoubleVar or IntVar here? > With a function > def treatment (): > requete = "insert into transactions ( date,amount,,....) > values(......) "% (varDate.get(), > varAmount.get Or float(varAmount.get()) | int(round(100 * float(varAmount.get()))) here > cur.execute ("select sum(amount) from transactions").I get > Sum.amout.transaction > ================= > 100-10.5....... > > instead of 110.5 > > It means that the select command does not add but concatenates the > different amounts. Why ? Sounds like you selected columns are strings, not numbers. Remember '123.5' + '-23' is '123.5-23', while 123.5 + -23 is 100.5 You need the amount column of the transactions table in the gadfly database to be a numeric type, not a string type. --Scott David Daniels scott.daniels at acm.org From maric at aristote.info Mon Jun 5 12:22:54 2006 From: maric at aristote.info (Maric Michaud) Date: Mon, 5 Jun 2006 18:22:54 +0200 Subject: strategy pattern and non-public virtual functions In-Reply-To: <1149516464.874257.194030@j55g2000cwa.googlegroups.com> References: <1149516464.874257.194030@j55g2000cwa.googlegroups.com> Message-ID: <200606051822.55920.maric@aristote.info> Le Lundi 05 Juin 2006 16:07, pythoncurious at gmail.com a ?crit?: > class Base { > ? public: > ? ? void f() { this->f_(); } > ? private: > ? ? virtual void f_() = 0; > }; > > class Derived : public Base { > ? private: > ? ? void f_() { // Do something } > }; > > int main() { > ? ? Derived d; > ? ? d.f(); > } This is just polymorphism, not strategy pattern, and I would expect f_ to be protected here not private. You want to ensure derived class will use a given method in the Base class, this could be done explicit with a good naming convention as Duncan said, but here is a strategy pattern to ensure a sanity check for example : class strategyBase(object) : def __call__(self, *sa) : raise NotImplementedError('abstract class') class InputProcessor(object) : def sanitize(self, *a) : return a def f(self, *a) : sa = self.sanitize(*a) return self.strategy(*sa) def __setStrategy(self, strat) : if not isinstance(strat, strategyBase) : raise ValueError("strat must be of type strategyBase") self.__strat = strat strategy = property(fget=lambda s : s.__strat, fset=__setStrategy) The main purpose of this is to define a common API for all Strategies, and this is really useful if you intend to manage many of them. -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From gokcemutlu at gmail.com Sun Jun 25 04:29:38 2006 From: gokcemutlu at gmail.com (gokcemutlu at gmail.com) Date: 25 Jun 2006 01:29:38 -0700 Subject: Can you help me with the below code? Urgent! Message-ID: <1151224178.479401.119620@r2g2000cwb.googlegroups.com> I want to trace a function while it executes and keep its local variables as states. In trace function all the things work well but after all when I print states, they are all the same. I couldn't solve the problem. I guess it's because of frame, please can you help me? import sys states = [] def traceit(frame, event, arg): location = frame.f_code.co_name if location == "afunc": states.append(frame.f_locals) print frame.f_locals return traceit def afunc(a, b, c): x = a + b y = b + c z = b rslt = x + y - z return rslt print "This is what I should see!" sys.settrace(traceit) afunc(1, 2, 3) sys.settrace(None) print "\nWhy does this happen and how can I solve it?" for s in states: print s From fredrik at pythonware.com Fri Jun 30 05:51:38 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 30 Jun 2006 11:51:38 +0200 Subject: Entry Widget problem References: <44A4F192.9010703@o2.pl> Message-ID: Marek S. wrote: > def __init__(self): ... > self.c=f.readline() > c1=int(self.c) > self.FieldList=[] > self.FieldList.append(c1) here you add an integer to the list. > def Pola(self,k,icol,irow,DefaultValue): > self.Tab=StringVar() ... > self.FieldList.append(self.Tab) and here you add a StringVar. From bdesth.quelquechose at free.quelquepart.fr Fri Jun 2 20:14:26 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 03 Jun 2006 02:14:26 +0200 Subject: New to Python: Do we have the concept of Hash in Python? In-Reply-To: References: <%aIfg.3027$EF1.232063@news20.bellglobal.com> Message-ID: <4480a4d5$0$20871$626a54ce@news.free.fr> Fredrik Lundh a ?crit : > "A.M" wrote: > > >>>are your boss aware of this ? >> >>In fact my boss is quite impressed with my progress so far. > > > *your* progress ? I think this meant "the progress status of the software". From sjmachin at lexicon.net Tue Jun 13 02:46:02 2006 From: sjmachin at lexicon.net (John Machin) Date: Tue, 13 Jun 2006 16:46:02 +1000 Subject: Getting "TypeError:list indices must be integers" In-Reply-To: References: Message-ID: <448E5F2A.5000008@lexicon.net> On 13/06/2006 4:11 PM, Girish Sahani wrote: > Hi, > Please check out the following loop,here indexList1 and indexList2 are a > list of numbers. Later you say they are integers. Note: Python calls 2.0 a float, not an integer. |>>> foo = [9, 8, 7] |>>> foo[2.0] Traceback (most recent call last): File "", line 1, in ? TypeError: list indices must be integers |>>> > > for index1 in indexList1: > for index2 in indexList2: > if ti1[index1] == ti2[index2] and not index1 != indexList1.pop(): Wouldn't ... and index1 == indexList1.pop() be easier to follow? Didn't I read earlier today somebody being admonished for modifying a list over which they were iterating? Who was that? You! What do you think indexList1.pop() is doing??? > index1+=1 > index2+=1 The above 2 statements have no effect at all. In particular, they *don't* affect the next value used by the relevant for statement, if that's what you were hoping for. > continue > elif index1 == indexList1.pop() and charList in pairList: > k = string2.index(char2[0]) > instance = ti2(k) > tiNew = ti1.append(instance) > tiNewList.append(tiNew) > else: > break > > On running my program, python gives me a TypeError saying: > > if ti1[index1] == ti2[index2] and not index1 != indexList1.pop(): > TypeError: list indices must be integers > > Even though index1 and index2 are really integers.Please help! How do you know that they are integers? Have you followed the advice given by readers of previous episodes of your adventures, and inserted print statements at relevant points? In this case, inserting print repr(index1), repr(index2) immediately after the 2nd for statement would be a very good idea. Please do come back and tell us what you find out, *and* what you have learned. HTH, John From diffuser78 at gmail.com Fri Jun 30 15:01:47 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 30 Jun 2006 12:01:47 -0700 Subject: efficiency question In-Reply-To: <1151668845.318085.276910@h44g2000cwa.googlegroups.com> References: <6AD91BEE-08AF-446D-AE17-B2FB5532E7FE@math.harvard.edu> <1151668845.318085.276910@h44g2000cwa.googlegroups.com> Message-ID: <1151694107.620186.73210@i40g2000cwc.googlegroups.com> can you please explain how to read these output...I mean how to understand them. A quick glance tells you that the latter approach has less number of instructions and thats why its better. Any more insight would help a lot. MTD wrote: > For the sake of comparison: > > >>> def cod(x): > ... tupple1 = ("abc", "def", "xyz") > ... tupple2 = ("pqr", "tuv", "123") > ... if x in tupple1: > ... doStuff() > ... elif x in tupple2: > ... doOtherStuff() > ... > >>> dis.dis(cod) > 2 0 LOAD_CONST 7 (('abc', 'def', 'xyz')) > 3 STORE_FAST 2 (tupple1) > > 3 6 LOAD_CONST 8 (('pqr', 'tuv', '123')) > 9 STORE_FAST 1 (tupple2) > > 4 12 LOAD_FAST 0 (x) > 15 LOAD_FAST 2 (tupple1) > 18 COMPARE_OP 6 (in) > 21 JUMP_IF_FALSE 11 (to 35) > 24 POP_TOP > > 5 25 LOAD_GLOBAL 3 (doStuff) > 28 CALL_FUNCTION 0 > 31 POP_TOP > 32 JUMP_FORWARD 25 (to 60) > >> 35 POP_TOP > > 6 36 LOAD_FAST 0 (x) > 39 LOAD_FAST 1 (tupple2) > 42 COMPARE_OP 6 (in) > 45 JUMP_IF_FALSE 11 (to 59) > 48 POP_TOP > > 7 49 LOAD_GLOBAL 4 (doOtherStuff) > 52 CALL_FUNCTION 0 > 55 POP_TOP > 56 JUMP_FORWARD 1 (to 60) > >> 59 POP_TOP > >> 60 LOAD_CONST 0 (None) > 63 RETURN_VALUE From jstroud at ucla.edu Sat Jun 10 19:26:54 2006 From: jstroud at ucla.edu (James Stroud) Date: Sat, 10 Jun 2006 16:26:54 -0700 Subject: Most elegant way to generate 3-char sequence In-Reply-To: References: <1149889784.391965.271570@h76g2000cwa.googlegroups.com> Message-ID: SuperHik wrote: > James Stroud wrote: > >> SuperHik wrote: >> >>> and the winner is... :D >>> David Isaac wrote: >>> >>>> alpha = string.lowercase >>>> x=(a+b+c for a in alpha for b in alpha for c in alpha) >>> >>> >>> >>> >> >> Not necessarily vying for winner, but David's solution is highly >> specific as it doesn't do so well for something like >> >> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab >> . >> . >> . >> zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzy >> zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz > > > Right. But that wasn't the question :p > >> >> >> James >> highly specific -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From anton at appsolutions.com Thu Jun 22 18:08:14 2006 From: anton at appsolutions.com (Anton van Straaten) Date: Thu, 22 Jun 2006 22:08:14 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: <1150904134.520639.71070@b68g2000cwa.googlegroups.com> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150904134.520639.71070@b68g2000cwa.googlegroups.com> Message-ID: Marshall wrote: > Can you be more explicit about what "latent types" means? > I'm sorry to say it's not at all natural or intuitive to me. > Are you referring to the types in the programmers head, > or the ones at runtime, or what? Sorry, that was a huge omission. (What I get for posting at 3:30am.) The short answer is that I'm most directly referring to "the types in the programmer's head". A more complete informal summary is as follows: Languages with latent type systems typically don't include type declarations in the source code of programs. The "static" type scheme of a given program in such a language is thus latent, in the English dictionary sense of the word, of something that is present but undeveloped. Terms in the program may be considered as having static types, and it is possible to infer those types, but it isn't necessarily easy to do so automatically, and there are usually many possible static type schemes that can be assigned to a given program. Programmers infer and reason about these latent types while they're writing or reading programs. Latent types become manifest when a programmer reasons about them, or documents them e.g. in comments. (As has already been noted, this definition may seem at odds with the definition given in the Scheme report, R5RS, but I'll address that in a separate post.) There's a close connection between latent types in the sense I've described, and the "tagged values" present at runtime. However, as type theorists will tell you, the tags used to tag values at runtime, as e.g. a number or a string or a FooBar object, are not the same thing as the sort of types which statically-typed languages have. A simple example of the distinction can be seen in the type of a function. Using Javascript as a lingua franca: function timestwo(x) { return x * 2 } In a statically-typed language, the type of a function like this might be something like "number -> number", which tells us three things: that timestwo is a function; that it accepts a number argument; and that it returns a number result. But if we ask Javascript what it thinks the type of timestwo is, by evaluating "typeof timestwo", it returns "function". That's because the value bound to timestwo has a tag associated with it which says, in effect, "this value is a function". But "function" is not a useful type. Why not? Because if all you know is that timestwo is a function, then you have no idea what an expression like "timestwo(foo)" means. You couldn't write working programs, or read them, if all you knew about functions was that they were functions. As a type, "function" is incomplete. By my definition, though, the latent type of timestwo is "number -> number". Any programmer looking at the function can figure out that this is its type, and programmers do exactly that when reasoning about a program. (Aside: technically, you can pass timestwo something other than a number, but then you get NaN back, which is usually not much use except to generate errors. I'll ignore that here; latent typing requires being less rigourous about some of these issues.) So, where do tagged values fit into this? Tags help to check types at runtime, but that doesn't mean that there's a 1:1 correspondence between tags and types. For example, when an expression such as "timestwo(5) * 3" is evaluated, three checks occur that are relevant to the type of timestwo: 1. Before the function call takes place, a check ensures that timestwo is a function. 2. Before the multiplication in "x * 2", a check ensures that x is a number. 3. When timestwo returns, before the subsequent multiplication by 3, a check ensures that the return type of timestwo is a number. These three checks correspond to the three pieces of information contained in the function type signature "number -> number". However, these dynamic checks still don't actually tell us the type of a function. All they do is check that in a particular case, the values involved are compatible with the type of the function. In many cases, the checks may infer a signature that's either more or less specific than the function's type, or they may infer an incomplete signature -- e.g., the return type doesn't need to be checked when evaluating "arr[i] = timestwo(5)". I used a function just as an example. There are many other cases where a value's tag doesn't match the static (or latent) type of the terms through which it flows. A simple example is an expression such as: (flag ? 5 : "foo") Here, the latent type of this expression could be described as "number | string". There won't be a runtime tag anywhere which represents that type, though, since the language implementation never deals with the actual type of expressions, except in those degenerate cases where the type is so simple that it happens to be a 1:1 match to the corresponding tag. It's only the programmer that "knows" that this expression has that type. Anton From bdesth.quelquechose at free.quelquepart.fr Mon Jun 5 10:19:03 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 05 Jun 2006 16:19:03 +0200 Subject: in python , could I accomplish the purpose that "a=Console.read()" used in C? In-Reply-To: <1149497732.381285.236810@h76g2000cwa.googlegroups.com> References: <1149423026.134144.58940@i40g2000cwc.googlegroups.com> <448364b7$0$31935$626a54ce@news.free.fr> <1149497732.381285.236810@h76g2000cwa.googlegroups.com> Message-ID: <44840db6$0$3870$626a54ce@news.free.fr> Ravi Teja a ?crit : > Bruno Desthuilliers wrote: > >>python a ?crit : >> >>>in python , could I accomplish the purpose that "a=Console.read()" used >>>in C? >> >> >>There's nothing like "Console.read()" in ansi-C. >> > > > He probably got it mixed up with C# which ( almost - Console.Read() ) > has that. > Yeps. Or may be MS-C++ too AFAICT. From pmartin at snakecard.com Thu Jun 29 22:12:49 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Thu, 29 Jun 2006 21:12:49 -0500 Subject: Icono en wxpython References: <91906ddf0606281609l17753eaexf12dd3b22433c514@mail.gmail.com> <44a3c7a2$0$21283$626a54ce@news.free.fr> Message-ID: Try Sourceforge. (si j'ai bien compris) Regards, Philippe Bruno Desthuilliers wrote: > Gabriel wrote: >> Hola: >> He echo un programa en wxpython. Se trata de un programa para >> desarrollos con microcontroladores como PIC's etc. en cuanto a >> transmisi?n RS232 se refiere. >> >> El programa es GNU y quiero publicarlo pronto pero no se como poner el >> ?cono a la ventana y al archivo en si... >> >> ?Alguien puede darme una mano con esto? >> >> Otra cosa ?d?nde puedo publicar el programa una vez que este terminado? >> >> Desde ya muchas gracias > > Bonjour. Je n'ai pas compris un seul mot de ton post, ? part qu'il > concernait une appli wxPython, des microcontrolleurs, et des > transmission RS232. Peut-?tre que si tu postais la question in English, > ?a aiderait un peu ?-) > > > -- > bruno desthuilliers > python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for > p in 'onurb at xiludom.gro'.split('@')])" From PPNTWIMBXFFC at spammotel.com Wed Jun 14 05:46:35 2006 From: PPNTWIMBXFFC at spammotel.com (Marco Aschwanden) Date: Wed, 14 Jun 2006 11:46:35 +0200 Subject: Using "external" vars on module load time Message-ID: Hi I have a script that looks for modules and tries to load them. After loading I attach the "server"-API function to it. module = __import__(module_name, globals(), locals(), []) module.server = server.server_api Now, some modules need the "server" functionality on load/init. I tried to modify the globals(): my_globals = globals().copy() my_globals['server'] = server.server_api module = __import__(module_name, my_globals, locals(), []) module.server = server.server_api This did not work as intended the module to be imported did not get the "server" from my_globals. The solution I have, is to add __init_module__() method that is called after the module was imported: module = __import__(module_name, globals(), locals(), []) module.server = server.server_api if module.__dict__.has_key('__init_module__'): module.__init_module__() This is not really satisfying. I would like: Load a module and hand in already the server_api. How can I achieve this? Thanks for any suggestions, Marco From luismgz at gmail.com Fri Jun 30 09:49:13 2006 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 30 Jun 2006 06:49:13 -0700 Subject: Reddit broke - should have remained on Lisp? In-Reply-To: <1151662765.178529.82670@75g2000cwc.googlegroups.com> References: <1151626961.232761.255550@d56g2000cwd.googlegroups.com> <1151627462.297352.205150@i40g2000cwc.googlegroups.com> <1151627924.322764.6040@y41g2000cwy.googlegroups.com> <1151628347.551890.48050@y41g2000cwy.googlegroups.com> <1151662765.178529.82670@75g2000cwc.googlegroups.com> Message-ID: <1151675353.665556.97520@x69g2000cwx.googlegroups.com> Alok wrote: > Luis M. Gonz?lez wrote: > > Alok wrote: > > > I was merely describing my experience and inviting others' response > > > about theirs. > > > > That's exactly what I'm doing. > > You misinterpret, I was talking about my experience with the site and > inviting response from other people about their experience with the > site. Now, I don't know much about python or lisp, but I have read > about this web-site's history with the two programming languages. And > hence I chose to post in comp.lang.lisp and comp.lang.python. > > Now if there were a reddit.technology.lisp or > reddit.technology.python, and if they had the same traction as these > usenet groups, then I could have posted there. But that was not an > option was it. > > > > > > Please don't misconstrue that as a blame on any language. > > > > I think it can be interpreted in many ways. > > Can you please explain what your interpretation is? > > > Now if you're not ready to read other people's oppinions, don't ask. > > > > Now, I think you are unfairly prejudiced about my not wanting to read > other people's opinion. I would rather have a 1000 acrid responses to > something I write and learn from it, than post into a responseless > vacuum. > > > > And of course, I disagree with your comments about ridicule etc. > > > > Ok. Dear Alok, I think is you who are misinterpreting me (or I didn't make myself clear). You posted a link to a joke from reddit, which is perfectly fine, is very funny. But below, you added a comment wondering whether the change from Lisp to Python may be a reason for a huge performance loss. I'm not a python bigot, but I just said that blamming a language choice for such a deficieny was ridiculous. There are hundreds of very complex web sites developed in python that doesn't suffer these problems, and, even if they are developed in python, you must take into account which other technologies they are using for deployment (web server, framework, mod_python, cgi, fastcgi, hardware, etc, etc...). Also, the fact that someone could be more versed or knowledgeable of one language compared to another one, doesn't make it better or worse. This is s subjective fact, and has nothing to do with the language. It has to do with who's using the language. Also, as someone pointed out above, don't you think that the huge incresement of traffic since they switched to python may have had something to do with this problem? Perhaps, their lack of experise in a new language didn't prepare them for facing such a challenge. Who knows? Yeah, perhaps if they sticked to Lisp, they could have handled the problem better. They are lispers, aren't they? Anyway, you posted a comment, you asked for opinons, you got mine. Sorry if I ofended you. It wasn't my intention. I'll make sure I place more smileys in my posts to avoid hurting feelings from now on :-) Luis From sreeram at tachyontech.net Fri Jun 30 16:01:04 2006 From: sreeram at tachyontech.net (K.S.Sreeram) Date: Sat, 01 Jul 2006 01:31:04 +0530 Subject: How to control permission of file? In-Reply-To: <12aavvb7vc58b48@corp.supernews.com> References: <12aavvb7vc58b48@corp.supernews.com> Message-ID: <44A58300.3000000@tachyontech.net> Grant Edwards wrote: > When one open()s a file (that doesn't exist) for writing , how > does one control that file's permissions (it's "mode" in Unix > terms). Check out 'os.open' It returns a file descriptor, and if you need a file object you can use 'os.fdopen' on the file descriptor Regards Sreeram -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 260 bytes Desc: OpenPGP digital signature URL: From fredrik at pythonware.com Sun Jun 11 18:23:21 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 12 Jun 2006 00:23:21 +0200 Subject: direct initialization of class attributes vs. declarations w/in __init__ In-Reply-To: <1150063606.929384.300040@j55g2000cwa.googlegroups.com> References: <1150041510.139609.171120@f6g2000cwb.googlegroups.com> <4f2thrF1fd4r4U1@uni-berlin.de> <1150043792.136250.99770@u72g2000cwu.googlegroups.com> <1150047314.025241.260750@c74g2000cwc.googlegroups.com> <1150062413.303012.177330@f6g2000cwb.googlegroups.com> <1150063606.929384.300040@j55g2000cwa.googlegroups.com> Message-ID: digitalorganics at gmail.com wrote: > Output from laptop comp.: > > 1 > 10 > 2 > 10 > 3 > 10 so how are you entering and running the code on your laptop ? what happens if you set the class attribute to 100 instead of 10 ? From bdesth.quelquechose at free.quelquepart.fr Sun Jun 4 23:11:36 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 05 Jun 2006 05:11:36 +0200 Subject: integer to binary... In-Reply-To: <12839b8doin7mff@corp.supernews.com> References: <1149189570.376091.319890@j55g2000cwa.googlegroups.com> <127ugf9jgu7av18@corp.supernews.com> <4480a084$0$6172$626a54ce@news.free.fr> <12839b8doin7mff@corp.supernews.com> Message-ID: <4483714c$0$27378$626a54ce@news.free.fr> Grant Edwards a ?crit : > On 2006-06-02, Bruno Desthuilliers wrote: > >>Grant Edwards a ?crit : >> >>>On 2006-06-01, nicolasg at gmail.com wrote: >>> >>>>does anyone know a module or something to convert numbers like integer >>>>to binary format ? >>> >>>They _are_ in binary format. >> >>Not really. > > Yes, really. No, not really. > Otherwise the bitwise boolean operations you > demonstrated wouldn't work as shown. Ho yes ? > >>>>>(7).__class__ >> >> >> >>>>>dir((7)) >> >>['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', >>'__delattr__', '__div__', '__divmod__', '__doc__', '__float__', >>'__floordiv__', '__getattribute__', '__getnewargs__', '__hash__', >>'__hex__', '__init__', '__int__', '__invert__', '__long__', >>'__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', >>'__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', >>'__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', >>'__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', >>'__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', >>'__rxor__', '__setattr__', '__str__', '__sub__', '__truediv__', '__xor__'] >> > > The fact that they impliment the xor operator is pretty much > proof that integers are ... objects, instance of the int class. Not really what I'd call "binary format" !-) Now if you go that way, it's of course true that everything on a computer ends up in a binary format.... It's true. > stored in binary format -- xor is only > defined for binary numbers. > class Prisonner(object): def __xor__(self, other): return "I'm not a (binary) number, I'm a free man" The fact that an object implements the xor operator is pretty much proof that the guy that wrote the class decided to implement the xor operator !-) Grant, I of course agree that, *for practical means*, one can consider that Python's integer are "already in binary format" - for a definition of "binary format" being "you can do bitwise ops on them". But the truth is that Python integers are objects (in the OO meaning) holding integer values - not integer values themselves. From Mike.S.Duffy at gmail.com Sat Jun 17 04:42:13 2006 From: Mike.S.Duffy at gmail.com (Mike Duffy) Date: 17 Jun 2006 01:42:13 -0700 Subject: Legitimate use of the "is" comparison operator? In-Reply-To: References: <20060617075308.29014.1287982850.divmod.quotient.2368@ohm> Message-ID: <1150533733.252877.238120@c74g2000cwc.googlegroups.com> Gary Herron wrote: > > >>> 100 is (99+1) > False > > >>> 2 is (1+1) > True > > >>> 100 is 100 > True > > This is highly implementation dependent. The current (C) implementation > of Python has a cache for small integers, so the attempt to compare > values with "is" works for some small integers, and fails for some large > integers, but curiously, not all instances of comparing large integers. > Ahh, thank you. That explains why Fredrick's and Jean-Paul's example did not work, but mine did (I was using *small* integers). Ok, well I definitely get the picture. Use the "is" operator for what it was intended for, or deal with broken code ;-) Thanks a lot guys. From sreeram at tachyontech.net Thu Jun 8 23:31:53 2006 From: sreeram at tachyontech.net (K.S.Sreeram) Date: Fri, 09 Jun 2006 09:01:53 +0530 Subject: what does %u mean? In-Reply-To: <1149823453.947116.200500@y43g2000cwc.googlegroups.com> References: <1149823453.947116.200500@y43g2000cwc.googlegroups.com> Message-ID: <4488EBA9.9060902@tachyontech.net> See: http://docs.python.org/lib/typesseq-strings.html u -> Unsigned decimal -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 260 bytes Desc: OpenPGP digital signature URL: From onurb at xiludom.gro Mon Jun 19 14:15:36 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Mon, 19 Jun 2006 20:15:36 +0200 Subject: [OT] code is data In-Reply-To: References: <44965f53$0$12743$636a55ce@news.free.fr> <4496b29f$0$27412$626a54ce@news.free.fr> Message-ID: <4496e9c9$0$14868$626a54ce@news.free.fr> Fredrik Lundh wrote: > Laurent Pointal wrote: >> Bruno Desthuilliers wrote: >>> Anton Vredegoor wrote: >>>> The idea is to have a way to transform a Python (.py) module into XML >>>> and then do source code manipulations in XML-space using ElementTree. > >>> > >>> My my my... I'm not against the idea of dynamic source code >>> transformation, but for heaven's sake, *why* would one put XML in the >>> mix ??????? > > > because lots of people know how to describe XML transformations, and > there are plenty of tools that implement such transformations efficiently ? Efficiently enough for dynamic (runtime) use ? -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From marshall.spight at gmail.com Thu Jun 22 21:56:40 2006 From: marshall.spight at gmail.com (Marshall) Date: 22 Jun 2006 18:56:40 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <7zpshbsvjy.fsf@app-1.diku.dk><7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <1150809118.677124.142230@u72g2000cwu.googlegroups.com> <1150815461.210286.53120@r2g2000cwb.googlegroups.com> <1150823297.816352.75370@u72g2000cwu.googlegroups.com> <7zzmg6amm1.fsf@app-3.diku.dk> <1150904475.363283.234730@y41g2000cwy.googlegroups.com> Message-ID: <1151027800.460188.116860@i40g2000cwc.googlegroups.com> Joachim Durchholz wrote: > Marshall schrieb: > > immutable = can't change > > vary-able = can change > > > > Clearly a contradiction in terms. > > Not in mathematics. So stipulated. However, it *is* a contradiction in English. Now, we often redefine or narrow terms for technical fields. However, when we find ourselves in a situation where we've inverted the English meaning with the technical meaning, or ended up with a contradiction, it ought to give us pause. > The understanding there is that a "variable" varies - not over time, but > according to the whim of the usage. (E.g. if a function is displayed in > a graph, the parameter varies along the X axis. If it's used within a > term, the parameter varies depending on how it's used. Etc.) > > Similarly for computer programs. > Of course, if values are immutable, the value associated with a > parameter name cannot vary within the same invocation - but it can still > vary from one invocation to the next. Again, stipulated. In fact I conceded this was a good point when it was first mentioned. However, we generally refer to parameters to functions as "parameters"-- you did it yourself above. What we generally (in programming) call variables are locals and globals. If the languages supports an update operation on those variables, then calling them variables makes sense. But "variable" has become such a catch-all term that we call public static final int FOO = 7; a variable, even though it can never, ever vary. That doesn't make any sense. If we care about precision in our terminology, we ought to distinguish among parameters, named values that support destructive update, named values that don't support destructive update, and possibly other things. Marshall From dnew at san.rr.com Fri Jun 16 17:10:50 2006 From: dnew at san.rr.com (Darren New) Date: Fri, 16 Jun 2006 21:10:50 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <2006061410510511272-raffaelcavallaro@pasdespamsilvousplaitmaccom> <2006061501423327544-raffaelcavallaro@pasdespamsilvousplaitmaccom> <_eBkg.14895$uy3.4988@tornado.socal.rr.com> <1sBkg.14897$uy3.4884@tornado.socal.rr.com> Message-ID: Matthias Blume wrote: > In Danvy's solution, the format argument is not a string. That's what I said, yes. >>You can't read the printf format from a configuration file >>(for example) to support separate languages. > You don't need to do that if you want to support separate languages. That's kind of irrelevant to the discussion. We're talking about collections of dynamically-typed objects, not the best mechanisms for supporting I18N. > Moreover, reading the format string from external input is a good way > of opening your program to security attacks, since ill-formed data on > external media are then able to crash you program. Still irrelevant to the point. > I am sure one could adapt Danvy's solution to support such a thing. I'm not. It's consuming arguments as it goes, from what I understood of the paper. It's translating, essentially, into a series of function calls in argument order. > Obviously, a Danvy-style solution (see, e.g., the one in SML/NJ's > library) is not necessarily structured that way. I don't see the > problem with typing, though. You asked for an example of a heterogenous list that would be awkward in a statically strongly-typed language. The arguments to printf() count, methinks. What would the second argument to apply be if the first argument is printf (since I'm reading this in the LISP group)? -- Darren New / San Diego, CA, USA (PST) My Bath Fu is strong, as I have studied under the Showerin' Monks. From cvanarsdall at mvista.com Thu Jun 22 16:01:48 2006 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Thu, 22 Jun 2006 13:01:48 -0700 Subject: Quick Question In-Reply-To: <1151006076.949700.130110@u72g2000cwu.googlegroups.com> References: <1151006076.949700.130110@u72g2000cwu.googlegroups.com> Message-ID: <449AF72C.3010508@mvista.com> xkenneth wrote: > I want to be able to cycle through an array and print something in > hexadecimal. Such as this > thisArray = ["AF","0F","5F"] > for x in range(len(thisArray)): > print "\x" + thisArray[x] > > However python chokes on the escaped identifier, how can I get around > this? > > Thanks! > Regards, > Ken > > If you have things in a list you can iterate through the list much easier: thisArray = ["AF","0F","5F"] for item in thisArray: print item In this array you store strings, so if you want to print stuff out in hex you need to give python integers, so let's say you have a list of integers: thisArray = [256,512,1024] for item in thisArray: print "%x"%item That will print those integers in hex. -carl -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From steven.klass at gmail.com Fri Jun 9 18:39:02 2006 From: steven.klass at gmail.com (rh0dium) Date: 9 Jun 2006 15:39:02 -0700 Subject: Weekend project - Directory simplifier - Shortest paths.. In-Reply-To: <1149891740.160372.9140@f6g2000cwb.googlegroups.com> References: <1149891740.160372.9140@f6g2000cwb.googlegroups.com> Message-ID: <1149892742.865953.327570@c74g2000cwc.googlegroups.com> rh0dium wrote: It should be noted that these are virtual not real so filecmp can't be used... From uval at rz.uni-karlsruhe.de Fri Jun 30 17:34:05 2006 From: uval at rz.uni-karlsruhe.de (=?ISO-8859-1?Q?Sch=FCle_Daniel?=) Date: Fri, 30 Jun 2006 23:34:05 +0200 Subject: How to control permission of file? In-Reply-To: <12aavvb7vc58b48@corp.supernews.com> References: <12aavvb7vc58b48@corp.supernews.com> Message-ID: Grant Edwards schrieb: > When one open()s a file (that doesn't exist) for writing , how > does one control that file's permissions (it's "mode" in Unix > terms). what do you mean by "contor file's mode"? usually you try to open and if you are not allowed you will get the exception >>> try: ... f = file("/etc/shadow") ... print f.read() ... except IOError, e: ... print e ... [Errno 13] Permission denied: '/etc/shadow' >>> if you want to know more about file attributes use os.stat and constants from stat module >>> import os >>> os.stat("/etc/shadow") (33184, 245390L, 771L, 1, 0, 15, 604L, 1151702662, 1149675585, 1149675585) >>> >>> import stat >>> stat.ST_SIZE 6 >>> os.stat("/etc/shadow")[stat.ST_SIZE] 604L >>> http://docs.python.org/lib/module-stat.html hth, Daniel From faulkner612 at comcast.net Tue Jun 6 16:32:56 2006 From: faulkner612 at comcast.net (faulkner) Date: 6 Jun 2006 13:32:56 -0700 Subject: what are you using python language for? In-Reply-To: References: Message-ID: <1149625976.834356.249140@y43g2000cwc.googlegroups.com> i'm writing a text editor [yes, it has quite a few interesting unique features]. this summer, i hope to make it collaborative like gobby. i also have a full-time job this summer at my college writing a small database system to manage student records. hacker1017 wrote: > im just asking out of curiosity. From aahz at pythoncraft.com Fri Jun 2 13:29:29 2006 From: aahz at pythoncraft.com (Aahz) Date: 2 Jun 2006 10:29:29 -0700 Subject: Are there something like "Effective Python"? References: <1149224468.481470.74580@i39g2000cwa.googlegroups.com> Message-ID: In article <1149224468.481470.74580 at i39g2000cwa.googlegroups.com>, Mike Meng wrote: > > For example, one of my friends read my program and suggest me to >move the re.compile() out of a for-loop, since the regular pattern is >fixed, and re.compile() is slow. I want to find more such advice, where >can I find them? Actually, that's a good example of a false optimization, unless you're using a lot of different regexes in the loop or it's an extremely tight loop, because the re module already caches regexes. Still, if it's a constant string, a good programmer would probably hoist it out of the loop because you should hoist ALL constant assignments out of a loop. (It's not particularly related to re.compile() in this case.) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I saw `cout' being shifted "Hello world" times to the left and stopped right there." --Steve Gonedes From Serge.Orlov at gmail.com Wed Jun 14 18:01:44 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 14 Jun 2006 15:01:44 -0700 Subject: memory leak problem with arrays In-Reply-To: <1150317325.614389.14770@i40g2000cwc.googlegroups.com> References: <1150317325.614389.14770@i40g2000cwc.googlegroups.com> Message-ID: <1150322504.136131.139350@i40g2000cwc.googlegroups.com> sonjaa wrote: > Hi > > I'm new to programming in python and I hope that this is the problem. > > I've created a cellular automata program in python with the numpy array > extensions. After each cycle/iteration the memory used to examine and > change the array as determined by the transition rules is never freed. > I've tried using "del" on every variable possible, but that hasn't > worked. Python keeps track of number of references to every object if the object has more that one reference by the time you use "del" the object is not freed, only number of references is decremented. Print the number of references for all the objects you think should be freed after each cycle/iteration, if is not equal 2 that means you are holding extra references to those objects. You can get the number of references to any object by calling sys.getrefcount(obj) From durumdara at gmail.com Wed Jun 14 05:55:26 2006 From: durumdara at gmail.com (Dara Durum) Date: Wed, 14 Jun 2006 11:55:26 +0200 Subject: IPC with mmap - freezed in Windows XP terminal ? Message-ID: <9e384ef60606140255j5054f2eah@mail.gmail.com> Hi ! I want to comm. between 2 procs with mmap - in Windows XP. Interesting thing I saw yesterday. When I start my mtest.py without redirection stdout, the program freezed. When I pushed Enter, is was released. (Just like when I use raw_input in the end of the code... :-)) For this effect I need to start my process from "Start Menu/run" "cmd" "mtest.py". When I start this program from Context, PyScripter, Total Commander, I don't see same effect. If I redirect sys.stdout, I don't see this effect. What is the problem ? I do wrong anything ? Or it is a bug ? Or my notebook do this ? (I have another example, and it is buggy too, but I tested only in my notebook.) Thanks for help: dd -------------- next part -------------- A non-text attachment was scrubbed... Name: fmapmgr.py Type: text/x-python Size: 2606 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: mtest.py Type: text/x-python Size: 555 bytes Desc: not available URL: From fredrik at pythonware.com Wed Jun 28 11:25:51 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 28 Jun 2006 17:25:51 +0200 Subject: SimpleXMLRPCServer and client IP address References: <2b1bd02c0606280805m164c4fb8s1a43d76480904fb7@mail.gmail.com> Message-ID: Jeremy Monnet wrote: > Tips I've found were : > - use the requestHandler and its method address_string(), but I didn't > an easy to understand example > - http://mail.python.org/pipermail/python-list/2006-May/340266.html > but this thread seems not to have been finished :-( maybe the explanation in that message was good enough for the poster ? Your handler object should be getting set up with the client_address property. If not you need to show us some small subset of your app that demonstrates the issue. You can also inherit from SimpleXMLRPCServer and override verify_request, from BaseServer, if you want the option of blocking requests based on source address. the second alternative should be straightforward enough: class MyXMLRPCServer(SimpleXMLRPCServer.SimpleXMLRPCServer): def verify_request(self, request, client_address): return CheckPerms(client_address) server = MyXMLRPCServer(...) ... if you need more control, you need to subclass SimpleXMLRPCHandler instead. > Furthermore, I think I should be able to access the socket object from > where I am (at starting of isOpen() ), but I don't know how. you cannot. the isOpen() function is your RPC handler, and it only sees things provided by the client. > "self" and "parent" are not defined, I can access the "server" object, but it > says the other end s not connected ("transport endpoint"). I think > this SimpleXMLRPCServer was not threaded (because it says in the API : > "answer all requests one at a time"), so I don't understand why in the > middle of my function the server.socket.getpeername() says it's not > connected. because the server socket isn't the same thing as the client socket -- the server socket is only used to listen for incoming connections; it creates a new client socket for each incoming request. From defcon8 at gmail.com Mon Jun 26 08:37:38 2006 From: defcon8 at gmail.com (defcon8) Date: 26 Jun 2006 05:37:38 -0700 Subject: Python database access In-Reply-To: <1151295558.067744.91470@b68g2000cwa.googlegroups.com> References: <1151295558.067744.91470@b68g2000cwa.googlegroups.com> Message-ID: <1151325458.897931.278380@y41g2000cwy.googlegroups.com> arvind wrote: > Hi all, > I am going to work on Python 2.4.3 and MSSQL database server on > Windows platform. > But I don't know how to make the connectivity or rather which module to > import. > I searched for the modules in the Python library, but I couldn't find > which module to go for. > Please help me out! I think there are a few recipes for mssql in the activestate python cookbook, or at least for odbc. From mgi820 at motorola.com Mon Jun 26 11:32:10 2006 From: mgi820 at motorola.com (Gary Duzan) Date: Mon, 26 Jun 2006 15:32:10 +0000 (UTC) Subject: Python taught in schools? References: <1151220913.406987.162420@u72g2000cwu.googlegroups.com> Message-ID: In article , Mirco Wahab wrote: >Thus spoke Cameron Laird (on 2006-06-25 13:08): > >> I'll gratuitously add that, even though I'm personally fond of >> C++, I think teaching it as is done in colleges and high schools >> (!) amounts to child abuse. It's wildly inappropriate. > >C++ programming requires you to >massively invest your thinking >first into the setup of your >build environment (can only be >beaten by Java here). A while back I had the opportunity to teach a section of an introductory computer science course in C++. They had recently abandoned Pascal in favor of C++ as the language of choice. There was certainly some spinup on the development environment to do, but it wasn't too terrible. I think the real problem with C++ is that there is a lot of conceptual baggage to work around to get to a useful program without having the students "unlearn" things later. Just basic things like const (in its various forms), pointers vs. references, class basics, headers, etc., are necessary for idiomatic C++ programming, but they get in the way of teaching more basic concepts of program construction. I understand that the school switched to Java a short time later, which is some improvement, but still has a good bit of baggage. Now the Schemers have taken over, so they teach Scheme as the introductory language. One thing about Scheme is that it doen't have a lot of baggage; there is no room for it in the spec. :-) To return to topicality for a moment, I think exposing new students to a combination of Scheme and Python might work well, providing different views of how to build programs, and leaving the students with both theoretical and practical foundations on which to build. Gary Duzan Motorola CHS p.s. Then sock them with ML or Haskell to weed out the weak ones. ;-) Then if they survive Occam, throw Java at them, so they'll know what they are missing but can still get a job... From onurb at xiludom.gro Sat Jun 17 12:21:33 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Sat, 17 Jun 2006 18:21:33 +0200 Subject: any subway experiences In-Reply-To: <1150533811.911621.112430@y41g2000cwy.googlegroups.com> References: <1150533811.911621.112430@y41g2000cwy.googlegroups.com> Message-ID: <44942c0e$0$17695$626a54ce@news.free.fr> a wrote: > thanks for reading > Too long experience with Paris (France) subway... Left Paris, feel better now !-) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From jkn_gg at nicorp.f9.co.uk Thu Jun 15 13:31:35 2006 From: jkn_gg at nicorp.f9.co.uk (jkn) Date: 15 Jun 2006 10:31:35 -0700 Subject: Tiddlywiki type project in Python? In-Reply-To: <1150386336_12135@sp6iad.superfeed.net> References: <1150289313.533749.52330@i40g2000cwc.googlegroups.com> <44900ae9$0$8386$626a54ce@news.free.fr> <1150291679.746132.114730@y43g2000cwc.googlegroups.com> <1150386336_12135@sp6iad.superfeed.net> Message-ID: <1150392695.604781.110030@r2g2000cwb.googlegroups.com> Hi Rick R. P. Dillon wrote: > I've been doing some work on a didiwiki-like program written in Python. > Since Python is [_not_] embedded in browsers, the didwiki approach make sense: > write the server in your language of choice (didwiki uses C), and lay > the necessary (simple) wiki code on top of the server. Roll the entire > thing into a single executable, and you have a personal wiki. The catch > is that you must run the executable before you can access your wiki, but > it is a small price to pay IMHO. > > Anyway, I'll either GPL or public-domain my code when I'm finished with > it and I'll post it here. My hope is it will be as fast on a reasonably > modern computer as didiwiki is. > > Rick That sounds interesting ... thanks. I'd never heard of didiwiki and from a brief browse it seems similar to what I have in mind. I will download it and have a proper look at it ... & will be glad to hear more of your project. Regards Jon N From max at alcyone.com Sun Jun 4 18:37:44 2006 From: max at alcyone.com (Erik Max Francis) Date: Sun, 04 Jun 2006 15:37:44 -0700 Subject: Max function question: How do I return the index of the maximum value of a list? In-Reply-To: <1149460177.951294.30320@h76g2000cwa.googlegroups.com> References: <1149459320.802652.186930@i40g2000cwc.googlegroups.com> <1149460177.951294.30320@h76g2000cwa.googlegroups.com> Message-ID: gene tani wrote: > http://www.rubyquiz.com/quiz24.html His question was for three-card poker, not normal poker. The ranking of hands in three-card poker isn't the same as in normal best five-card poker rankings; for instance, in three-card poker, a straight beats a flush. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Could it be / That we need loving to survive -- Neneh Cherry From scott.daniels at acm.org Mon Jun 26 20:57:50 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Mon, 26 Jun 2006 17:57:50 -0700 Subject: Extracting 3-byte integers In-Reply-To: References: Message-ID: <44a07d71$1@nntp0.pdx.net> Bob Greschke wrote: > I have some binary data read from a file that is arranged like > <3-byte int> <3-byte int> <3-byte int> etc. > The "ints" are big-endian and there are 169 of them. Is there any clever > way to convert these to regular Python ints other than (struct) unpack'ing > them one at a time and doing the math? Best way is with scipy (or Numeric or numarray), but for vanilla Python: import array, itertools ubytes = array.array('B') sbytes = array.array('b') ubytes.fromfile(binarysource, 169 * 3) sbytes.fromstring(ubytes[::3].tostring()) result = array.array('i', (msb * 256 + mid) * 256 + lsb for msb, mid, lsb in itertools.izip(sbytes, ubytes[1::3], ubytes[2::3]))) If you want to get fancy, you can replace the last statement with: del ubytes[::3] uhalf = array.array('H') uhalf.fromstring(ubytes.tostring()) if array.array('H', [1]) != '\x00\x01': uhalf.byteswap() result = array.array('i', (msb * 65536 + low for msb, low in itertools.izip(sbytes, uhalf))) That was fun. --Scott David Daniels scott.daniels at acm.org From Sebastien.Boisgerault at gmail.com Wed Jun 14 13:33:21 2006 From: Sebastien.Boisgerault at gmail.com (=?iso-8859-1?q?S=E9bastien_Boisg=E9rault?=) Date: 14 Jun 2006 10:33:21 -0700 Subject: Numerics, NaNs, IEEE 754 and C99 References: <12904mjhl493t49@corp.supernews.com> <4490315e$1@nntp0.pdx.net> Message-ID: <1150306401.423825.39490@g10g2000cwb.googlegroups.com> Jeez, 12 posts in this IEEE 754 thread, and still no message from uncle timmy ? ;) Please, we need enlightenment here and *now* :) platform-dependent accident'ly yours, SB From maric at aristote.info Tue Jun 13 12:11:53 2006 From: maric at aristote.info (Maric Michaud) Date: Tue, 13 Jun 2006 18:11:53 +0200 Subject: a string problem In-Reply-To: References: <1150206140.912224.113420@p79g2000cwp.googlegroups.com> Message-ID: <200606131811.54091.maric@aristote.info> Le Mardi 13 Juin 2006 15:59, John Salerno a ?crit?: > And I'm actually ashamed to admit that I know the RE way, but not the > regular string manipulation way, if there is one! eheh, In [39]: import string In [40]: sub, s1, s2 = 'string', 're string2, ,string1', 're string2, ,string' In [41]: sub in [ e.strip(string.punctuation) for e in s1.split() ] Out[41]: False In [42]: sub in [ e.strip(string.punctuation) for e in s2.split() ] Out[42]: True > This seems like > something easy enough to do without REs though. Yes, but python way seems a little faster python2.4 -mtimeit -s "import re" "re.match('\bstring\b', 're string2, ,string1') and True" 100000 loops, best of 3: 7.3 usec per loop python2.4 -mtimeit -s "import string" "'string' in [ e.strip(string.punctuation) for e in 're string2, ,string1'.split() ]" 100000 loops, best of 3: 6.99 usec per loop -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From michael.tiller at gmail.com Wed Jun 28 12:29:08 2006 From: michael.tiller at gmail.com (michael.tiller at gmail.com) Date: 28 Jun 2006 09:29:08 -0700 Subject: Modelica In-Reply-To: <1151407787.676569.57700@m73g2000cwd.googlegroups.com> References: <1151407787.676569.57700@m73g2000cwd.googlegroups.com> Message-ID: <1151512148.189704.294920@j72g2000cwa.googlegroups.com> Srijit Kumar Bhadra wrote: > I am looking for possible options to interface Modelica > (http://www.modelica.org/) with Python (scipy and numpy). Any > suggestions? When you say "interface", what do you mean? Do you want to be able to process Modelica models or do you simply want to be able to communicate with a Modelica tool. > Best Regards, > Srijit -- Mike From samschul at pacbell.net Fri Jun 2 23:38:41 2006 From: samschul at pacbell.net (sam) Date: 2 Jun 2006 20:38:41 -0700 Subject: Seg fault in python extension module References: <4480F004.7000602@lexicon.net> Message-ID: <1149305921.145967.248740@i39g2000cwa.googlegroups.com> I recommend that you also replace the NULL after the METH_VARARGS with a valid documentations string such as: static PyMethodDef modglMethods[] = { { (char *)"glVertex4f", _wrap_glVertex4f, METH_VARARGS, "My Doc String"}, { NULL, NULL, 0, NULL } }; Sam Schulenburg From diffuser78 at gmail.com Thu Jun 22 16:02:22 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 22 Jun 2006 13:02:22 -0700 Subject: Network Programming in Python In-Reply-To: References: <1151002934.586359.174540@m73g2000cwd.googlegroups.com> Message-ID: <1151006542.682915.83500@c74g2000cwc.googlegroups.com> I have Python 2.4.2 on windows and Linux both. I got an import error. how can we obtain the twisted libraries ? When I try to run your code Jean-Paul Calderone wrote: > On 22 Jun 2006 12:02:14 -0700, diffuser78 at gmail.com wrote: > >I am a newbie in python. I want to learn and implement a small > >networking concept. Please help me. Every help is appreciated. > > > >I have one Linux Box and one Windows PC. I want to have a daemon > >running on Windows PC which listens on some specicif port number. I > >want to send a TCP/IP or UDP/IP packet from Linux box to Windows PC to > >start some application. As Windows PC recieves such a packet from Linux > >Box it executes a certain .exe file. I want to implement this concept. > > > >In short I want to remotely send command from Linux to Windows PC to > >start a particular application. > > > >Thanks, Every help is appreciated. > > > > Untested: > > from twisted.internet import protocol, reactor > from twisted.protocols import basic > > COMMANDS = { > "xterm": ("/usr/bin/xterm", {"DISPLAY": ":1.0"}), > } > > class CommandLauncher(basic.LineReceiver): > def lineReceived(self, line): > try: > cmd, env = COMMANDS[line] > except KeyError: > self.sendLine("error") > else: > reactor.spawnProcess(None, cmd, env=env) > self.sendLine("okay") > > f = protocol.ServerFactory() > f.protocol = CommandLauncher > reactor.listenTCP(12345, f) > reactor.run() > > You should be able to telnet to this (port 12345) and type in > names of commands for it to run. Of course, xterm isn't a very > good win32 program to run but I couldn't think of a better example. > You could also write a program to send command requests to this > server, instead of using telnet. > > Jean-Paul From david.nospam.hopwood at blueyonder.co.uk Wed Jun 21 15:02:19 2006 From: david.nospam.hopwood at blueyonder.co.uk (David Hopwood) Date: Wed, 21 Jun 2006 19:02:19 GMT Subject: What is a type error? In-Reply-To: <44992e6c$2$664$bed64819@news.gradwell.net> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <7i3mg.204167$8W1.155367@fe1.news.blueyonder.co.uk> <44992e6c$2$664$bed64819@news.gradwell.net> Message-ID: <%Igmg.464974$xt.353729@fe3.news.blueyonder.co.uk> Chris Uppal wrote: > David Hopwood wrote: > >> When people talk about "types" being associated with values in a "latently typed" >> or "dynamically typed" language, they really mean *tag*, not type. > > I don't think that's true. Maybe /some/ people do confuse the two, but I am > certainly a counter-example ;-) > > The tag (if any) is part of the runtime machinery (or, if not, then I don't > understand what you mean by the word), and while that is certainly a reasonably > approximation to the type of the object/value, it is only an approximation, > and -- what's more -- is only an approximation to the type as yielded by one > specific (albeit abstract, maybe even hypothetical) type system. Yes. I should perhaps have mentioned that people sometimes mean "protocol" rather than "tag" or "type" (a protocol being the set of messages that an object can respond to, roughly speaking). > If I send #someMessage to a proxy object which has not had its referent set > (and assuming the default value, presumably some variant of nil, does not > understand #someMessage), then that's just as much a type error as sending > #someMessage to a variable holding a nil value. It's an error, certainly. People usually call it a type error. But does that terminology actually make sense? Typical programming languages have many kinds of semantic error that can occur at run-time: null references, array index out of bounds, assertion failures, failed casts, "message not understood", ArrayStoreExceptions in Java, arithmetic overflow, divide by zero, etc. Conventionally, some of these errors are called "type errors" and some are not. But there seems to be little rhyme or reason to this categorization, as far as I can see. If in a particular language, both array index bounds errors and "message not understood" can occur at run-time, then there's no objective reason to call one a type error and the other not. Both *could* potentially be caught by a type-based analysis in some cases, and both *are not* caught by such an analysis in that language. A more consistent terminology would reserve "type error" for errors that occur when a typechecking/inference algorithm fails, or when an explicit type coercion or typecheck fails. According to this view, the only instances where a run-time error should be called a "type error" are: - a failed cast, or no match for any branch of a 'typecase' construct. Here the construct that fails is a coercion of a value to a specific type, or a check that it conforms to that type, and so the term "type error" makes sense. - cases where a typechecking/inference algorithm fails at run-time (e.g. in a language with staged compilation, or dynamic loading with link-time typechecking). In other cases, just say "run-time error". > If I then assign the referent > of the proxy to some object which does understand #someMessage, then it is not > a type error to send #someMessage to the proxy. So the type has changed, but > nothing in the tag system of the language implementation has changed. In the terminology I'm suggesting, the object has no type in this language (assuming we're talking about a Smalltalk-like language without any type system extensions). So there is no type error, and no inconsistency. Objects in this language do have protocols, so this situation can be described as a change to the object's protocol, which changes whether a given message causes a protocol error. -- David Hopwood From zhaodapu at gmail.com Fri Jun 30 03:40:41 2006 From: zhaodapu at gmail.com (zdp) Date: 30 Jun 2006 00:40:41 -0700 Subject: Py2exe make wxPython window looks bad Message-ID: <1151653241.416599.6450@i40g2000cwc.googlegroups.com> Dear all: I made a window program by wxPython. Split windows, treectrl, listctrl and textctrl are used. When I program in python, the look & feel of the window controls are like the windos XP look & feel, with thin and flat border (My os is window XP). It's natural because, as I know, wxPython use native look and feel. But when I convert the program to EXE file by Py2exe, and run it, the look & feel is bad. It's just like the windows 9x. All controls has a thick and emboss border. However, the scrollbars look good, same as the window XP. So I'm puzzled. What's the problem and how can I get a XP look & feel window program? Should I add some code in my program to set the look and feel, or, set some options in py2exe script to force the generated exe has specified look and feel? The setup.py is very simple as following: -------------setup.py--------------------- import sys, os from distutils.core import setup import py2exe import glob setup( name = "mainframe", windows = ["mainframe.py"] ) From michele.petrazzo at TOGLIunipex.it Fri Jun 30 03:49:52 2006 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Fri, 30 Jun 2006 07:49:52 GMT Subject: python for windows internet filter / firewall In-Reply-To: <1151590961.464723.249360@p79g2000cwp.googlegroups.com> References: <1151590961.464723.249360@p79g2000cwp.googlegroups.com> Message-ID: thorley at gmail.com wrote: > Greetings, > > I'm interested in a simple content-based internet firewall/filter, > similar to dansguardian (http://dansguardian.org/), Firewall and filter are two things totally separated! - If you want to do something like a "page filtering", like dansguard and squidguard, you can simple do it with python, because you have to act like a proxy that leave of not visit a page. - If you have to do a firewall... I think you can't, especially if you are on win. Take a look at wipfw (wipfw.sf.net) that do what you want > but written in python, Of course :) and for windows. Why? All that work with networking (and not only that) work better with *nix OS! > I assumed such a project would already exist, Firewall I don't think, and the same for the filtering (I know only something like a plugin for squid, so for *nix platform). > but my searches on freshmeat, and google turned up empty. I would be > interested in starting my own project if necessary, so I have two > questions: > > 1) Does any one no of such a project? > > 2) Is this even reasonable in python and how might I get started? > (e.g. win32 COM?) win32COM for do what? You can do it in not so difficult manner: Take twisted and its proxy class, make some outline code (for filter the pages) and enjoy! (work also on win) > > Thanks much -- matthew > P.s. Don't forgot to share your code, when it'll work :) Bye, Michele From shejo284 at gmail.com Tue Jun 20 05:23:44 2006 From: shejo284 at gmail.com (Sheldon) Date: 20 Jun 2006 02:23:44 -0700 Subject: comparing two arrays In-Reply-To: <4fnqoqF1k8n10U1@uni-berlin.de> References: <1150721380.948808.231760@h76g2000cwa.googlegroups.com> <4fnlbiF1j83q2U1@uni-berlin.de> <4fnqoqF1k8n10U1@uni-berlin.de> Message-ID: <1150795424.752973.303420@g10g2000cwb.googlegroups.com> Diez B. Roggisch skrev: > Diez B. Roggisch wrote: > > > print [i for i, _ in enumerate((None for v in zip(a, b) where v == > > (1,1)))] > > > > should give you the list of indices. > > I musunderstood your question. Use > > > print [i for i, _ in enumerate((None for x, y in zip(a, b) where x == y))] > > instead. > > Diez Hi Diez, I wish I say that I understood what you wrote here but I can't. Do you mind explaining a little more? /sheldon From fredrik at pythonware.com Fri Jun 30 07:36:29 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 30 Jun 2006 13:36:29 +0200 Subject: Way for see if dict has a key References: <6V6pg.21624$_J1.271925@twister2.libero.it> Message-ID: Michele Petrazzo wrote: >> Michele Petrazzo wrote: >> >>>>> key in dict >>>> new syntax (2.3 and later). >>> So, following it, it can be used for the operations like len? >> >> what's "it" in this sentence? > > It, is the thought that the new 2.3 introduce. support for "key in dictionary" form was added in 2.3 (in earlier versions, "in" was only supported for sequences, not for mappings). len(dictionary) works in all Python versions. From onurb at xiludom.gro Fri Jun 30 07:43:24 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Fri, 30 Jun 2006 13:43:24 +0200 Subject: Way for see if dict has a key In-Reply-To: <1151667333.569664.152670@h44g2000cwa.googlegroups.com> References: <6V6pg.21624$_J1.271925@twister2.libero.it> <44a5041f$0$29637$636a55ce@news.free.fr> <4F7pg.21676$_J1.272665@twister2.libero.it> <1151667333.569664.152670@h44g2000cwa.googlegroups.com> Message-ID: <44a50e5c$0$11383$626a54ce@news.free.fr> looping wrote: > Michele Petrazzo wrote: > >>Bruno Desthuilliers wrote: >> >>>>but what the better >>> >>>Depends on the context. >>> >> >>If know only one context: see if the key are into the dict... What other >>context do you know? >> > > Why do you want to do that ? > > if key in dict: > value = dict[key] > else: > value = None > > could be write: value = dict.get(key, None) (snip) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From dav.phillips at ntlworld.com Tue Jun 6 05:52:04 2006 From: dav.phillips at ntlworld.com (dav.phillips at ntlworld.com) Date: 6 Jun 2006 02:52:04 -0700 Subject: Checking var is a number? In-Reply-To: References: <1149583700.145737.170720@j55g2000cwa.googlegroups.com> Message-ID: <1149587524.850955.165180@i39g2000cwa.googlegroups.com> > Good luck! > Laszlo I actually managed to get it sorted but i like that way of doing it much better actually :) Cheers David P From aleax at mac.com Wed Jun 14 10:59:05 2006 From: aleax at mac.com (Alex Martelli) Date: Wed, 14 Jun 2006 07:59:05 -0700 Subject: numeric/numpy/numarray References: <1150188484.888977.189510@y43g2000cwc.googlegroups.com> Message-ID: <1hgwwnm.lhpxrs1gkfp6N%aleax@mac.com> Bryan wrote: ... > so, was Numarray written *before* NumPY, or was it a reimplementation of > NumPy which implies it came *after* NumPy? it seems clear that Numeric is > the old one and i read is not being worked on anymore. so that leaves > Numarray and numpy. which of these two should i use? I'll voice a heretic thought: me, I'm sticking with good old Numeric until the situation with the newer packages settles down. Yes, Numeric is not being developed any more, but to me that also means it won't "change under me" and break something... and, it serves my personal computational needs until something equally stable finally arrives. (Of course, if and when I hit some bug in Numeric that will never be solved, or need some other add-on package which in turn demands a different numeric-array-computation underpinning, I'll have to change, but, so far, I have not found myself in either of these situations). Alex From deets at nospam.web.de Sat Jun 24 07:14:23 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 24 Jun 2006 13:14:23 +0200 Subject: USB and Python In-Reply-To: References: Message-ID: <4g4l49F1lcaj4U1@uni-berlin.de> Sybren Stuvel schrieb: > Philippe Martin enlightened us with: >> I need to talk to a USB device (PC or other) from Python - I am not >> talking about mounting a file system but sharing information as you >> would though a TCP-IP socket layer or an RS232 interface. > > You could wrap libusb on Linux. PyUSB already does that. OP seems to have a bad google day... Diez From deets at nospam.web.de Fri Jun 23 09:03:34 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 23 Jun 2006 15:03:34 +0200 Subject: Reuseable iterators - which is better? In-Reply-To: References: Message-ID: <4g2751F1jkkchU1@uni-berlin.de> zefciu schrieb: > In the tutorial there is an example iterator class that revesrses the > string given to the constructor. The problem is that this class works > only once, unlike built-in types like string. How to modify it that it > could work several times? I have tried two approaches. They both work, > but which of them is stylistically better? > > class Reverse: #original one > "Iterator for looping over a sequence backwards" > def __init__(self, data): > self.data = data > self.index = len(data) > def __iter__(self): > return self > def next(self): > if self.index == 0: > raise StopIteration > self.index = self.index - 1 > return self.data[self.index] > > class Reverse: #1st approach > "Reuseable Iterator for looping over a sequence backwards" > def __init__(self, data): > self.data = data > self.index = len(data) > def __iter__(self): > return self > def next(self): > if self.index == 0: > self.index = len(self.data) #Reset when previous # > iterator goes out > raise StopIteration > self.index = self.index - 1 > return self.data[self.index] > > class Reverse: #2nd approach > "Reuseable Iterator for looping over a sequence backwards" > def __init__(self, data): > self.data = data > def __iter__(self): > self.index = len(self.data) #Reset as a part of iterator # creation > return self > def next(self): > if self.index == 0: > raise StopIteration > self.index = self.index - 1 > return self.data[self.index] None. You don't reuse iterators! In the actualy example, reusage is possible due to the whole data being known & available. But there might be cases where this isn't possible - e.g. fetching data from a remote location which is too large to fit into memory for re-iteration. So generally speakiing, if you need an iterator, construct it. Regards, Diez From robert.kern at gmail.com Thu Jun 1 14:56:07 2006 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 01 Jun 2006 13:56:07 -0500 Subject: numpy bug In-Reply-To: <447f3338$1_7@news.bluewin.ch> References: <447f3338$1_7@news.bluewin.ch> Message-ID: Boris Borcic wrote: > after a while trying to find the legal manner to file numpy bug reports, > since it's a simple one, I thought maybe a first step is to describe the bug > here. Then maybe someone will direct me to the right channel. Register an account on our Trac, and then you can create new tickets. We require registration because we were getting bombarded with spam tickets. http://projects.scipy.org/scipy/numpy Also, the appropriate mailing list would be numpy-discussion: http://www.scipy.org/Mailing_Lists > So, numpy appears not to correctly compute bitwise_and.reduce and > bitwise_or.reduce : instead of reducing over the complete axis, these methods > only take the extremities into account. Illustration : > > >>> from numpy import * > >>> bitwise_or.reduce(array([8,256,32,8])) > 8 Indeed. Please create a ticket. In the meantime, the .accumulate() method works correctly; you can use the last item to get the correct result for .reduce(). -- 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 From bearophileHUGS at lycos.com Sat Jun 24 17:03:08 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 24 Jun 2006 14:03:08 -0700 Subject: 2Qs In-Reply-To: References: Message-ID: <1151182988.018895.29060@r2g2000cwb.googlegroups.com> SuperHik, for the second question there is builtin sum(): >>> values = 10.5, 5, -12 >>> sum(values) 3.5 Your if becomes: if x>10 and y>10 and z>10 and sum(tritup(x,y,z)): print "OK" Bye, bearophile From cdsmith at twu.net Sun Jun 25 14:22:13 2006 From: cdsmith at twu.net (Chris Smith) Date: Sun, 25 Jun 2006 12:22:13 -0600 Subject: What is Expressiveness in a Computer Language References: <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <0%Wlg.3521$MF6.947@tornado.socal.rr.com> <44992e6c$0$664$bed64819@news.gradwell.net> <1151010139.960608.122470@b68g2000cwa.googlegroups.com> Message-ID: Joachim Durchholz wrote: > > The immutability comes from the fact (perhaps implicit in these > > textbooks, or perhaps they are not really texts on formal type theory) > > that types are assigned to expressions, > > That doesn't *define* what's a type or what isn't! > I'm sorry if you don't like it, but that's all there is. That's the point that's being missed here. It's not as if there's this thing called a type, and then we can consider how it is used by formal type systems. A type, in formal type theory, is ANY label that is assigned to expressions of a program for the purpose of making a formal type system work. If you wish to claim a different use of the word and then try to define what is or is not a type, then be my guest. However, formal type theory will still not adopt whatever restrictions you come up with, and will continue to use the word type as the field has been using the word for a good part of a century now. The first step toward considering the similarities and differences between the different uses of "type" in dynamic type systems and formal type theory is to avoid confusing aspects of one field with the other. -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation From ciccio at unical.it Wed Jun 7 09:37:45 2006 From: ciccio at unical.it (ciccio at unical.it) Date: Wed, 7 Jun 2006 15:37:45 +0200 Subject: help to install MySQL-python module Message-ID: <1149687465.4486d6a9e5c5e@webmail.unical.it> Dear python users, I have an account on a Linux Cluster. I installed python version 2.3.5 on my account. I need to install the module MySQL-python to interact with a MySQL server already installed on the cluster. However, I read the README file but running python setup.py build the system fails to build the module and gives me the following error: error: invalid Python installation: unable to open /usr/local/lib/python2.3/config/Makefile (No such file or directory) How can I solve this problem? Thank you in advance Ernesto ------------------------------------------------- This mail sent through IMP: http://horde.org/imp/ From iainking at gmail.com Fri Jun 30 04:17:16 2006 From: iainking at gmail.com (Iain King) Date: 30 Jun 2006 01:17:16 -0700 Subject: conecting with a MsAcces DB by dao In-Reply-To: <1151650208.783778.186690@d56g2000cwd.googlegroups.com> References: <1151650208.783778.186690@d56g2000cwd.googlegroups.com> Message-ID: <1151655436.083906.143380@75g2000cwc.googlegroups.com> luis wrote: > Hi > I'm using activestate python 2.4 on win xp 2 ed. and Ms Access 2002 > (reading first http://starship.python.net/crew/bwilk/access.html) > I have writed the following code > > def append_from_Access(self): > try: > import ... > conn = win32com.client.Dispatch(r'ADODB.Connection') > DSN = "PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA > SOURCE=C:/Afile.mdb;" > conn.Open(DSN) > except Exception, inst: > ... > try: > sql_statement='SELECT * FROM Mytable' > rs = win32com.client.Dispatch(r'ADODB.Recordset') > rs.Open(sql_statement, conn, 1, 3) > while not rs.EOF: > id=rs.Fields(colName.Value) #colName, valid column name > ... > rs.MoveNext() > rs.Close() > conn.Close() > > except Exception, inst: > ... > > I'm using it for reading tables or queries in a mdb file. > With some mdb it works fine and return a no empty recordset, but with > others mdb files, the recordsets are void (opening the tables or > recorsets with Ms Access are not void). > Some help is welcome, > Thanks in advance > Luis I don't know if it's the problem your asking about, but your rs.MoveNext() should be inside the while loop, no? Iain From onurb at xiludom.gro Thu Jun 8 04:47:31 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 08 Jun 2006 10:47:31 +0200 Subject: language-x-isms In-Reply-To: References: Message-ID: <4487e425$0$21211$626a54ce@news.free.fr> Bryan wrote: > does anyone know if there is a collection somewhere of common python > mistakes or inefficiencies or unpythonic code that java developers make > when first starting out writing python code? Try googling for "python is not java" !-) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From shejo284 at gmail.com Sun Jun 25 13:34:42 2006 From: shejo284 at gmail.com (Sheldon) Date: 25 Jun 2006 10:34:42 -0700 Subject: array manipulation without for loops In-Reply-To: <1hhhg1j.11oc03fuoikz8N%aleax@mac.com> References: <1151251578.463273.24370@m73g2000cwd.googlegroups.com> <1151253182.496596.185420@r2g2000cwb.googlegroups.com> <1hhhes5.1hw0kbeniihqiN%aleax@mac.com> <1151254570.730665.298450@r2g2000cwb.googlegroups.com> <1hhhg1j.11oc03fuoikz8N%aleax@mac.com> Message-ID: <1151256882.568752.118970@b68g2000cwa.googlegroups.com> Hi Alex, I will code this in a little while and get back to you. Terrific! I saw this function but I skipped over it without realizing what it could do. The Numeric doc is not very good and I am just getting into Python so your book sounds great especially since it covers Numeric. I will look into it when I get back to work tomorrow. Bye for now, Sheldon Alex Martelli wrote: > Sheldon wrote: > > > Alex, > > > > I am using Numeric and have created 3 arrays: zero((1215,1215),Float) > > Two arrays are compared and one is used to hold the mean difference > > between the two compared arrays. Then I compare 290 or 340 pairs of > > arrays. I know that memory is a problem and that is why I don't open > > all of these arrays at the same time. I cannot install Numpy due to my > > working conditions. Sorry I should have made it clear that is was > > Numeric I was working with. > > It's OK, even if the hard-core numeric-python people are all > evangelizing for migration to numpy (for reasons that are of course > quite defensible!), I think it's quite OK to stick with good old Numeric > for the moment (and that's exactly what I do for my own personal use!). > > So, anyway, I'll assume you mean your 1215 x 1215 arrays were created by > calling Numeric.zeros, not "zero" (with no trailing s) which is a name > that does not exists in Numeric. > > Looking back to your original post, let's say that you have two such > arrays, a and b, both 1215x1215 and of Numeric.Float type, and the > entries of each array are all worth 1, 2, or 255 (that's how I read your > original post; if that's not the case, please specify). We want to > write a function that alters both a and b, specifically setting to 255 > all entries in each array whose corresponding entries are 255 in the > other array. > > Now that's pretty easy -- for example: > > import Numeric > > def equalize(a, b, v=255): > Numeric.putmask(a, b==v, v) > Numeric.putmask(b, a==v, v) > > if __name__ == '__main__': > a = Numeric.zeros((5,5), Numeric.Float) > b = Numeric.zeros((5,5), Numeric.Float) > a[1,2]=a[2,1]=b[3,4]=b[0,2]=255 > a[3,0]=a[0,0]=1 > b[0,3]=b[4,4]=2 > print "Before:" > print a > print b > equalize(a, b) > print "After:" > print a > print b > > > brain:~/pynut alex$ python ab.py > Before: > [[ 1. 0. 0. 0. 0.] > [ 0. 0. 255. 0. 0.] > [ 0. 255. 0. 0. 0.] > [ 1. 0. 0. 0. 0.] > [ 0. 0. 0. 0. 0.]] > [[ 0. 0. 255. 2. 0.] > [ 0. 0. 0. 0. 0.] > [ 0. 0. 0. 0. 0.] > [ 0. 0. 0. 0. 255.] > [ 0. 0. 0. 0. 2.]] > After: > [[ 1. 0. 255. 0. 0.] > [ 0. 0. 255. 0. 0.] > [ 0. 255. 0. 0. 0.] > [ 1. 0. 0. 0. 255.] > [ 0. 0. 0. 0. 0.]] > [[ 0. 0. 255. 2. 0.] > [ 0. 0. 255. 0. 0.] > [ 0. 255. 0. 0. 0.] > [ 0. 0. 0. 0. 255.] > [ 0. 0. 0. 0. 2.]] > brain:~/pynut alex$ > > Of course I'm using tiny arrays here, for speed of running and ease of > display and eyeball-checking, but everything should work just as well in > your case. Care to check and let us know? > > Numeric has pretty good documentation (numpy's is probably even better, > but it is not available for free, so I don't know!), and if you don't > find that documentation sufficient you might want to have a look to my > book "Python in a Nutshell" which devotes a chapter to Numeric (it also > is not available for free, but you can get a subscription to O'Reilly's > Safari online-books repository, which is free for the first two weeks, > and lets you look at many books including Python in a Nutshell -- if you > don't want to pay monthly subscription fees, make sure you cancel your > trial subscription before two weeks have passed!!!). > > I strongly recommend that, in some way or other, you DO get a taste of > the huge amount of functionality that Numeric provides for you -- with > the size of computational tasks you're talking about, an investment of > 2-3 hours spent becoming deeply familiar with everything Numeric offers > may well repay itself in savings of ten times as much execution time, > and what other investments offer such ROI as 1000%?-) > > > Alex From pats at acm.org Fri Jun 23 17:08:39 2006 From: pats at acm.org (Patricia Shanahan) Date: Fri, 23 Jun 2006 21:08:39 GMT Subject: Saying "latently-typed language" is making a category mistake In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <86Qmg.10725$o4.1907@newsread2.news.pas.earthlink.net> Message-ID: Chris Smith wrote: > Patricia Shanahan wrote: >> Vesa Karvonen wrote: >> ... >>> An example of a form of informal reasoning that (practically) every >>> programmer does daily is termination analysis. There are type systems >>> that guarantee termination, but I think that is fair to say that it is not >>> yet understood how to make a practical general purpose language, whose >>> type system would guarantee termination (or at least I'm not aware of such >>> a language). It should also be clear that termination analysis need not >>> be done informally. Given a program, it may be possible to formally prove >>> that it terminates. >> To make the halting problem decidable one would have to do one of two >> things: Depend on memory size limits, or have a language that really is >> less expressive, at a very deep level, than any of the languages >> mentioned in the newsgroups header for this message. > > Patricia, perhaps I'm misunderstanding you here. To make the halting > problem decidable is quite a different thing than to say "given a > program, I may be able to prove that it terminates" (so long as you also > acknowledge the implicit other possibility: I also may not be able to > prove it in any finite bounded amount of time, even if it does > terminate!) > > The fact that the halting problem is undecidable is not a sufficient > reason to reject the kind of analysis that is performed by programmers > to convince themselves that their programs are guaranteed to terminate. > Indeed, proofs that algorithms are guaranteed to terminate even in > pathological cases are quite common. Indeed, every assignment of a > worst-case time bound to an algorithm is also a proof of termination. > > This is, of course, a very good reason to reject the idea that the > static type system for any Turing-complete language could ever perform > this same kind analysis. > Of course, we can, and should, prefer programs we can prove terminate. Languages can make it easier or harder to write provably terminating programs. Patricia From onurb at xiludom.gro Fri Jun 30 08:55:15 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Fri, 30 Jun 2006 14:55:15 +0200 Subject: Way for see if dict has a key In-Reply-To: References: <6V6pg.21624$_J1.271925@twister2.libero.it><44a5041f$0$29637$636a55ce@news.free.fr><4F7pg.21676$_J1.272665@twister2.libero.it> <1151666867.604260.116320@h44g2000cwa.googlegroups.com> Message-ID: <44a51f34$0$6794$626a54ce@news.free.fr> Fredrik Lundh wrote: > "Andr?" wrote: > > >>Perhaps Bruno meant this: >> >>try: >> ... my_dict[key] ... >>except: >>... >> >>when we expect that the key will most often be in my_dict so that >>exception will be raised rarely, otherwise use > > > on my machine, "key in dict" is about twice as fast as the full try/getitem con- > struct when the key is present in the dict, Doesn't it depends on the number of keys in the dict ? > so that's not a very good optimization. FWIW, I personaly didn't meant to present it as an optimisation - just as one more possible way to test the existence of a given key... > now, if the OP had been interested in the associated value, things might have > been a bit different. > > > > > -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From rschroev_nospam_ml at fastmail.fm Thu Jun 15 18:21:51 2006 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Thu, 15 Jun 2006 22:21:51 GMT Subject: a good programming text editor (not IDE) In-Reply-To: <1150400573.981904.83160@f6g2000cwb.googlegroups.com> References: <_xgkg.2317$No6.48542@news.tufts.edu> <1150393919.514359.55580@h76g2000cwa.googlegroups.com> <1150400573.981904.83160@f6g2000cwb.googlegroups.com> Message-ID: <34lkg.484119$Db6.12511358@phobos.telenet-ops.be> olsongt at verizon.net schreef: > If you use it for a little bit, one day you'll be editing a document in > Word, or notepad, or SciTE, or Eclipse; you'll instinctively type > '[ESC]:wq', and be suprised that the app is still open. That's when > you realize there's no turning back. Exactly... it happens very regularly that my C++ compiler complains about :w, jjj or kkkk in my code. Being able to keep your hands on the base row instead of having to switch back and forth to the arrow keys is a tremendous benefit, which I didn't appreciate that much until I learned by experience that I unconsciously try, unsuccessfully of course, to do it in other editors. BTW, you can type :x instead of :wq. 33% shorter! -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From fredrik at pythonware.com Thu Jun 22 15:51:27 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 22 Jun 2006 21:51:27 +0200 Subject: Network Programming in Python In-Reply-To: <1151004213.415841.296450@u72g2000cwu.googlegroups.com> References: <1151002934.586359.174540@m73g2000cwd.googlegroups.com> <1151004213.415841.296450@u72g2000cwu.googlegroups.com> Message-ID: diffuser78 at gmail.com wrote: > Thanks...I will read that up...could you give me some more headstart or > if you any sample code which I can study. both chapters I pointed you to contain examples. From kaiser.vocote at gmail.com Fri Jun 30 08:43:28 2006 From: kaiser.vocote at gmail.com (Andreas Kaiser) Date: 30 Jun 2006 05:43:28 -0700 Subject: Py2exe make wxPython window looks bad In-Reply-To: <1151653241.416599.6450@i40g2000cwc.googlegroups.com> References: <1151653241.416599.6450@i40g2000cwc.googlegroups.com> Message-ID: <1151671408.061039.89780@x69g2000cwx.googlegroups.com> zdp schrieb: > But when I convert the program to EXE file by Py2exe, and run it, the > look & feel is bad. It's just like the windows 9x. All controls has a > thick and emboss border. However, the scrollbars look good, same as the > window XP. XP needs a manifest file in the setup.py or as a single file in the program dir. See examples in the py2exe installation dir. Andreas From bencvt at gmail.com Tue Jun 6 21:35:36 2006 From: bencvt at gmail.com (Ben Cartwright) Date: 6 Jun 2006 18:35:36 -0700 Subject: Function Verification In-Reply-To: <1149641403.078295.231730@h76g2000cwa.googlegroups.com> References: <1149641403.078295.231730@h76g2000cwa.googlegroups.com> Message-ID: <1149644136.039113.33410@j55g2000cwa.googlegroups.com> Ws wrote: > I'm trying to write up a module that *safely* sets sys.stderr and > sys.stdout, and am currently having troubles with the function > verification. I need to assure that the function can indeed be called > as the Python manual specifies that sys.stdout and sys.stderr should be > defined (standard file-like objects, only requiring a function named > "write"). > My problem is in verifying the class we're trying to redirect output > to. > This is what I have so far: > def _VerifyOutputStream(fh): > if 'write' not in dir(fh): > raise AttributeError, "The Output Stream should have a write > method." > if not callable(fh.write): > raise TypeError, "The Output Stream's write method is not > callable." > In the above _VerifyOutputStream function, how would I verify that the > fh.write method requires only one argument, as the built-in file > objects do? Why not just call the function with an empty string? def _VerifyOutputStream(fh): fh.write('') Note that you don't need to manually check for AttributeError or TypeError. Python will do that for you. It's generally better to act first and ask forgiveness later. --Ben From python.list at tim.thechases.com Sat Jun 3 11:20:09 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 03 Jun 2006 10:20:09 -0500 Subject: integer to binary... In-Reply-To: <12839b8doin7mff@corp.supernews.com> References: <1149189570.376091.319890@j55g2000cwa.googlegroups.com> <127ugf9jgu7av18@corp.supernews.com> <4480a084$0$6172$626a54ce@news.free.fr> <12839b8doin7mff@corp.supernews.com> Message-ID: <4481A8A9.4030902@tim.thechases.com> > The fact that they impliment the xor operator is pretty much > proof that integers are stored in binary format -- xor is only > defined for binary numbers. Um...let's not use bad logic/proofs for evidencing this... >>> hasattr(set(), "__xor__") True :) -tkc From cdsmith at twu.net Fri Jun 23 12:55:30 2006 From: cdsmith at twu.net (Chris Smith) Date: Fri, 23 Jun 2006 10:55:30 -0600 Subject: What is a type error? References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <7i3mg.204167$8W1.155367@fe1.news.blueyonder.co.uk> <44992e6c$2$664$bed64819@news.gradwell.net> <%Igmg.464974$xt.353729@fe3.news.blueyonder.co.uk> <449aaea0$2$656$bed64819@news.gradwell.net> <449bde60$0$663$bed64819@news.gradwell.net> Message-ID: Chris Uppal wrote: > That was the point of my first sentence (quoted above). I take it, and I > assumed that you shared my view, that there is no single "the" type system -- > that /a/ type system will yield judgements on matters which it has been > designed to judge. Yes, I definitely agree. My point was that if you leave BOTH the "something" and the response to verification failure undefined, then your definition of a dynamic type system is a generalization of the definition of a conditional expression. That is (using Java), if (x != 0) y = 1 / x; else y = 999999999; is not all that much different from (now restricting to Java): try { y = 1 / x; } catch (ArithmeticException e) { y = 999999999; } So is one of them a use of a dynamic type system, where the other is not? > Incidentally, using that idea, we get a fairly close analogy to the difference > between strong and weak static type systems. I think, actually, that the analogy of the strong/weak distinction merely has to do with how much verification is done. But then, I dislike discussion of strong/weak type systems in the first place. It doesn't make any sense to me to say that we verify something and then don't do anything if the verification fails. In those cases, I'd just say that verification doesn't really exist or is incorrectly implemented. Of course, this would make the type system weaker. > I wonder whether that way of looking at it -- the "error" never happens since > it is replaced by a valid operation -- puts what I want to call dynamic type > systems onto a closer footing with static type systems. Perhaps. I'm thinking some things over before I respond to Anton. I'll do that first, and some of my thoughts there may end up being relevant to this question. > b) I want to separate the systems of reasoning (whether formal or informal, > static or dynamic, implemented or merely conceptual, and /whatever/ we call 'em > ;-) from the language semantics. I have no objection to > being used as part of a language specification, but I don't want to restrict > types to that. In the pragmatic sense of this desire, I'd suggest that a way to characterize this is that your type system is a set of changes to the language semantics. By applying them to a language L, you obtain a different language L' which you can then use. If your type system has any impact on the set of programs accepted by the language (static types) or on any observable behavior which they exhibit (dynamic types), then I can't see a justification for claiming that the result is the same language; and if it does not, then the whole exercise is silly. > Of course, we can talk about what kinds of operations we want to forbid, but > that seems (to me) to be orthogonal to this discussion. Indeed, the question > of dynamic/static is largely irrelevant to a discussion of what operations we > want to police, except insofar as certain checks might require information > which isn't available to a (feasible) static theorem prover. Indeed, that is orthogonal to the discussion from the perspective of static types. If you are proposing that it is also orthogonal with respect to dynamic types, that will be a welcome step toward our goal of a grand unified type theory, I suppose. I have heard from others in this thread that they don't believe so. I am also interested in your response to the specific example involving an if statement at the beginning of this reply. -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation From ddvlad at gmail.com Thu Jun 22 09:12:45 2006 From: ddvlad at gmail.com (Vlad Dogaru) Date: Thu, 22 Jun 2006 16:12:45 +0300 Subject: Using Python as a web scripting language Message-ID: Hello everyone, I am learning Python and have heard it can be used similarly to PHP for web scripting. Because I find the latter not entirely to my liking, I would like to use Python. How should I configure my web server, what do I need, where should I start at, etc. I realise this sort of question pops up regularly, so just give me a starting point and I'll work my way from there (hopefully). Thanks in advance, Vlad Dogaru -- If I have somehow managed to break some sort of rules, either etiquette or English, by all means educate me. -------------- next part -------------- An HTML attachment was scrubbed... URL: From hancock at anansispaceworks.com Fri Jun 2 15:21:47 2006 From: hancock at anansispaceworks.com (Terry Hancock) Date: Fri, 02 Jun 2006 19:21:47 +0000 Subject: An oddity in list comparison and element assignment In-Reply-To: <1hg9nl6.xivwcd7n0j5N%aleax@mac.com> References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> <1hg9nl6.xivwcd7n0j5N%aleax@mac.com> Message-ID: <44808FCB.1020206@anansispaceworks.com> Alex Martelli wrote: > to be called "identical" by ALL observers (because trying to > ascertain the differences, if any, would inevitably perturb the > systems irretrievably by Heisenberg's effect Not to detract from your point, but the "Heisenberg effect", if you mean the "Heisenberg uncertainty principle" is much more fundamental (and quantumly "spooky") than this. You are merely talking about the observer disturbing the system by the process of observation, which is a common problem, but has nothing to do with Heisenberg, and AFAIK, doesn't really have a name. It's a normal application of classical physics. I'm sorry to nitpick, it's just that it's one of those misconceptions that never wants to die, like thinking that gravity is caused by magnetism or the Earth's rotation, or that you can "get too close and be 'sucked in' by a strong gravity field", or that things are "weightless" in orbit, because they're "too far from the Earth's gravity". Cheers, Terry -- Terry Hancock (hancock at AnansiSpaceworks.com) Anansi Spaceworks http://www.AnansiSpaceworks.com From onurb at xiludom.gro Fri Jun 30 11:26:51 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Fri, 30 Jun 2006 17:26:51 +0200 Subject: Way for see if dict has a key In-Reply-To: References: <6V6pg.21624$_J1.271925@twister2.libero.it> <44a5041f$0$29637$636a55ce@news.free.fr> <4F7pg.21676$_J1.272665@twister2.libero.it> <1151667333.569664.152670@h44g2000cwa.googlegroups.com> <44a50e5c$0$11383$626a54ce@news.free.fr> Message-ID: <44a542bc$0$25491$626a54ce@news.free.fr> Georg Brandl wrote: > Bruno Desthuilliers wrote: > >> looping wrote: >> >>> Michele Petrazzo wrote: >>> >>>> Bruno Desthuilliers wrote: >>>> >>>>>> but what the better >>>>> >>>>> >>>>> Depends on the context. >>>>> >>>> >>>> If know only one context: see if the key are into the dict... What >>>> other >>>> context do you know? >>>> >>> >>> Why do you want to do that ? >>> >>> if key in dict: >>> value = dict[key] >>> else: >>> value = None >>> >>> could be write: >> >> >> value = dict.get(key, None) > > > value = dict.get(key) Yes - but : 1/ not everybody knows that dict.get() takes a second optional param. Note that, while it happens that the default return value of dict.get() is the same as in the above example, but it may not have been the case. 2/ Since dict.get() implicitely returns None while getattr() defaults to raising an AttributeError unless you provide a default, I prefer to be very explicit when using dict.get(). -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From jeethu at tachyontech.net Thu Jun 22 05:46:56 2006 From: jeethu at tachyontech.net (Jeethu Rao) Date: Thu, 22 Jun 2006 15:16:56 +0530 Subject: Python to PHP Login System (HTTP Post) In-Reply-To: References: Message-ID: <449A6710.4030107@tachyontech.net> You need to use httplib. http://docs.python.org/lib/httplib-examples.html Jeethu Rao From alanalan at newsgroup.nospam Thu Jun 1 19:08:04 2006 From: alanalan at newsgroup.nospam (A.M) Date: Thu, 1 Jun 2006 19:08:04 -0400 Subject: Can Python format long integer 123456789 to 12,3456,789 ? Message-ID: <8oKfg.1621$Su3.139425@news20.bellglobal.com> Hi, Is there any built in feature in Python that can format long integer 123456789 to 12,3456,789 ? Thank you, Alan From thomas.grove at nepinc.com Fri Jun 30 10:27:32 2006 From: thomas.grove at nepinc.com (Tom Grove) Date: Fri, 30 Jun 2006 10:27:32 -0400 Subject: Chapter 9 Tutorial for Classes Not Working Message-ID: <44A534D4.9060404@nepinc.com> Here is my version: Python 2.4.3 (#2, May 9 2006, 21:56:54) [GCC 3.4.4 [FreeBSD] 20050518] on freebsd6 I am trying the classes example from the tutorial because some other class related stuff I am doing is not working either. Straight from Chapter 9: class MyClass: "A simple example class" i = 12345 def f(self): return 'hello world' From here I run: x = MyClass xf = x.f while True: print xf() This gives the following error: Traceback (most recent call last): File "", line 2, in ? TypeError: unbound method f() must be called with MyClass instance as first argument (got nothing instead) Please help...this is killing me! -Tom From junkytownMAKNI at gmail.com Fri Jun 2 08:56:54 2006 From: junkytownMAKNI at gmail.com (SuperHik) Date: Fri, 02 Jun 2006 14:56:54 +0200 Subject: Tkinter: select multiple entries in Listbox widget? In-Reply-To: References: Message-ID: Rob Williscroft wrote: > Bernard Lebel wrote in news:mailman.6413.1149178158.27775.python- > list at python.org in comp.lang.python: > >> Hello, >> >> Is there an option or a way to allow the selection of multiple entries >> in the Listbox widget? I could not find any, and would like to allow >> the end user to select multiple entries. >> >> > > When configuring use: > > selectmode = "multiple" > > e.g.: > > import Tkinter as tk > > root = tk.Tk() > > a = tk.Listbox( root, selectmode = "multiple" ) > for i in range(10): > a.insert( i, str(i) + " item" ) > > a.pack() > root.mainloop() > > I found the answer here: > > http://www.python.org/doc/life-preserver/ClassListbox.html > > Though I had to guess the `= "multiple"` part. > > Rob. cool. never needed it so far but it's nice to know :D From david at boddie.org.uk Tue Jun 20 09:36:29 2006 From: david at boddie.org.uk (David Boddie) Date: 20 Jun 2006 06:36:29 -0700 Subject: =?iso-8859-1?q?Re:_comparing_of_python_GUI=B4s?= References: <1150806788.026172.140150@h76g2000cwa.googlegroups.com> Message-ID: <1150810589.132950.181800@h76g2000cwa.googlegroups.com> Bayazee wrote: > i want some info ... > plz tell me the benefit (or any data) of each gui (pyqt , pyqtk , > wxpython , tkinter ..) > in the other hand wich one you offer (and why ?) ? Take a look at these resources: http://wiki.python.org/moin/GuiProgramming http://www.awaretek.com/toolkits.html The last one will be especially useful in helping you make some kind of informed decision. David From dnew at san.rr.com Fri Jun 23 21:21:37 2006 From: dnew at san.rr.com (Darren New) Date: Sat, 24 Jun 2006 01:21:37 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150908952.804184.218990@r2g2000cwb.googlegroups.com> <1150991074.705803.211570@m73g2000cwd.googlegroups.com> <1151083239.829296.33030@i40g2000cwc.googlegroups.com> <1151083931.162325.268050@g10g2000cwb.googlegroups.com> <1151086320.564736.272500@y41g2000cwy.googlegroups.com> <1151100483.057344.310970@g10g2000cwb.googlegroups.com> Message-ID: Dr.Ruud wrote: > You can write self-modifying code in C, No, by violating the standards and invoking undefined behavior, you can write self-modifying code. I wouldn't say you're still "in C" any more, tho. -- Darren New / San Diego, CA, USA (PST) Native Americans used every part of the buffalo, including the wings. From ptmcg at austin.rr._bogus_.com Fri Jun 30 13:38:15 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 30 Jun 2006 17:38:15 GMT Subject: Regular Expression - old regex module vs. re module References: <1151607229.548737.145800@d56g2000cwd.googlegroups.com> <12aaigaohtou291@corp.supernews.com> Message-ID: "Jim Segrave" wrote in message news:12aaigaohtou291 at corp.supernews.com... > > If fails for floats specified as ###. or .###, it outputs an integer > format and the decimal point separately. It also ignores \# which > should prevent the '#' from being included in a format. > True. What is the spec for these formatting strings, anyway? I Googled a while, and it does not appear that this is really a Perl string formatting technique, despite the OP's comments to the contrary. And I'm afraid my limited Regex knowledge leaves the OP's example impenetrable to me. I got lost among the '\'s and parens. I actually thought that "###." was *not* intended to be floating point, but instead represented an integer before a sentence-ending period. You do have to be careful of making *both* leading and trailing digits optional, or else simple sentence punctuating periods will get converted to "%1f"! As for *ignoring* "\#", it would seem to me we would rather convert this to "#", since "#" shouldn't be escaped in normal string interpolation. The following modified version adds handling for "\#", "\<" and "\>", and real numbers with no integer part. The resulting program isn't radically different from the first version. (I've highlighted the changes with "<===" marks.) -- Paul ------------------ from pyparsing import Combine,Word,Optional,Regex """ read Perl-style formatting placeholders and replace with proper %x string interp formatters ###### -> %6d ##.### -> %6.3f <<<<< -> %-5s >>>>> -> %5s """ # set up patterns to be matched # (note use of results name in realFormat, for easy access to # decimal places substring) intFormat = Word("#") realFormat = Combine(Optional(Word("#"))+"."+ # <=== Word("#").setResultsName("decPlaces")) leftString = Word("<") rightString = Word(">") escapedChar = Regex(r"\\[#<>]") # <=== # define parse actions for each - the matched tokens are the third # arg to parse actions; parse actions will replace the incoming tokens with # value returned from the parse action intFormat.setParseAction( lambda s,l,toks: "%%%dd" % len(toks[0]) ) realFormat.setParseAction( lambda s,l,toks: "%%%d.%df" % (len(toks[0]),len(toks.decPlaces)) ) leftString.setParseAction( lambda s,l,toks: "%%-%ds" % len(toks[0]) ) rightString.setParseAction( lambda s,l,toks: "%%%ds" % len(toks[0]) ) escapedChar.setParseAction( lambda s,l,toks: toks[0][1] ) # <=== # collect all formatters into a single "grammar" # - note reals are checked before ints formatters = rightString | leftString | realFormat | intFormat | escapedChar # <=== # set up our test string, and use transform string to invoke parse actions # on any matched tokens testString = r""" This is a string with ints: #### # ############### floats: #####.# ###.###### #.# .### left-justified strings: <<<<<<<< << < right-justified strings: >>>>>>>>>> >> > int at end of sentence: ####. I want \##, please. """ print testString print formatters.transformString( testString ) ------------------ Prints: This is a string with ints: #### # ############### floats: #####.# ###.###### #.# .### left-justified strings: <<<<<<<< << < right-justified strings: >>>>>>>>>> >> > int at end of sentence: ####. I want \##, please. This is a string with ints: %4d %1d %15d floats: %7.1f %10.6f %3.1f %4.3f left-justified strings: %-8s %-2s %-1s right-justified strings: %10s %2s %1s int at end of sentence: %4d. I want #%1d, please. From steve at holdenweb.com Tue Jun 13 02:15:58 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 13 Jun 2006 07:15:58 +0100 Subject: [newbie]apache authentication questions In-Reply-To: <1150173351.116073.316640@u72g2000cwu.googlegroups.com> References: <1150132535.766644.99870@g10g2000cwb.googlegroups.com> <1150173351.116073.316640@u72g2000cwu.googlegroups.com> Message-ID: grahamd at dscpl.com.au wrote: > Steve Holden wrote: > >>nuffnough at gmail.com wrote: >>Since HTTP authentication is managed by the browser it's difficult to >>integrate it with web application authentication: basically you have to >>choose between the two. There's no way for the server to tell the >>browser to start presenting the required authentication credentials >>except by raising a 401 (not authorised) error response, which is what >>makes the browser bring up its little popup. > > > It is not impossible though and in cases where you don't have a choice > but to use a HTTP authentication scheme, use of AJAX may be the > answer to still allowing use of a form based login scheme. See: > > http://www.peej.co.uk/articles/http-auth-with-html-forms.html > That's neat! regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From luismgz at gmail.com Wed Jun 28 13:45:18 2006 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 28 Jun 2006 10:45:18 -0700 Subject: compiling python (or ironpython) to .exe or .dll for or not for .NET In-Reply-To: <1151501398.664329.142920@d56g2000cwd.googlegroups.com> References: <1151501398.664329.142920@d56g2000cwd.googlegroups.com> Message-ID: <1151516718.925363.186330@d56g2000cwd.googlegroups.com> per9000 wrote: > Hi python people, > > I am working with .NET (in C++/CLI and C#) but since I really love > python I'd like to do things for .NET (or whatever) from python. > > Has anyone tried it? > > What (costless) compilers are good? > > Are there any (costless) editors like MS Visual Express you have tried? > > Is the newest Ironpython really as old as from 2004 July 28 (as stated > on http://www.ironpython.com/)? > > Thanks. > > /Per Erik Strandberg > yet another Fibonaccilover Ironpython development is going full steam towards version 1 (right now is in beta 8), and it's close to completion (see the codeplex link above). It is a faithful implementation of the python language for the .NET framework. Regarding IDEs for Ironpython, I know they are developing a Visual Studio integration (I've not tried it though) and I don't know what's its current state. I'm sure that sooner or later, someone will write a binding for the free SharpDevelop ide. luis From grflanagan at yahoo.co.uk Fri Jun 2 01:39:33 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 1 Jun 2006 22:39:33 -0700 Subject: grouping a flat list of number by range References: <1149196642.001466.53990@c74g2000cwc.googlegroups.com> Message-ID: <1149226773.350717.271520@g10g2000cwb.googlegroups.com> joh12005 at yahoo.fr wrote: > hello, > > i'm looking for a way to have a list of number grouped by consecutive > interval, after a search, for example : > > [3, 6, 7, 8, 12, 13, 15] > > => > > [[3, 4], [6,9], [12, 14], [15, 16]] > > (6, not following 3, so 3 => [3:4] ; 7, 8 following 6 so 6, 7, 8 => > [6:9], and so on) > > i was able to to it without generators/yield but i think it could be > better with them, may be do you an idea? > > best regards, > a list comprehension/itertools version (this won't work with an empty list): from itertools import groupby a = [3, 6, 7, 8, 12, 13, 15] result = [[3, 4], [6,9], [12, 14], [15, 16]] b = [ list(g)[0] for k,g in groupby(range(a[0],a[-1]+2), lambda x: x in a)] c = [ b[i:i+2] for i in range(0,len(a),2) ] assert c == result Gerard From tjreedy at udel.edu Mon Jun 26 15:36:55 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 26 Jun 2006 15:36:55 -0400 Subject: Beginner Programmer Question References: <1151342733.742416.180370@r2g2000cwb.googlegroups.com><1151343383.139891.219270@u72g2000cwu.googlegroups.com><1151343641.509435.245210@u72g2000cwu.googlegroups.com><1151343759.716134.169950@c74g2000cwc.googlegroups.com><1151343949.958134.257960@b68g2000cwa.googlegroups.com> <1151344078.584742.95990@y41g2000cwy.googlegroups.com> Message-ID: wrote in message news:1151344078.584742.95990 at y41g2000cwy.googlegroups.com... > > whats the difference between raw input and input? *That* you should look up in the builtin functions section of chapter 1? of the library reference manual. Chapter 2 of the same on builtin types is also important to skim and be able to refer back to. From jzgoda at o2.usun.pl Thu Jun 15 17:26:05 2006 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Thu, 15 Jun 2006 23:26:05 +0200 Subject: Which compiler will Python 2.5 / Windows (Intel) be built with? In-Reply-To: References: <1150367139.495114.148550@g10g2000cwb.googlegroups.com> <44917535$1@nntp0.pdx.net> <1150391891.130185.4640@f6g2000cwb.googlegroups.com> <4491b9e1$1@nntp0.pdx.net> Message-ID: Fredrik Lundh napisa?(a): >> Sorry, gals and guys, but if you force us to buy something irrelevant >> like VC2003, you will not get our sympathy. How should I explain my boss >> that we need to buy one Pro license more, just to be able to build our >> Python app? Please, don't left us with pants down. > > huh? 2.5 isn't released yet. if you *have* a Python app, you can > continue to use the same compiler when you upgrade from 2.4 and 2.5. > it's not like anyone is forcing you to uninstall the compiler just > because you upgrade Python... We don't have VC2003. We still use 2.3, as 2.3.3 for a long time was the latest available version for iSeries. Consider Python to be a part of "dll-hell". Why wouldn't Python dev team standarize on one compiler for all officially supported platforms? -- Jarek Zgoda http://jpa.berlios.de/ From peter.mosley at talk21.com Thu Jun 22 04:23:18 2006 From: peter.mosley at talk21.com (peter) Date: 22 Jun 2006 01:23:18 -0700 Subject: tkMessagebox.askyesno always returns False References: <1150922362.746933.276430@i40g2000cwc.googlegroups.com> Message-ID: <1150964598.102052.36500@y41g2000cwy.googlegroups.com> It's a moderately large application, and so impractical to post it all. I'll have a go at isolating circumstances where this fault occurs then post the preceeding code - but not before this evening (London time) when I might have some free time. Peter From steve at REMOVETHIScyber.com.au Sun Jun 25 03:30:09 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 25 Jun 2006 17:30:09 +1000 Subject: String negative indices? References: <1151054259.765401.252230@b68g2000cwa.googlegroups.com> <1151152577.661130.5690@g10g2000cwb.googlegroups.com> Message-ID: On Sat, 24 Jun 2006 21:15:17 -0700, Erik Max Francis wrote: > Steven D'Aprano wrote: > >> In mathematics, well, maybe... certainly in the Real number system, there >> is no difference, and +0 and -0 are just two ways of writing the same >> thing. In the hyperreals, +0 and -0 are the same, but there are >> infinitesimals which are different, and signed. I don't know enough about >> the surreals to comment. In matrix maths, there are an infinite number of >> different matrices where all the elements are zero -- they are all >> distinct, different, zeroes. > > What do you even mean by that? By "matrix maths," do you just mean > matrices whose elements are reals, or something else? Given any matrix M, there is a matrix Z such that M+Z = M. That matrix Z is equivalent to zero in the reals, where x+0 = x. In the reals, there is only one "zero", 0. In matrices, there are an infinite number of "zeroes": 1x1 matrix: [0] 1x2 matrix: [0 0] 1x3 matrix: [0 0 0] 2x2 matrix: [0 0] [0 0] etc. It is true that none of these are exactly equivalent to +0 and -0, but my point was that there can be more than one distinct zero in pure mathematics, and there is nothing wrong with the concept of a system with more than one distinct zero. -- Steven From python-url at phaseit.net Tue Jun 6 20:20:14 2006 From: python-url at phaseit.net (Cameron Laird) Date: Wed, 7 Jun 2006 00:20:14 +0000 (UTC) Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jun 7) Message-ID: QOTW: "You can gain substantial speed-ups in very certain cases, but the main point of Pyrex is ease of wrapping, not of speeding-up." - Simon Percivall "The rule of thumb for all your Python Vs C questions is ... 1.) Choose Python by default. . . ." - Ravi Teja Do you remember Python's early (notice the mention of traversal of the World-Wide Web. All of it!) days? Guido invites your reminiscences: http://www.artima.com/forums/flat.jsp?forum=106&thread=161207 Paul Boddie wraps up the "how can I compile Python?" FAQ as authoritatively as possible (at least for the moment): http://groups.google.com/group/comp.lang.python/msg/ccdadf2b24af0f91 Nick Craig-Wood contributes a Process definition to access a Linux process table programmatically: http://groups.google.com/group/comp.lang.python/msg/61ae7c3716fa17db Embedding Python? Initialization is more subtle than first appears. Stefan Schukat explains an example which arises when working with win32: http://groups.google.com/group/comp.lang.python/msg/5cb4424ba6c8fa97 pysqlite has a create_function. Gerhard Haering illustrates its use: http://groups.google.com/group/comp.lang.python/msg/f100756cf7569e13 ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. For far, FAR more Python reading than any one mind should absorb, much of it quite interesting, several pages index much of the universe of Pybloggers. http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog http://www.planetpython.org/ http://mechanicalcat.net/pyblagg.html comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html Steve Bethard, Tim Lesher, and Tony Meyer continue the marvelous tradition early borne by Andrew Kuchling, Michael Hudson and Brett Cannon 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/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 http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topic/python/ (requires subscription) http://groups-beta.google.com/groups?q=python-url+group:comp.lang.python*&start=0&scoring=d& http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From sigzero at gmail.com Fri Jun 30 13:53:01 2006 From: sigzero at gmail.com (Robert Hicks) Date: 30 Jun 2006 10:53:01 -0700 Subject: sum fonction in gadfly In-Reply-To: <1151614282.661048.103630@b68g2000cwa.googlegroups.com> References: <1151137825.177814.217180@u72g2000cwu.googlegroups.com> <449d253d$1@nntp0.pdx.net> <1151154192.030596.223840@r2g2000cwb.googlegroups.com> <1151614282.661048.103630@b68g2000cwa.googlegroups.com> Message-ID: <1151689981.253966.146830@d56g2000cwd.googlegroups.com> aaronwmail-usenet at yahoo.com wrote: > Robert Hicks wrote: > > I haven't been keeping up. Is Gadfly still in development? > > I always find this question a little > irritating -- gadfly is perfect the > way it is :). If it ain't broke don't > fix it. At least until the python guys > make another non-backwards-compatible > change that makes a patch necessary > (speaking of things that irritate me...). > > Seriously, there are a few problems > that could be fixed that I can > think of, but mostly it works for what > it is -- why are people so concerned > that it's not changing? > I didn't mean to be irritating and I wasn't concerned about it not changing but I could probably have stated the question a little better. For some reason I thought it was a dead project so maybe "still being maintained" would be a better statement. I dunno. Robert From n8pease at yahoo.com Wed Jun 21 18:25:11 2006 From: n8pease at yahoo.com (nate) Date: 21 Jun 2006 15:25:11 -0700 Subject: SendKeys for mac? Message-ID: <1150928711.151943.159560@b68g2000cwa.googlegroups.com> does anyone know if there is a way to inject keyboard events to a mac similar to the way SendKeys works for a windows machine? (Can you point me at it?) thanks, n From tim.golden at viacom-outdoor.co.uk Thu Jun 29 10:14:45 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 29 Jun 2006 15:14:45 +0100 Subject: Event notification system - where to start ? Message-ID: [geskerrett at hotmail.com] | We have been asked to develop and application for a client that is a | 'notification" system. We would like to use python, but are | struggling to find the right starting point. Any suggestions, tips or | sample code would be appreciated. | | Application outline; [... snip ...] Looks to me like you can do this really easily with Pyro. Have a look at http://pyro.sf.net and in particular at the Event Server http://pyro.sourceforge.net/manual/6-eventserver.html. It's really easy to get into, and there are several examples in the distribution. 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 ________________________________________________________________________ From xah at xahlee.org Wed Jun 7 21:35:52 2006 From: xah at xahlee.org (Xah Lee) Date: 7 Jun 2006 18:35:52 -0700 Subject: =?utf-8?B?VGhlIE5hdHVyZSBvZiB0aGUg4oCcVW5peCBQaGlsb3NvcGh54oCd?= In-Reply-To: <1149080931.582431.95560@j55g2000cwa.googlegroups.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1149080931.582431.95560@j55g2000cwa.googlegroups.com> Message-ID: <1149730552.161534.121350@i40g2000cwc.googlegroups.com> The Nature of the ?Unix Philosophy? Xah Lee, 2006-05 In the computing industry, especially among unix community, we often hear that there's a ?Unix Philosophy?. In this essay, i dissect the nature and characterization of such ?unix philosophy?, as have been described by Brian Kernighan, Rob Pike, Dennis Ritchie, Ken Thompson, and Richard P Gabriel et al, and in recent years by Eric Raymond. There is no one definite set of priciples that is the so-called ?unix philosophy?, but rather, it consistest of various slogans developed over the decades by unix programers that purport to describe the way unix is supposed to have been designed. The characteristics include: ?keep it simple?, ?make it fast?, ?keep it small?, ?make it work on 99% of cases, but generality and correctness are less important?, ?diversity rules?, ?User interface is not important, raw power is good?, ?everything should be a file?, ?architecture is less important than immediate workability?. Often, these are expressed by chantible slogans that exhibits juvenile humor, such as ?small is beautiful?, ?KISS (Keep It Simple, Stupid)?. Suppose, we take a team of student programers to produce a large software system. When the software is done, give it to software critics to analyze and come up with some principles that characterize its design decisions, without disclosing the nature of the programers. The characterization of such software, will more or less fit the descriptions of the ?Unix Philosophy? as described in different ways by various unix celebrities. For example, it would focus on implementation simplicity as opposed to interface simplicity. It will not be consistent in user interface, but exhibits rawness. It would be correct only for most cases, as opposed to mathematically correct or generic. It would employee simplistic data structures and formats such as text-files, as opposed to a structured system or binary format that requires a spec. It would be speedy, but less on scalability. It would consists of many small programs, as opposed to one large system with inter-dependent components. It would be easy to patch and port, but difficult to upgrade its structure or adapt entirely new assumptions. The essence of this theory is that when a software is produced for real world use, it is necessary that it works in some acceptable way, otherwise the software will be continuously debugged and refined. A software system written by a bunch of student or otherwise under-educated programers, but refined long enough for acceptably practical, real world use, will necessarily develop characteristics that is known as the Unix Philosophy. ---- This article is archived at: http://xahlee.org/UnixResource_dir/writ/unix_phil.html Xah xah at xahlee.org ? http://xahlee.org/ From mdudley at king-cart.com Sun Jun 4 13:21:25 2006 From: mdudley at king-cart.com (Marshall Dudley) Date: Sun, 04 Jun 2006 13:21:25 -0400 Subject: Installation Problem References: <44830900.155C7297@king-cart.com> Message-ID: <44831694.A022913A@king-cart.com> Sorry, this is a FreeBSD system 4.8-RELEASE I found another set of documents that say to use the following to install:: python setup.py install but after running it, I still have the same problem. Marshall Marshall Dudley wrote: > I am trying to install python, but am having problems. I did what the > README file said, and it created an executible code in the current > directory as it said it would when I typed "make". It seemed to say to > copy the executable over to the /usr/local directory, which I did. > > If I type ./python in the directory I did the make in I get: > > execonn# ./python > Python 2.4.3 (#1, May 31 2006, 07:50:04) > [GCC 2.95.4 20020320 [FreeBSD]] on freebsd4 > Type "help", "copyright", "credits" or "license" for more information. > >>> > > Which is I believe correct. > > But if I type /usr/local/python I get: > > Python 2.4.3 (#1, May 31 2006, 07:50:04) > [GCC 2.95.4 20020320 [FreeBSD]] on freebsd4 > Type "help", "copyright", "credits" or "license" for more information. > >>> > execonn# /usr/local/python > Could not find platform independent libraries > Could not find platform dependent libraries > Consider setting $PYTHONHOME to [:] > 'import site' failed; use -v for traceback > Python 2.4.3 (#1, May 31 2006, 07:50:04) > [GCC 2.95.4 20020320 [FreeBSD]] on freebsd4 > Type "help", "copyright", "credits" or "license" for more information. > >>> > > So nothing that tries to use it works. > > Any assistance would be appreciated. > > Thanks, > > Marshall From Dennis.Benzinger at gmx.net Tue Jun 20 15:17:41 2006 From: Dennis.Benzinger at gmx.net (Dennis Benzinger) Date: Tue, 20 Jun 2006 21:17:41 +0200 Subject: Python with Eclipse In-Reply-To: <9OBlg.6681$FR1.4810@dukeread05> References: <449679c3@news.uni-ulm.de> <9OBlg.6681$FR1.4810@dukeread05> Message-ID: <449849dc$1@news.uni-ulm.de> Philippe Martin wrote: > Dennis Benzinger wrote: > >> Stan Cook wrote: >>> I've been trying to use Eclipse with Python on Linux for a while and >>> have noticed something odd. After running the code or debugging a few >>> times, its responsiveness gets really bad. Upon checking the equivalent >>> of the task manager, I find several instances of Python running. When I >>> kill these instances, the responsiveness comes back. I'm not sure if >>> there is a better place to post this, but it is Python related. Is this >>> just an issue with Eclipse or is there something else I should inspect? >>> >>> Any help would be appreciated. >>> >>> Regards, >>> >>> S Cook >> Which Python plugin are you using? PyDev? >> >> >> Bye, >> Dennis > > Hi, > > What other plugins are there ? > > Regards, > > Philippe > In the Python wiki there is a page about Eclipse plugins for Python: http://wiki.python.org/moin/EclipsePythonIntegration Bye, Dennis From sjmachin at lexicon.net Sat Jun 10 04:28:33 2006 From: sjmachin at lexicon.net (John Machin) Date: Sat, 10 Jun 2006 18:28:33 +1000 Subject: Adding extra frames to traceback in C module In-Reply-To: References: Message-ID: <448A82B1.8030305@lexicon.net> On 10/06/2006 1:24 PM, Roger Binns wrote: > One thing I would like to do in my extension module is > add extra frames to the traceback when an extension > occurs. At the moment C code is invisible to tracebacks. > This is relevant when the C code makes a Python callback. [snip] > I couldn't find anything on the web or in the documentation > to explain how to do it. I did find snippets of code > doing things like PyTraceback_Here but they use a real > Python frame which I don't have and don't know how to > synthesize. In the C code generated by Pyrex, the frame is faked up on the fly if an error occurs: C:\junk>demotrbackmain.py Traceback (most recent call last): File "C:\junk\demotrbackmain.py", line 12, in ? funcb() File "C:\junk\demotrbackmain.py", line 3, in funcb demotrback.funcc(funce) File "demotrback.pyx", line 2, in demotrback.funcc funcd1(cbfunc) File "demotrback.pyx", line 5, in demotrback.funcd1 funcd2(callb) File "demotrback.pyx", line 8, in demotrback.funcd2 callb() File "C:\junk\demotrbackmain.py", line 6, in funce funcf() File "C:\junk\demotrbackmain.py", line 9, in funcf x = 1 / 0 ZeroDivisionError: integer division or modulo by zero Check out http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/version/Doc/overview.html#ExceptionValues then whip up some quick examples and look at the generated code. HTH, John From klaus at seistrup.dk Thu Jun 1 14:29:26 2006 From: klaus at seistrup.dk (Klaus Alexander Seistrup) Date: Thu, 1 Jun 2006 18:29:26 +0000 (UTC) Subject: Member index in toples References: <_TFfg.2976$EF1.229574@news20.bellglobal.com> Message-ID: A.M skrev: > I have a tuple like this: > > T = ("One","Two","Three","Four") > > Is there any built-in way to find what is the index of "Two" > withouot looping within the tuple? > > Is the same feature available for lists or dictionaries? Lists have an index method: #v+ >>> L = list(T) >>> L.index('Three') 2 >>> #v- Dictionaries are unordered and hence indices don't make much sense. Mvh, -- Klaus Alexander Seistrup SubZeroNet, Copenhagen, Denmark http://magnetic-ink.dk/ From maric at aristote.info Mon Jun 26 20:06:48 2006 From: maric at aristote.info (Maric Michaud) Date: Tue, 27 Jun 2006 02:06:48 +0200 Subject: replace a method in class: how? In-Reply-To: <44a07037$0$1020$626a54ce@news.free.fr> References: <44a07037$0$1020$626a54ce@news.free.fr> Message-ID: <200606270206.49447.maric@aristote.info> Le mardi 27 juin 2006 05:05, Bruno Desthuilliers a ?crit?: > import types > t.update = types.MethodType(another_update) This works with : t.update = types.MethodType(another_update, t) Oh, this *really* misleading what the intent of the programmer is, and In [29]: t.update Out[29]: of <__main__.a instance at 0xa774d96c>> all let think it's a method defined in t's class. I prefer early binding with default parameters : In [30]: def another_update(self, param) :pass ....: In [31]: t.update = lambda x, self=t : another_update(self, x) In [32]: t.update = lambda x, self=t, func=another_update : func(self, x) In [33]: t.update Out[33]: at 0xa7744aac> So we have a function and know it (probably) belongs to the instance. -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From aisaac0 at verizon.net Thu Jun 1 10:07:15 2006 From: aisaac0 at verizon.net (David Isaac) Date: Thu, 01 Jun 2006 14:07:15 GMT Subject: argmax Message-ID: 1. Why is there no argmax built-in? (This would return the index of the largest element in a sequence.) 2. Is this a good argmax (as long as I know the iterable is finite)? def argmax(iterable): return max(izip( iterable, count() ))[1] 3. If this is the only place in a module where I need count and izip, should I import them at the module level or at the level of the function? What are the considerations here? Thanks, Alan Isaac From steven.bethard at gmail.com Fri Jun 16 11:36:41 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 16 Jun 2006 09:36:41 -0600 Subject: __lt__ slowing the "in" operator even if not called In-Reply-To: <1150412162.593718.61580@g10g2000cwb.googlegroups.com> References: <1150318630.203249.191250@r2g2000cwb.googlegroups.com> <1150383992.319124.128520@h76g2000cwa.googlegroups.com> <1150412162.593718.61580@g10g2000cwb.googlegroups.com> Message-ID: Emanuele Aina wrote: > andrewdalke at gmail.com dettagli?: > >>> Someone can explain me why? >> The list's __contains__ method is very simple > > [...] > >> So if you define "__lt__" in your object then the type gets a richcmp >> function and your == test implicit in the 'in' search always incurs the >> cost of figuring out that "__eq__" is not defined. > > Thank you for the detailed explanation! :) > > Do you think I should report this as a performance bug, maybe with the > 'wishlist' priority, or I should accept the truth and hope for better > luck next time? ;) It certainly wouldn't hurt to report it. But I suspect it's not ever going to get "fixed". Classes with a __lt__ but no __eq__ really aren't that common. STeVe From cdsmith at twu.net Tue Jun 27 01:48:00 2006 From: cdsmith at twu.net (Chris Smith) Date: Mon, 26 Jun 2006 23:48:00 -0600 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> Message-ID: Chris F Clark wrote: > And to me the question is what kinds of types apply to these dynamic > programs, where in fact you may have to solve the halting problem to > know exactly when some statement is executed. Yes, I believe (static) type systems will always end up approximating (conservatively) the possible behavior of programs in order to perform their verification. > Or, perhaps we have static type checkers which can do > computations of unbounded complexity. However, I thought that one of > the characteristics of type systems was that they did not allow > unbounded complexity and weren't Turing Complete. Honestly, I suspect you'd get disagreement within the field of type theory about this. Certainly, there are plenty of researchers who have proposed type systems that potentially don't even terminate. The consensus appears to be that they are worth studying within the field of type theory, but I note that Pierce still hasn't dropped the word "tractable" from his definition in his introductory text, despite acknowledging only a couple pages later that languages exist whose type systems are undecidable, and apparently co-authoring a paper on one of them. The consensus seems to be that such systems are interesting if they terminate quickly for interesting cases (in which case, I suppose, you could hope to eventually be able to formalize what cases are interesting, and derive a truly tractable type system that checks that interesting subset). Interestingly, Pierce gives ML as an example of a language whose type checker does not necesarily run in polynomial time (thus failing some concepts of "tractable") but that does just fine in practice. I am just quoting here, so I don't know exactly how this is true. Marshall mentioned template meta-programming in C++, which is definitely Turing- complete. -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation From webraviteja at gmail.com Mon Jun 5 04:55:32 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 5 Jun 2006 01:55:32 -0700 Subject: in python , could I accomplish the purpose that "a=Console.read()" used in C? In-Reply-To: <448364b7$0$31935$626a54ce@news.free.fr> References: <1149423026.134144.58940@i40g2000cwc.googlegroups.com> <448364b7$0$31935$626a54ce@news.free.fr> Message-ID: <1149497732.381285.236810@h76g2000cwa.googlegroups.com> Bruno Desthuilliers wrote: > python a ?crit : > > in python , could I accomplish the purpose that "a=Console.read()" used > > in C? > > > There's nothing like "Console.read()" in ansi-C. > He probably got it mixed up with C# which ( almost - Console.Read() ) has that. From tinman31337 at gmail.com Thu Jun 29 20:49:53 2006 From: tinman31337 at gmail.com (Tin Gherdanarra) Date: Fri, 30 Jun 2006 02:49:53 +0200 Subject: Reddit broke - should have remained on Lisp? In-Reply-To: <1151628347.551890.48050@y41g2000cwy.googlegroups.com> References: <1151626961.232761.255550@d56g2000cwd.googlegroups.com> <1151627462.297352.205150@i40g2000cwc.googlegroups.com> <1151627924.322764.6040@y41g2000cwy.googlegroups.com> <1151628347.551890.48050@y41g2000cwy.googlegroups.com> Message-ID: <4gjaphF1nnoc6U2@individual.net> Luis M. Gonz?lez wrote: > Alok wrote: > >>I was merely describing my experience and inviting others' response >>about theirs. > > > That's exactly what I'm doing. > > >>Please don't misconstrue that as a blame on any language. > > > I think it can be interpreted in many ways. > Now if you're not ready to read other people's oppinions, don't ask. > > >>And of course, I disagree with your comments about ridicule etc. > > > Ok. > C'mon guys! That "looks like..." thingy is an genre JOKE on the reddit-jokers' own expense, right? Knock it OFF! -- Lisp kann nicht kratzen, denn Lisp ist fluessig From dingbat at codesmiths.com Fri Jun 30 08:46:46 2006 From: dingbat at codesmiths.com (Andy Dingley ) Date: 30 Jun 2006 05:46:46 -0700 Subject: list comprehension In-Reply-To: <1151602493.629010.269360@i40g2000cwc.googlegroups.com> References: <1151600332.552024.119990@y41g2000cwy.googlegroups.com> <1151602493.629010.269360@i40g2000cwc.googlegroups.com> Message-ID: <1151671605.957887.158150@m73g2000cwd.googlegroups.com> Simon Forman wrote: > There's more to it, but that's the basic idea. This much I knew, but _why_ and _when_ would I choose to use list comprehension (for good Python style), rather than using a simple "traditional" loop ? If I want to generate something that's simply ( [1] + [2] + [3]+... ) then list comprehension is obviously the tool of choice. I suspect though that there's more to it than this. Is list comprehension also treatable as a sneaky concise formulation for nested lists, where they're as much about selection of individual elements, so much as concatenation of the sequence? What happens if a comprehension has side effects, such as from calling a function within it? Is this regarded as good or bad coding style? Is it evil (as structured programming would claim) or is it a concise formulation for an iterator or visitor pattern ? From gyows at sbcglobal.net Tue Jun 6 13:06:26 2006 From: gyows at sbcglobal.net (Ransom) Date: 6 Jun 2006 10:06:26 -0700 Subject: Newbie: returning dynamicly built lists (using win32com) Message-ID: <1149613586.862299.125070@u72g2000cwu.googlegroups.com> Very newb here, but my question will hopefully be obvious to someone. Code: import string from win32com.client import Dispatch docdir = 'E:\\scripts\\Python\\RSAutomation\\' def getOldData(testcases): excel = Dispatch("Excel.Application") excel.Workbooks.Open(docdir + 'FILE.xls') # load and create list from file (testcases.csv) for rsinput in testcases.xreadlines(): inputlist = string.split(rsinput, ',') # iterate through and update spreadsheet input cellx = range(3,51) values = range(0,48) for i,r in zip(cellx, values): excel.ActiveSheet.Cells(i,2).Value = inputlist[r] # TODO: read output from cell 32,6 into a tuple or list and then return list to __main__ [THIS IS WHERE I AM HAVING A PROBLEM] print excel.ActiveSheet.Cells(32,6) <--This prints properly as loop executes excel.ActiveWorkbook.Close(SaveChanges=0) excel.Quit() if __name__ == "__main__": csv_testcases = open('arse_testcases.csv','r') getOldData(csv_testcases) OK, so what is happening is that I am sending a list of data to an overly complicated spreadsheet that produces it's own output (in cell 32,6). As I loop through multiple test cases, the print statement calling into COM for the cell data seems to be printing out results just fine. But when I try and put the output from the spreadsheet into a dynamic list after the TODO section thusly: outputlist = [] outputlist.extend(excel.ActiveSheet.Cells(32,6) return outputlist I get an error like: [] I need to be able to return the dynamically generated built up by the responses from the spreadsheet lookup call (the exce.Activesheet thingy). Is there a better way to get this dynamically built list out of the funtion? Thanks!!! From meyer at mesw.de Thu Jun 15 18:35:21 2006 From: meyer at mesw.de (meyer at mesw.de) Date: 15 Jun 2006 15:35:21 -0700 Subject: Which compiler will Python 2.5 / Windows (Intel) be built with? In-Reply-To: <4491d3c0$1@nntp0.pdx.net> References: <1150367139.495114.148550@g10g2000cwb.googlegroups.com> <44917535$1@nntp0.pdx.net> <1150391891.130185.4640@f6g2000cwb.googlegroups.com> <4491b9e1$1@nntp0.pdx.net> <1150406005.948538.188950@h76g2000cwa.googlegroups.com> <4491d3c0$1@nntp0.pdx.net> Message-ID: <1150410921.201231.277880@c74g2000cwc.googlegroups.com> Scott, thanks for your clear words. Scott David Daniels wrote: > Nor was it clear to the PyDev community. Microsoft offered free > development systems to those among the PyDev group who were core > developers, and we took that offer. At the time we had no idea > it was on such a short-windowed product. VC6 lasted a _long_ time. Hmm, I see.... > As nikie pointed out, you can buy a 1-year MSDN Pro Subscription that > includes the VS2003 system. All that stopped is the free toolkit. The MSDN Pro Subscription is not really an option because we have no use for the 2005 compiler at all if it doesn't work with Python. I think we'll just try to get some boxed version of Visual Studio 2003 Professional from somewhere. > Taking percentages of people who complain is not reflect necessarily > reflective of percentages of the general population. Of course you're right, but still I think you will get lots of complaints once 2.5 is out and people realize that they (again) have to buy a compiler to compile extensions. Don't get me wrong, it's not a problem for me, but it will be a problem for other people. > If I recall > correctly, there was some angst about using VC6, because it was only > available for a hefty-for-hobbyists price. That was quelled with the > explanation that essentially all Windows developers used the Visual > Studio toolkit. The difference here is that back then one had no other option than to buy the compiler. Today, there _is_ a free Microsoft compiler available, but it unfortunately is the wrong one. > As to MinGW, nobody has signed up to commit long-term to doing the PyDev > work that is required to get (and keep) it working. Such a developer > would be welcome. There _are_ notes out there on the web to help you > get such things going; I have done my own little bit to share what I > know about how to do that. As for what compiler vendor to use, I agree that it is the right decision to use the Microsoft compiler on Microsoft platforms even if it means buying it. GCC is not really an alternative on Windows. Markus From junkytownMAKNI at gmail.com Wed Jun 7 06:26:38 2006 From: junkytownMAKNI at gmail.com (SuperHik) Date: Wed, 07 Jun 2006 12:26:38 +0200 Subject: newbie: python application on a web page In-Reply-To: <9PSdnTgkR_-HehjZnZ2dnUVZ_qidnZ2d@is.co.za> References: <1149615269.695229.88820@j55g2000cwa.googlegroups.com> <1149624046.762779.225240@h76g2000cwa.googlegroups.com> <9PSdnTgkR_-HehjZnZ2dnUVZ_qidnZ2d@is.co.za> Message-ID: Max wrote: > puzz wrote: >> sorry about the missunderstanding... >> >> but my question is "how" and not "where" to put it online >> and that's where the "newbie" comes from >> >> P M > > If you just want to make it available for download, that's easy. If you > want to make it open source, you could upload it to > planet-source-code.com (I used to put a lot there; don't know if they > have a python section) or SourceForge depending on your "market". > > But what I think you want is a web interface (where a user goes to your > site and uses it in the browser window). This is more tricky, but you're > almost certainly going to have to abandon Tkinter. You could try doing > an applet in Jython (which compiles Python to Java bytecode so you could > in theory do a Java-style applet). > > The alternative is to have the curve drawn server-side, so you would > have an HTML form on the page, and on clicking a button, load the graph > (into an "iframe" or something perhaps [I have a feeling iframes have > been deprecated - check first]). In which case you'd want to look up > CGI, AJAX, etc. > > --Max Could it be done with SVG XML? From ketil+news at ii.uib.no Tue Jun 20 09:16:32 2006 From: ketil+news at ii.uib.no (Ketil Malde) Date: Tue, 20 Jun 2006 15:16:32 +0200 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> Message-ID: Andreas Rossberg writes: >> "A language is latently typed if a value has a property - called it's >> type - attached to it, and given it's type it can only represent values >> defined by a certain class." I thought the point was to separate the (bitwise) representation of a value from its interpretation (which is its type). In a static system, the interpretation is derived from context, in a dynamic system values must carry some form of tags specifying which interpretation to use. I think this applies - conceptually, at least - also to expressions? My impression is that dynamic typers tend to include more general properties in their concept of types (div by zero, srqt of negatives, etc). -k -- If I haven't seen further, it is by standing in the footprints of giants From rogue_pedro at yahoo.com Fri Jun 30 19:26:39 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 30 Jun 2006 16:26:39 -0700 Subject: Newb Tkinter Question: Object has no attribute 'tk' In-Reply-To: <1151699637.322220.228050@b68g2000cwa.googlegroups.com> References: <1151699637.322220.228050@b68g2000cwa.googlegroups.com> Message-ID: <1151709999.214966.313300@p79g2000cwp.googlegroups.com> python programming newb wrote: > Hi all, first post. > > I'm new to python and tkinter. I'm trying to write a program that > opens the root window with a button that then opens a toplevel window > that then has it's own widgets. I can get the new toplevel window to > open but none of the widgets appear. The console gives me: > > AttributeError: 'NewWindow' object has no attribute 'tk' > > Here's my code: Please post the entire traceback, not just the error message, thanks. ~Simon From venkatbo at yahoo.com Tue Jun 27 15:26:44 2006 From: venkatbo at yahoo.com (venkatbo at yahoo.com) Date: 27 Jun 2006 12:26:44 -0700 Subject: How to disable tk inclusion in py build In-Reply-To: References: <1151422992.208936.54600@j72g2000cwa.googlegroups.com> Message-ID: <1151436404.809094.220650@j72g2000cwa.googlegroups.com> Hi Fredrick, > since _tkinter.so is only built if it's found by the setup script, > and if built, it's only loaded if you actually use it, why bother > "disabling" it ? I don't want it to build tk into the py dist, even if it finds it on the build box - its not needed in the deployment. Keeping it out will make the deployed pkg leaner. Don't want end-users accessing it, since its not meant to be accessed. Thanks, /venkat From cdsmith at twu.net Sat Jun 24 23:15:28 2006 From: cdsmith at twu.net (Chris Smith) Date: Sat, 24 Jun 2006 21:15:28 -0600 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> Message-ID: Chris F Clark wrote: > Do you reject that there could be something more general than what a > type theorist discusses? Or do you reject calling such things a type? I think that the correspondence partly in the wrong direction to describe it that way. If someone were to stand up and say "every possible but of reasoning about program correctness or behavior is type reasoning", then I'd be happy to say that formal type systems are a subset of that kind of reasoning. However, that's quite the statement to ask of anyone. So far, everyone has wanted to say that there are some kinds of reasoning that are type reasoning and some that are not. If that is the case, then a formal type system is in that sense more general than this intuitive notion of type, since formal type systems are not limited to verifying any specific category of statements about program behavior (except, perhaps that they are intended to verify guarantees, not possibilities; I don't believe it would fit all definitions of formal types to try to verify that it is possible for a program to terminate, for example). What I can't agree to is that what you propose is actually more general. It is more general in some ways, and more limited in others. As such, the best you can say is that is analogous to formal types in some ways, but certainly not that it's a generalization of them. > Let you write: > > because we could say that anything that checks types is a type system, > > and then worry about verifying that it's a sound type system without > > worrying about whether it's a subset of the perfect type system. > > I'm particularly interested if something unsound (and perhaps > ambiguous) could be called a type system. Yes, although this is sort of a pedantic question in the first place, I believe that an unsound type system would still generally be called a type system in formal type theory. However, I have to qualify that with a clarification of what is meant by unsound. We mean that it DOES assign types to expressions, but that those types are either not sufficient to prove what we want about program behavior, or they are not consistent so that a program that was well typed may reduce to poorly typed program during its execution. Obviously, such type systems don't prove anything at all, but they probably still count as type systems. (I'll point out briefly that a typical, but not required, approach to type theory is to define program semantics so that the evaluator lacks even the rules to continue evaluating programs that are poorly typed or that don't have the property of interest. Hence, you'll see statements like one earlier in this thread that part of type-soundness is a guarantee that the evaluation or semantics doesn't get stuck. I actually think this is an unfortunate confusion of the model with the thing being modeled, and the actual requirement of interest is that the typing relation is defined so that all well-typed terms have the interesting property which we are trying to prove. It is irrelevant whether the definition of the language semantics happens to contain rules that generalize to ill-typed programs or not.) I suspect, though, that you mean something else by unsound. I don't know what you mean, or whether it could be considered formally a type system. > > 1. The domain is the set of inputs to that expression which are going to > > produce a correct result. > > > > 2. The domain is the set of inputs that I expected this expression to > > work with when I wrote it. > > > > 3. The domain is the set of inputs for which the expression has a > > defined result within the language semantics. > Actually, I like 2 quite well. There is some set in my mind when I'm > writing a particular expression. It is likely an ill-defined set, but > I don't notice that. That set is exactly the "type". I don't actually mind #2 when we're talking about types that exist in the programmer's mind. I suspect that it may get some complaint along the lines that in the presence of type polymorphism, programmers don't need to be (perhaps rarely are) thinking of any specific set of values when they write code. I would agree with that statement, but point out that I can define at least my informal kind of set by saying, for instance, "the set of all inputs on which X operations make sense". I believe there is more of a concrete difference between #1 and #2 than you may realize. If we restrict types to considering the domain of functions without regard to the context in which they are called, then there are plenty of inputs on which this function does its own job quite well, but a global analysis tool may be able to conclude that if that input has been passed in, then this program already beyond the possibility of producing a correct result. #1 would, therefore, be a more global form of analysis than #2, rather than being merely a question of whether you are fallible or not. > Expanding that a little. I expect the language to catch type errors > where I violate model 3. So would I. (Actually, that's another pesky question; if the language "catches" it, did the error even occur, or did the expression just gain a defined result such that domain #3 is indistinguishable from the set of all possible inputs. I tend to agree with Chris Uppal, I suppose, that the latter is really the case, so that dynamic type systems in languages, if they are sound, prevent concept #3 from ever being in question. But, of course, you don't think about it that way, which distinguishes 2 from 3.) -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation From alanalan at newsgroup.nospam Thu Jun 1 17:45:02 2006 From: alanalan at newsgroup.nospam (A.M) Date: Thu, 1 Jun 2006 17:45:02 -0400 Subject: Using print instead of file.write(str) References: <447f4c9a$0$6174$626a54ce@news.free.fr> <1149197601.238826.151200@f6g2000cwb.googlegroups.com> Message-ID: Yes, it saved my time big time. Thank you Bruno. I use the print >>>file to generate HTML files. print is very flexible and nice. The dictionary formatting that Brunto said is awesome! Thanks again, Alan "Jon Clements" wrote in message news:1149197601.238826.151200 at f6g2000cwb.googlegroups.com... Didn't know of the >> syntax: lovely to know about it Bruno - thank you. To the OP - I find the print statement useful for something like: print 'this','is','a','test' >>> 'this is a test' (with implicit newline and implicit spacing between parameters) If you want more control (more flexibility, perhaps?) over the formatting of the output: be it spacing between parameters or newline control, use the methods Bruno describes below. I'm not sure if you can suppress the spacing between elements (would love to be corrected though); to stop the implicit newline use something like print 'testing', >>> 'testing' (but - with the leading comma, the newline is suppressed) I personally find that print is convenient for sentences (or writing 'lines'). Thought it worth pointing this out in case, like some I know, you come across a cropper with certain output streams. All the best, Jon. Bruno Desthuilliers wrote: > A.M a ?crit : > > Hi, > > > > > > I found print much more flexible that write method. Can I use print > > instead > > of file.write method? > > > > f = open("/path/to/file") > print >> f, "this is my %s message" % "first" > f.close() > > To print to stderr: > > import sys > print >> sys.stderr, "oops" > > FWIW, you and use string formating anywhere, not only in print statements: > > s = "some %s and % formating" % ("nice", "cool") > print s > > You can also use "dict formating": > > names = {"other": "A.M.", "me" : "bruno"} > s = "hello %(other)s, my name is %(me)s" % names From Dennis.Benzinger at gmx.net Mon Jun 19 06:17:39 2006 From: Dennis.Benzinger at gmx.net (Dennis Benzinger) Date: Mon, 19 Jun 2006 12:17:39 +0200 Subject: Python with Eclipse In-Reply-To: References: Message-ID: <449679c3@news.uni-ulm.de> Stan Cook wrote: > I've been trying to use Eclipse with Python on Linux for a while and > have noticed something odd. After running the code or debugging a few > times, its responsiveness gets really bad. Upon checking the equivalent > of the task manager, I find several instances of Python running. When I > kill these instances, the responsiveness comes back. I'm not sure if > there is a better place to post this, but it is Python related. Is this > just an issue with Eclipse or is there something else I should inspect? > > Any help would be appreciated. > > Regards, > > S Cook Which Python plugin are you using? PyDev? Bye, Dennis From irmen.NOSPAM at xs4all.nl Thu Jun 22 16:06:55 2006 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Thu, 22 Jun 2006 22:06:55 +0200 Subject: Network Programming in Python In-Reply-To: <1151005542.852613.115870@r2g2000cwb.googlegroups.com> References: <1151002934.586359.174540@m73g2000cwd.googlegroups.com> <1151005542.852613.115870@r2g2000cwb.googlegroups.com> Message-ID: <449af860$0$31645$e4fe514c@news.xs4all.nl> tactics40 at gmail.com wrote: > > Really, was that so hard? > > Python makes sockets a total breeze. You can write an 80's style HTTP > server in less than a page of code. But making a *good* 80's style http/socket server is a lot of work. Better pick one of the high level protocols built on top of it, to shield you from the gory details of raw socket programming. --Irmen From claudio.grondi at freenet.de Thu Jun 22 17:03:44 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Thu, 22 Jun 2006 23:03:44 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> Message-ID: Xah Lee wrote: > in March, i posted a essay ?What is Expressiveness in a Computer > Language?, archived at: > http://xahlee.org/perl-python/what_is_expresiveness.html > > I was informed then that there is a academic paper written on this > subject. > > On the Expressive Power of Programming Languages, by Matthias > Felleisen, 1990. > http://www.ccs.neu.edu/home/cobbe/pl-seminar-jr/notes/2003-sep-26/expressive-slides.pdf > > Has anyone read this paper? And, would anyone be interested in giving a > summary? > > thanks. > > Xah > xah at xahlee.org > ? http://xahlee.org/ > Looking this thread growing it appears to me, that at least one thing becomes evident here: Xah unwillingness to learn from the bad past experience contaminates others (who are still posting to his trolling threads). Here another try to rescue these ones who are just virgin enough not to know what I am speaking about: Citation from http://www.xahlee.org/Netiquette_dir/_/art_trolling.html : """ What I want this document to focus on is how to create entertaining trolls. I have drawn on the expertise of the writer's of some of Usenet's finest and best remembered trolls. Trolls are for fun. The object of recreational trolling is to sit back and laugh at all those gullible idiots that will believe *anything*. [...] Section 5 Know Your Audience Remember that you have two audiences. The people who are going to get the maximum enjoyment out of your post are other trollers. You need to keep in contact with them through both your troll itself and the way you direct its effect. It is trollers that you are trying to entertain so be creative - trollers don't just want a laugh from you they want to see good trolls so that they can also learn how to improve their own in the never ending search for the perfect troll. [...] Section 6 Following-Up Try not to follow-up to your own troll. The troll itself quickly becomes forgotten in the chaos and if you just sit back you can avoid being blamed for causing it. Remember, if you do follow up you are talking to an idiot. Treat them with the ill-respect they deserve. """ Claudio Grondi (a past 'gullible idiot' who learned to enjoy the fun of being the audience) From juho.schultz at pp.inet.fi Mon Jun 26 15:52:25 2006 From: juho.schultz at pp.inet.fi (Juho Schultz) Date: 26 Jun 2006 12:52:25 -0700 Subject: break the loop in one object and then return In-Reply-To: <1151343860.239200.179270@c74g2000cwc.googlegroups.com> References: <1151343860.239200.179270@c74g2000cwc.googlegroups.com> Message-ID: <1151351545.164418.28870@r2g2000cwb.googlegroups.com> Alex Pavluck wrote: > I am trying to write the following code to block up evaluation and > prompting for entering new information. However, when I break the loop > in one object and then return it does not start at the beginning again > but rather at the point where it exited. Can someone look at the > following code and give me some feedback. > If you want a loop, write a loop. eval() is a built-in function. Better leave the names of builtins as they are. > > yournum = input("I am thinking of a number between 1 and 100.\n Guess > which number: ") > mynum = (yournum-5) > If the users first guess is 2, mynum becomes -3... Better use this - to ensure 100 >= mynum >= 1, and the user can guess right on 1st try. import random mynum = random.randint(1,100) input evaluates a user-supplied string, and is a bit dangerous. (Run your original program, and give "mynum" as your second guess.) So use yournum = int(raw_input("I am thinking... you could use one while loop instead of two functions and one global variable. while (yournum != mynum): if yournum < mynum: print "Too low." else: print "Too high." yournum = int(raw_input("Guess again:")) print "You got it!" From william.xwl at gmail.com Fri Jun 16 14:34:34 2006 From: william.xwl at gmail.com (William) Date: Sat, 17 Jun 2006 02:34:34 +0800 Subject: BeautifulSoup error In-Reply-To: <1150480595.935649.188270@h76g2000cwa.googlegroups.com> References: <1150480595.935649.188270@h76g2000cwa.googlegroups.com> Message-ID: "Serge Orlov" writes: [...] > Look at the traceback: you're not calling BeautifulSoup module! In > fact, there is no feed method in the current BeautifulSoup > documentation. Maybe it used to work well, but now it's definitely > going to fail. As I understand documentation you need to write > > soup = BeautifulSoup(port) Ah, yes ! Things change ! :-) BeautifulSoup feed() method used to exist before 3.0.0, and was left over to SGMLParser later. As explained in the changlog, http://www.crummy.com/software/BeautifulSoup/CHANGELOG.html Release 3.0.0 (2006/05/28), "Who would not give all else for two p" Beautiful Soup no longer implements a feed method. You need to pass a string or a filehandle into the soup constructor, not with feed after the soup has been created. There is still a feed method, but it's the feed method implemented by SGMLParser and calling it will bypass Beautiful Soup and cause problems. Thanks for all the help ! -- William Thrashing is just virtual crashing. From slawomir.nowaczyk.847 at student.lu.se Thu Jun 15 18:05:01 2006 From: slawomir.nowaczyk.847 at student.lu.se (Slawomir Nowaczyk) Date: Fri, 16 Jun 2006 00:05:01 +0200 Subject: a good programming text editor (not IDE) In-Reply-To: <1150402733.116243.9680@y41g2000cwy.googlegroups.com> References: <_xgkg.2317$No6.48542@news.tufts.edu> <1150402733.116243.9680@y41g2000cwy.googlegroups.com> Message-ID: <20060616000408.CCB0.SLAWOMIR.NOWACZYK.847@student.lu.se> On Thu, 15 Jun 2006 13:18:53 -0700 BartlebyScrivener wrote: #> Emacs must be dying if this thread could get all the way to 20 with #> nobody arguing with the vi folks. We have learned the important lesson: those who are looking for true enlightenment will find Emacs anyway. We no longer feel the need to argue with people who praise various versions of notepad ;-) ;-) ;-) -- Best wishes, Slawomir Nowaczyk ( Slawomir.Nowaczyk at cs.lth.se ) Conscience is what hurts when everything else feels so good. From fredrik at pythonware.com Fri Jun 16 05:52:54 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 16 Jun 2006 11:52:54 +0200 Subject: Pb console Effbot References: <449094cb$0$1022$ba4acef3@news.orange.fr> Message-ID: "M?ta-MCI" wrote: > I installed the Console of EFFBOT (http://effbot.org/downloads/#console). > It functions well. It's a very fun/friendly tool. > > Except a detail: when I send (by console.write()) more than 53200 characters, it does not occur > anything. > I circumvented the problem, with a loop which sends ranges of 50000 characters. > > But, I would like to know if somebody already encountered this problem. it's probably some (undocumented) limitation in the Windows Console API (possibly combined with some sloppy error checking in console.write). I'll add it to the TODO list... From g.brandl-nospam at gmx.net Wed Jun 28 09:55:38 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Wed, 28 Jun 2006 15:55:38 +0200 Subject: how do i make an array global In-Reply-To: <44a25ab4$0$1017$626a54ce@news.free.fr> References: <1151472238.400461.42350@p79g2000cwp.googlegroups.com> <44a25ab4$0$1017$626a54ce@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > a wrote: >> def fn(): >> for i in range(l) > > l is not defined - you should have an error here. > >> global count >> count[i]= .... >> >> how do i declare count to be global if it is an array > > Just like it was an integer No. If he's only mutating "count", he doesn't need a global declaration. >> subsequently i should access or define count as an array > > You need to define count before. > >> error: >> global name 'count' is not defined > > He... > > *but* > You probably should not do that anyway. Globals are *evil*. Do you realize that every variable you set in a module's namespace is a global when used by a function? Globals are *not* evil. > And functions modifying globals is the worst possible thing. > There are very few chances you *need* a global here. Look at the use case first. For small scripts, sometimes re-assigning global names or mutating objects refered to by global names is essential. For large-scale packages, though, I agree with you that mutating globals is bad. Georg From slawomir.nowaczyk.847 at student.lu.se Thu Jun 1 17:56:10 2006 From: slawomir.nowaczyk.847 at student.lu.se (Slawomir Nowaczyk) Date: Thu, 01 Jun 2006 23:56:10 +0200 Subject: An oddity in list comparison and element assignment In-Reply-To: <1149194434.528648.148860@u72g2000cwu.googlegroups.com> References: <447f152f@nntp0.pdx.net> <1149194434.528648.148860@u72g2000cwu.googlegroups.com> Message-ID: <20060601234417.FC2E.SLAWOMIR.NOWACZYK.847@student.lu.se> On Thu, 01 Jun 2006 13:40:34 -0700 michael.f.ellis at gmail.com wrote: #> Scott David Daniels wrote: #> > Would you say that envelope containing five $100 bills is equal to #> > an envelope containing five $100 bills with different serial numbers? #> Yes (unless I was testing the assertion that the second envelope did #> not contain counterfeits of the first) So, what if Bank of America later decided that bills with serial numbers containing "7" are no longer valid? In other word, *if* you assume equality must be preserved by future modifications, than no two different (modifiable) objects can ever be really equal. -- Best wishes, Slawomir Nowaczyk ( Slawomir.Nowaczyk at cs.lth.se ) I believe that math illiteracy affects 7 out of every 5 people. From teekaysoh at gmail.com Sun Jun 11 19:33:00 2006 From: teekaysoh at gmail.com (teekaysoh at gmail.com) Date: 11 Jun 2006 16:33:00 -0700 Subject: @func call syntax Message-ID: <1150068780.001520.326910@g10g2000cwb.googlegroups.com> Hi, I am new to Python, here I'd like to have a question: I noticed a special way to call a function in a program: @function_name No argv is passed, even though the function_name asks for one. Any idea what this @something syntax is trying to achieve. I haven't been able to find any answer of on the google web and groups. TIA. From nicolasg at gmail.com Thu Jun 1 15:42:20 2006 From: nicolasg at gmail.com (nicolasg at gmail.com) Date: 1 Jun 2006 12:42:20 -0700 Subject: integer to binary... In-Reply-To: <127ugf9jgu7av18@corp.supernews.com> References: <1149189570.376091.319890@j55g2000cwa.googlegroups.com> <127ugf9jgu7av18@corp.supernews.com> Message-ID: <1149190940.548582.27200@h76g2000cwa.googlegroups.com> Grant Edwards wrote: > On 2006-06-01, nicolasg at gmail.com wrote: > > > does anyone know a module or something to convert numbers like integer > > to binary format ? > > They _are_ in binary format. > > > for example I want to convert number 7 to 0111 so I can make some > > bitwise operations... > > Just do it: > > >>> 7 & 3 > 3 > >>> 7 | 8 > 15 > > > -- I know I can do that but I need to operate in every bit separeted. > Grant Edwards grante Yow! QUIET!! I'm being > at CREATIVE!! Is it GREAT > visi.com yet? It's s'posed to SMOKEY > THE BEAR... From wegwerp at gmail.com Mon Jun 19 10:23:36 2006 From: wegwerp at gmail.com (Bas) Date: 19 Jun 2006 07:23:36 -0700 Subject: comparing two arrays References: <1150721380.948808.231760@h76g2000cwa.googlegroups.com> Message-ID: <1150727011.990165.228480@i40g2000cwc.googlegroups.com> You are comparing a normal python list to a constant, which are obviously unequal. Try converting your lists to arrays first (untested): import numeric/numpy as N a =N.array([0,1,2,5,6,6]) b = N.array([5,4,1,6,4,6]) print a==6 and b==6 print N.where(a==6 and b==6) hth, Bas Sheldon wrote: > Hi, > > I have two arrays that are identical and contain 1s and zeros. Only the > ones are valid and I need to know where both arrays have ones in the > same position. I thought logical_and would work but this example proves > otherwise: > >>> a = [0,1,2,5,6,6] > >>> b = [5,4,1,6,4,6] > >>> Numeric.logical_and(a==6,b==6) > 0 > >>> Numeric.where(a==b,1,0) > 0 > >>> Numeric.where(a==6 and b==6,1,0) > 0 > > The where() statement is also worhtless here. Does anyone have any > suggestion on how to do this? > > Thanks in advance, > Sheldon From jstroud at ucla.edu Wed Jun 28 17:54:09 2006 From: jstroud at ucla.edu (James Stroud) Date: Wed, 28 Jun 2006 14:54:09 -0700 Subject: curiosity about the nature of identity (in python) Message-ID: Hello all, What /is/ identity in python? For example, we can always count on py> None is None True But I have noticed that this works for strings: py> "none" is "none" True and, for example, integers: py> 42 is 42 True And I have noticed that this works for equivalent expressions: py> 42 is (40 + 2) True So, I'm guessing that the integer 42, or the string "none" is cached somewhere and python looks to see if it is in the cache when evaluating 'is'. My guess is supported with this test: py> id(42) 149679044 py> id(40+2) 149679044 py> id(7*6) 149679044 So, I guess my question is to what extent is this equivalency implementation dependent? Is this equivalency a requirement for a legitimate python implementation? Won't these checks slow down evaluation of 'is' considerably? Does '==' ever fall back and use 'is' (or 'id') for evaluation? Just curious. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From raffaelcavallaro at pas-d'espam-s'il-vous-plait-mac.com Sat Jun 17 09:08:59 2006 From: raffaelcavallaro at pas-d'espam-s'il-vous-plait-mac.com (Raffael Cavallaro) Date: Sat, 17 Jun 2006 09:08:59 -0400 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <2006061410510511272-raffaelcavallaro@pasdespamsilvousplaitmaccom> <2006061501423327544-raffaelcavallaro@pasdespamsilvousplaitmaccom> <2006061611492350073-raffaelcavallaro@pasdespamsilvousplaitmaccom> <2006061618250975249-raffaelcavallaro@pasdespamsilvousplaitmaccom> Message-ID: <2006061709085950073-raffaelcavallaro@pasdespamsilvousplaitmaccom> On 2006-06-17 07:03:19 -0400, Joachim Durchholz said: > I don't see static checking and explorative programming as opposites. > Of course, in practice, environments that combine these don't seem to > exist (except maybe in experimental or little-known state). Right. Unfortunately the philosophical leanings of those who design these two types of languages tend to show themselves as different tastes in development style - for example, static type advocates don't often want a very dynamic development environment that would allow a program to run for testing even when parts of it arent defined yet, and dynamic type advocates don't want a compiler preventing them from doing so because the program can't yet be proven statically correct. Dynamic typing advocates don't generally want a compiler error for ambiguous typing - for example, adding a float and an int - but static typing advocates generally do. Of course there's little reason one couldn't have a language that allowed the full range to be switchable so that programmers could tighten up compiler warnings and errors as the program becomes more fully formed. Unfortunately we're not quite there yet. For my tastes something like sbcl*, with its type inference and very detailed warnings and notes is as good as it gets for now. I can basically ignore warnings and notes early on, but use them to allow the compiler to improve the code it generates once the program is doing what I want correctly. [*] I don't mean to exclude other common lisp implementations that do type inference here - I just happen to use sbcl. From ptmcg at austin.rr._bogus_.com Wed Jun 21 11:00:00 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 21 Jun 2006 15:00:00 GMT Subject: How to override the doc of an object instance. References: <200606211539.02663.maric@aristote.info> Message-ID: "David Huard" wrote in message news:mailman.7313.1150898365.27775.python-list at python.org... > On Wed, 21 Jun 2006 15:39:02 +0200, Maric Michaud wrote: > > > This is w.__class__.x.__doc__. > > Thanks, > > So in order to implement what I want, I should rather consider an > ipython hack to print w.__class__.x.__doc__ when it exists, instead of > w.x.__doc_ ? Does this makes sense or it will ruin the standard behaviour? > > David > No need to, just assign your special docstrings to w.x.__doc__, and print w.x.__doc__. Instances that have special docstrings will print their instance-specific versions; instances without instance-specific docstrings will print the class-level version. See below. -- Paul >>> class W(object): ... "Class-level docstring for W" ... pass ... >>> z = W() >>> z.__doc__ 'Class-level docstring for W' >>> z.__doc__ = "instance-level docstring, just for z" >>> z.__doc__ 'instance-level docstring, just for z' >>> zz = W() >>> print zz.__doc__ Class-level docstring for W >>> print z.__doc__ instance-level docstring, just for z From Serge.Orlov at gmail.com Tue Jun 13 18:09:57 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 13 Jun 2006 15:09:57 -0700 Subject: [OT] Re: Python open proxy honeypot References: Message-ID: <1150236597.152868.250740@y43g2000cwc.googlegroups.com> Alex Reinhart wrote: > Being deluged by spam like nearly all of us (though fortunately I have a > very good spam filter), I also hate spam as much as almost everybody. I > know basic Python (enough to make a simple IRC bot) and I figured a good > project to help learn Python would be to make a simple "proxypot." > > I've done some research and found one already existing, written in Perl > (http://www.proxypot.org/). However, I prefer the syntax and ease of > Python (and Proxypot is no longer maintained, as far as I can see), so I > decided to write my own. I have just one question: > > Is running Python's built-in smtpd, pretending to accept and forward all > messages, enough to get me noticed by a spammer, or do I have to do > something else to "advertise" my script as an open proxy? > > I'm hoping to make this proxy script "distributed", in that several > honeypots are run on different servers, and the results are then > collected on a central server that provides statistics and a listing of > all spammers caught. So, just out of curiosity, I'd like to know how > many people would actually be willing to run a honeypot on their server, > and how many are opposed to the idea (just so I know if the concept is > even valid). IMHO it's pretty useless, spammers are starting to use botnets, and the more you make inconvenient to them use open proxies, the more of them will move to closed botnets. My spam folder at gmail is not growing anymore for many months (it is about 600-700 spams a month). Have spammers given up spamming gmail.com only or is it global trend? From steve at holdenweb.com Tue Jun 13 13:02:47 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 13 Jun 2006 18:02:47 +0100 Subject: Python 411. In-Reply-To: <448E8E53.90200@cc.umanitoba.ca> References: <1150152755.474292.39010@j55g2000cwa.googlegroups.com> <1150188399.809316.172840@f14g2000cwb.googlegroups.com> <448E8E53.90200@cc.umanitoba.ca> Message-ID: Brian van den Broek wrote: > Mike T said unto the world upon 13/06/06 10:46 AM: > >>What exactly is 411 in this context? A reference to higher education >>perhaps? Or perhaps part of the American constitution? What exactly? >>Also for that matter what is 101? >> >>Cheers, >>Mike >> > > > Hi Mike, > > 411 is the number one dials in North America to reach directory > assistance (getting telephone numbers). So, it has a slang usage > meaning something like information. Introductory university course in > a field are often numbered 101 (i.e. Computer Science 101). So, that > number has acquired a slang meaning of basic and introductory information. > > Where I did my undergrad studies, a few Departments had 001 classes. > Somehow that felt more honest ;-) > Surely 000 would have been more consistent ... regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From Mike.S.Duffy at gmail.com Wed Jun 28 18:39:59 2006 From: Mike.S.Duffy at gmail.com (Mike Duffy) Date: 28 Jun 2006 15:39:59 -0700 Subject: ? on scipy.fftpack In-Reply-To: References: <1151513772.828636.225540@p79g2000cwp.googlegroups.com> Message-ID: <1151534399.780493.156490@x69g2000cwx.googlegroups.com> Oops, sorry. I see what you mean. I was reading the docs for the regular (complex) fft function, since that was what I was initially having the bug with. I was just using the rfft to simplify things, but I guess that was ironic. Anyway, I appreciate your help and don't mean to burden you. Again, I will suubmit this to the scipy list. From d4rkritu4l at gmail.com Thu Jun 22 13:19:23 2006 From: d4rkritu4l at gmail.com (ph0b0s) Date: Thu, 22 Jun 2006 19:19:23 +0200 Subject: Confused by subclassing, threading and scopes... Message-ID: <449AD11B.1070400@gmail.com> An HTML attachment was scrubbed... URL: From dakman at gmail.com Mon Jun 19 11:53:12 2006 From: dakman at gmail.com (dakman at gmail.com) Date: 19 Jun 2006 08:53:12 -0700 Subject: Installing Python on Windows Vista In-Reply-To: <1150731053.741522.190010@p79g2000cwp.googlegroups.com> References: <1150731053.741522.190010@p79g2000cwp.googlegroups.com> Message-ID: <1150732391.956521.125310@r2g2000cwb.googlegroups.com> Padraig wrote: > Hi all, > > Just a quick question... when I try to install Python on Windows Vista > Beta 2 the installer seems to hang after I select the destination > folder, saying that it will "return when it has finished calculating > disk space requirements". I just can't seem to get past that step. I've > also tried installing both 2.4.3 and 2.4.2 with no luck. > > Any help would be very much appreciated. > > Many thanks > > P I've heard that Windows Vista has many restrictions on reading/writing to the disk, perhaps you do not have an admin account? From anton.vredegoor at gmail.com Sat Jun 3 03:06:39 2006 From: anton.vredegoor at gmail.com (anton.vredegoor at gmail.com) Date: Sat, 03 Jun 2006 09:06:39 +0200 Subject: An oddity in list comparison and element assignment In-Reply-To: <1hgbu61.1gtkkjh1aca3i8N%aleax@mac.com> References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> <1hg9nl6.xivwcd7n0j5N%aleax@mac.com> <1149277242.199765.213600@g10g2000cwb.googlegroups.com> <1hgbhhi.mcrge51cyj2isN%aleax@mac.com> <1hgbu61.1gtkkjh1aca3i8N%aleax@mac.com> Message-ID: Alex Martelli wrote: > wrote: >> Can somebody please shut down this bot? I think it's running out of > > Much as you might love for somebody to "shut me down", that > (unfortunately, no doubt, from your viewpoint) is quite unlikely to > happen. Although "making predictions is always difficult, especially > about the future", the most likely course of events is that I shall > continue for a while to survive, probably in tolerable health. You've got that completely wrong. I was not trying to kill you but I was trying to revive you. A process that is not evolving is dead. Stopping it frees up valuable resources that enable it to become alive again. Anton 'being alive is being mutable' From fuzzyman at gmail.com Sun Jun 4 18:43:49 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 4 Jun 2006 15:43:49 -0700 Subject: [ANN] ConfigObj 4.3.2 Released Message-ID: <1149461029.273580.199290@g10g2000cwb.googlegroups.com> `ConfigObj 4.3.2 `_ has just been released. You can download it from `configobj-4.3.2.zip `_. ConfigObj is a config file reader and writer. It has *many* features, but the main one is that it is simple to use. Its features include : * Nested sections (subsections), to any level * List values * Multiple line values * String interpolation (substitution) * Integrated with a powerful validation system - including automatic type checking/conversion - repeated sections - and allowing default values * All comments in the file are preserved * The order of keys/sections is preserved * No external dependencies * Full Unicode support * A powerful ``unrepr`` mode for storing basic datatypes This is a bugfix and minor feature enhancement release. There is a bugfix in `unrepr mode `_, and exception handling has been improved. The full changelog is : Changed error handling, if parsing finds a single error then that error will be re-raised. That error will still have an ``errors`` and a ``config`` attribute. That means the error will be more comprehensible. Fixed bug where '\n' terminated files could be truncated. Bugfix in ``unrepr`` mode, it couldn't handle '#' in values. (Thanks to Philippe Normand for the report.) As a consequence of this fix, ConfigObj doesn't now keep inline comments in ``unrepr`` mode. This is because the parser in the `compiler package `_ doesn't keep comments. {sm;:-)} Error messages are now more useful. They tell you the number of parsing errors and the line number of the first error. (In the case of multiple errors.) Line numbers in exceptions now start at 1, not 0. Errors in ``unrepr`` mode are now handled the same way as in the normal mode. The errors stored will be an ``UnreprError``. There is also a proposal to support `PEP 292 `_ string substitution (which is much better). This will be the target of the next release of **ConfigObj**. From george.sakkis at gmail.com Thu Jun 22 21:24:54 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 22 Jun 2006 18:24:54 -0700 Subject: String negative indices? References: Message-ID: <1151025894.539991.283110@c74g2000cwc.googlegroups.com> drtimh... at comcast.net wrote: > I'm just starting out on Python, and am stumped by what appears an oddity in the way negative indices are handled. > > For example, to get the last character in a string, I can enter "x[-1]". To get the 2nd and 3rd to last, I can enter x[-3:-1] etc. This is fine. > > Logically, I should be able to enter x[-2:-0] to get the last and next to last characters. However, since Python doesn't distinguish between positive and negative zero, this doesn't work. Instead, I have to enter x[-2:]. > > With simple constants, this is ok, but it's a little more annoying when the start and end of the range are in variables somewhere. The only way I can find of making this work without lots of special-case "if" logic is to translate negative subscripts to positive, which kinda defeats the purpose of the negative subscripts anyway. > > Is there some magic I'm missing here? Wouldn't it actually be better for Python to treat 0 as a special case here, so that x[-2:0] and x[-2:] generated the same result? > > --Tim x[-2:None] I'm not sure if it qualifies as "magic" but you're right, it's not more obvious than 0 would be. George From matth at gmx.net Fri Jun 2 12:08:21 2006 From: matth at gmx.net (Matthieu Pichaud) Date: Fri, 2 Jun 2006 18:08:21 +0200 Subject: Package Message-ID: I have a problem organizing my programs in packages and subpackages. I use python.2.3.3 I built a test structure to try to understand how it worked: /test /test/__init__.py (containing: __all__=['test1']) /test/test1/ /test/test1/__init__.py (containing: __all__=['test2']) /test/test1/test2/ /test/test1/test2/__init__.py (containing: __all__=['test3']) /test/test1/test2/test3.py (containing: print 'test3') Then I run: >>> from test import * >>> test1 >>> test2 Traceback (most recent call last): File "", line 1, in ? NameError: name 'test2' is not defined So it seems that I am very limited in the number of subpackages I can create. Is it normal? Am I silly organizing my programs like that? Thanks for your help! Matth From george.sakkis at gmail.com Thu Jun 15 08:38:10 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 15 Jun 2006 05:38:10 -0700 Subject: nested functions References: <1150344748.652441.316680@g10g2000cwb.googlegroups.com> Message-ID: <1150375090.506586.174430@g10g2000cwb.googlegroups.com> Duncan Booth wrote: > Fredrik Lundh wrote: > > > George Sakkis wrote: > > > >> It shouldn't come as a surprise if it turns out to be slower, since > >> the nested function is redefined every time the outer is called. > > > > except that it isn't, really: all that happens is that a new function > > object is created from prebuilt parts, and assigned to a local > > variable. it's not slower than, say, a method call. > > > It looks to be somewhat faster than a method call: > > C:\temp>\python24\lib\timeit.py -s "import t" "t.testMethod(t.instance, > 42)" > 1000 loops, best of 3: 1.58 msec per loop > > C:\temp>\python24\lib\timeit.py -s "import t" "t.testMethod2(t.instance, > 42)" > 100 loops, best of 3: 1.61 msec per loop > > C:\temp>\python24\lib\timeit.py -s "import t" "t.testNested(t.instance, > 42)" > 1000 loops, best of 3: 1.06 msec per loop > > C:\temp>\python24\lib\timeit.py -s "import t" "t.testNested2(t.instance, > 42)" > 1000 loops, best of 3: 1.08 msec per loop > > C:\temp>\python24\lib\timeit.py -s "import t" "t.testNested3(t.instance, > 42)" > 1000 loops, best of 3: 1.13 msec per loop > > C:\temp>\python24\lib\timeit.py -s "import t" "t.testNested4(t.instance, > 42)" > 1000 loops, best of 3: 1.23 msec per loop > > > --------- t.py ------------- > class C: > def m1(self): > return 42 > > def m2(self, x): > return x > > instance = C() > > def testMethod(instance,x): > n = 0 > while n < 100000: > n += instance.m1() > > def testMethod2(instance, x): > n = 0 > while n < 100000: > n += instance.m2(x) > > def testNested(instance, x): > def m1(): > return 42 > n = 0 > while n < 100000: > n += m1() > > def testNested2(instance, x): > def m2(): > return x > n = 0 > while n < 100000: > n += m2() > > def testNested3(instance, x): > def m2(y): > return y > n = 0 > while n < 100000: > n += m2(x) > > def testNested4(instance, x): > def m2(y): > return x > n = 0 > while n < 100000: > n += m2(x) > > ---------------------------- > > The differences between the nested function calls show how difficult it can > be guessing what will be faster: #3 show that all, else being equal, > accessing the closure is much slower than accessing a parameter, but #2 > shows that not passing any parameters to the nested function more than > compensates for the single slow closure access. It would also be interesting to add unnested versions of m1(), m2() (functions, not methods) to the comparison. George From fredrik at pythonware.com Sat Jun 3 13:12:13 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 03 Jun 2006 19:12:13 +0200 Subject: image lib & Qt4 In-Reply-To: <44819AEF.6040609@tachyontech.net> References: <1149173540.470829.34940@c74g2000cwc.googlegroups.com> <4e8haiF1dp2heU1@uni-berlin.de> <1149180814.585713.209640@i39g2000cwa.googlegroups.com> <44818202.8060607@tachyontech.net> <448191A5.1050502@tachyontech.net> <44819AEF.6040609@tachyontech.net> Message-ID: K.S.Sreeram wrote: > so does that mean the BGRA raw mode is supported in PIL 1.1.6? possibly; I haven't checked. it does mean that some future version will most likely support it, at least. From bdesth.quelquechose at free.quelquepart.fr Sun Jun 4 22:15:23 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 05 Jun 2006 04:15:23 +0200 Subject: mutable member, bug or ... In-Reply-To: References: Message-ID: <4483641f$0$31935$626a54ce@news.free.fr> Sambo a ?crit : > By accident I assigned int to a class member 'count' which was > initialized to (empty) string and had no error till I tried to use it as > string, obviously. Why was there no error on assignment( near the end ). Python is dynamically typed - which means that it's not the name that holds type info, but the object itself. names are just, well, names... BTW, I failed to see where you assigned an int to the class attribute 'count'. I just saw a try to call a string - which should raise a TypeError. > class Cgroup_info: Do yourself (and anyone having to work on or with your code) a favour: use new-style classes (ie : inherit from 'object'). And FWIW, the convention for class names is CamelCase - preferably without MS-like hungarian annotation. > group_name = "" > count = "0" #last time checked and processed/retrieved > first = "0" > last = "" > retrieval_type = "" # allways , ask( if more than some limit), > none > date_checked = "" > time_checked = "" > new_count = "" > new_first = "" > new_last = "" > # local storage maintanance vars > pointer_file = "" > message_file = "" > #maintanance vars cur_mess_num = 0 > cur_mess_id = "" All these are *class* attributes (meaning they belong to the class object itself, not to instances). I really doubt this is what you want. If you hope to have all the above as instance attributes, you must assign them to the instance (usually in the __init__() method, which main purpose is to initialize the newly created instance. > def __init__( self ): > group_name = "" this creates a local variable 'group_name', bound to an empty string. Using the reference to the current instance (usually named 'self', and always passed in as first param) is *not* optional. > count = "0" #last time checked and processed/retrieved and this creates a local variable 'count', bound to string '0'. Of course, both are lost as soon as the __init__() returns. > def get_count( self ): > print self.count, type( self.count ) > return string.atoi( self.count, 10 ) the string module is mostly deprecated. Use str object methods instead - or if you just want to create an int from it's representation as a string, int(self.count). > class server_info: > def "(server_info::)"get_group_stat( self, grp ): invalid syntax. > gr_info = Cgroup_info() and a problem with indentation here. > gr_info.group_name = grp Tthis create a new instance attribute "group_name" on the gr_info object. This instance attribute will shadow the class attribute of the same name. Also, FWIW, if you always know the value for group_name when instanciating a Cgroup_info object, you might as well pass it to the initializer. > try: > ind = self.group_list.index( grp ) The common convention for indices in each and every language is 'i'. If you really want a meaningful name, then group_index would be better. Also, for this kind of lookups, dicts are really faster than lists. > except ValueError: > gr_info.count(0) I didn't see any method "count()" in the declaration of class CGroup_info. I saw an attribute named "count", but it was bound to a string - which is not callable. > return ( gr_info ) parenthesis here are useless (and FWIW, they would be just as useless in C++). > print ind > if len( self.group_list[ind].split() ) == 4: > gr_info.count = self.group_list[ind].split()[1] > gr_info.first = self.group_list[ind].split()[2] > gr_info.last = self.group_list[ind].split()[3] group_list[ind] is the same as grp, isn't it ? if so, using grp directly might be much more efficient *and* much more readable. Also, you're calling 4 times the same method. This is highly inefficient. Try this instead: parts = grp.split() if len(parts) == 4: gr_info.count, gr_info.first, gr_info.last = parts[1:] > else: > gr_info.count = gr_info.first = gr_info.last = "0" This style of "chained assignment" can be a real gotcha in Python. In this case, it is safe since "0" is immutable. But using a mutable object instead would lead to probably unexpected results. Try this: a = b = [] a.append(1) print b You have to understand that Python "variables" (the correct name is "bindings") are just the association (in a given namespace) of a name and a *reference* (kind of a smart pointer) to an object. > return( gr_info ) Here's a possible rewrite of your code. It's certainly not how it should be done, but (apart from going into wild guesses) it's difficult to come up with anything better without knowing the specs. Anyway, it should help you grasp a more pythonic way to do things: class GroupInfo(object): def __init__(self, group_name, count="0", first="0", last=""): self.group_name = group_name self.count = count #last time checked and processed/retrieved self.first = first self.last = last self.retrieval_type = "" # always , ask( if more than some limit), none self.date_checked = "" self.time_checked = "" self.new_count = "" self.new_first = "" self.new_last = "" # local storage maintanance vars self.pointer_file = "" self.message_file = "" #maintanance vars self.cur_mess_num = 0 self.cur_mess_id = "" # if you want to store count as string # but retrieve it as an int. The setter will # be used by the initializer, and will then create # the implementation attribute _count def _get_count(self): return int(self._count) def _set_count(self, value): self._count = str(value) count = property(_get_count, _set_count) class ServerInfo(object): def __init__(self, ???) self._groups = {} # dict lookup is faster # ... def has_group(self, group_name): return self._groups.has_key(group_name) def get_group_stat(self, group_name): if not self.has_group(group_name): return GroupInfo(group_name, "0") parts = group_name.split() if len(parts) != 4: parts = [None, "0", "0", "0"] return GroupInfo(group_name, *(parts[1:4])) As a last point, I'd second Fredrik : don't try to write C++ in Python. Learn to write Python instead. The (freely available) "Dive into Python" book should be a good place to get started. HTH From rpw3 at rpw3.org Wed Jun 21 23:19:24 2006 From: rpw3 at rpw3.org (Rob Warnock) Date: Wed, 21 Jun 2006 22:19:24 -0500 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150904134.520639.71070@b68g2000cwa.googlegroups.com> Message-ID: <4padnQn3SOWhkQfZnZ2dnUVZ_rqdnZ2d@speakeasy.net> Marshall wrote: +--------------- | Anton van Straaten wrote: | > 3. A really natural term to refer to types which programmers reason | > about, even if they are not statically checked, is "latent types". It | > captures the situation very well intuitively, and it has plenty of | > precedent -- e.g. it's mentioned in the Scheme reports, R5RS and its | > predecessors, going back at least a decade or so (haven't dug to check | > when it first appeared). | | Can you be more explicit about what "latent types" means? | I'm sorry to say it's not at all natural or intuitive to me. | Are you referring to the types in the programmers head, | or the ones at runtime, or what? +--------------- Here's what the Scheme Standard has to say: http://www.schemers.org/Documents/Standards/R5RS/HTML/r5rs-Z-H-4.html 1.1 Semantics ... Scheme has latent as opposed to manifest types. Types are assoc- iated with values (also called objects) rather than with variables. (Some authors refer to languages with latent types as weakly typed or dynamically typed languages.) Other languages with latent types are APL, Snobol, and other dialects of Lisp. Languages with manifest types (sometimes referred to as strongly typed or statically typed languages) include Algol 60, Pascal, and C. To me, the word "latent" means that when handed a value of unknown type at runtime, I can look at it or perform TYPE-OF on it or TYPECASE or something and thereby discover its actual type at the moment[1], whereas "manifest" means that types[2] are lexically apparent in the code. -Rob [1] I added "at the moment", since I remembered that in Common Lisp one may change the type of a value at runtime, specifically, a CLOS instance may change type "out from under you" if someone performs a CHANGE-CLASS on it or redefines its CLASS definition. [Though maybe the latter is more a change of the *type* itself rather than a change of the *object's* type per se.] [2] Usually of a variables or locations, but sometimes of expressions. ----- Rob Warnock 627 26th Avenue San Mateo, CA 94403 (650)572-2607 From robert.kern at gmail.com Wed Jun 21 02:11:51 2006 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 21 Jun 2006 01:11:51 -0500 Subject: Initializing a set from a list In-Reply-To: <1150869540.796459.202330@u72g2000cwu.googlegroups.com> References: <1150869540.796459.202330@u72g2000cwu.googlegroups.com> Message-ID: Xiaolei Li wrote: > Hi, > > I'm trying to initialize a set from a list but am unable to do so. My > list "c", looks like: > > [(1.00909, 0.91969999999999996, -0.13550388182991072, 0), > (0.87423999999999991, 0.6666700000000001, -0.21230487137222254, 0)] > > So basically a list of 2 tuples, each with 4 elements. Since tuples > are immutable, I think a set should be able to support them. > > Anyway, I then do: > > set_c = set(c) > > And instead of getting a set, I get "None" when I try to print out > set_c. len(set_c) complains "TypeError: len() of unsized object." > Help? >>> c = [(1.00909, 0.91969999999999996, -0.13550388182991072, 0), ... (0.87423999999999991, 0.6666700000000001, -0.21230487137222254, 0)] >>> set_c = set(c) >>> set_c set([(1.00909, 0.91969999999999996, -0.13550388182991072, 0), (0.87423999999999991, 0.6666700000000001, -0.21230487137222254, 0)]) >>> Please copy-and-paste the exact code that you wrote and the exact output. -- 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 From invalid at invalid.net Wed Jun 7 21:52:53 2006 From: invalid at invalid.net (Frank Silvermann) Date: Wed, 07 Jun 2006 21:52:53 -0400 Subject: The Nature of the =?UTF-8?B?4oCcVW5peCBQaGlsb3NvcGh54oCd?= In-Reply-To: <1149730552.161534.121350@i40g2000cwc.googlegroups.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1149080931.582431.95560@j55g2000cwa.googlegroups.com> <1149730552.161534.121350@i40g2000cwc.googlegroups.com> Message-ID: <4487822b$0$30709$ec3e2dad@news.usenetmonster.com> Xah Lee wrote: > The Nature of the ?Unix Philosophy? > > Xah Lee, 2006-05 > > In the computing industry, especially among unix community, we often > hear that there's a ?Unix Philosophy?. In this essay, i dissect the > nature and characterization of such ?unix philosophy?, as have been > described by Brian Kernighan, Rob Pike, Dennis Ritchie, Ken Thompson, > and Richard P Gabriel et al, and in recent years by Eric Raymond. > Unix Philosophy. > ---- > This article is archived at: > http://xahlee.org/UnixResource_dir/writ/unix_phil.html > > Xah > xah at xahlee.org > ? http://xahlee.org/ > Sigma may impress some, but it does not impress me until you realize that philosophers can't count. That you have lower-case for the first person nominative pronoun is one thing, but that you have a difference in subject versus predicate is certainly something that Confucious criticizes. frank ------------------ tja From tactics40 at gmail.com Mon Jun 26 16:02:44 2006 From: tactics40 at gmail.com (tac-tics) Date: 26 Jun 2006 13:02:44 -0700 Subject: Freezing Python with jythonc In-Reply-To: <1151344176.995788.297350@u72g2000cwu.googlegroups.com> References: <1151344176.995788.297350@u72g2000cwu.googlegroups.com> Message-ID: <1151352164.799987.204060@y41g2000cwy.googlegroups.com> > What am I doing wrong? Nevermind, I figured it out. -classpath overwrites the classpath.... not augments. I needed to use -classpath ".;jython.jar" and it works fine. From onurb at xiludom.gro Fri Jun 23 09:36:42 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Fri, 23 Jun 2006 15:36:42 +0200 Subject: Specifing arguments type for a function In-Reply-To: <1151042100.731065.19510@r2g2000cwb.googlegroups.com> References: <200606201328.02784.maric@aristote.info> <1150804645.542646.38570@g10g2000cwb.googlegroups.com> <449afb64$0$16558$636a55ce@news.free.fr> <1151020127.152656.26860@m73g2000cwd.googlegroups.com> <9cum92trvgb271b776l2lg4rdfj3ed951g@4ax.com> <1151042100.731065.19510@r2g2000cwb.googlegroups.com> Message-ID: <449bee6a$0$31126$626a54ce@news.free.fr> George Sakkis wrote: > Dennis Lee Bieber wrote: > >>On 22 Jun 2006 16:48:47 -0700, "George Sakkis" >>declaimed the following in comp.lang.python: >> >> >>>What does __setitem__ have to do with iterability ? >> >> It confirms that the object is indexable, and mutable -- ie; a list, >>not a tuple or a string. > > > Ok, I'll try once more: What does __setitem__ have to do with > **iterability**, not mutability or indexability ? Nothing. > I was commenting on > Maric's post that although some objects are typically iterable, they > are often treated as atomic by some/many/most applications (e.g. > strings). It's not rocket science. No, it's not rocket science. It's not rocket science neither to understand that, for the concrete examples you used (ie strings and tuples), it's quite easy to detect'em without testing the concrete type. As you said, what is to be considered as scalar and what's to be considered as sequence highly depends on the problem at hand. But doing the distinction does not always implies testing concrete type or mro. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From sturnfie at gmail.com Mon Jun 5 12:34:48 2006 From: sturnfie at gmail.com (sturnfie at gmail.com) Date: 5 Jun 2006 09:34:48 -0700 Subject: xml.sax problem: getting parse() to read a string Message-ID: <1149525288.546237.78700@u72g2000cwu.googlegroups.com> Hey all, I recently came across the xml.sax libraries and am trying to use them. I am currently making a string variable, and am attempting to pass it into a parser instance as follows: def parseMessage(self, message): #create a XML parser parser = make_parser() #create an instance of our handler class #generic, prints out to screen on all events dh = docHandler() #tell parser to use our handler parser.setContentHandler(dh) #start it going, will trigger on events as defined in the docHandler class parser.parse(message) return "message" is the following text: ----------------- - - timestamp - asdasd asdasds --------------- This is dying with the following errors. File "...../python/lib/python2.4/urllib.py", line 77, in urlopen return opener.open(url) File "...../python/lib/python2.4/urllib.py", line 180, in open return getattr(self, name)(url) File "...../python/lib/python2.4/urllib.py", line 409, in open_file return self.open_local_file(url) File "...../python/lib/python2.4/urllib.py", line 419, in open_local_file raise IOError(e.errno, e.strerror, e.filename) IOError: [Errno 2] No such file or directory: '?xml version="1.0" ?>\n- \n - \n timestamp\n - \n asdasd\n asdasds\n \n \n Message-ID: In article , "Richard Brodie" wrote: >"Sion Arrowsmith" wrote in message >news:gLB*BXekr at news.chiark.greenend.org.uk... > >>>By the way, you _do_ realize that your "&" characters should be escaped >>>as "&", don't you? >> >> No they shouldn't. They part of the url, which is (IIRC) a CDATA >> attribute of the A element, not PCDATA. > >It is CDATA but ampersands still need to be escaped. I believe it's common for CGI argument-parsing routines to accept ";" as a synonym for "&" as the argument separator. Certainly the code I use does. From rogue_pedro at yahoo.com Fri Jun 30 21:45:42 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 30 Jun 2006 18:45:42 -0700 Subject: list comprehension In-Reply-To: <44a5231e$0$7224$626a54ce@news.free.fr> References: <1151600332.552024.119990@y41g2000cwy.googlegroups.com> <1151602493.629010.269360@i40g2000cwc.googlegroups.com> <1151671605.957887.158150@m73g2000cwd.googlegroups.com> <44a5231e$0$7224$626a54ce@news.free.fr> Message-ID: <1151718342.465818.291490@p79g2000cwp.googlegroups.com> Bruno Desthuilliers wrote: > Andy Dingley wrote: > > Simon Forman wrote: > > > >>There's more to it, but that's the basic idea. > > > > This much I knew, but _why_ and _when_ would I choose to use list > > comprehension (for good Python style), rather than using a simple > > "traditional" loop ? > > Whenever it's more readable. > Yeah. Also, it's faster. ~Simon From aleax at mac.com Mon Jun 26 10:59:55 2006 From: aleax at mac.com (Alex Martelli) Date: Mon, 26 Jun 2006 07:59:55 -0700 Subject: Python taught in schools? References: <1151220913.406987.162420@u72g2000cwu.googlegroups.com> <1hhhbmb.qcvbcn14uox59N%aleax@mac.com> Message-ID: <1hhj4j2.1yaslus7ovcjaN%aleax@mac.com> Lawrence D'Oliveiro wrote: > In article <1hhhbmb.qcvbcn14uox59N%aleax at mac.com>, > aleax at mac.com (Alex Martelli) wrote: > > >... let's try some google searches and see the number of million hits...: > > But how reliable are those estimates of numbers of hits, anyway? More > than once I've got a page showing something like "Results 1 - 10 of > about 36 hits", only to find that there were no more pages after the > second one. If it could get estimates so wrong with such small numbers, > how can you trust the large ones? If your experience in the matter dates from a few months ago (and most of us may have done Google searches for years, contributing to form our impressions) it may perhaps not be all that applicable any more, according to rumors from early this year (e.g. ) and blogging notes by Matt Cutts at . If you can give examples of a query which estimates the (small) number of results very badly, net of course of Duncan Booth's observation regarding Google's attempts to filter out near-duplicates, I'll be glad to look further into the matter (my group is Production Systems, just about as far from such issues as you can imagine -- rather, we write software to keep our clusters, networks &c smoothly running, monitor them, and so forth -- but, of course, I do have friends over in Search Quality and related groups... fortunately, Google has so far managed to avoid much of the "silos syndrome"... so I'll be glad to check it out, but I do need specific examples!-). Alex From yinglcs at gmail.com Fri Jun 9 00:31:36 2006 From: yinglcs at gmail.com (yinglcs at gmail.com) Date: 8 Jun 2006 21:31:36 -0700 Subject: How to extract 2 integers from a string in python? Message-ID: <1149827496.857621.88550@h76g2000cwa.googlegroups.com> Hi, how can I extract 2 integers from a string in python? for example, my source string is this: Total size: 173233 (371587) I want to extract the integer 173233 and 371587 from that soource string, how can I do that? From news at andmc.com Sun Jun 25 14:28:01 2006 From: news at andmc.com (Andrew McDonagh) Date: Sun, 25 Jun 2006 19:28:01 +0100 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <0%Wlg.3521$MF6.947@tornado.socal.rr.com> <44992e6c$0$664$bed64819@news.gradwell.net> <1151010139.960608.122470@b68g2000cwa.googlegroups.com> Message-ID: Joachim Durchholz wrote: > Chris Smith schrieb: >> Joachim Durchholz wrote: >>> Sorry, I have to insist that it's not me who's stretching terms here. >>> >>> All textbook definitions that I have seen define a type as the >>> set/operations/axioms triple I mentioned above. >>> No mention of immutability, at least not in the definitions. >> >> The immutability comes from the fact (perhaps implicit in these >> textbooks, or perhaps they are not really texts on formal type theory) >> that types are assigned to expressions, > > That doesn't *define* what's a type or what isn't! > > If it's impossible to assign types to all expressions of a program in a > language, that does mean that there's no useful type theory for the > program, but it most definitely does not mean that there are no types in > the program. > I can still sensibly talk about sets of values, sets of allowable > operations over each value, and about relationships between inputs and > outputs of these operations. > > So programs have types, even if they don't have a static type system. > Q.E.D. > Of course not. Otherwise programs using dynamically typed systems wouldnt exist. > Regards, > Jo I haven't read all of this thread, I wonder, is the problem to do with Class being mistaken for Type? (which is usually the issue) From david.nospam.hopwood at blueyonder.co.uk Sat Jun 24 11:30:36 2006 From: david.nospam.hopwood at blueyonder.co.uk (David Hopwood) Date: Sat, 24 Jun 2006 15:30:36 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: <449bde5f$2$663$bed64819@news.gradwell.net> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150908952.804184.218990@r2g2000cwb.googlegroups.com> <1150991074.705803.211570@m73g2000cwd.googlegroups.com> <449bde5f$2$663$bed64819@news.gradwell.net> Message-ID: Chris Uppal wrote: > David Hopwood wrote: > >>>But some of the advocates of statically >>>typed languages wish to lump these languages together with assembly >>>language a "untyped" in an attempt to label them as unsafe. >> >>A common term for languages which have defined behaviour at run-time is >>"memory safe". For example, "Smalltalk is untyped and memory safe." >>That's not too objectionable, is it? > > I find it too weak, as if to say: "well, ok, it can't actually corrupt memory > as such, but the program logic is still apt go all over the shop"... Well, it might ;-) (In case anyone thinks I am being pejorative toward not-statically-typed languages here, I would say that the program logic can *also* "go all over the shop" in a statically typed, memory safe language. To avoid this, you need at least a language that is "secure" in the sense used in capability systems, which is a stronger property than memory safety.) -- David Hopwood From dnew at san.rr.com Fri Jun 16 15:06:46 2006 From: dnew at san.rr.com (Darren New) Date: Fri, 16 Jun 2006 19:06:46 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <2006061410510511272-raffaelcavallaro@pasdespamsilvousplaitmaccom> <2006061501423327544-raffaelcavallaro@pasdespamsilvousplaitmaccom> <_eBkg.14895$uy3.4988@tornado.socal.rr.com> <1sBkg.14897$uy3.4884@tornado.socal.rr.com> Message-ID: Matthias Blume wrote: > Very good statically typed versions of printf exist. See, e.g., > Danvy's unparsing combinators. That seems to ignore the fact that the pattern is a string, which means that printf's first argument in Danvy's mechanism has to be a literal. You can't read the printf format from a configuration file (for example) to support separate languages. It doesn't look like the version of printf that can print its arguments in an order different from the order provided in the argument list is supported either; something like "%3$d" or some such. Second, what's the type of the argument that printf, sprintf, fprintf, kprintf, etc all pass to the subroutine that actually does the formatting? (Called vprintf, I think?) -- Darren New / San Diego, CA, USA (PST) My Bath Fu is strong, as I have studied under the Showerin' Monks. From ldo at geek-central.gen.new_zealand Tue Jun 27 01:11:34 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 27 Jun 2006 17:11:34 +1200 Subject: Python taught in schools? References: <1151220913.406987.162420@u72g2000cwu.googlegroups.com> Message-ID: In article , mgi820 at motorola.com (Gary Duzan) wrote: > I understand that the school switched [from C++] to Java a short > time later, which is some improvement, but still has a good bit of > baggage. Java started out trying to avoid most of the complexities of C++, but ended up having to reintroduce many of them anyway. >p.s. Then sock them with ML or Haskell to weed out the weak ones. ;-) > Then if they survive Occam, throw Java at them, so they'll > know what they are missing but can still get a job... And yet, because they didn't start with Java, they'll still have the ability to think. Which is bound to annoy PHBs out in the "real" world ... From claudio.grondi at freenet.de Mon Jun 26 14:09:20 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Mon, 26 Jun 2006 20:09:20 +0200 Subject: Beginner Programmer Question In-Reply-To: <1151343473.722970.251360@r2g2000cwb.googlegroups.com> References: <1151342733.742416.180370@r2g2000cwb.googlegroups.com> <1151343383.139891.219270@u72g2000cwu.googlegroups.com> <1151343473.722970.251360@r2g2000cwb.googlegroups.com> Message-ID: kydavis77 at gmail.com wrote: > kydavis77 at gmail.com wrote: > >>Claudio Grondi wrote: >> >>>kydavis77 at gmail.com wrote: >>> >>>>I am doing alot of reading and trying to teach myself how to program. >>>>I can not figure out how to make "Write a program that continually >>>>reads in numbers from the user and adds them together until the sum >>>>reaches 100." this work. If someone could show me the correct code so i >>>>can learn from that it would be much appreciated. Thanks >>>> >>> >>>Isn't it your homework? >>>Why can't you figure it out? >>>What have you tried? >>> >>>Claudio >> >>I am doing alot of reading, and the problem didnt come with an answer. >>I dont understand how to get it to continually input numbers and add >>all those together > > > #Add up to 100 program > > #What number are you adding up to? > bigone = 100 > > number = input("Whats the first number?") > number2 = input ("Whats the second number?") > nu3 = number+number2 > while nu3 < bigone: # you are missing the input and building the sum here: number3 = input ("Whats the next number?") nu3 = nu3 + number3 > print ("Not there yet, next number please") # so nu3 gets never changed and your loop runs forever. > > > print "Finally there!" > > thats what i thought maybe it was...but after the first two numbers it > just continually scrolls on the screen with finally there Yes, because you have no input command in the loop and no sum changing the value of nu3. But you should get scrolling with "Not there yet, next number please" not with "Finally there!" according to your code. I suppose your next question will be what tutorial is the best for a newbie, so I suggest you start with: http://wiki.python.org/moin/BeginnersGuide Claudio From steven.bethard at gmail.com Wed Jun 14 10:56:22 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 14 Jun 2006 08:56:22 -0600 Subject: python-dev Summary for 2006-05-01 through 2006-05-15 In-Reply-To: References: Message-ID: garabik-news-2005-05 at kassiopeia.juls.savba.sk wrote: > This summary is tagged as being in ISO-8859-1 encoding: > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > However, it really is in UTF-8 Hmm... I guess Gmail's automatic encoding selection isn't working for the summaries. I've changed my Gmail settings to always use UTF-8. I should be sending out another summary next week, so we can see if that worked. Thanks for the catch! Steve From deets at nospam.web.de Wed Jun 7 12:25:14 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 07 Jun 2006 18:25:14 +0200 Subject: creating and naming objects References: <1149696358.065614.76150@h76g2000cwa.googlegroups.com> Message-ID: <4eocvdF1fnh8mU1@uni-berlin.de> Brian wrote: > I have a question that some may consider silly, but it has me a bit > stuck and I would appreciate some help in understanding what is going > on. > > For example, lets say that I have a class that creates a student > object. > > Class Student: > def setName(self, name) > self.name = name > def setId(self, id) > self.id = id > > Then I instantiate that object in a method: > > def createStudent(): > foo = Student() > /add stuff > > Now, suppose that I want to create another Student. Do I need to name > that Student something other than foo? What happens to the original > object? If I do not supplant the original data of Student (maybe no id > for this student) does it retain the data of the previous Student > object that was not altered? I guess I am asking how do I > differentiate between objects when I do not know how many I need to > create and do not want to hard code names like Student1, Student2 etc. > > I hope that I am clear about what I am asking. You seem to confuse the terms class and instance. An object is the instance of a class. You can have as many Students as you like. You just have to keep a reference around for retrieval. E.g. students = [Student("student %i" % i) for i in xrange(100)] will create a list of 100 (boringly named) students. The foo = Student("foo") will create a Student-object and the name foo refers to it. You are free to rebind foo to another Student or something completely different. foo = Student("foo") foo = 10 When you do so, and no other references to the Student-objects are held, it will actually disappear - due to garbage collection. Diez From nothingcanfulfill at gmail.com Tue Jun 6 21:44:37 2006 From: nothingcanfulfill at gmail.com (Ws) Date: 6 Jun 2006 18:44:37 -0700 Subject: Function Verification In-Reply-To: <1149644136.039113.33410@j55g2000cwa.googlegroups.com> References: <1149641403.078295.231730@h76g2000cwa.googlegroups.com> <1149644136.039113.33410@j55g2000cwa.googlegroups.com> Message-ID: <1149644677.660434.193330@g10g2000cwb.googlegroups.com> Ah, damn. That would've been soo much simpler. =S Thanks for the advice man. -Wes Ben Cartwright wrote: > Ws wrote: > > I'm trying to write up a module that *safely* sets sys.stderr and > > sys.stdout, and am currently having troubles with the function > > verification. I need to assure that the function can indeed be called > > as the Python manual specifies that sys.stdout and sys.stderr should be > > defined (standard file-like objects, only requiring a function named > > "write"). > > > My problem is in verifying the class we're trying to redirect output > > to. > > This is what I have so far: > > def _VerifyOutputStream(fh): > > if 'write' not in dir(fh): > > raise AttributeError, "The Output Stream should have a write > > method." > > if not callable(fh.write): > > raise TypeError, "The Output Stream's write method is not > > callable." > > > In the above _VerifyOutputStream function, how would I verify that the > > fh.write method requires only one argument, as the built-in file > > objects do? > > Why not just call the function with an empty string? > > def _VerifyOutputStream(fh): > fh.write('') > > Note that you don't need to manually check for AttributeError or > TypeError. Python will do that for you. It's generally better to act > first and ask forgiveness later. > > --Ben From david.nospam.hopwood at blueyonder.co.uk Sat Jun 24 18:39:23 2006 From: david.nospam.hopwood at blueyonder.co.uk (David Hopwood) Date: Sat, 24 Jun 2006 22:39:23 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150904134.520639.71070@b68g2000cwa.googlegroups.com> <1151056505.908723.162580@u72g2000cwu.googlegroups.com> Message-ID: Anton van Straaten wrote: > David Hopwood wrote: > >> I can accept that dynamic tagging provides some support for latent typing >> performed "in the programmer's head". But that still does not mean that >> dynamic tagging is the same thing as latent typing > > No, I'm not saying it is, although I am saying that the former supports > the latter. But since the relevant feature that the languages in question possess is dynamic tagging, it is more precise and accurate to use that term to describe them. Also, dynamic tagging is only a minor help in this respect, as evidenced by the fact that explicit tag tests are quite rarely used by most programs, if I'm not mistaken. IMHO, the support does not go far enough for it to be considered a defining characteristic of these languages. When tag tests are used implicitly by other language features such as pattern matching and dynamic dispatch, they are used for purposes that are equally applicable to statically typed and non-(statically-typed) languages. >> or that languages >> that use dynamic tagging are "latently typed". This simply is not a >> property of the language (as you've already conceded). > > Right. I see at least two issues here: one is that as a matter of > shorthand, compressing "language which supports latent typing" to > "latently-typed language" ought to be fine, as long as the term's > meaning is understood. If, for the sake of argument, "language which supports latent typing" is to be compressed to "latently-typed language", then statically typed languages must be considered also latently typed. After all, statically typed languages support expression and verification of the "types in the programmer's head" at least as well as non-(statically-typed) languages do. In particular, most recent statically typed OO languages use dynamic tagging and are memory safe. And they support comments ;-) This is not, quite obviously, what most people mean when they say that a particular *language* is "latently typed". They almost always mean that the language is dynamically tagged, *not* statically typed, and memory safe. That is how this term is used in R5RS, for example. > But beyond that, there's an issue here about the definition of "the > language". When programming in a latently-typed language, a lot of > action goes on outside the language - reasoning about static properties > of programs that are not captured by the semantics of the language. This is true of programming in any language. > This means that there's a sense in which the language that the > programmer programs in is not the same language that has a formal > semantic definition. As I mentioned in another post, programmers are > essentially mentally programming in a richer language - a language which > has informal (static) types - but the code they write down elides this > type information, or else puts it in comments. If you consider stuff that might be in the programmer's head as part of the program, where do you stop? When I maintain a program written by someone I've never met, I have no idea what was in that programmer's head. All I have is comments, which may be (and frequently are, unfortunately) inaccurate. (Actually, it's worse than that -- if I come back to a program 5 years later, I probably have little idea what was in my head at the time I wrote it.) > We have to accept, then, that the formal semantic definitions of > dynamically-checked languages are incomplete in some important ways. > Referring to those semantic definitions as "the language", as though > that's all there is to the language in a broader sense, is misleading. Bah, humbug. The language is just the language. > In this context, the term "latently-typed language" refers to the > language that a programmer experiences, not to the subset of that > language which is all that we're typically able to formally define. I'm with Marshall -- this is way too mystical for me. -- David Hopwood From akameswaran at gmail.com Fri Jun 9 17:38:28 2006 From: akameswaran at gmail.com (akameswaran at gmail.com) Date: 9 Jun 2006 14:38:28 -0700 Subject: More pythonic shell sort? In-Reply-To: References: <1149886830.566152.304500@h76g2000cwa.googlegroups.com> Message-ID: <1149889108.496363.41610@c74g2000cwc.googlegroups.com> Fredrik Lundh wrote: > akameswaran at gmail.com wrote: > > > An aside - can anyone tell me where the use += and -= is documented? > > http://docs.python.org/ref/augassign.html > http://pyref.infogami.com/assignments > > Thanks!!! From jes at nl.demon.net Mon Jun 5 13:52:02 2006 From: jes at nl.demon.net (Jim Segrave) Date: Mon, 05 Jun 2006 17:52:02 -0000 Subject: Large Dictionaries References: <1147699064.107490@teuthos> <447af556$1@nntp0.pdx.net> Message-ID: <1288rq2mkj9r40b@corp.supernews.com> In article , Tim Peters wrote: >[Scott David Daniels] >>> For example, time timsort (Python's internal sort) on pre-sorted >>> data; you'll find it is handled faster than random data. > >O(N) vs O(N log N), in fact. > >[Lawrence D'Oliveiro] >> But isn't that how a reasonable sorting algorithm should behave? Less >> work to do if the data is already sorted? > >For example, the O(N log N) heapsort is unreasonable compared to the >O(N**2) bubblesort by that reasoning (pre-sorted is actually a bad >case for heapsort, but a good case for bubblesort)? O(N log N) >sorting algorithms helped by pre-existing order are uncommon, unless >they do extra work to detect and exploit pre-existing order. Actually, presorted lists are not a bad case for heapsort - it's quite immune to any existing order or lack thereof, whereas some other sorts, quicksort being a prime example, require great care to avoid pathological cases. -- Jim Segrave (jes at jes-2.demon.nl) From fairwinds at eastlink.ca Fri Jun 2 17:15:28 2006 From: fairwinds at eastlink.ca (David Pratt) Date: Fri, 02 Jun 2006 18:15:28 -0300 Subject: Initializing an attribute that needs the object Message-ID: <4480AA70.2020804@eastlink.ca> Hi. I want to have different handlers to do perform logic. The problem is the Handler requires an instance of the factory since it will use its own methods in conjunction with methods of the factory. Once I have got a Factory instance I can give it a new handler (see below). It would be more flexible if I could provide a handle in constructor - but how to do this when it requires the object itself. Would I use a super for this sort of thing? Many thanks Regards, David class Factory: def __init__(self): self.some_handler = Handler(self) f = Factory() f.some_handler = AnotherHandler(f) From alanmk at hotmail.com Thu Jun 8 06:54:52 2006 From: alanmk at hotmail.com (Alan Kennedy) Date: 8 Jun 2006 03:54:52 -0700 Subject: language-x-isms References: <1149753206.451066.120960@h76g2000cwa.googlegroups.com> <1149759486.695563.110640@g10g2000cwb.googlegroups.com> <1149760633.796809.166430@h76g2000cwa.googlegroups.com> <1149762625.346302.135220@y43g2000cwc.googlegroups.com> Message-ID: <1149764092.806419.322130@i39g2000cwa.googlegroups.com> [Alan Kennedy] >> Your comment makes "using a user-defined enumerate [on cpython] is >> slower than using the built-in version" makes no sense in relation to >> the code I posted Fredrik Lundh wrote: > try combining with the second sentence in my post. OK, so putting "at least in CPython, using a user-defined enumerate function is a bit slower than using the built-in version" together with """ in fact, if performance is important, the following can sometimes be the most efficient way to loop over things ix = 0 for fibo in my_list: do something with ix and my_list[ix] ix += 1 """ We still don't get anything that sheds light on how the code I posted is deficient. Why can't you just say "I made a mistake, I thought your code replaced the builtin enumerate, but it doesnt"? I'm sorry I posted it now, what a rigmarole. -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From scott.daniels at acm.org Fri Jun 23 20:43:59 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Fri, 23 Jun 2006 17:43:59 -0700 Subject: Clearing pythonwin environment In-Reply-To: <1151100961.103470.141790@i40g2000cwc.googlegroups.com> References: <1151012168.838694.235610@c74g2000cwc.googlegroups.com> <449c4071$1@nntp0.pdx.net> <1151100961.103470.141790@i40g2000cwc.googlegroups.com> Message-ID: <449c85c8@nntp0.pdx.net> Network Ninja wrote: > Scott David Daniels wrote: >> keep = set(['__builtins__', '__doc__', '__name__', >> 'pywin', 'keep', 'item', 'globs']) # Faster to test >> globs = globals() >> for item in dir(): >> if item not in keep: >> del globs[item] >> del globs, item > > This did not work, it gave an error saying "NameError: name 'globs' is > not defined". I suspect that was because you did not include the last entry in the "keep" set above. By the way, another way to clean up: def cleanup(keep=set(['__builtins__', '__doc__', '__name__', 'pywin', 'cleanup']): globs = globals() for item in set(globs) - keep: del globs[item] Then, simply call: cleanup() > So can you explain the [] after globals()? How does that work? globals() returns a dict (or dict-like object) that reflects and access the current global environment. Imagine: globs = dict(a=1, b='2', c='iii') print globs del globs['b'] print globs --Scott David Daniels scott.daniels at acm.org From alanalan at newsgroup.nospam Thu Jun 8 18:58:24 2006 From: alanalan at newsgroup.nospam (A.M) Date: Thu, 8 Jun 2006 18:58:24 -0400 Subject: Win XP: Problem with shell scripting in Python Message-ID: Hi, I am having difficulty with shell scripting in Python. I use the following command to run a DOS command and put the return value in a Python variable: print os.popen('DIR').read() It works very fine with DIR command, but for commands like "MD :" it doesn't return the error message into the string: print os.popen('MD :').read() # No error message When I use Ruby, it works perfect: `md :` The filename, directory name, or volume label syntax is incorrect. I am also having problem with redirecting the python script output to a file: That means I can redirect the output to a file by using pipes like this: Python.exe script.py >file.txt But the sequence of contents in file.txt doesn't match with command execution sequence! When I don't use pipes, the output sequence is fine when I see the output on the monitor screen. Am I missing anything? Considering the fact that Ruby doesn't have any problem with redirecting STDOUT into files or string variables, is Python the right tool for this kinds of shell scripting? Any help would be appreciated, Alan From sjmachin at lexicon.net Sun Jun 4 19:36:14 2006 From: sjmachin at lexicon.net (John Machin) Date: Mon, 05 Jun 2006 09:36:14 +1000 Subject: deleting texts between patterns In-Reply-To: References: <1147420279.664699.181200@i40g2000cwc.googlegroups.com> <1147421468.912908.271280@i39g2000cwa.googlegroups.com> <44645C03.3070500@lexicon.net> Message-ID: <44836E6E.3070709@lexicon.net> On 5/06/2006 2:51 AM, Baoqiu Cui wrote: > John Machin writes: > >> Uh-oh. >> >> Try this: >> >>>>> pat = re.compile('(?<=abc\n).*?(?=xyz\n)', re.DOTALL) >>>>> re.sub(pat, '', linestr) >> 'blahfubarabc\nxyz\nxyzzy' > > This regexp still has a problem. It may remove the lines between two > lines like 'aaabc' and 'xxxyz' (and also removes the first two 'x's in > 'xxxyz'). > > The following regexp works better: > > pattern = re.compile('(?<=^abc\n).*?(?=^xyz\n)', re.DOTALL | re.MULTILINE) > You are quite correct. Your reply, and the rejoinder below, only add to the proposition that regexes are not necessarily the best choice for every text-processing job :-) Just in case the last line is 'xyz' but is not terminated by '\n': pattern = re.compile('(?<=^abc\n).*?(?=^xyz$)', re.DOTALL | re.MULTILINE) Cheers, John From eval.apply at gmail.com Fri Jun 9 10:34:47 2006 From: eval.apply at gmail.com (Joe Marshall) Date: 9 Jun 2006 07:34:47 -0700 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> Message-ID: <1149863687.298352.45980@h76g2000cwa.googlegroups.com> Xah Lee wrote: > in March, i posted a essay "What is Expressiveness in a Computer > Language", archived at: > http://xahlee.org/perl-python/what_is_expresiveness.html > > I was informed then that there is a academic paper written on this > subject. > > On the Expressive Power of Programming Languages, by Matthias > Felleisen, 1990. > http://www.ccs.neu.edu/home/cobbe/pl-seminar-jr/notes/2003-sep-26/expressive-slides.pdf > > Has anyone read this paper? And, would anyone be interested in giving a > summary? The gist of the paper is this: Some computer languages seem to be `more expressive' than others. But anything that can be computed in one Turing complete language can be computed in any other Turing complete language. Clearly the notion of expressiveness isn't concerned with ultimately computing the answer. Felleisen's paper puts forth a formal definition of expressiveness in terms of semantic equivilances of small, local constructs. In his definition, wholescale program transformation is disallowed so you cannot appeal to Turing completeness to claim program equivalence. Expressiveness isn't necessarily a good thing. For instance, in C, you can express the addresses of variables by using pointers. You cannot express the same thing in Java, and most people consider this to be a good idea. From jantod at gmail.com Thu Jun 22 08:44:40 2006 From: jantod at gmail.com (jantod at gmail.com) Date: 22 Jun 2006 05:44:40 -0700 Subject: returning index of minimum in a list of lists References: <1150901648.832039.165590@b68g2000cwa.googlegroups.com> Message-ID: <1150980280.431461.172060@m73g2000cwd.googlegroups.com> JJLaRocque at gmail.com wrote: > Hi all, > Is there a simple python function to return the list index of the > minimum entry in a list of lists? > ie, for [[3,3,3,3], [3,3,3,1], [3,3,3,3]] to return 2,4. > Or, same question but just for a list of numbers, not a list of lists. > Thanks, > Josh Untested: items = [] for x, a in enumerate(L): for y, b in enumerate(a): items.append((b, (x,y))) x, y = min(items)[1] You could also change this to a generator: def f(L): for x, a in enumerate(L): for y, b in ebumerate(a): yield b, (x,y) x, y = min(f(L))[1] From mark.dufour at gmail.com Thu Jun 29 12:27:08 2006 From: mark.dufour at gmail.com (Mark Dufour) Date: Thu, 29 Jun 2006 18:27:08 +0200 Subject: slow non-blocking reads Message-ID: <8180ef690606290927u7be4663dpe99ab59844245e6d@mail.gmail.com> hello all, I am trying to fire up a child process using os.popen2, and have the parent and child communicate in a non-blocking fashion. it works, but somehow it's unbearably slow. the following simulates a blocking readline: import os, fcntl fi, fo = os.popen2('./child') fcntl.fcntl(fo.fileno(), fcntl.F_SETFL, os.O_NONBLOCK) def getline(): line = '' while 1: try: line += os.read(fo.fileno(), 1) if line.endswith('\n'): return line except OSError: pass print getline() while 1: fi.write('echo echo echo\n') fi.flush() print getline() and this is the child process, written in C: tcgetattr(0, &tty); tty.c_lflag &= ~ICANON; tty.c_cc[VTIME] = 0; tty.c_cc[VMIN] = 0; tcsetattr(0, TCSADRAIN, &tty); fds[0].fd = 0; fds[0].events = POLLIN; fcntl(0, F_SETFL, O_NONBLOCK); printf("start\n"); fflush(stdout); while(1) { if( poll(fds, 1, 0) > 0) { if((fds[0].fd == 0) && (fds[0].revents & POLLIN)) { read(0, &c, 1); printf("%c", c); fflush(stdout); } } } the child sends a 'start' message and then echoes the parent. any thoughts about why this runs extremely slowly? thanks! mark dufour. -- if vars: self.output('; '.join([self.type(var)+' '+name for (name,var) in vars.items()])+';') From josiah.carlson at gmail.com Fri Jun 16 12:02:58 2006 From: josiah.carlson at gmail.com (josiah.carlson at gmail.com) Date: 16 Jun 2006 09:02:58 -0700 Subject: a good programming text editor (not IDE) In-Reply-To: References: <_xgkg.2317$No6.48542@news.tufts.edu> <1150430810.039713.262660@f6g2000cwb.googlegroups.com> Message-ID: <1150473778.141830.232740@g10g2000cwb.googlegroups.com> Walter D?rwald wrote: > I tried it out and the first problem I noticed is that on Windows > opening a file from a Samba drive doesn't seem to work, as PyPE converts > the filename to lowercase. ...Samba is tricky, and I hadn't thought of it before. Normal Windows is case-insensitive but case-preserving, and PyPE uses Python's os.path.normcase(os.path.normpath(os.path.realpath(...))) to do path/file normalization mapping for open files (keeping the non-case-normalized filename), so that you can't really make the mistake of opening the same file twice. This normally works on platforms with consistant case handling, but if you are using Samba running on any non-OSX *nix (whose filename case handling is not like other *nixes) from Windows, there gets to be a bit of a problem as your *nix case handling is different from Windows. I have an idea of what needs to be done, and the fix for it will be in PyPE 2.4.1, which I plan on releasing by June 30th. - Josiah From pc at p-cos.net Tue Jun 27 17:04:39 2006 From: pc at p-cos.net (Pascal Costanza) Date: Tue, 27 Jun 2006 23:04:39 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: <1151432002.905190.152470@y41g2000cwy.googlegroups.com> References: <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <1151384511.223582.305760@m73g2000cwd.googlegroups.com> <1151425350.679754.278820@i40g2000cwc.googlegroups.com> <1151432002.905190.152470@y41g2000cwy.googlegroups.com> Message-ID: <4gdkr6F1ldalhU4@individual.net> Marshall wrote: > Joe Marshall wrote: >> Marshall wrote: >> It isn't clear to me which programs we would have to give up, either. >> I don't have much experience in sophisticated typed languages. It is >> rather easy to find programs that baffle an unsophisticated typed >> language (C, C++, Java, etc.). > > C and Java, certainly, but I'm wary these days about making > any statement about limitations on C++'s type system, for it is > subtle and quick to anger. > >> Looking back in comp.lang.lisp, I see these examples: >> >> (defun noisy-apply (f arglist) >> (format t "I am now about to apply ~s to ~s" f arglist) >> (apply f arglist)) >> >> (defun blackhole (argument) >> (declare (ignore argument)) >> #'blackhole) >> > The noisy-apply function I think I understand; it's generic on the > entire arglist. In fact, if I read it correctly, it's even generic > on the *arity* of the function, which is actually pretty impressive. > True? This is an issue I've been wrestling with in my own type > system investigations: how to address genericity across arity. > > Does noisy-apply get invoked the same way as other functions? > That would be cool. > > As to the black hole function, could you explain it a bit? I apologize > for my lisp-ignorance. I am sure there is a world of significance > in the # ' on the third line, but I have no idea what it is. You can ignore the #'. In Scheme this as follows: (define blackhole (argument) blackhole) It just means that the function blackhole returns the function blackhole. Pascal -- 3rd European Lisp Workshop July 3 - Nantes, France - co-located with ECOOP 2006 http://lisp-ecoop06.bknr.net/ From vinay_sajip at yahoo.co.uk Tue Jun 27 02:59:22 2006 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 26 Jun 2006 23:59:22 -0700 Subject: logging error with RotatingFileHandler References: <_asng.501715$x64.12701762@phobos.telenet-ops.be> Message-ID: <1151391562.198586.249130@m73g2000cwd.googlegroups.com> flupke wrote: > File "C:\Python24\lib\logging\handlers.py", line 134, in doRollover > self.handleError(record) > NameError: global name 'record' is not defined There's a bug in doRollover's exception handling, which is masking the true error - which is most probably an exception being thrown in os.rename. I'll look at fixing this bug asap. Most likely, it'll be done by let the exception propagate up from doRollover to its caller. Regards, Vinay Sajip From benmorrow at tiscali.co.uk Wed Jun 21 00:08:37 2006 From: benmorrow at tiscali.co.uk (Ben Morrow) Date: Wed, 21 Jun 2006 05:08:37 +0100 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <4fo19aF1jsudeU1@individual.net> Message-ID: <5btmm3-ghu.ln1@osiris.mauzo.dyndns.org> Quoth David Hopwood : > Pascal Costanza wrote: > > Chris Smith wrote: > > > > Types can be represented at runtime via type tags. You could insist on > > using the term "dynamically tagged languages", but this wouldn't change > > a lot. Exactly _because_ it doesn't make sense in a statically typed > > setting, the term "dynamically typed language" is good enough to > > communicate what we are talking about - i.e. not (static) typing. > > Oh, but it *does* make sense to talk about dynamic tagging in a statically > typed language. Though I'm *seriously* reluctant to encourage this thread... A prime example of this is Perl, which has both static and dynamic typing. Variables are statically typed scalar/array/hash, and then scalars are dynamically typed string/int/unsigned/float/ref. > That's part of what makes the term "dynamically typed" harmful: it implies > a dichotomy between "dynamically typed" and "statically typed" languages, > when in fact dynamic tagging and static typing are (mostly) independent > features. Nevertheless, I see no problem in calling both of these 'typing'. They are both means to the same end: causing a bunch of bits to be interpreted in a meaningful fashion. The only difference is whether the distinction is made a compile- or run-time. The above para had no ambiguities... Ben -- Every twenty-four hours about 34k children die from the effects of poverty. Meanwhile, the latest estimate is that 2800 people died on 9/11, so it's like that image, that ghastly, grey-billowing, double-barrelled fall, repeated twelve times every day. Full of children. [Iain Banks] benmorrow at tiscali.co.uk From invalidemail at aerojockey.com Fri Jun 30 14:08:38 2006 From: invalidemail at aerojockey.com (Carl Banks) Date: 30 Jun 2006 11:08:38 -0700 Subject: Numeric help! In-Reply-To: <1151660774.576559.298730@h44g2000cwa.googlegroups.com> References: <1151510615.139278.167520@j72g2000cwa.googlegroups.com> <1151540468.434688.242530@75g2000cwc.googlegroups.com> <1151573125.651727.322660@i40g2000cwc.googlegroups.com> <1151591837.540485.80860@j72g2000cwa.googlegroups.com> <1151660774.576559.298730@h44g2000cwa.googlegroups.com> Message-ID: <1151690918.618969.223020@d56g2000cwd.googlegroups.com> Sheldon wrote: > average(compress(ravel(equal(wk,z)),ravel(sattmp)),axis=None) > This is much more compact and elegant. Thanks for pointing this out. > I don't know why average() returned a divide by zero error and to avoid > this I inserted this if statement. Now it works much better ! Probably you had a case where the array length was zero, but it wouldn't happen in the present case unless your input arrays are zero by zero. Carl Banks From bdesth.quelquechose at free.quelquepart.fr Wed Jun 28 22:02:56 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 29 Jun 2006 04:02:56 +0200 Subject: for and while loops In-Reply-To: <1151531527.496772.65130@i40g2000cwc.googlegroups.com> References: <1151531527.496772.65130@i40g2000cwc.googlegroups.com> Message-ID: <44a3047e$0$6207$626a54ce@news.free.fr> kydavis77 at gmail.com a ?crit : > i was wondering if anyone could point me to some good reading about the > for and while loops There's not much to say. while : will execute as long as is True. for in : will execute for each in . ie : for letter in ["a", "b", "c"]: do_something_with(letter) is equivalent to letter = "a" do_something_with(letter) letter = "b" do_something_with(letter) letter = "c" do_something_with(letter) > i am trying to write some programs > "Exercise 1 > > Write a program that continually reads in numbers from the user and > adds them together until the sum reaches 100. Since it's nearly impossible to predict how much iteration will be necessary for this condition to be satisfied[1], you want a while loop. The condition is 'the_sum >= 100' (starting with 'the_sum == 0'). The body of the loop is mainly : read a number in, add it to the_sum. [1] FWIW, we have 0 < number of iterations < +infinity, since nothing specifies that the user can not enter negative numbers !-) > Write another program > that reads 100 numbers from the user and prints out the sum. " Here you have a definite number of iterations, so it's a clear use case for a for loop, which will take care of the loop count by itself. Now since the for loop iterates over a sequence, you need such a sequence of 100 items. The canonical solution is the range(count) function, which will produce a sequence of integers. The body of the loop is exactly the same as in the previous case. > but im not quite grasping those functions.. which 'functions' ? 'for .. in ..' and 'while ..' are statements (instructions), not functions. A functions is eval'd, and returns a value. A statement is executed, and has no value. HTH From grflanagan at yahoo.co.uk Thu Jun 22 10:33:37 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 22 Jun 2006 07:33:37 -0700 Subject: How to generate all permutations of a string? In-Reply-To: References: Message-ID: <1150986817.276999.81910@u72g2000cwu.googlegroups.com> Girish Sahani wrote: > Hi guys, > I want to generate all permutations of a string. I've managed to > generate all cyclic permutations. Please help :) > http://gflanagan.net/site/python/05/Johnson.html Gerard From gherron at islandtraining.com Sat Jun 17 04:18:23 2006 From: gherron at islandtraining.com (Gary Herron) Date: Sat, 17 Jun 2006 01:18:23 -0700 Subject: Legitimate use of the "is" comparison operator? In-Reply-To: <20060617075308.29014.1287982850.divmod.quotient.2368@ohm> References: <20060617075308.29014.1287982850.divmod.quotient.2368@ohm> Message-ID: <4493BACF.4000807@islandtraining.com> Jean-Paul Calderone wrote: > On 17 Jun 2006 00:49:51 -0700, Mike Duffy wrote: > >> I just recently realized that the comparison operator "is" actually >> works for comparing numeric values. Now, I know that its intended use >> is for testing object identity, but I have used it for a few other >> things, such as type checking, and I was just wondering whether or not >> it is considered bad practice in the Python Community to use it for >> numerics as well. >> >> Example: >> >> a = range(5) >> b = range(5) >> >> if len(a) is len(b): >> print "They're the same size!" >> else: >> print "They're not the same size!" >> >> > > No, this is wrong. > An even simpler demo of why this DEAD WRONG: Consider: >>> 100 is (99+1) False This is asking if two different ways of computing the value (of 100) are stored internally as one object with that value or two separate objects each with that value. But, lest you think you understand that, consider also: >>> 2 is (1+1) True >>> 100 is 100 True This is highly implementation dependent. The current (C) implementation of Python has a cache for small integers, so the attempt to compare values with "is" works for some small integers, and fails for some large integers, but curiously, not all instances of comparing large integers. Gary Herron > >>>> a = range(100) >>>> b = range(100) >>>> len(a) is len(b) >>>> > False > > Use "is" to determine if two variables refer to exactly the same > object, never to determine if two objects are equal. > > Jean-Paul > From zlatko.matic1 at sb.t-com.hr Mon Jun 12 13:03:19 2006 From: zlatko.matic1 at sb.t-com.hr (tatamata) Date: Mon, 12 Jun 2006 19:03:19 +0200 Subject: Boa constructor- is it still alive? Message-ID: Does anyone know is Boa constructor project still alive? I visited Boa web site and it seems that it hasn't been updated for a long time.... From esj at harvee.org Tue Jun 13 19:12:05 2006 From: esj at harvee.org (Eric S. Johansson) Date: Tue, 13 Jun 2006 19:12:05 -0400 Subject: [*SPAM*] Python open proxy honeypot In-Reply-To: References: Message-ID: <448F4645.5090700@harvee.org> Alex Reinhart wrote: > Yeah, I just realized that. What would I do to act as an open proxy as well? emulate the Apache proxy capability, especially the reverse proxy. more seriously, what you need to do is from common proxy and web server ports, accept proxy requests with a destination port number of 25 and pretend to relay them. at least, that was the behavior I saw on a misconfigured Apache web server proxy. for what it's worth, I advocate abandoning Apache as it is too complex to configure correctly quickly. This is especially true of the built-in proxy. For what it's worth, folks should consider using alternatives like pound (very good secure proxy) and Cherokee (my favorite). But seriously, any web server except IIS is better than Apache. Find one that works for your application and use it. ---eric From michele.simionato at gmail.com Mon Jun 19 09:03:33 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 19 Jun 2006 06:03:33 -0700 Subject: code is data In-Reply-To: <1150560461.967123.112300@f6g2000cwb.googlegroups.com> References: <1150560461.967123.112300@f6g2000cwb.googlegroups.com> Message-ID: <1150722213.202352.224970@u72g2000cwu.googlegroups.com> John Roth wrote: > I saw the "make" statement as a breath of fresh air. > Then it got shot down for what were, to me, totally > trivial reasons. Which reasons? I as I recall, Guido cut it out without giving any reason. Of course Guido has the right to do so, but it is not respectful of all the work people like Steven Bethard and others did :-( Michele Simionato From artur_spruce at yahoo.com Thu Jun 29 08:58:40 2006 From: artur_spruce at yahoo.com (AdSR) Date: 29 Jun 2006 05:58:40 -0700 Subject: Amara: Where's my attribute? References: <1151570478.731909.154790@b68g2000cwa.googlegroups.com> Message-ID: <1151585919.998989.58520@b68g2000cwa.googlegroups.com> Fredrik Lundh wrote: > [cut] > the documents are 100% identical in XML infoset terms, so what's the problem here ? Looks like the problem is somewere else, after all: Some software relies on these "unused" xmlns attributes, most notably XML Schema tools. Which is unfortunate, because xmlns attributes indeed have the full right to receive special treatment. > > I see that people have reported similar problems with other XML toolkits, so I guess this is a > > general namespace ugliness. > > lack of namespace understanding, more likely. May I suggest a saying: Never attribute to lack of knowledge what you can attribute to confusing signals :) Yours truly, AdSR From fredrik at pythonware.com Thu Jun 1 12:25:32 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 1 Jun 2006 18:25:32 +0200 Subject: An oddity in list comparison and element assignment References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com><1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> Message-ID: michael.f.ellis at gmail.com wrote: > As to containers, would you say that envelope containing five $100 > bills is the same as an envelope containing a single $100 bill and 4 > xerox copies of it? If so, I'd like to engage in some envelope > exchanges with you :-) if you spent as much time *learning* stuff as you spend making up irrelevant examples, you might end up learning how assignments, repeat operators, and references work in Python. it's only hard to understand if you don't want to understand it. From timx at nospam.dev.null Mon Jun 5 04:16:24 2006 From: timx at nospam.dev.null (Tim X) Date: Mon, 05 Jun 2006 18:16:24 +1000 Subject: Apologies for cross post [was Re: HOST - dreamhost.com / Liberality (Hosting, Basic Requirement)] References: <4482CDDA.9060905@lazaridis.com> Message-ID: <874pz0kofb.fsf_-_@tiger.rapttech.com.au> My apologies for not trimming the long list of crossposted groups. I hit 'y' when thinking 'n'! Tim -- tcross (at) rapttech dot com dot au From paul at boddie.org.uk Mon Jun 12 18:55:13 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 12 Jun 2006 15:55:13 -0700 Subject: Writing PNG with pure Python References: <1149853401.521169.112530@i39g2000cwa.googlegroups.com> <1149889778.182865.181600@f6g2000cwb.googlegroups.com> <1149910872.025017.60160@i40g2000cwc.googlegroups.com> Message-ID: <1150152913.315502.16840@u72g2000cwu.googlegroups.com> Johann C. Rocholl wrote: > The MIT license is enticingly short and simple, thank you for the tip. > > I have now decided to license my project (including the pure python PNG > library) under the Apache License 2.0 which is less restrictive than > the GPL in terms of sublicensing. But it is also incompatible with the GPL: http://www.fsf.org/licensing/licenses/index_html#GPLIncompatibleLicenses It's obviously your decision about how you license your own code, but I'd advise you to disregard the "Pythonic license" rhetoric, whatever that means: Python's original licence was regarded as not being enough of a licence by some lawyers (that's what some people refer to as the original Python licence); subsequent licences aren't recommended for application to any other works (like various licences of the Python code over the years); despite advocacy for permissive licences by some parties, there exist numerous successful GPL'd and LGPL'd Python projects (meaning that projects licensed in such a way are not lesser members of the community). Moreover, any licensing gymnastics undertaken by the PSF did involve various extra somersaults to remain GPL-compatible, meaning that even people who favour permissive licences regard "licence interoperability" positively. If you're convinced that a permissive licence suits your code best, please consider something whose side-effects you understand. If the additional patent grant or licence termination clauses (which the FSF don't regard as a bad thing, just something incompatible with the current GPL/LGPL) are specifically what you want, then the Apache Licence may be what you're after; otherwise, you should choose something less baroque and better understood, perhaps from this list: http://www.fsf.org/licensing/licenses/index_html#GPLCompatibleLicenses Yes, one of the best places to find out about non-FSF licences is actually the FSF themselves, undermining various myths some people like to put forward. Paul From anton at appsolutions.com Thu Jun 22 19:32:19 2006 From: anton at appsolutions.com (Anton van Straaten) Date: Thu, 22 Jun 2006 23:32:19 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> Message-ID: <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> Vesa Karvonen wrote: > In comp.lang.functional Anton van Straaten wrote: > [...] > > This static vs dynamic type thing reminds me of one article written by > Bjarne Stroustrup where he notes that "Object-Oriented" has become a > synonym for "good". More precisely, it seems to me that both camps > (static & dynamic) think that "typed" is a synonym for having > "well-defined semantics" or being "safe" and therefore feel the need > to be able to speak of their language as "typed" whether or not it > makes sense. I reject this comparison. There's much more to it than that. The point is that the reasoning which programmers perform when working with an program in a latently-typed language bears many close similiarities to the purpose and behavior of type systems. This isn't an attempt to jump on any bandwagons, it's an attempt to characterize what is actually happening in real programs and with real programmers. I'm relating that activity to type systems because that is what it most closely relates to. Usually, formal type theory ignores such things, because of course what's in the programmer's head is outside the domain of the formal definition of an untyped language. But all that means is that formal type theory can't account for the entirety of what's happening in the case of programs in untyped languages. Unless you can provide some alternate theory of the subject that's better than what I'm offering, it's not sufficient to complain "but that goes beyond (static/syntactic) type theory". Yes, it goes beyond traditional type theory, because it's addressing with something which traditional type theory doesn't address. There are reasons to connect it to type theory, and if you can't see those reasons, you need to be more explicit about why. > I agree. I think that instead of "statically typed" we should say > "typed" and instead of "(dynamically|latently) typed" we should say > "untyped". The problem with "untyped" is that there are obvious differences in typing behavior between the untyped lambda calculus and, say, a language like Scheme (and many others). Like all latently-typed languages, Scheme includes, in the language, mechanisms to tag values in a way that supports checks which help the programmer to ensure that the program's behavior matches the latent type scheme that the programmer has in mind. See my other recent reply to Marshall for a more detailed explanation of what I mean. I'm suggesting that if a language classifies and tags values in a way that supports the programmer in static reasoning about the behavior of terms, that calling it "untyped" does not capture the entire picture, even if it's technically accurate in a restricted sense (i.e. in the sense that terms don't have static types that are known within the language). Let me come at this from another direction: what do you call the classifications into number, string, vector etc. that a language like Scheme does? And when someone writes a program which includes the following lines, how would you characterize the contents of the comment: ; third : integer -> integer (define (third n) (quotient n 3)) In my experience, answering these questions without using the word "type" results in a lot of silliness. And if you do use "type", then you're going to have to adjust the rest of your position significantly. >>In a statically-checked language, people tend to confuse automated >>static checking with the existence of types, because they're thinking in >>a strictly formal sense: they're restricting their world view to what >>they see "within" the language. > > > That is not unreasonable. You see, you can't have types unless you > have a type system. Types without a type system are like answers > without questions - it just doesn't make any sense. The first point I was making is that *automated* checking has very little to do with anything, and conflating static types with automated checking tends to lead to a lot of confusion on both sides of the static/dynamic fence. But as to your point, latently typed languages have informal type systems. Show me a latently typed language or program, and I can tell you a lot about its type system or type scheme. Soft type inferencers demonstrate this by actually defining a type system and inferring type schemes for programs. That's a challenging thing for an automated tool to do, but programmers routinely perform the same sort of activity on an informal basis. >>But a program as seen by the programmer has types: the programmer >>performs (static) type inference when reasoning about the program, and >>debugs those inferences when debugging the program, finally ending up >>with a program which has a perfectly good type scheme. It's may be >>messy compared to say an HM type scheme, and it's usually not proved to >>be perfect, but that again is an orthogonal issue. > > > There is a huge hole in your argument above. Types really do not make > sense without a type system. To claim that a program has a type > scheme, you must first specify the type system. Otherwise it just > doesn't make any sense. Again, the type system is informal. What you're essentially saying is that only things that are formally defined make sense. But you can't wish dynamically-checked languages out of existence. So again, how would you characterize these issues in dynamically-checked languages? Saying that it's just a matter of well-defined semantics doesn't do anything to address the details of what's going on. I'm asking for a more specific account than that. >>Mathematicians operated for thousands of years without automated >>checking of proofs, so you can't argue that because a >>dynamically-checked program hasn't had its type scheme proved correct, >>that it somehow doesn't have types. That would be a bit like arguing >>that we didn't have Math until automated theorem provers came along. > > > No - not at all. First of all, mathematics has matured quite a bit > since the early days. I'm sure you've heard of the axiomatic method. > However, what you are missing is that to prove that your program has > types, you first need to specify a type system. Similarly, to prove > something in math you start by specifying [fill in the rest]. I agree, to make the comparison perfect, you'd need to define a type system. But that's been done in various cases. So is your complaint simply that most programmers are working with informal type systems? I've already stipulated that. However, I think that you want to suggest that those programmers are not working with type systems at all. This reminds me of a comedy skit which parodied the transparency of Superman's secret identity: Clark Kent is standing in front of Lois Lane and removes his glasses for some reason. Lois looks confused and says "where did Clark go?" Clark quickly puts his glasses back on, and Lois breathes a sigh of relief, "Oh, there you are, Clark". The problem we're dealing with in this case is that anything that's not formally defined is essentially claimed to not exist. It's lucky that this isn't really the case, otherwise much of the world around us would vanish in a puff of formalist skepticism. We're discussing systems that operate on an informal basis: in this case, the reasoning about the classification of values which flow through terms in a dynamically-checked language. If you can produce a useful formal model of those systems that doesn't omit significant information, that's great, and I'm all ears. However, claiming that e.g. using a universal type is a complete model what's happening misses the point: it doesn't account at all for the reasoning process I've just described. >>1. "Untyped" is really quite a misleading term, unless you're talking >>about something like the untyped lambda calculus. That, I will agree, >>can reasonably be called untyped. > > > Untyped is not misleading. "Typed" is not a synonym for "safe" or > "having well-defined semantics". Again, your two suggested replacements don't come close to capturing what I'm talking about. Without better alternatives, "type" is the closest appropriate term. I'm qualifying it with the term "latent", precisely to indicate that I'm not talking about formally-defined types. I'm open to alternative terminology or ways of characterizing this, but they need to address issues that exist outside the boundaries of formal type systems, so simply applying terms from formal type theory is not usually sufficient. >>So, will y'all just switch from using "dynamically typed" to "latently >>typed" > > > I won't (use "latently typed"). At least not without further > qualification. This and my other recent post give a fair amount of qualification, so let me know if you need anything else to be convinced. :) But to be fair, I'll start using "untyped" if you can come up with a satisfactory answer to the two questions I asked above, just before I used the word "silliness". Anton From johnjsal at NOSPAMgmail.com Thu Jun 8 16:48:39 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 08 Jun 2006 20:48:39 GMT Subject: Importing again and again In-Reply-To: <1149796920.757115.290840@h76g2000cwa.googlegroups.com> References: <1149796920.757115.290840@h76g2000cwa.googlegroups.com> Message-ID: abcd wrote: > def foo(): > import bar > bar.printStuff() > > foo() > foo() > foo() > foo() > > ...will that re-import bar 4 times...or just import it once? is this a > big performance hit? > > thanks > Given a file called bar.py with the following contents: print "I'm being imported!" def printStuff(): print 'stuff' I get this output when I import foo.py: >>> import foo I'm being imported! stuff stuff stuff stuff >>> From marshall.spight at gmail.com Tue Jun 27 13:53:41 2006 From: marshall.spight at gmail.com (Marshall) Date: 27 Jun 2006 10:53:41 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <1151384511.223582.305760@m73g2000cwd.googlegroups.com> <1151420883.426116.288300@b68g2000cwa.googlegroups.com> Message-ID: <1151430821.728345.31600@p79g2000cwp.googlegroups.com> David Hopwood wrote: > Marshall wrote: > > David Hopwood wrote: > >>Marshall wrote: > >> > >>>The real question is, are there some programs that we > >>>can't write *at all* in a statically typed language, because > >>>they'll *never* be typable? > >> > >>In a statically typed language that has a "dynamic" type, all > >>dynamically typed programs are straightforwardly expressible. > > > > So, how does this "dynamic" type work? > > > > > It can't simply be the "any" type, because that type has no/few > > functions defined on it. > > It isn't. From the abstract of the above paper: > > [...] even in statically typed languages, there is often the need to > deal with data whose type cannot be determined at compile time. To handle > such situations safely, we propose to add a type Dynamic whose values are > pairs of a value v and a type tag T where v has the type denoted by T. > Instances of Dynamic are built with an explicit tagging construct and > inspected with a type safe typecase construct. Well, all this says is that the type "dynamic" is a way to explicitly indicate the inclusion of rtti. But that doesn't address my objection; if a typesafe typecase construct is required, it's not like using a dynamic language. They don't require typecase to inspect values before one can, say, invoke a function. > "Gradual typing" as described in > is > another alternative. The difference between gradual typing and a > "dynamic" type is one of convenience rather than expressiveness -- > gradual typing does not require explicit tagging and typecase constructs. Perhaps this is the one I should read; it sounds closer to what I'm talking about. Marshall From DustanGroups at gmail.com Mon Jun 5 21:08:50 2006 From: DustanGroups at gmail.com (Dustan) Date: 5 Jun 2006 18:08:50 -0700 Subject: Again, Downloading and Displaying an Image from the Internet in Tkinter In-Reply-To: <1149555597.559051.162590@i39g2000cwa.googlegroups.com> References: <1149555597.559051.162590@i39g2000cwa.googlegroups.com> Message-ID: <1149556130.667899.199470@j55g2000cwa.googlegroups.com> I wrote: > Nobody answered last time. I guess they wanted me to give it a shot. > Well, here is how I download the image (it's a class method): > > def download_image(self): > web_download=self.opener.open(self.url) > save=open("image.jpg","w") > save.writelines(web_download.readlines()) > save.close() > web_download.close() > > self.opener is urllib.URLopener(), self.url is the url for the image. > > I display the image as follows: > > self.image=t.Label(self.frame,image=path+"\\image.jpg") > > t is Tkinter, path is sys.path[0]. > (if sys.path[0] is not the proper way of getting the program's path, > inform me; I hunted it down without any reference to look to) > > > But the image won't display, using any application (including Tkinter, > paint, Firefox, etc.). I'm assuming the reason it can't be read is > because the image is protected from downloading. > > So, once again, is there a better way to download and display an image > using Tkinter? > > Did I try hard enough for you? Are you going to help me this time? I should probably also mention, the only reason I downloaded the image to a file was because I don't know of any other way to do it. I feel no need to save the image to my hard drive. From fredrik at pythonware.com Tue Jun 6 15:25:33 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 06 Jun 2006 21:25:33 +0200 Subject: tkinter: making widgets instance or not? In-Reply-To: References: Message-ID: John Salerno wrote: > I'm wondering, why is frame created as a local variable, and the buttons > as instance variables? What is the difference? Can you make frame an > instance variable, or vice versa? Tkinter maintains its own widget hierarchy, and widgets don't go away unless you explicitly destroy them (by calling "destroy" on a widget or a widget parent), so you don't really need to keep references to them. however, if you need to access a widget later on, it might be a good idea to save a reference to it somewhere... From fredrik at pythonware.com Thu Jun 8 10:52:36 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 08 Jun 2006 16:52:36 +0200 Subject: cos: "Integer Required"?!?!?!? In-Reply-To: <1149777499.262577.318070@u72g2000cwu.googlegroups.com> References: <1149777499.262577.318070@u72g2000cwu.googlegroups.com> Message-ID: moonman wrote: > import math > > .... > > cos_phi = math.cos(math.radians(XPLMGetDataf(self.ACphi))) # Error > occurs here what error ? it's a lot easier to help if you include the traceback. > Now XPLMGetDataf should be returning float. should be ? have you verified this ? try adding print self.ACphi, type(self.ACphi) value = XPLMGetDataf(self.ACphi) print value, type(value) before the cos_phi line, and let us know what it prints. > Is there something that I'm completely missing about how Python does > tyonig or something? not necessarily, but you may need to work a little on your trouble- shooting skills (rule 1: when in doubt, use print. print is your friend). From rod at sudden.net Tue Jun 20 14:26:52 2006 From: rod at sudden.net (Sudden Disruption) Date: 20 Jun 2006 11:26:52 -0700 Subject: Iteration over recursion? In-Reply-To: <4498211b$0$8390$626a54ce@news.free.fr> References: <1150808045.539887.291180@i40g2000cwc.googlegroups.com> <1150816827.826028.114740@h76g2000cwa.googlegroups.com> <4498211b$0$8390$626a54ce@news.free.fr> Message-ID: <1150828012.837354.160110@u72g2000cwu.googlegroups.com> Bruno, > It doesn't. Technical possible, but BDFL's decision... Sure. But why bother? Anything that can be done with recursion can be done with iteration. Turng proved that in 1936. Recursion was just an attempt to "unify" design approach by abstracting itteration and creating a new context. It allowed the programmer to isolate himself from the reality that he was actually iterating. Talk about mind fuck. It seems things were just to simple the way they were. Like all fashion, this too shall pass. Sudden Disruption -- Sudden View... the radical option for editing text http://www.sudden.net/ http://suddendisruption.blogspot.com From deets at nospam.web.de Thu Jun 15 12:12:57 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 15 Jun 2006 18:12:57 +0200 Subject: Python is fun (useless social thread) ;-) In-Reply-To: References: Message-ID: <4fdf87F1j0644U1@uni-berlin.de> Sybren Stuvel schrieb: > John Salerno enlightened us with: >> Did you have to learn it for a job? > > Nope, but I do most of my job in Python nowadays. I heard rumours > about it being a nice language. After my first look at it, I was > hooked! > >> Also, how did you go about learning it? > > I first followed the tutorial, then simply started using it. And I > watch this newsgroup to see if there are new things to learn. > >> Was there any necessity in the specifics you learned, or did you >> just dabble in something (e.g. wxPython) for fun? > > Mostly dabbling, although I learned (and improved) TLSLite because I > needed it for my graduation project. > >> Are there still some things you feel you need to learn or improve? > > I'd love to be able to calll functions from Windows DLLs on x86 Linux. > Don't know if it'll be possible, though. Ideas anyone? WINE? If you can run a DLL on linux, you can ultimately run a windows python on linux I guess :) Diez From tinman31337 at gmail.com Tue Jun 27 12:09:54 2006 From: tinman31337 at gmail.com (Tin Gherdanarra) Date: Tue, 27 Jun 2006 18:09:54 +0200 Subject: languages with full unicode support In-Reply-To: <1151276031.641318@elch.in-berlin.de> References: <1151251736.590910.36050@u72g2000cwu.googlegroups.com> <1151276031.641318@elch.in-berlin.de> Message-ID: <4gd3iiF1md4lcU1@individual.net> Oliver Bandel wrote: > > ????? Xah-Lee san ;-) Uhm, I'd guess that Xah is Chinese. Be careful with such things in real life; Koreans might beat you up for this. Stay alive! > > > Xah Lee wrote: > >> Languages with Full Unicode Support >> >> As far as i know, Java and JavaScript are languages with full, complete >> unicode support. That is, they allow names to be defined using unicode. > > > Can you explain what you mena with the names here? > > >> (the JavaScript engine used by FireFox support this) >> >> As far as i know, here's few other lang's status: >> >> C ? No. > > > Well, is this (only) a language issue? > > On Plan-9 all things seem to be UTF-8 based, > and when you use C for programming, I would think > that C can handle this also. > > But I only have read some papers about Plan-9 and did not developed on > it.... > > Only a try to have a different view on it. > > If someone knows more, please let us know :) > > > Ciao, > Oliver -- Lisp kann nicht kratzen, denn Lisp ist fluessig From jcrocholl at googlemail.com Fri Jun 9 23:41:12 2006 From: jcrocholl at googlemail.com (Johann C. Rocholl) Date: 9 Jun 2006 20:41:12 -0700 Subject: Writing PNG with pure Python References: <1149853401.521169.112530@i39g2000cwa.googlegroups.com> <1149889778.182865.181600@f6g2000cwb.googlegroups.com> Message-ID: <1149910872.025017.60160@i40g2000cwc.googlegroups.com> The MIT license is enticingly short and simple, thank you for the tip. I have now decided to license my project (including the pure python PNG library) under the Apache License 2.0 which is less restrictive than the GPL in terms of sublicensing. The Apache License looks modern and well-maintained to me. My project runs on Apache, so there is some context there as well. Also, this change will simplify things if I ever want to contribute some of the code to the Python Software Foundation. Cheers, Johann From hale at tulane.edu Mon Jun 12 22:17:28 2006 From: hale at tulane.edu (hale at tulane.edu) Date: 12 Jun 2006 19:17:28 -0700 Subject: ANN: PyGUI 1.7.2-1 In-Reply-To: References: Message-ID: <1150165048.582537.53640@h76g2000cwa.googlegroups.com> greg wrote: > I have uploaded a new PyGUI 1.7.2 package to correct > a couple of errors in the setup.py file. > > http://www.cosc.canterbury.ac.nz/~greg/python_gui/ > > ----------------------------------------------------- > > What is PyGUI? > -------------- > > PyGUI is an experimental highly-Pythonic cross-platform > GUI API. Implementations are currently available for > MacOSX and Gtk. For a full description of the project > goals, see the PyGUI web page at the above address. > > -- > Greg I downloaded the new version of PyGUI, but I am having some problems with running it in the IDLE ide. I will use BlobEdit.py as an example. If I run the the makefile, then blobedit runs ok as an application. If I use the terminal, and execute pythonw with argument blobedit.py, then it runs ok. However, if I try to run blobedit.py in the IDLE ide, I get an error since it tries to open a file when no file was given. Looking at your code, I see that you noticed certain situation where this occurs and tried to handle it by comparing path == sys.argv[0] and skipping opening the file in this case. But, when running it within IDLE, the path is equal to "8833" for some reason. I tried to hunt down where the problem occurs, but I was led to the method "application_openFile_(self, ns_app, path)" in the class _PyGui_NSApplication. I couldn't find out how this method ever got called though. Is there some way to work around this problem? Thanks. -- Bill Hale From cdsmith at twu.net Fri Jun 23 20:01:28 2006 From: cdsmith at twu.net (Chris Smith) Date: Fri, 23 Jun 2006 18:01:28 -0600 Subject: Saying "latently-typed language" is making a category mistake References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <449c5b85$0$656$bed64819@news.gradwell.net> Message-ID: Chris Uppal wrote: > > I'd be more careful in the analogy, there. Since type theory (as > > applied to programming languages, anyway) is really just a set of > > methods of proving arbitrary statements about program behaviors, > > Not "arbitrary" -- there is only a specific class of statements that any given > type system can address. And, even if a given statement can be proved, then it > might not be something that most people would want to call a statement of type > (e.g. x > y). [My understanding is that we're discussing static types and type theory here. If you mean dynamic types, then what I'm about to say won't apply.] I acknowledge that there are things that type systems are not going to be capable of proving. These are not excluded a priori from the set of problems that would count as type errors if the language's type system caught them. They are merely excluded for pragmatic reasons from the set of errors that someone would be likely to write a type system to check. That is the case simply because there is a decided disadvantage in having a compiler that isn't guaranteed to ever finish compiling your program, or that doesn't finish in polynomial time on some representative quantity in nearly all cases, etc. On the other hand, statements about program behavior that can be proved in reasonable time frames are universally valid subjects for type systems. If they don't look like type errors now, they nevertheless will when the type system is completed to demonstrate them. If someone were to write a language in which is could be statically proved that a pair of expressions has the property that when each is evaluated to their respective values x and y, (x > y) will be true, then proving this would be a valid subject of type theory. We would then define that property as a type, whose values are all pairs that have the property (or, I suppose, a nominal type whose values are constrained to be pairs that have this property, though that would get painful very quickly), and then checking this property when that type is required -- such as when I am passing (x - y) as a parameter to a function that requires a positive integer -- would be called type checking. In fact, we've come full circle. The intial point on which I disagreed with Torben, while it was couched in a terminological dispute, was whether there existed a (strict) subset of programming errors that are defined to be type errors. Torben defined the relationship between static and dynamic types in terms of when they solved "type errors", implying that this set is the same between the two. A lot of the questions I'm asking elsewhere in this thread are chosen to help me understand whether such a set truly exists for the dynamic type world; but I believe I know enough that I can absolutely deny its existence within the realm of type theory. I believe that even Pierce's phrase "for proving the absence of certain program behaviors" in his definition of a type system only excludes possible proofs that are not interesting for determining correctness, if in fact it limits the possible scope of type systems at all. However, your definition of type errors may be relevant for understanding concepts of dynamic types. I had understood you to say earlier that you thought something could validly qualify as a dynamic type system without regard for the type of problem that it verifies (that was denoted by "something" in a previous conversation). I suppose I was misinterpreting you. So your definition was: > It seems to me that most (all ? by definition ??) kinds of reasoning where we > want to invoke the word "type" tend to have a form where we reduce values (and > other things we want to reason about) to equivalence classes[*] w.r.t the > judgements we wish to make, and (usually) enrich that structure with > more-or-less stereotypical rules about which classes are substitutable for > which other ones. So that once we know what "type" something is, we can > short-circuit a load of reasoning based on the language semantics, by > translating into type-land where we already have a much simpler calculus to > guide us to the same answer. > > (Or representative symbols, or... The point is just that we throw away the > details which don't affect the judgements.) I don't even know where I'd start in considering the forms of reasoning that are used in proving things. Hmm. I'll have to ponder this for a while. > I think that, just as for static theorem proving, there is informal reasoning > that fits the "type" label, and informal reasoning that doesn't. So while I disagree in the static case, it seems likely that this is true of what is meant by dynamic types, at least by most people in this discussion. I'd previously classified you as not agreeing. -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation From prinster at mail.com Fri Jun 9 01:13:59 2006 From: prinster at mail.com (Stephen Prinster) Date: Fri, 09 Jun 2006 05:13:59 GMT Subject: How to extract 2 integers from a string in python? In-Reply-To: <1149827496.857621.88550@h76g2000cwa.googlegroups.com> References: <1149827496.857621.88550@h76g2000cwa.googlegroups.com> Message-ID: yinglcs at gmail.com wrote: > Hi, > > how can I extract 2 integers from a string in python? > > for example, my source string is this: > Total size: 173233 (371587) > > I want to extract the integer 173233 and 371587 from that soource > string, how can I do that? > Use split() to split the string into four strings, using spaces as separators, then use int() to convert the resulting strings that interest you. >>> a, b, c, d = 'Total size: 173233 (371857)'.split() >>> first_int, second_int = int(c), int(d[1:-1]) >>> first_int 173233 >>> second_int 371857 HTH Steve P From quentel.pierre at wanadoo.fr Wed Jun 21 04:35:20 2006 From: quentel.pierre at wanadoo.fr (Pierre Quentel) Date: 21 Jun 2006 01:35:20 -0700 Subject: Search substring in a string and get index of all occurances In-Reply-To: References: Message-ID: <1150878920.578168.211200@g10g2000cwb.googlegroups.com> mystring = 'John has a really nice powerbook.' substr = ' ' # space pos = 0 indices = [] while True: i = mystring.find(substr,pos) if i==-1: break indices.append(i) pos = i+1 print indices > [4, 8, 10, 17, 22] Pierre From cm012b5105 at blueyonder.co.uk Tue Jun 13 15:56:31 2006 From: cm012b5105 at blueyonder.co.uk (carmel stanley) Date: Tue, 13 Jun 2006 20:56:31 +0100 Subject: interactive programme & pyTTS Message-ID: <001201c68f23$778e0020$984cfea9@aries> Hi i have been making an interactive programme,i have recently tried using "pyTTS" with it. This is a small ammount of it. import pyTTS tts = pyTTS.Create() tts.Rate = -3 tts.Speak('hi molly how old are you?.') s = raw_input ("how old are you?") if s=='3': print "thats great" else: print "tuttut" tts.speak('tututut') What i dont get is if i type in "4" it prints "tuttut" but it does not say it,am i overlooking something here. Thanks nige -------------- next part -------------- An HTML attachment was scrubbed... URL: From michele.simionato at gmail.com Fri Jun 23 07:28:38 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 23 Jun 2006 04:28:38 -0700 Subject: Using metaclassed to dynamically generate a class based on a parameter to the objects init function. In-Reply-To: <1151061557.682689.189440@c74g2000cwc.googlegroups.com> References: <1151018669.849641.265990@g10g2000cwb.googlegroups.com> <449bb4d6$0$32258$626a54ce@news.free.fr> <1151061557.682689.189440@c74g2000cwc.googlegroups.com> Message-ID: <1151062118.023172.253290@i40g2000cwc.googlegroups.com> sashang at gmail.com wrote: > However I do think the solution to my problem lies with > them since I have to dynamically generate a class and metaclasses > provide a mechanism for doing this. You rarely need a custom metaclass to generate classes. A class factory def makeclass(classname, *attributes): cls = type(classname, mybases, mydic) for name, value in attributes: setattr(cls, name, attr) return cls is the typical solution for your use case. OTOH, if you are looking for use classes for metaclasses, look at the Python Wiki and use Google. Michele Simionato From bdesth.quelquechose at free.quelquepart.fr Thu Jun 1 22:25:54 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 02 Jun 2006 04:25:54 +0200 Subject: if not CGI: In-Reply-To: References: Message-ID: <447f722b$0$30312$626a54ce@news.free.fr> Max a ?crit : (snip) > But now I'm ready to do it in the real world. Nothing complicated, but a > real project. And I have to choose my tools. Zope, Plone, Django, what > are these? Zope -> an application server Plone -> a CMS built upon Zope Django -> a MVC fullstack framework (fullstack : integration with a server + ORM + template system + various utilities). > I don't have to stick with Python, although it's my preferred > language. I know Python, Java and C++. But I'm ready to learn Ruby if > RoR is as good as they say. RoR is not bad, but really over-hyped. There's no shortage of at least as good solutions in Python. You may want to look at Django, Turbogears, Pylons, web.py etc. for fullstack MVC frameworks. There are more barebones solutions, like CherryPy (the application server Turbogears is built upon), Myghty (extended perl::Mason port, used by Pylons), mod_python (if you're an hard-core Apache fanatic), WebStack (if you want to deploy on almost any server), and some other pieces like formencode (form validation), SQLObject (ORM, used by Turbogears and Pylons), SQLAlchemy (another ORM, very promising, by the author of Myghty), Routes (port of RoR routes, used by Pylons) and a lot of templating systems. So you can even build your own fullstack framework from existing pieces (that's what Turbogears and Pylons are doing FWIW). And also whole lot of more specific solutions : Albatross, Quixote, Karrigel, Twisted/nevow, (...), and of course Zope 2.x and 3.x, but it may be overkill and long to learn. Also, FWIW, Trac is almost a usable (somewhat minimalist) framework on it's own. So the problem is not "are there good solutions", but "which one to choose" !-) The answer of course depends on what you want and what you like, but taking a few days to play with Turbogears, Django and Pylons might be a good idea. > I could do it in Python cgi (or mod_python). But it seems from all the > hype that this is not a good way to write scaleable, extensible web > applications. Trac is a perfect counter-example IMHO. From python at hope.cz Mon Jun 5 10:23:53 2006 From: python at hope.cz (Lad) Date: 5 Jun 2006 07:23:53 -0700 Subject: How to add few pictures into one In-Reply-To: References: <1149511692.796038.155930@c74g2000cwc.googlegroups.com> Message-ID: <1149517433.880564.128350@h76g2000cwa.googlegroups.com> K.S.Sreeram wrote: > Lad wrote: > > Hello , > > is it possible to add( with PYTHON language) several image files into > > one? > > Google for 'Python Imaging Library'... > > Regards > Sreeram > > > Thank you for your reply. I was thinking about this: to open each image file in binary mode , read it and write into the result image file? Is that possible? Regards, L From maric at aristote.info Thu Jun 1 07:29:14 2006 From: maric at aristote.info (Maric Michaud) Date: Thu, 1 Jun 2006 13:29:14 +0200 Subject: Function mistaken for a method In-Reply-To: References: Message-ID: <200606011329.15661.maric@aristote.info> Le Jeudi 01 Juin 2006 13:12, Eric Brunel a ?crit : > class C1(C): > f = int int is not a function but a type, but it's callable so int(0) return 0. > class C2(C): > f = lambda x: x != 0 lambda is a function, applied as a class attribute it becomes a method so it's called with a first parameter representing the instance, self.f(0) in the __init__ becomes C2.f(self, 0), so the lambda should be : f = lambda s, x: x != 0 # s for self, some poeple use _ this exactly the same as : def f(self, val) : return x != 0 (that lambda will return True or False i expect this is not what you want) -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From nicolasg at gmail.com Sat Jun 17 13:47:30 2006 From: nicolasg at gmail.com (nicolasg at gmail.com) Date: 17 Jun 2006 10:47:30 -0700 Subject: File read and writing in binary mode... References: <1150286103.249888.99610@i40g2000cwc.googlegroups.com> <4fac35F1id8juU1@uni-berlin.de> Message-ID: <1150566450.010414.96700@h76g2000cwa.googlegroups.com> > > Solution: only use binary files, and do the newline-translation yourself > if needed. > > Diez The probelm is if I can't use only binary files... How can I do the newline-translation myself ? if check the text and found the diferrence between binary and text is the '\r' instead of '\'n' . I can't change every '\n' because it will change the real '\n' ones.... From mikael at isy.liu.se Thu Jun 8 11:51:22 2006 From: mikael at isy.liu.se (Mikael Olofsson) Date: Thu, 08 Jun 2006 17:51:22 +0200 Subject: cos: "Integer Required"?!?!?!? In-Reply-To: <1149780685.768525.276850@h76g2000cwa.googlegroups.com> References: <1149777499.262577.318070@u72g2000cwu.googlegroups.com> <2aqdnQ8uYZLpoxXZnZ2dnUVZ_qadnZ2d@comcast.com> <1149780685.768525.276850@h76g2000cwa.googlegroups.com> Message-ID: moonman wrote: > print self.ACphi, type(self.ACphi) yields: > 19412557 > > value = XPLMGetDataf(self.ACphi); print value type(value ) yields: > -0.674469709396 > > print math.radians(XPLMGetDataf(self.ACphi)), > type(math.radians(XPLMGetDataf(self.ACphi))) yields: > > TypeError > : > an integer is required > > Am I totally missing something about 'math'. Does it really expect an > int? Not my Python: >>> math.radians(-0.674469709396) -0.011771717133929535 This all seems very confusing. Have you tried exactly the above? Do you perhaps have a module of your own called math, that Python might be importing? Or is your math not a module, but some other object that happens to have a method called radians, that expects an int? Or have you accidentally redefined math.radians? /MiO From cdsmith at twu.net Fri Jun 23 13:08:31 2006 From: cdsmith at twu.net (Chris Smith) Date: Fri, 23 Jun 2006 11:08:31 -0600 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150902275.129780.50260@p79g2000cwp.googlegroups.com> <1150918629.818145.143220@y41g2000cwy.googlegroups.com> <4fv081F1jh4ifU1@individual.net> <1150967543.947096.72840@g10g2000cwb.googlegroups.com> <4fv84rF1kp06kU1@individual.net> <1150988625.527780.148710@c74g2000cwc.googlegroups.com> <4g22l7F1j8p4mU1@individual.net> <1151081129.290382.297530@r2g2000cwb.googlegroups.com> Message-ID: Marshall wrote: > Ouch; I have a really hard time understanding this. > > I can't see how you'd call + on a and b if you think they might > not be numbers. If they could be something other than numbers, > and you're treating them as if they are, is that sort of like > doing a case analysis and only filling in one of the cases? > If so, wouldn't you want to record that fact somehow? The obvious answer -- I don't know if it's what Pascal meant -- is that they might be 4x4 matrices, or anything else that behaves predictably under some operation that could be called addition. As a mathematical analogy, the entire mathematical field of group theory comes from the idea of performing operations on values without really knowing what the values (or the operations) really are, but only knowing a few axioms by which the relationship between the objects and the operation is constrained. [As an interesting coincidence, group theory papers frequently use the addition symbol to represent the (arbitrary) binary relation of an Abelian group. Not that this has anything to do with choosing "+" for the example here.] Programming languages do this all the time, as well. The most popular example is the OO sense of the word polymorphism. That's all about being able to write code that works with a range of values regardless of (or, at least, a range that less constraining than equlity in) types. -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation From larry.bates at websafe.com Thu Jun 15 15:50:22 2006 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 15 Jun 2006 14:50:22 -0500 Subject: Python in Windows ng In-Reply-To: <449131ab$0$10456$afc38c87@news.optusnet.com.au> References: <449131ab$0$10456$afc38c87@news.optusnet.com.au> Message-ID: <4491B9FE.1020000@websafe.com> veritas wrote: > Can anyone tell me of a good newsgroup for running/programming Python on > Windows OS ? > > Thanks in advance . > > comp.lang.python is fine. If you want to use Python on Windows do yourself a favor and pick up a copy of Python Programming on Win32 (Mark Hammond and Andy Robinson). It covers lots of Windows "specific" things and has good examples of writing services and COM objects. -Larry Bates From jes at nl.demon.net Thu Jun 1 19:13:44 2006 From: jes at nl.demon.net (Jim Segrave) Date: Thu, 01 Jun 2006 23:13:44 -0000 Subject: grouping a flat list of number by range References: <1149196642.001466.53990@c74g2000cwc.googlegroups.com> <1149201416.196975.123370@c74g2000cwc.googlegroups.com> <1149202388.135494.148890@u72g2000cwu.googlegroups.com> Message-ID: <127ut58e8q0ok5a@corp.supernews.com> In article <1149202388.135494.148890 at u72g2000cwu.googlegroups.com>, Paddy wrote: >I did a little re-arranging of the generator version: > >def interv3(inlist): > tmp = inlist[0] > valinc = tmp+1 > for val in inlist[1:]: > if val != valinc: > yield [tmp, valinc]; > tmp = val > valinc = val+1 > yield [tmp, valinc] Still fails when passed an empty list, the initial assignment to tmp is an IndexError -- Jim Segrave (jes at jes-2.demon.nl) From scruffy.mogwai at gmail.com Thu Jun 8 23:44:42 2006 From: scruffy.mogwai at gmail.com (scruffy.mogwai at gmail.com) Date: 8 Jun 2006 20:44:42 -0700 Subject: what does %u mean? In-Reply-To: <1149824520.553473.189380@u72g2000cwu.googlegroups.com> References: <1149823453.947116.200500@y43g2000cwc.googlegroups.com> <1149824520.553473.189380@u72g2000cwu.googlegroups.com> Message-ID: <1149824682.754178.131640@f6g2000cwb.googlegroups.com> Someone beat me to the reply -- and their explanation sounds a lot better than mine! i guess you learn something new everyday... scruffy.mog... at gmail.com wrote: > I'm not sure, but I think it has something to do with unicode. > print "%i" % 1 // Prints the integer 1 as a string. > print "%u" % (-5) // Prints -5 as a unicode string??? > > yaru22 wrote: > > Hi. I just started learning python. > > > > In the exercise in my book, it asks me to try print "%u" % (-5) > > > > I'm wondering what this %u mean? > > > > Thank you. > > > > Regards, > > > > Brian. From salvatore.didio at wanadoo.fr Tue Jun 13 09:03:03 2006 From: salvatore.didio at wanadoo.fr (Salvatore) Date: 13 Jun 2006 06:03:03 -0700 Subject: "Adding" dictionnaries In-Reply-To: <1150203354.861658.181110@h76g2000cwa.googlegroups.com> References: <1150203354.861658.181110@h76g2000cwa.googlegroups.com> Message-ID: <1150203783.897858.221300@h76g2000cwa.googlegroups.com> While reading the doc i've found 'update' :-) From edreamleo at charter.net Fri Jun 23 07:58:15 2006 From: edreamleo at charter.net (Edward K. Ream) Date: Fri, 23 Jun 2006 06:58:15 -0500 Subject: Leo 4.4.1 beta 2 released Message-ID: Leo 4.4.1 beta 2 is now available at: http://sourceforge.net/project/showfiles.php?group_id=3458&package_id=29106 Leo is a text editor, data organizer, project manager and much more. See: http://webpages.charter.net/edreamleo/intro.html The highlights of Leo 4.4.1: ---------------------------- - Multiple editors in Leo's body pane. - Search commands now support regex replace patterns: \1, \2, etc. - Support for external debuggers: see http://webpages.charter.net/edreamleo/debuggers.html - The scripting plugin now creates a Debug Script button. - New commands including run-unit-test, python-help and toggle-invisibles. Links: ------ 4.4.1: http://webpages.charter.net/edreamleo/new-4-4-1.html 4.4: http://webpages.charter.net/edreamleo/new-4-4.html Leo: http://webpages.charter.net/edreamleo/front.html Home: http://sourceforge.net/projects/leo/ Download: http://sourceforge.net/project/showfiles.php?group_id=3458 CVS: http://leo.tigris.org/source/browse/leo/ Quotes: http://webpages.charter.net/edreamleo/testimonials.html -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From raffaelcavallaro at pas-d'espam-s'il-vous-plait-mac.com Fri Jun 16 12:09:54 2006 From: raffaelcavallaro at pas-d'espam-s'il-vous-plait-mac.com (Raffael Cavallaro) Date: Fri, 16 Jun 2006 12:09:54 -0400 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <2006061410510511272-raffaelcavallaro@pasdespamsilvousplaitmaccom> <2006061501423327544-raffaelcavallaro@pasdespamsilvousplaitmaccom> Message-ID: <2006061612095416807-raffaelcavallaro@pasdespamsilvousplaitmaccom> On 2006-06-16 05:22:08 -0400, Joachim Durchholz said: > And this is a typical dynamic type advocate's response when told that static typing has different needs: > "*I* don't see the usefulness of static typing so *you* shouldn't want it, either." But I haven't made this sort of argument. I never said you shouldn't use static typing if you want to. There are indeed types of software where one wants the guarantees provided by static type checks. For example, software that controls irreplaceable or very expensive equipment such as space craft, or software that can kill people if it fails such as software for aircraft or medical devices. The problem for static typing advocates is that most software is not of this type. There is a very large class of software where user inputs are unpredictable and/or where input data comes from an untrusted source. In these cases run-time checks are going to be needed anyway so the advantages of static type checking are greatly reduced - you end up doing run-time checks anyway, precisely the thing you were trying to avoid by doing static analysis. In software like this it isn't worth satisfying a static type checker because you don't get much of the benefit anyway and it means forgoing such advantages of dynamic typing as being able to run and test portions of a program before other parts are written (forward references to as yet nonexistent functions). Ideally one wants a language with switchable typing - static where possible and necessary, dynamic elsewhere. To a certain extent this is what common lisp does but it requires programmer declarations. Some implementations try to move beyond this by doing type inference and alerting the programmer to potential static guarantees that the programmer could make that would allow the compiler to do a better job. In effect the argument comes down to which kind of typing one thinks should be the default. Dynamic typing advocates think that static typing is the wrong default. The notion that static typing can prove program correctness is flawed - it can only prove that type constraints are not violated but not necessarily that program logic is correct. It seems to me that if we set aside that class of software where safety is paramount - mostly embedded software such as aircraft and medical devices - we are left mostly with efficiency concerns. The 80-20 rule suggests that most code doesn't really need the efficiency provided by static guarantees. So static typing should be invoked for that small portion of a program where efficiency is really needed and that dynamic typing should be the default elswhere. This is how common lisp works - dynamic typing by default with static guarantees available where one needs them. From aahz at pythoncraft.com Wed Jun 7 14:32:37 2006 From: aahz at pythoncraft.com (Aahz) Date: 7 Jun 2006 11:32:37 -0700 Subject: CENSORSHIP - Django Project (Schema Evolution Support) References: <4486B9FB.9030804@lazaridis.com> <6asd825u537kpp2aurhaeo1i41f61akbd6@4ax.com> Message-ID: In article , Erik Max Francis wrote: >Rene Pijlman wrote: >> >> Wikipedia always tells the Absolute Truth, because if it doesn't, we can >> edit it and fix it right away. > >Tell that to John Seigenthaler. Rene was making a joke, I think. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I saw `cout' being shifted "Hello world" times to the left and stopped right there." --Steve Gonedes From ptmcg at austin.rr._bogus_.com Tue Jun 13 20:21:14 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 14 Jun 2006 00:21:14 GMT Subject: "groupby" is brilliant! References: <1150180151.643245.148210@y43g2000cwc.googlegroups.com> <448F351A.7000201@lexicon.net> <448F36D3.1070003@islandtraining.com> <448F4076.6090407@lexicon.net> Message-ID: <_DIjg.24503$bk5.8873@tornado.texas.rr.com> John Machin" wrote in message news:448F4076.6090407 at lexicon.net... > On 14/06/2006 8:38 AM, Robert Kern wrote: > > Gary Herron wrote: > >> John Machin wrote: > >> > >>> On 13/06/2006 6:28 PM, Paul McGuire wrote: > >>> > >>>> (Oh, and I like groupby too! Combine it with sort to quickly create > >>>> histograms.) > >>>> > >>>> # tally a histogram of a list of values from 1-10 > >>>> dataValueRange = range(1,11) > >>>> data = [random.choice(dataValueRange) for i in xrange(10000)] > >>>> > >>>> hist = [ (k,len(list(g))) for k,g in itertools.groupby(sorted(data)) ] > >>> That len(list(g)) looks like it uses O(N) memory just to find out what N > >>> is :-( > >> Not at all! A python list *knows* its length at all times. len() is a > >> constant time lookup of an internal attribute. > > > > The point is that you had to create the list in the first place. g is an iterator. > > > > I didn't have to create a list in the first place. Paul did. The point > of my post was to avoid the memory grab caused by list(g) by seeking a > way that just counted g's output. > > Sorry for the confusion my lack of clarity has evidently caused. I'll > rephrase: > > That whole construct > len(list(g)) > looks like it uses O(N) memory just to find out what N is. > Better? Ok, ok!!! Here's a non-O(N) memory allocation, using a generator expression to count the number of items in the list. hist = [ (k,sum(1 for _g in g)) for k,g in itertools.groupby(sorted(data)) ] -- Paul From rschroev_nospam_ml at fastmail.fm Sat Jun 17 05:28:45 2006 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sat, 17 Jun 2006 09:28:45 GMT Subject: Which compiler will Python 2.5 / Windows (Intel) be built with? In-Reply-To: <1150444191.618761.22810@c74g2000cwc.googlegroups.com> References: <1150367139.495114.148550@g10g2000cwb.googlegroups.com> <44917535$1@nntp0.pdx.net> <1150391891.130185.4640@f6g2000cwb.googlegroups.com> <4492414C.10505@v.loewis.de> <1150444191.618761.22810@c74g2000cwc.googlegroups.com> Message-ID: meyer at mesw.de schreef: > * The code created by the Windows GCC is not as good as the one created > by the Microsoft compiler Isn't Python for other platforms built with GCC? Seems to me that if it GCC is good enough for other platforms, it's good enough for Windows. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From ptmcg at austin.rr._bogus_.com Tue Jun 20 23:39:28 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 21 Jun 2006 03:39:28 GMT Subject: Psyco performance References: <1150819763.818687.114360@y41g2000cwy.googlegroups.com> <44981e4c$0$29812$626a54ce@news.free.fr> <1150839749.939196.142440@r2g2000cwb.googlegroups.com> Message-ID: wrote in message news:1150839749.939196.142440 at r2g2000cwb.googlegroups.com... > > Place all the code in a function. Even without psyco you might get > > somewhat better performances then. And I doubt psyco can optimise code > > that isn't in a function anyway. > > > > And lastly, most of the code is probably spend computing x**2 which is > > already optimised C code. > > I've changed the code to include a class, method call, and function. > Now the Psyco code is quite a bit slower. Is this a valid way to test > Psyco's effects? When I run the following code I get this result: > > without psyco = 0.96840101186 > with psyco = 1.82430169197 > with psyco = 0.855900680114 slower > > Here are 3 different implementations of foo, with varying degrees of improvement. func without with foo1: 0.1727 0.0106 foo2: 0.1020 0.1012 foo3: 0.3632 0.8068 foo1 is just a brute force for-loop summing the values of the composed list, foo2 calls sum(), and foo3 is the original foo using reduce(). Surprisingly, brute force + psyco beats reduce and sum without psyco. psyco's strength is in compiling Python code inside functions. In foo2 and foo3, most of the processing is done not in explicit Python, but in C code implementation of sum and reduce, so the psyco processing is actually adding more than it is optimizing. -- Paul import time import psyco time.clock() class Test(object): def __init__(self, value): self.value = value def foo1(self): z = 0 for i in range(self.value): z += i return z def foo2(self): return sum(list(range(0,self.value))) def foo3(self): return reduce(lambda x,y : x + y, list(range(0,self.value))) def test(n,f): l = [Test(i) for i in range(1, n)] return [f(x) for x in l] n = 1000 fns = (Test.foo1, Test.foo2, Test.foo3) no_psyco = [] with_psyco = [] for fn in fns: t1 = time.clock() l2 = test(n,fn) t2 = time.clock() no_psyco.append( t2 - t1 ) psyco.full() for fn in fns: t1 = time.clock() l2 = test(n,fn) t2 = time.clock() with_psyco.append( t2 - t1 ) for fnData in zip([f.func_name for f in fns],no_psyco,with_psyco): print "%s: %.4f %.4f" % fnData From ilias at lazaridis.com Wed Jun 7 11:47:56 2006 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Wed, 07 Jun 2006 18:47:56 +0300 Subject: CENSORSHIP - Django Project (Schema Evolution Support) In-Reply-To: <6asd825u537kpp2aurhaeo1i41f61akbd6@4ax.com> References: <4486B9FB.9030804@lazaridis.com> <4ent10F1f9d3gU1@uni-berlin.de> <6asd825u537kpp2aurhaeo1i41f61akbd6@4ax.com> Message-ID: Rene Pijlman wrote: > Ilias Lazaridis: >> What is the credibility and value of the provided "wikipedia" entry? > > Wikipedia always tells the Absolute Truth, because if it doesn't, we can > edit it and fix it right away. fascinating! . -- http://lazaridis.com From python.list at tim.thechases.com Wed Jun 14 12:34:28 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 14 Jun 2006 11:34:28 -0500 Subject: Python Help In-Reply-To: References: Message-ID: <44903A94.8010702@tim.thechases.com> > I have recently downloaded Python 2.4.3 on Windows XP. The > program does not recongnize when I type in python:" name > 'python' is not defined". Please tell me how to correct this. Sounds like you don't have it in your path. In XP, use Win+Break to pull up your system properties (the same as right-clicking on "My Computer" and chosing "Properties"). On the "Advanced" tab, press the "Environment Variables" button. If you want the change to be just for your user, add a new variable under the top section, named "PATH", with a value of "%PATH%;c:\Program Files\Python24" (or wherever the path to python.exe resides). If a PATH variable already exists, you can just edit it, appending a semicolon followed by the path to the directory containing python.exe If you want to make python accessible for all users on the machine, you can do the same sort of process in the bottom pane of that window. Restart your command-shell and you should be good to go. Or, if you've got stuff in your command shell you don't want to lose, you can just use c:\> path %PATH%;c:\Progra~1\Python24\ which will set the path for that particular command window, but this change will be forgotten when you close the window. -tkc From puzzld_me at yahoo.com Tue Jun 6 16:00:46 2006 From: puzzld_me at yahoo.com (puzz) Date: 6 Jun 2006 13:00:46 -0700 Subject: newbie: python application on a web page In-Reply-To: <1149615269.695229.88820@j55g2000cwa.googlegroups.com> References: <1149615269.695229.88820@j55g2000cwa.googlegroups.com> Message-ID: <1149624046.762779.225240@h76g2000cwa.googlegroups.com> sorry about the missunderstanding... but my question is "how" and not "where" to put it online and that's where the "newbie" comes from P M puzz wrote: > Hi all, > > I am so new to everything, I don't even know where to post my > question... do bear... > > I made this Python calculator that will take an equation as an input > and will display the computed curves on a shiny Tkinter interface > > Now, I'd like to make this application available on a public web > page... and all I could come up with was this post > > Hints?! > I'd also appreciate a link to a beginner forum > > Thanks > > Puzzled Me From gh at ghaering.de Fri Jun 2 20:34:31 2006 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Sat, 03 Jun 2006 02:34:31 +0200 Subject: [ANNOUNCE] pyPgSQL 2.5 released Message-ID: <4480D917.7010405@ghaering.de> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hello, the last pyPgSQL release was in July 2003. Now, after a much too long time I went through all items in the bugtracker and created a release. pyPgSQL is a Python database adapter for PostgreSQL databases. Its homepage is at http://pypgsql.sf.net/. Downloads are available here: http://sourceforge.net/project/showfiles.php?group_id=16528&package_id=20458&release_id=421992 There is a source package and Windows binaries for Python 2.4. The Windows binaries are dynamically linked this time, so you will need a PostgreSQL client library installation to make sure the DLLs are found. It's probably easiest to just include the PostgreSQL bin and lib directory in your PATH. Attached is a ChangeLog. - -- Gerhard -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2.2 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFEgNkXdIO4ozGCH14RAgqlAJ9nNNGM1cTzMK804tV3ItOlDBcuBQCfYvQR GFaIhZnChH8ORdW7qMHKJMA= =K3Y4 -----END PGP SIGNATURE----- -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: Announce URL: From runlevelten at gmail.com Tue Jun 20 11:27:50 2006 From: runlevelten at gmail.com (Ten) Date: Tue, 20 Jun 2006 16:27:50 +0100 Subject: wxPython GUI designer In-Reply-To: <4496b343@127.0.0.1> References: <1150661348.837969.46870@r2g2000cwb.googlegroups.com> <1150664728.435902.210930@y41g2000cwy.googlegroups.com> <4496b343@127.0.0.1> Message-ID: <200606201627.50477.runlevelten@gmail.com> On Monday 19 June 2006 15:23, DarkBlue wrote: > prepare to shed lots of tears before > overcoming the initial disbelieve, that there is nothing > better available for python. Ahem - not strictly true - that should read "there is nothing better for wxPython". Not being pedantic, it's just not true to say nothing better is available for python. Qtdesigner seems about on a par with the GUI design in Microsoft's Visual Studio software to me. Cheers, Ten -- There are 10 types of people in this world, those who understand binary, and those who don't. From cfc at shell01.TheWorld.com Sun Jun 25 12:22:44 2006 From: cfc at shell01.TheWorld.com (Chris F Clark) Date: 25 Jun 2006 12:22:44 -0400 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <1151199196.870389.81960@p79g2000cwp.googlegroups.com> Message-ID: Chris F Clark (I) wrote: > I'm particularly interested if something unsound (and perhaps > ambiguous) could be called a type system. I definitely consider such > things type systems. "Marshall" wrote: > I don't understand. You are saying you prefer to investigate the > unsound over the sound? ... > Again, I cannot understand this. In a technical realm, vagueness > is the opposite of understanding. At the risk of injecting too much irrelevant philosophy into the discussion, I will with great trepdiation reply. First in the abstrtact: No, understanding is approximating. The world is inherently vague. We make false symbolic models of the world which are consistent, but at some level they do not reflect reality, because reality isn't consistent. Only by abtracting away the inherent infinite amout of subtlety present in the real universe can we come to comprehensible models. Those models can be consistent, but they are not the universe. The models in their consistency, prove things which are not true about the real universe. Now in the concrete: In my work productivity is ultimately important. Therefore, we live by the 80-20 rule in numerous variations. One of ths things we do to achieve productivity is simplify things. In fact, we are more interested in an unsound simplification that is right 80% of the time, but takes only 20% of the effort to compute, than a completely sound (100% right) model which takes 100% of the time to compute (which is 5 times as long). We are playing the probabilities. It's not that we don't respect the sound underpining, the model which is consistent and establishes certain truths. However, what we want is the rule of thumb which is far simpler and approximates the sound model with reasonable accuracy. In particular, we accept two types of unsoundness in the model. One, we accept a model which gives wrong answers which are detectable. We code tests to catch those cases, and use a different model to get the right answer. Two, we accept a model which gets the right answer only when over-provisioned. for example, if we know a loop will occassionaly not converge in the n-steps that it theoretically should, we will run the loop for n+m steps until the approximation also converges--even if that requires allocating m extra copies of some small element than are theoretically necessary. A small waste of a small resource, is ok if it saves a waste of a more critical resource--the most critical resource of all being our project timeliness. We do the same things in our abstract reasoning (including our type model). The problems we are solving are too large for us to understand. Therefore, we make simplifications, simplifications we know are inaccurate and potentially unsound. Our algorithm then solves the simplified model, which we think covers the main portion of the problem. It also attempts to detect when it has encountered a problem that is outside of the simplified region, on the edge so to speak. Now, in general, we can figure out how to handle certain edge cases, and we do it. However, some times the edge of one part of the algorithm intereacts with an edge of another part of the algorithm and we get a "corner case". Because our model is too simple and the reasoning it allows is thus unsound, the algorithm will occassionally compute the wrong results for some of those corners. We use the same techniques for dealing with them. Dynamic tagging is one way of catching when we have gotten the wrong answer in our type simplification. Marshall's last point: > I flipped a coin to see who would win the election; it came > up "Bush". Therefore I *knew* who was going to win the > election before it happened. See the probem? Flipping one coin to determine an election is not playing the probabilities correctly. You need a plausible explanation for why the coin should predict the right answer and a track record of it being correct. If you had a coin that had correctly predicted the previous 42 presidencies and you had an explanation why the coin was right, then it would be credible and I would be willing to wager that it could also predict that the coin could tell us who the 44th president would be. One flip and no explanation is not sufficient. (And to the abstract point, to me that is all knowledge is, some convincing amount of examples and a plausible explanation--anyone who thinks they have more is appealing to a "knowledge" of the universe that I don't accept.) I do not want incredible unsound reasoning, just reasoning that is marginal, within a margin of safety that I can control. Everyone that I have know of has as far as I can tell made simplifying assumptions to make the world tractable. Very rarely do we deal with the world completely formally. Look at where that got Russell and Whitehead. I'm just trying to be "honest" about that fact and find ways to compensate for my own failures. -Chris From g.brandl-nospam at gmx.net Fri Jun 30 17:20:37 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Fri, 30 Jun 2006 23:20:37 +0200 Subject: Import bug: Module executed twice when imported! In-Reply-To: References: Message-ID: Peter Maas wrote: > The docs tell us > (http://www.python.org/doc/2.4.2/lib/built-in-funcs.html): > > ------------------------- begin ------------------------------- > execfile(filename[, globals[, locals]]) > > This function is similar to the exec statement, but parses a file > instead of a string. It is different from the import statement in that > it does not use the module administration -- it reads the file > unconditionally and does not create a new module. > ------------------------- end --------------------------------- > > I claim this as a well documented (and thus exspectable) Python behaviour. > execfile() just executes a file unconditionally without searching in > sys.modules. That's its purpose, otherwise it would be a synonym of > the import statement. This has nothing directly to do with the "problem" since the seemingly double imported module is not the one that's execfile'd. Georg From leventyilmaz at gmail.com Fri Jun 16 13:17:45 2006 From: leventyilmaz at gmail.com (leventyilmaz at gmail.com) Date: 16 Jun 2006 10:17:45 -0700 Subject: add elements to indexed list locations Message-ID: <1150478265.122559.283000@f6g2000cwb.googlegroups.com> Hi, I have a very simple problem, but do not know an elegant way to accomplish this. ### # I have a list of names: names = ['clark', 'super', 'peter', 'spider', 'bruce', 'bat'] # and another set of names that I want to insert into # the names list at some indexed locations: surnames = { 1: 'kent', 3:'parker', 5:'wayne' } # The thing I couldn't figure out is, after I insert a # surname the rest of the indices are not valid. # That is, the following won't work: for i, x in surnames.iteritems(): names.insert(i,surnames[i]) ### I am searching a nice way to do this. For instance, is there a more robust way to store indices (as some sort of pointers maybe?) - Levent From timothy.williams at nvl.army.mil Tue Jun 13 10:25:52 2006 From: timothy.williams at nvl.army.mil (timw.google) Date: 13 Jun 2006 07:25:52 -0700 Subject: pylab doesn't find numpy on Windows In-Reply-To: References: <1150205073.203361.304190@f14g2000cwb.googlegroups.com> Message-ID: <1150208752.864425.58530@p79g2000cwp.googlegroups.com> Thanks. That did it. Alexandre Fayolle wrote: > Le 13-06-2006, timw.google nous disait: > > Hi all. > > > > I installed matplotlib 0.87.3 under Python 2.4 on both Linux (FC3) and > > Windows XP Pro. On the linux install, I can import pylab, but when I > > try to do the same thing on the Windows installation, I get > > > >>>> from pylab import * > > > > > ImportError: No module named Numeric > > > > I have numpy 0.9.8 installed in both places too. > > it is trying to load Numeric python. You need to configure matplotlib to > use numpy by saying > > numerix : numpy > > in the matplotlibrc file. > > > -- > Alexandre Fayolle LOGILAB, Paris (France) > Formations Python, Zope, Plone, Debian: http://www.logilab.fr/formations > D?veloppement logiciel sur mesure: http://www.logilab.fr/services > Python et calcul scientifique: http://www.logilab.fr/science From lm-stemc at aub.edu.lb Mon Jun 19 04:56:58 2006 From: lm-stemc at aub.edu.lb (Mohamad Nazzal) Date: Mon, 19 Jun 2006 11:56:58 +0300 Subject: Does anyone find what is fun in programming...? Message-ID: You all suck. Am a programmer, and I must confess that I am dumb since am a programmer. Stop being silly and talk about programming as if you're writing a beautiful story. You're not more than coding generators. It's the most boring work that anybody can imagine. Am a computer sciences graduate, and I am now a programmer, but I hope that soon I can escape from this shit. Am studying Business management right now, and I want to change the whole previous orientation of my career, you know why, because programming sucks the same as the programmers suck. We're a bunch of freaks, we don't have social life, actually I have a social life and that is why I can't go on with programming, and sure I won't let programming corrupt my head. You all, start the change and escape from programming. That is for your own benefit. And unfortunately now after clicking on the send button, I have to go back to my program and start this shit again. Go all to hell -------------- next part -------------- An HTML attachment was scrubbed... URL: From issforum-bounces at iss.net Tue Jun 20 06:56:08 2006 From: issforum-bounces at iss.net (issforum-bounces at iss.net) Date: Tue, 20 Jun 2006 06:56:08 -0400 Subject: The results of your email commands Message-ID: The results of your email command are provided below. Attached is your original message. - Results: Ignoring non-text/plain MIME parts - Unprocessed: Found virus HTML_Netsky.P in file email-body The file is deleted. Found virus WORM_NETSKY.P in file message.scr The file is deleted. --------------------------------------------------------- - Done. -------------- next part -------------- An embedded message was scrubbed... From: python-list at python.org Subject: Mail Delivery (failure issforum-request at iss.net) Date: Tue, 20 Jun 2006 03:55:58 -0700 Size: 2860 URL: From fredrik at pythonware.com Mon Jun 26 08:59:37 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 26 Jun 2006 14:59:37 +0200 Subject: About python 2.5 and its try statement. References: <1151325349.040404.77730@i40g2000cwc.googlegroups.com> Message-ID: "defcon8" wrote: >I can't remember the proposal number, but many of you reading will have > probably read the features that will be added to python 2.5. The actual > part I wanted to talk about was the finally part of try. Isn't it > totally defeating a compiler's job by executing the finally part even > if there is an error in the previous statements? Or have I understood > something wrong? sounds like you're confusing compilation and execution, and compilation errors (syntax errors) with runtime errors (exceptions). try-finally is a runtime thing, not a compile time thing. From miki.tebeka at gmail.com Tue Jun 20 00:43:13 2006 From: miki.tebeka at gmail.com (Miki) Date: 19 Jun 2006 21:43:13 -0700 Subject: can't find win32api from embedded pyrun call In-Reply-To: <1150765862.185334.53290@u72g2000cwu.googlegroups.com> References: <1150765862.185334.53290@u72g2000cwu.googlegroups.com> Message-ID: <1150778593.107920.286580@b68g2000cwa.googlegroups.com> Hello Jim, > // Py_Initialize(); > Py_InitializeEx(0); > PyRun_SimpleString("from win32com.client import *"); > > Here's what it does on the last line: > > File "D:\Python\Lib\site-packages\win32com\__init__.py", line 5, in ? > import win32api, sys, ok > ImportError: No module named win32api > > The same line runs fine in IDLE or at the command prompt. It also runs > without complaint if I run a release version of the app. To build the > debug version I had to build python42_d.lib/dll myself. The reason I > can't call PyInitialize is that it crashes with an "invalid signal" > error. > > I don't think it's a path issue -- I've checked system path, sys.path, > pythonpath env var, and the pythonpath entry in the registry, all of > them loaded with directories including the one with win32api.pyd. > Besides, if it were an install or path problem, why would it work at > the command prompt? IIRC you need to set the path explicitly in an embedded interpreter. See the code in "site.py" (which again IMO is *not* imported when the interpreter starts). HTH, Miki http://pythonwise.blogspot.com/ From robert.thorpe at antenova.com Fri Jun 23 14:12:00 2006 From: robert.thorpe at antenova.com (Rob Thorpe) Date: 23 Jun 2006 11:12:00 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: <1151083931.162325.268050@g10g2000cwb.googlegroups.com> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150908952.804184.218990@r2g2000cwb.googlegroups.com> <1150991074.705803.211570@m73g2000cwd.googlegroups.com> <1151083239.829296.33030@i40g2000cwc.googlegroups.com> <1151083931.162325.268050@g10g2000cwb.googlegroups.com> Message-ID: <1151086320.564736.272500@y41g2000cwy.googlegroups.com> rossberg at ps.uni-sb.de wrote: > Rob Thorpe wrote: > > > > But it differs from latently typed languages like python, perl or lisp. > > In such a language there is no information about the type the variable > > stores. The programmer cannot write code to test it, and so can't > > write functions that issue errors if given arguments of the wrong type. > > The programmer must use his or her memory to substitute for that > > facility. As far as I can see this is a significant distinction and > > warrants a further category for latently typed languages. > > Take one of these languages. You have a variable that is supposed to > store functions from int to int. Can you test that a given function > meets this requirement? The answer is no for python and perl AFAIK. Also no for lisp _aux naturelle_ (you can do it by modifying lisp though of-course, I believe you can make it entirely statically typed if you want). But the analogous criticism could be made of statically typed languages. Can I make a type in C that can only have values between 1 and 10? How about a variable that can only hold odd numbers, or, to make it more difficult, say fibonacci numbers? > You see, IMO the difference is marginal. From my point of view, the > fact that you can do such tests *in some very trivial cases* They are not very trivial for practical programming purposes though, they are important. > in the > languages you mention is an artefact, nothing fundamental. The cases can be far from trivial. In lisp a type specifier can mean something like "argument must be a 10x10 matrix with top corner element larger than 35" You can also, for example, easily make predicates that tell if a value is odd, or a fibonacci number. The system simply extends in different directions. From xivulon at gmail.com Wed Jun 7 14:13:05 2006 From: xivulon at gmail.com (ago) Date: 7 Jun 2006 11:13:05 -0700 Subject: Matplotlib 0.87.2 incompatible with numpy 0.9.8 In-Reply-To: <1149703391.093311.36440@f6g2000cwb.googlegroups.com> References: <1149703391.093311.36440@f6g2000cwb.googlegroups.com> Message-ID: <1149703985.309723.104600@h76g2000cwa.googlegroups.com> ago wrote: > I was not able to make matplotlib 0.87.2 work with numpy 0.9.8 (there > is an error in multiarray.pyd that crashes python). I have noticed that > there is a new version 0.87.3, but I was waiting for the windows > egg/exe version for python 2.4. I tried to compile from sources with > little luck. Does the version 0.87.3 fix the problem? When will the > egg/exe be released? I posted too soon, the egg for 0.87.3 just appeared on sourceforge... But I need the new version of wxWindwos now... Downloading it now... From davidh at ilm.com Tue Jun 20 19:38:59 2006 From: davidh at ilm.com (David Hirschfield) Date: Tue, 20 Jun 2006 16:38:59 -0700 Subject: Getting external name of passed variable In-Reply-To: <1150846320.921138.285100@c74g2000cwc.googlegroups.com> References: <4498420F.1050504@ilm.com> <1150846320.921138.285100@c74g2000cwc.googlegroups.com> Message-ID: <44988713.5020404@ilm.com> Cool, thanks. Stack inspection of sorts it is. -Dave faulkner wrote: >>>> import sys >>>> tellme = lambda x: [k for k, v in sys._getframe(1).f_locals.iteritems() if v == x] >>>> a=1 >>>> tellme(a) >>>> > ['a'] > > Michael Spencer wrote: > >> David Hirschfield wrote: >> >>> I'm not sure this is possible, but it sure would help me if I could do it. >>> >>> Can a function learn the name of the variable that the caller used to >>> pass it a value? For example: >>> >>> def test(x): >>> print x >>> >>> val = 100 >>> test(val) >>> >>> Is it possible for function "test()" to find out that the variable it is >>> passed, "x", was called "val" by the caller? >>> Some kind of stack inspection? >>> >> Perhaps, but don't try it ;-) >> >>> Any help greatly appreciated, >>> -David >>> >>> >> Can't you use keyword arguments? >> >> >>> def test(**kw): >> ... print kw >> ... >> >>> test(val=3) >> {'val': 3} >> >>> test(val=3, otherval = 4) >> {'otherval': 4, 'val': 3} >> >>> >> >> Michael >> > > -- Presenting: mediocre nebula. -------------- next part -------------- An HTML attachment was scrubbed... URL: From aleax at mac.com Sun Jun 25 13:26:16 2006 From: aleax at mac.com (Alex Martelli) Date: Sun, 25 Jun 2006 10:26:16 -0700 Subject: array manipulation without for loops References: <1151251578.463273.24370@m73g2000cwd.googlegroups.com> <1151253182.496596.185420@r2g2000cwb.googlegroups.com> <1hhhes5.1hw0kbeniihqiN%aleax@mac.com> <1151254570.730665.298450@r2g2000cwb.googlegroups.com> Message-ID: <1hhhg1j.11oc03fuoikz8N%aleax@mac.com> Sheldon wrote: > Alex, > > I am using Numeric and have created 3 arrays: zero((1215,1215),Float) > Two arrays are compared and one is used to hold the mean difference > between the two compared arrays. Then I compare 290 or 340 pairs of > arrays. I know that memory is a problem and that is why I don't open > all of these arrays at the same time. I cannot install Numpy due to my > working conditions. Sorry I should have made it clear that is was > Numeric I was working with. It's OK, even if the hard-core numeric-python people are all evangelizing for migration to numpy (for reasons that are of course quite defensible!), I think it's quite OK to stick with good old Numeric for the moment (and that's exactly what I do for my own personal use!). So, anyway, I'll assume you mean your 1215 x 1215 arrays were created by calling Numeric.zeros, not "zero" (with no trailing s) which is a name that does not exists in Numeric. Looking back to your original post, let's say that you have two such arrays, a and b, both 1215x1215 and of Numeric.Float type, and the entries of each array are all worth 1, 2, or 255 (that's how I read your original post; if that's not the case, please specify). We want to write a function that alters both a and b, specifically setting to 255 all entries in each array whose corresponding entries are 255 in the other array. Now that's pretty easy -- for example: import Numeric def equalize(a, b, v=255): Numeric.putmask(a, b==v, v) Numeric.putmask(b, a==v, v) if __name__ == '__main__': a = Numeric.zeros((5,5), Numeric.Float) b = Numeric.zeros((5,5), Numeric.Float) a[1,2]=a[2,1]=b[3,4]=b[0,2]=255 a[3,0]=a[0,0]=1 b[0,3]=b[4,4]=2 print "Before:" print a print b equalize(a, b) print "After:" print a print b brain:~/pynut alex$ python ab.py Before: [[ 1. 0. 0. 0. 0.] [ 0. 0. 255. 0. 0.] [ 0. 255. 0. 0. 0.] [ 1. 0. 0. 0. 0.] [ 0. 0. 0. 0. 0.]] [[ 0. 0. 255. 2. 0.] [ 0. 0. 0. 0. 0.] [ 0. 0. 0. 0. 0.] [ 0. 0. 0. 0. 255.] [ 0. 0. 0. 0. 2.]] After: [[ 1. 0. 255. 0. 0.] [ 0. 0. 255. 0. 0.] [ 0. 255. 0. 0. 0.] [ 1. 0. 0. 0. 255.] [ 0. 0. 0. 0. 0.]] [[ 0. 0. 255. 2. 0.] [ 0. 0. 255. 0. 0.] [ 0. 255. 0. 0. 0.] [ 0. 0. 0. 0. 255.] [ 0. 0. 0. 0. 2.]] brain:~/pynut alex$ Of course I'm using tiny arrays here, for speed of running and ease of display and eyeball-checking, but everything should work just as well in your case. Care to check and let us know? Numeric has pretty good documentation (numpy's is probably even better, but it is not available for free, so I don't know!), and if you don't find that documentation sufficient you might want to have a look to my book "Python in a Nutshell" which devotes a chapter to Numeric (it also is not available for free, but you can get a subscription to O'Reilly's Safari online-books repository, which is free for the first two weeks, and lets you look at many books including Python in a Nutshell -- if you don't want to pay monthly subscription fees, make sure you cancel your trial subscription before two weeks have passed!!!). I strongly recommend that, in some way or other, you DO get a taste of the huge amount of functionality that Numeric provides for you -- with the size of computational tasks you're talking about, an investment of 2-3 hours spent becoming deeply familiar with everything Numeric offers may well repay itself in savings of ten times as much execution time, and what other investments offer such ROI as 1000%?-) Alex From cdsmith at twu.net Sun Jun 25 13:18:15 2006 From: cdsmith at twu.net (Chris Smith) Date: Sun, 25 Jun 2006 11:18:15 -0600 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <1151199196.870389.81960@p79g2000cwp.googlegroups.com> <_xrng.108673$H71.2451@newssvr13.news.prodigy.com> Message-ID: Anton van Straaten wrote: > The problem is that there are no useful sound definitions for the type > systems (in the static sense) of dynamically-typed languages. Yet, we > work with type-like static properties in those languages all the time, > as I've been describing. I honestly don't find it very compelling that there are similarities between the kinds of reasoning that goes on in static type systems versus those used by programmers in dynamically typed languages. Rather, of course there are similarities. It would be shocking if there were not similarities. These similarities, though, have nothing to with the core nature of types. Basically, there are ways to reason about programs being correct. Static type systems describe their reasoning (which is always axiomatic in nature) by assigning "types" to expressions. Programmers in dynamically typed languages still care about the correctness of their programs, though, and they find ways to reason about their programs as well. That reasoning is not completely axiomatic, but we spend an entire lifetime applying this basic logical system, and it makes sense that programmers would try to reason from premises to conclusions in ways similar to a type system. Sometimes they may even ape other type systems with which they are familiar; but even a programmer who has never worked in a typed language would apply the same kind of logic as is used by type systems, because it's a form of logic with which basically all human beings are familiar and have practiced since the age of three (disclaimer: I am not a child psychologist). On the other hand, programmers don't restrict themselves to that kind of pure axiomatic logic (regardless of whether the language they are working in is typed). The also reason inductively -- in the informal sense -- and are satisfied with the resulting high probabilities. They generally apply intuitions about a problem statement that is almost surely not written clearly enough to be understood by a machine. And so forth. What makes static type systems interesting is not the fact that these logical processes of reasoning exist; it is the fact that they are formalized with definite axioms and rules of inference, performed entirely on the program before execution, and designed to be entirely evaluatable in finite time bounds according to some procedure or set of rules, so that a type system may be checked and the same conclusion reached regardless of who (or what) is doing the checking. All that, and they still reach interesting conclusions about programs. If informal reasoning about types doesn't meet these criteria (and it doesn't), then it simply doesn't make sense to call it a type system (I'm using the static terminology here). It may make sense to discuss some of the ways that programmer reasoning resembles types, if indeed there are resemblances beyond just that they use the same basic rules of logic. It may even make sense to try to identify a subset of programmer reasoning that even more resembles... or perhaps even is... a type system. It still doesn't make sense to call programmer reasoning in general a type system. In the same post here, you simultaneously suppose that there's something inherently informal about the type reasoning in dynamic languages; and then talk about the type system "in the static sense" of a dynamic language. How is this possibly consistent? > We know that we can easily take dynamically-typed program fragments and > assign them type schemes, and we can make sure that the type schemes > that we use in all our program fragments use the same type system. Again, it would be surprising if this were not true. If programmers do, in fact, tend to reason correctly about their programs, then one would expect that there are formal proofs that could be found that they are right. That doesn't make their programming in any way like a formal proof. I tend to think that a large number of true statements are provable, and that programmers are good enough to make a large number of statements true. Hence, I'd expect that it would be possible to find a large number of true, provable statements in any code, regardless of language. > So we actually have quite a bit of evidence about the presence of static > types in dynamically-typed programs. No. What we have is quite a bit of evidence about properties remaining true in dynamically typed programs, which could have been verified by static typing. > We're currently discussing something that so far has only been captured > fairly informally. If we restrict ourselves to only what we can say > about it formally, then the conversation was over before it began. I agree with that statement. However, I think the conversation regarding static typing is also over when you decide that the answer is to weaken static typing until the word applies to informal reasoning. If the goal isn't to reach a formal understanding, then the word "static type" shouldn't be used; and when that is the goal, it still shouldn't be applied to process that aren't formalized until they manage to become formalized. Hopefully, this isn't perceived as too picky. I've already conceded that we can use "type" in a way that's incompatible with all existing research literature. I would, however, like to retain some word with actually has that meaning. Otherwise, we are just going to be linguistically prevented from discussing it. -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation From sjmachin at lexicon.net Thu Jun 1 23:08:52 2006 From: sjmachin at lexicon.net (John Machin) Date: 1 Jun 2006 20:08:52 -0700 Subject: C# equivalent to range() In-Reply-To: <1149217547.618703.209770@i39g2000cwa.googlegroups.com> References: <1149214153.359809.288610@i39g2000cwa.googlegroups.com> <1149214491.034665.29030@j55g2000cwa.googlegroups.com> <1149217547.618703.209770@i39g2000cwa.googlegroups.com> Message-ID: <1149217732.260986.295180@u72g2000cwu.googlegroups.com> Neuruss wrote: > John Machin wrote: > > Neuruss wrote: > > > I'm sorry for asking about another language here, but since I only know > > > Python and I'm trying to write something in C#, I guess this is the > > > best place... > > > > > > > Bad guess. Ask questions about language X on comp.lang.X > > Well, perhaps I should. > And I should also explain how range and extend work in python, which is > almost the same thing... > > I thougt that maybe some python programmer could have experience here > with c# and give me a little hint. > > But unfortunately, there are people here who are not willing to waste > their time helping, but enjoy to waste their time niggling... > Plonk. From simon at brunningonline.net Wed Jun 14 07:07:46 2006 From: simon at brunningonline.net (Simon Brunning) Date: Wed, 14 Jun 2006 12:07:46 +0100 Subject: joining NoneType and DateTimeType In-Reply-To: <1150281819.253235.118960@f6g2000cwb.googlegroups.com> References: <1150281819.253235.118960@f6g2000cwb.googlegroups.com> Message-ID: <8c7f10c60606140407n53bdd6a4m595be71ce5cdcbe0@mail.gmail.com> On 14 Jun 2006 03:43:39 -0700, s99999999s2003 at yahoo.com wrote: > i have some databse results that are NoneType and DateTimeType. now i > have trouble > joining these row results together like "|".join(result) as it says > cannot join NoneType , DateTimeType . How can i change these types so i > can join the columns together as string? "|".join(str(column) for column in result) -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From steve at holdenweb.com Wed Jun 7 14:48:33 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 07 Jun 2006 19:48:33 +0100 Subject: printing backslash In-Reply-To: <1149699610.014336.98540@g10g2000cwb.googlegroups.com> References: <1149699610.014336.98540@g10g2000cwb.googlegroups.com> Message-ID: micklee74 at hotmail.com wrote: > hi > how can i sucessfully print |\| in the output of a print command > > a = "|\|" > print a > > but it gives me "|\\|" > No it doesn't: >>> a = "|\|" >>> print a |\| >>> > i tried raw strings too, but it doesn't print |\| . It prints |\\| > instead > > eventually, i also want |\| to be inside a list: > alist = ["|\|", 'blah', 'blah'] . How can i put |\| inside a list? > > can someone show me how it can be done? > thanks > Well, you've got it now, so I won't labour the point. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From jvvhie at gmail.com Mon Jun 26 01:07:45 2006 From: jvvhie at gmail.com (jvvhie at gmail.com) Date: 25 Jun 2006 22:07:45 -0700 Subject: Python "sub-interpreter," security Message-ID: <1151298465.155786.317310@u72g2000cwu.googlegroups.com> Hello, I am writing a pure-Python game engine that interprets the code of game objects within the same process with the exec statement. My main goal is to make as much power available as possible and exec seems like the best way to do that. This is my "proof-of-concept" code(only 18 lines and some whitespace, including the test): http://people.ucsc.edu/~jhofmann/programmables.py I showed this to the Pygame list and recieved some interest and a completely different, more sophisticated implementation: http://codereactor.net/~shang/interpret/ As-is, both versions are wide-open security holes. I think that I can patch them up if I run checks on the statements and eliminate all language features that pose risks. Then, features that are useful but not needed at their full capacity can be accessed through functions designed to be secure. Forcing a crash is not considered an exploit for this purpose(since it's a game engine - if it crashes, the user can recover and lose no data) What I'd like to know is, is it possible to meet this level of security, and if so, which features have to be eliminated? The two that I'm sure should go are module imports and self-modifying code. But in the latter case, I don't know all the ways that might be done. It seems like a very complicated problem, and if I can't solve it I might leave the whole thing unsecured. From spiralx at gmail.com Sat Jun 3 12:00:58 2006 From: spiralx at gmail.com (James) Date: Sat, 3 Jun 2006 17:00:58 +0100 Subject: can python be a "shell" of c++ program? In-Reply-To: References: Message-ID: <7ee3dcd80606030900p7ad62ad0i6e06f9ec1fba2f23@mail.gmail.com> Yes you can, although it might be a fair bit of work depending on the complexity of your codebase. Basically you would need to write Python extensions to expose your C++ classes as Python modules, using SWIG or the Python extension code in the Boost C++ libraries. You'd then embed an interpreter in your program which would allow you to use Python code within it - either from a script or individual commands. It's a fairly common use of Python :) James On 03/06/06, key9 wrote: > Hi all > > I have some data to process, whith complex mechanism,I put these process > mechanism as plugins. > and design lots of classes to abstract data themselves. > > but the question is how to drive them work together. > > That cause too much jobs: I should write UI,parser......almost a completed > system. > > The problem is I don't know what these processed data will finally needed to > display to user. > maybe this , may be that, these can not know on design time. > > what I need is on outside of program, > I can use some interface to get these data what I want , or push back data, > or told program to recalculate it. > > > can I have a way to drive c++ code use this script-like way ? > > > thank you very much From nobody at nowhere.com Thu Jun 15 18:35:59 2006 From: nobody at nowhere.com (Andrew) Date: Thu, 15 Jun 2006 15:35:59 -0700 Subject: Scapy Port to Windows Message-ID: <1293o6k9r73666c@corp.supernews.com> Hello Everyone I'm just writing to inform the newsgroup or anyone who is interested. I have some what of a working copy of scapy, ported to Windows, based on the notes provided on the scapy mailing list for reference http://www.secdev.org/projects/scapy/ (scapy windows) for python version 24 http://www.techshinobi.de/software/scapyandpack.zip (scapy windows) for python version 23 http://www.techshinobi.de/software/pyscapy23.zip however my testing and skill with this application is limited. Ive been trying to get this src code to work with it: >>> www.techshinobi.de/software/IPFreelysrc.zip and it has been successful Please note I am not really a good programmer I have a small - medium knowledge of programming (compared to some of you guys) If anyone is interested in assisting with a full working version of scapy on windows, I believe it would be very beneficial to the growth of the scapy project Thank You in Advance Cheers Andrew :) From skip at pobox.com Thu Jun 1 14:29:55 2006 From: skip at pobox.com (skip at pobox.com) Date: Thu, 1 Jun 2006 13:29:55 -0500 Subject: Member index in toples In-Reply-To: <_TFfg.2976$EF1.229574@news20.bellglobal.com> References: <_TFfg.2976$EF1.229574@news20.bellglobal.com> Message-ID: <17535.12835.850965.102573@montanaro.dyndns.org> Alan> T = ("One","Two","Three","Four") Alan> Is there any built-in way to find what is the index of "Two" Alan> withouot looping within the tuple? One thing to consider is the different uses intended for tuples and lists. Tuples should not be treated as immutable lists, though many people use them that way. Think of lists as arrays of objects of uniform type. Think of tuples more like Pascal records or C structs. You probably want to use a list in the above case. That said, note that Python provides lots of introspection capability. Try this at an interpreter prompt: T = ("One","Two","Three","Four") L = list(T) help(L) or from a shell prompt: pydoc list The help it returns suggests that L.index("Two") will tell you the index of "Two" in L. Alan> Is the same feature available for lists or dictionaries? Dictionaries are inherently unordered. You probably want to consider the truth of this expression: "Two" in mydict for a suitably defined dictionary. It answers whether "Two" exists as a key in mydict. Skip From aleax at mac.com Thu Jun 1 22:16:14 2006 From: aleax at mac.com (Alex Martelli) Date: Thu, 1 Jun 2006 19:16:14 -0700 Subject: An oddity in list comparison and element assignment References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> Message-ID: <1hg9nl6.xivwcd7n0j5N%aleax@mac.com> wrote: > Hi Alex, > With all due respect to your well-deserved standing in the Python > community, I'm not convinced that equality shouldn't imply invariance > under identical operations. So, why aren't you satisfying my request? Provide a simple concrete definition of what your idea of equality WOULD behave like. I notice that your lack of response stands out like a sore thumb -- all you're providing is a set of constraints you desire and a collection of illfounded analogies and handwaving. Traditional mathematics does not support the concept of "change", nor the distinction between equality and identity; the "real world" has no way to define what modifications are "identical" except by their effects (if the results differ, either the original equality was ill-posited or the modifications were not "identical"). But the real world DOES have the concept of "performing exactly the same sequence of operational steps", and, by THAT definition of "equal modifications", then your assertion: > make identical modifications to the engines of two identical > automobiles, I expect the difference in performance to be identical. is ill-founded -- or, rather, your *expectation* may be ill-founded. Take two systems of any significant complexity that are similar enough to be called "identical" by ALL observers (because trying to ascertain the differences, if any, would inevitably perturb the systems irretrievably by Heisenberg's effect -- i.e., there are no OBSERVABLE differences, which by Occam's Razor requires you to posit the systems are equal, because you cannot prove otherwise -- and entities must not be multiplied beyond necessity, so supposing that "observably equal" systems are indeed equal is Occam-compliant). Now, perform "identical" (ditto) modifications: in the real world, due to quantum effects, there WILL be sub-observable differences in what you're doing to the first one and to the second one. If the systems are unstable to start with, they may well amplify those differences to observable proportions -- and there you are: the effect of the "equal" change on "equal" system may easily become observably unequal. Philosophically, you may classify this as an "observation" of both systems, which reasoning backwards lead you to posit that either the systems were NOT equal to start with or the modifications weren't... that is, IF you also posit determinism, which, as well we know, is an unwarrantedly strong hypothesis for systems in which the differences at quantum level matter. Feel free to follow Einstein (and diverse light-years away from the last few decades of physics) in positing that there MUST exist "hidden variables" (unobservable except maybe in destructive, irreversible ways) explaining the difference -- I'll stick with the mainstream of physics and claim your expectation was badly founded to start with. I can debate epistemology with the best, but this is not really the proper forum for this -- starting with the crucial distinction, what it means, in mathematics OR in the real world, to state that two systems are "equal but NOT identical"? In the end, such debates tend to prove rather futile and unproductive, however. In the world of programming languages, we cut through the chase by requesting *operational* (Brouwer-ian, mathematically speaking) definitions. Provide the *operational* definition of how you WANT equality checking to work, contrast it with my simple two-lines one, and THEN we can have a meaningful debate of which one is the correct one to use in the core of a programming language that has the (blessing and curse of) mutable data objects... Alex From troy.melhase at gmail.com Tue Jun 20 21:53:34 2006 From: troy.melhase at gmail.com (Troy Melhase) Date: Tue, 20 Jun 2006 17:53:34 -0800 Subject: Simple question regarding module initialization In-Reply-To: <28dc07920606201846q30e04f2cx28c021818774b4fb@mail.gmail.com> References: <28dc07920606201846q30e04f2cx28c021818774b4fb@mail.gmail.com> Message-ID: $ ipython in [1]: __import__? Type: builtin_function_or_method Base Class: String Form: Namespace: Python builtin Docstring: __import__(name, globals, locals, fromlist) -> module Import a module. The globals are only used to determine the context; they are not modified. The locals are currently unused. The fromlist should be a list of names to emulate ``from name import ...'', or an empty list to emulate ``import name''. When importing a module from a package, note that __import__('A.B', ...) returns package A when fromlist is empty, but its submodule B when fromlist is not empty. On 6/20/06, Patrick M. Nielsen wrote: > Hi guys. > > Yes, this is very much a neophyte question, but I was pondering; > > modules = ['stackless', > 'sys', > 'slsocket as socket', > 'random, time', > 'traceback', > 'string', > 'util'] > > for module in modules: > print "Loading %s..." % module > exec 'import %s' % module > > > Although I like the outcome of writing it like this, I don't feel good about > it. Is this against standard Python conventions or morals? Loading modules > this way, that is (instead of just importing it all "the right way" and > making a print statement for each one). > > From stefan.behnel-n05pAM at web.de Wed Jun 28 02:40:24 2006 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Wed, 28 Jun 2006 08:40:24 +0200 Subject: xml.sax.xmlreader and expat In-Reply-To: References: <2006062717023716807-garyrob@goombahcom> Message-ID: <44a22474$0$26271$9b4e6d93@newsread2.arcor-online.net> Fredrik Lundh wrote: > Gary Robinson wrote: > >> We're using xml.sax.xmlreader in our app (http://www.goombah.com, >> which is written in Python). >> >> In Python 2.3.x, does that use the C-language expat under the hood? > > yes. > >> The reason I'm asking is because we're wondering if we can speed up >> the parsing significantly. > > if you want speed, you don't really want any of the xml.sax or xml.dom > stuff. I'm a bit biased, but I'd recommend the iterparse interface to > cElementTree or to lxml (if you want to do more than just parsing): http://cheeseshop.python.org/pypi/lxml/1.1alpha Why? http://effbot.org/zone/celementtree.htm#benchmarks http://codespeak.net/lxml/performance.html#parsing-and-serialising Stefan From steve at holdenweb.com Wed Jun 14 05:18:55 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 14 Jun 2006 10:18:55 +0100 Subject: Earthquake and Tornado Forecasting Programs June 13, 2006 In-Reply-To: <448EFE0D.3B2D968B@yahoo.com> References: <448eef76$0$30713$ec3e2dad@news.usenetmonster.com> <448EFE0D.3B2D968B@yahoo.com> Message-ID: CBFalconer wrote: > Frank Silvermann wrote: > >>[snip] >>I look forward to a day when meteorology has more to do with precise >>models than models, although I'm all for Russian-style delivery of such >>data. I forecast that a lot of people will be surprised by the weather >>today, as they are categorical idiots, as is the OP. frank > > > Oh for a newsreader that can eliminate all such ugly excessively > cross-posted articles lacking follow-ups. PLONK thread is the only > remaining answer. > And oh for a newsgroup where people will just do the plonking without feeling a necessity to add fuel to the fire ... ? -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From yaru22 at gmail.com Thu Jun 8 23:24:14 2006 From: yaru22 at gmail.com (yaru22) Date: 8 Jun 2006 20:24:14 -0700 Subject: what does %u mean? Message-ID: <1149823453.947116.200500@y43g2000cwc.googlegroups.com> Hi. I just started learning python. In the exercise in my book, it asks me to try print "%u" % (-5) I'm wondering what this %u mean? Thank you. Regards, Brian. From andre.roberge at gmail.com Thu Jun 29 16:15:52 2006 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: 29 Jun 2006 13:15:52 -0700 Subject: Running DocTest on Strings In-Reply-To: <1151608782.326915.197440@i40g2000cwc.googlegroups.com> References: <1151578889.243272.167750@y41g2000cwy.googlegroups.com> <1151608782.326915.197440@i40g2000cwc.googlegroups.com> Message-ID: <1151612152.760417.105410@x69g2000cwx.googlegroups.com> Paddy wrote: > notanotheridiot wrote: > > Hi, > > I have two strings - a docstring containing doctests and a code string > > containing code to be tested with those doctests. I've been trying for > > a day now to run the test without concatenating the two strings, > > adding: > > > > import doctest > > doctest.testmod > > > > to the bottom, writing it all to a file and executing it using popen(). > > > > There must be some way of doing this without writing to a temporary > > file, any ideas? > > > > thanks in advance, > > > > johannes Woolard > Create the concatenated string then exec it? I know from experience that this approach does not work. When you do that, the entire module from which it is run turns out to be scanned for doctests - not only the string being executed by exec. However, I understand that Johannes found a solution. Andr? > > - Pad. From scott.daniels at acm.org Wed Jun 14 17:51:17 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Wed, 14 Jun 2006 14:51:17 -0700 Subject: Question about the Exception class In-Reply-To: References: Message-ID: <4490800f$1@nntp0.pdx.net> Carl J. Van Arsdall wrote: > So this is probably a fairly basic question, but help me out because I'm > just not lining things up and I'm somewhat new to the world of exception > handling. > > What's the benefit to inheriting an exception from and of the available > parent exception classes? Does one subclass have benefits over any > other? Most of what I see involves making a new class and inheriting > from Exception so that one can have an exception class with a name of > their choosing. If you didn't care about the name would there be any > benefit to making a subclass versus raising StandardError or something > else equally vanilla? Are there any difference to library provided > exceptions other than their names? > > -carl > If you create a new exception class that is a subclass of, say, "ValueError," Your exception may have some specific data that assists you in discovering the source of the problem. Meanwhile, any code that says: try: something() except ValueError, error: ... will catch your new exception in the ValueError clause. Subclasses of exceptions can be seen as more specific version of the parent. --Scott David Daniels scott.daniels at acm.org From invalidemail at aerojockey.com Fri Jun 2 21:52:57 2006 From: invalidemail at aerojockey.com (Carl Banks) Date: 2 Jun 2006 18:52:57 -0700 Subject: announce: DaVinci Rendering Engine In-Reply-To: References: Message-ID: <1149299576.937958.176450@i40g2000cwc.googlegroups.com> K.S.Sreeram wrote: > Hi All, > > I've started working on a new open source graphics library called > DaVinci. DaVinci aims to provide a declarative vector graphics based > framework for building GUIs. > > http://tachyon.in/davinci/ I hope it'll get St. John's face right this time. Carl Banks From onurb at xiludom.gro Thu Jun 1 09:07:26 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 01 Jun 2006 15:07:26 +0200 Subject: Function mistaken for a method In-Reply-To: References: Message-ID: <447ee701$0$22029$626a54ce@news.free.fr> Eric Brunel wrote: > Hi all, > > I just stepped on a thing that I can't explain. Here is some code > showing the problem: > > ----------------------------- > class C: Do yourself a favour : use new-style classes. class C(object) > f = None > def __init__(self): > if self.f is not None: > self.x = self.f(0) > else: > self.x = 0 > > class C1(C): > f = int > > class C2(C): > f = lambda x: x != 0 > > o1 = C1() > print o1.x > > o2 = C2() > print o2.x > ----------------------------- > > Basically, I want an optional variant function across sub-classes of > the same class. > > I did it like in C1 for a start, then I needed > something like C2. The result is... surprising: > > 0 > Traceback (most recent call last): > File "func-vs-meth.py", line 18, in ? > o2 = C2() > File "func-vs-meth.py", line 5, in __init__ > self.x = self.f(0) > TypeError: () takes exactly 1 argument (2 given) Not surprising at all. Functions implement the descriptor protocol[1]. When bound to a class and looked up via an instance, it's the __get__ method of the function object that get called - with the instance as param, as defined by the descriptor protocol. This method then return the function wrapped - with the instance - in an Method object - which itself, when called, returns the result of calling the function *with the instance as first parameter*. Which is how methods can work on the instance, and why one has to explicitly declare the instance parameter in "functions to be used as methods", but not explicitly pass it at call time. (please some guru correct me if I missed something here, but AFAIK it must be a correct enough description of method invocation mechanism in Python). [1] about descriptors, see: http://docs.python.org/ref/descriptors.html http://www.geocities.com/foetsch/python/new_style_classes.htm#descriptors > So the first works and o1.x is actually 0. int is not a function. >>> type(int) int is a type. A Python type is a callable object, and act as a factory for instances of it. If the type doesn't implement the descriptor protocol, when bound to a class and looked up via an instance, normal lookup rules apply. So the type object is returned as is. In your case, since int does'nt implement the descriptor protocol, once looked up (and returned as is), it's called with a correct argument - so everything runs fine. Try this: class Obj(object): def __new__(cls, val, *args, **kw): print "in Obj.__new__" print "- called with :" print " cls :", cls print " val :", val print " args: %s" % str(args) print " kw : %s" % kw obj = object.__new__(cls, *args, **kw) print "got : %s - %s" % (obj, dir(obj)) return obj def __init__(self, *args, **kw): print "in Obj.__init__" print "- called with :" print " args: %s" % str(args) print " kw : %s" % kw class C4(C): f = Obj > But the second fails because > self is also being passed as the first argument to the lambda. Of course. It's a function, and it's bound to a class, and looked up via an instance of the class. Try this: def truc(*args, **kw): print "in truc()__" print "- called with :" print " args: %s" % str(args) print " kw : %s" % kw if len(args) > 1: return args[1] class C6(C): f = truc > Defining > a "real" function doesn't help: the error is the same. What' a "real" function ?-) lambdas *are* real functions. >>> type(lambda x: x) >>> > My actual question is: why does it work in one case and not in the > other? cf above. > As I see it, int is just a function with one parameter, Nope, it's a type. Functions are just one kind of callable. Types are callables too, as are any object overloading the call operator - which is '()' - by implementing the __call__(self, ...) method. class NotAFunc(object): def __call__(self): print "I'm not a function" return 42 func = NotAFunc() func() > and the > lambda is just another one. True. And functions implement the descriptor protocol. > So why does the first work, and not the > second? What 'black magic' takes place so that int is not mistaken for > a method in the first case? cf above. If you understood all my explanations, you now know how to solve the problem. Else, here the solution: class C3(C): f = lambda self, x: return x -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From peace.is.our.profession at gmx.de Fri Jun 16 10:13:05 2006 From: peace.is.our.profession at gmx.de (Mirco Wahab) Date: Fri, 16 Jun 2006 16:13:05 +0200 Subject: Python is fun (useless social thread) ;-) In-Reply-To: References: Message-ID: Thus spoke John Salerno (on 2006-06-15 15:50): > Did you have to learn it for a job? No, I was just interested in things that are found interesting ;-) > Or did you just like what you saw and decided to learn it for fun? I read some remarks, from "both sides", on the feasibility of a programming language with 'invisible braces', so I thought 'give it a try'. > Also, how did you go about learning it? (i.e., like I described above, I > started with the main stuff then moved on to the different available > frameworks) Good question: I started with 'Myghty', this is, as you probably know, a (imho excellent) framework for developing web applications from components. 'Myghty' is a almost complete port of Perl's 'Mason' (which is what Amazon and others run at), - what I knew already smoehow. I also tried Pylons (base component of MVC system for web apps), but waved the flag after some time. > Was there any necessity in the specifics you learned, > or did you just dabble in something (e.g. wxPython) for fun? Another motivation was to find out something about the (nowadays) huge amount on SciPy related (software (http://www.scipy.org/Topical_Software). > Are there still some things you feel you need to learn or improve? I came all the way up from Basic/Fortran/x86-Assembler/C/C++ to todays 'lightweight languages' (Dr.Dobbs says they are) in the the Python/Perl/Ruby-Group. For my personal taste(!), Python is in the end 'to unspectacular', means: I didn't manage to learn to be really expressive in it - and to enjoy that ;-) But thats a matter of taste, these languages are like weapons (tools), that you use to express yourself on the battlefield of your tasks. And you _have_ to love and praise your sword, otherwise you won't be able to handle it appropriate - in your dreadful encounters ... > Additional comments/complains here: :) What I don't like in Python - easy things are too easy (even beginners can handle that, PIL etc.), - complicated things are too complicated (I had hard times to remember things), - invisible braces ;-) (just personal taste) - no integrated regex support (used to use re's very much, but milage my vary) Regards Mirco From samschul at pacbell.net Sun Jun 11 17:37:09 2006 From: samschul at pacbell.net (sam) Date: 11 Jun 2006 14:37:09 -0700 Subject: Most elegant way to generate 3-char sequence References: <1149889784.391965.271570@h76g2000cwa.googlegroups.com> Message-ID: <1150061829.075501.117380@y43g2000cwc.googlegroups.com> I have found that the more elegant the code is, the harder it is for me to understand what it is trying to accomplish. It is my opinion that "Keep It Simple" wins over elegance. When I have had the urge to get elegant, I make sure I comment the elegance so my less elegant co-workers can figure out what I was trying to accomplish. Sam Schulenburg James Stroud wrote: > Fredrik Lundh wrote: > > James Stroud wrote: > > > >> See the actual question: > >> > >> >How would you construct a generator to acheive this? > > > > > > if you don't think the context provided by the subject line and the > > sentence before the question is important, how come you're so sure what > > "this" refers to ? > > > > > > > > I'm getting the feeling that "correct" answers have nothing to do with > correctness (i.e. working code) but on some vague notion of "elegance". > Please point me to the page where code elegance is precisely defined so > that I may construct my answers appropriately. And yes, I am too lazy to > google "code elegance". > > James > > -- > James Stroud > UCLA-DOE Institute for Genomics and Proteomics > Box 951570 > Los Angeles, CA 90095 > > http://www.jamesstroud.com/ From william.xwl at gmail.com Fri Jun 16 07:20:57 2006 From: william.xwl at gmail.com (William Xu) Date: Fri, 16 Jun 2006 19:20:57 +0800 Subject: BeautifulSoup error References: <871wtpdbas.fsf@www.williamxu.com> <874pylllqn.fsf@benfinney.id.au> Message-ID: <87ejxpqrc6.fsf@www.williamxu.com> Ben Finney writes: > William Xu writes: > >> >>> import urllib >> >>> from BeautifulSoup import BeautifulSoup >> >>> url = 'http://www.google.com' >> >>> port = urllib.urlopen(url).read() > > Gets the data from the HTTP response. (I'm not sure why you call this > "port".) The data is HTML text encoded to a string of bytes according > to the character encoding specified in the response header fields. i thought we can read and write to a port, like port in scheme. :-) [...] > Get the character encoding specified in the HTTP response, and decode > the data to Unicode from that encoding. How can i do this? i'm afraid i can't figure it out in the manual.. -- William I just uploaded xtoolplaces-1.6. It fixes all bugs but one: It still coredumps instead of doing something useful. The upstream author's e-mail address bounces, Redhat doesn't provide it and I never used it. -- Sven Rudolph From nick at craig-wood.com Sat Jun 10 04:30:03 2006 From: nick at craig-wood.com (Nick Craig-Wood) Date: Sat, 10 Jun 2006 03:30:03 -0500 Subject: os.link makes a copy, not a link References: <1149898122.054522.96910@y43g2000cwc.googlegroups.com> Message-ID: Carl Banks wrote: > Dan M wrote: > > I'm a little bit confused. According to the sources I've looked at on the > > net, > > os.link('file1', 'file2') > > should make a hard link from file1 to file2. But what I'm finding is that > > it's actually making a copy. Am I forgetting a step or something? > > > > Python 2.3.4 running on CentOS 4.3 > > Are file1 and file2 on the same filesystem? Looks like os.link just > calls the OS's link system call, which, for your system, might copy the > file. The link(2) system call on linux never does that. Eg >>> import os >>> file("z", "w").write("test") >>> os.link("z", "/dev/shm/z") Traceback (most recent call last): File "", line 1, in ? OSError: [Errno 18] Invalid cross-device link >> -- Nick Craig-Wood -- http://www.craig-wood.com/nick From thorley at gmail.com Thu Jun 29 10:22:41 2006 From: thorley at gmail.com (thorley at gmail.com) Date: 29 Jun 2006 07:22:41 -0700 Subject: python for windows internet filter / firewall Message-ID: <1151590961.464723.249360@p79g2000cwp.googlegroups.com> Greetings, I'm interested in a simple content-based internet firewall/filter, similar to dansguardian (http://dansguardian.org/), but written in python, and for windows. I assumed such a project would already exist, but my searches on freshmeat, and google turned up empty. I would be interested in starting my own project if necessary, so I have two questions: 1) Does any one no of such a project? 2) Is this even reasonable in python and how might I get started? (e.g. win32 COM?) Thanks much -- matthew From n8pease at yahoo.com Mon Jun 26 19:40:55 2006 From: n8pease at yahoo.com (nate) Date: 26 Jun 2006 16:40:55 -0700 Subject: replace a method in class: how? In-Reply-To: References: Message-ID: <1151365255.574865.249790@u72g2000cwu.googlegroups.com> I don't know a ton about this, but it seems to work if you use: This.update = another_update (instead of t.update = another_update) after saying This.update = another_update, if you enter This.update, it says , (it's unbound) but if you call t.update(5) it will print: another 5 From alikakakhel at yahoo.com Sat Jun 3 17:17:59 2006 From: alikakakhel at yahoo.com (greenflame) Date: 3 Jun 2006 14:17:59 -0700 Subject: Making a second window with Tkinter In-Reply-To: References: <1149282184.587252.59160@y43g2000cwc.googlegroups.com> <1149305472.893535.67770@h76g2000cwa.googlegroups.com> Message-ID: <1149369479.699846.205410@u72g2000cwu.googlegroups.com> What you said about why my code is wrong is still a bit fuzzy but it worked! From deets at nospam.web.de Tue Jun 13 09:33:42 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 13 Jun 2006 15:33:42 +0200 Subject: What's wrong in this HTML Source file of a Bank References: <1150196896.819711.154640@c74g2000cwc.googlegroups.com> <1150204559.415713.288600@h76g2000cwa.googlegroups.com> <1150205478.055121.60300@u72g2000cwu.googlegroups.com> Message-ID: <4f7t7dF1f0g44U1@uni-berlin.de> Thaqalainnaqvi at gmail.com wrote: > > They don't know whats happeing despite sending them several e-mails. So what? How are _we_ supposed to know? Even if somebody here found a bug in their java script (this is a Python NG, btw...) - now _how_ exactly are you planning to update their website with that information? It's their problem, and thus unfortunately yours. So - change your bank, or keep pestering them. Diez From marshall.spight at gmail.com Thu Jun 22 22:03:34 2006 From: marshall.spight at gmail.com (Marshall) Date: 22 Jun 2006 19:03:34 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: <449b07bb$0$11073$9b4e6d93@newsread4.arcor-online.net> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <449b07bb$0$11073$9b4e6d93@newsread4.arcor-online.net> Message-ID: <1151028214.668765.182330@p79g2000cwp.googlegroups.com> Timo Stamm wrote: > > This is actually one of the most interesting threads I have read in a > long time. If you ignore the evangelism, there is a lot if high-quality > information and first-hand experience you couldn't find in a dozen books. Hear hear! This is an *excellent* thread. The evangelism is at rock-bottom and the open exploration of other people's way of thinking is at what looks to me like an all-time high. Marshall From marshall.spight at gmail.com Thu Jun 22 10:50:52 2006 From: marshall.spight at gmail.com (Marshall) Date: 22 Jun 2006 07:50:52 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <7zpshbsvjy.fsf@app-1.diku.dk><4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <0%Wlg.3521$MF6.947@tornado.socal.rr.com> <44992e6c$0$664$bed64819@news.gradwell.net> <1150916327.332627.124400@g10g2000cwb.googlegroups.com> Message-ID: <1150987852.784870.7610@y41g2000cwy.googlegroups.com> Andreas Rossberg wrote: > Marshall wrote: > > > > What prohibits us from describing an abstract type as a set of values? > > If you identify an abstract type with the set of underlying values then > it is equivalent to the underlying representation type, i.e. there is no > abstraction. I don't follow. Are you saying that a set cannot be described intentionally? How is "the set of all objects that implement the Foo interface" not sufficiently abstract? Is it possible you are mixing in implementation concerns? > >>There were papers observing this as early as 1970. > > > > References? > > This is 1973, actually, but most relevant: > > James Morris > Types Are Not Sets. > Proc. 1st ACM Symposium on Principles of Programming Languages, 1973 Okay. Since this paper is in the ACM walled garden, I'll have to wait until next week to get a look at it. But thanks for the reference. > >>(There are also theoretic problems with the types-as-sets view, because > >>sufficiently rich type systems can no longer be given direct models in > >>standard set theory. For example, first-class polymorphism would run > >>afoul the axiom of foundation.) > > > > There is no reason why we must limit ourselves to "standard set theory" > > any more than we have to limit ourselves to standard type theory. > > Both are progressing, and set theory seems to me to be a good > > choice for a foundation. What else would you use? > > I'm no expert here, but Category Theory is a preferred choice in many > areas of PLT. Fair enough. Marshall From fuzzyman at gmail.com Sun Jun 4 18:42:25 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 4 Jun 2006 15:42:25 -0700 Subject: [ANN] ConfigObj 4.3.2 Released Message-ID: <1149460945.857068.308620@i40g2000cwc.googlegroups.com> `ConfigObj 4.3.2 `_ has just been released. You can download it from `configobj-4.3.2.zip `_. This is a bugfix and minor feature enhancement release. There is a bugfix in `unrepr mode `_, and exception handling has been improved. The full changelog is : Changed error handling, if parsing finds a single error then that error will be re-raised. That error will still have an ``errors`` and a ``config`` attribute. That means the error will be more comprehensible. Fixed bug where '\n' terminated files could be truncated. Bugfix in ``unrepr`` mode, it couldn't handle '#' in values. (Thanks to Philippe Normand for the report.) As a consequence of this fix, ConfigObj doesn't now keep inline comments in ``unrepr`` mode. This is because the parser in the `compiler package `_ doesn't keep comments. {sm;:-)} Error messages are now more useful. They tell you the number of parsing errors and the line number of the first error. (In the case of multiple errors.) Line numbers in exceptions now start at 1, not 0. Errors in ``unrepr`` mode are now handled the same way as in the normal mode. The errors stored will be an ``UnreprError``. There is also a proposal to support `PEP 292 `_ string substitution (which is much better). This will be the target of the next release of **ConfigObj**. From mail at microcorp.co.za Mon Jun 12 06:55:48 2006 From: mail at microcorp.co.za (H J van Rooyen) Date: Mon, 12 Jun 2006 12:55:48 +0200 Subject: Intermittent Failure on Serial Port (Trace Result) Message-ID: <005601c68e0e$e7d1a3c0$03000080@hendrik> 8<-------------- (snip) old fail: | | > | > Traceback (most recent call last): | | > | > File "portofile.py", line 232, in ? | | > | > ret_val = main_routine(port, pollstruct, pfifo) | | > | > File "portofile.py", line 108, in main_routine | | > | > send_nak(port, timeout) # so bad luck - comms error | | > | > File "/home/hvr/Polling/lib/readerpoll.py", line 125, in send_nak | | > | > port.flush() | | > | > IOError: [Errno 29] Illegal seek | | > | > close failed: [Errno 29] Illegal seek | | > | > | | > | | | > | | | > | > Where can I find out what the Errno 29 really means? | | > | > Is this Python, the OS or maybe hardware? | | > | | | > | It is from kernel: grep -w 29 `locate errno` | | > | /usr/include/asm-generic/errno-base.h: #define ESPIPE 29 | | > | /* Illegal seek */ | | > | | | > | man lseek: | | > | | | > | ERRORS: | | > | ESPIPE fildes is associated with a pipe, socket, or FIFO. | | > | | | > | RESTRICTIONS: | | > | Linux specific restrictions: using lseek on a tty device | | > | returns ESPIPE. | | > | | > | | > Thanks for the info - so the Kernel sometimes bombs me out - does anybody | know | | > why the python flush sometimes calls lseek? | | | | I thought it was your own flush method. If it is file.flush method that | | makes the issue more complicated, since stdlib file.flush doesn't call | | lseek method. I suggest you run your program using strace to log system | | calls, without such log it's pretty hard to say what's going on. The | | most interesting part is the end, but make sure you have enough space | | for the whole log, it's going to be big. 8<---------------- (snip) New Konsole output: ../logs/composite/rawlog Pipe exists already we get here - thread identity is: 1079298992 New Thread identity printed by new thread is: 1079298992 we get here too 5 0123456789012345 Sefie Sewenstein is in 5 02700000021348 Error record - catch her, catch him 3 9E00000049592001 Antonie de Kompaan is in 2 8A00000870BEDE01 Bertus Bierdrinker is in At 2006/06/12 10:03:20 The following people were in: 0123456789012345 Sefie Sewenstein 9E00000049592001 Antonie de Kompaan 8A00000870BEDE01 Bertus Bierdrinker Traceback (most recent call last): File "portofile.py", line 232, in ? ret_val = main_routine(port, pollstruct, pfifo) File "portofile.py", line 90, in main_routine s, ret_val = poll_one(port, addy, dtype, timeout) # poll one reader File "/home/hvr/Polling/lib/readerpoll.py", line 81, in poll_one port.flush() # make sure it goes IOError: [Errno 29] Illegal seek close failed: [Errno 29] Illegal seek ---------------------end of Konsole output -------------------- We have the whole of that session captured by strace - some 45 Mb of it. Note that the point of failure is not the same place in the python file, but it is according to the traceback, again at a flush call... The "close failed" is explicable - it seems to happen during closedown, with the port already broken.., Here is the the last bit of the trace - I cant figure out who or what calls the lseek on file 3 to get the ESPIPE result... There are some comments added to the trace and the code below like this <<<<<<<<<[comment] --------------------------strace output (tail of) ------------------------------- gettimeofday({1150099428, 256932}, NULL) = 0 gettimeofday({1150099428, 257043}, NULL) = 0 gettimeofday({1150099428, 311401}, NULL) = 0 futex(0x80a8918, FUTEX_WAKE, 1) = 0 futex(0x80a8918, FUTEX_WAKE, 1) = 0 write(3, "\6~7\1", 4) = 4 <<<<<<<<<<<<<<<< [This was last write and it came out on port] [I would have expected the flush here soon] [but it does not seem to be a system call] gettimeofday({1150099428, 409245}, NULL) = 0 <<<<<<<<[this looks like the start of waiting for the echo] gettimeofday({1150099428, 409350}, NULL) = 0 futex(0x80a8918, FUTEX_WAKE, 1) = 0 read(3, 0x4003a000, 4096) = -1 EAGAIN (Resource temporarily unavailable) gettimeofday({1150099428, 409821}, NULL) = 0 futex(0x80a8918, FUTEX_WAKE, 1) = 0 futex(0x80a8918, FUTEX_WAKE, 1) = 0 read(3, 0x4003a000, 4096) = -1 EAGAIN (Resource temporarily unavailable) gettimeofday({1150099428, 411038}, NULL) = 0 futex(0x80a8918, FUTEX_WAKE, 1) = 0 read(3, 0x4003a000, 4096) = -1 EAGAIN (Resource temporarily unavailable) gettimeofday({1150099428, 411530}, NULL) = 0 futex(0x80a8918, FUTEX_WAKE, 1) = 0 read(3, 0x4003a000, 4096) = -1 EAGAIN (Resource temporarily unavailable) gettimeofday({1150099428, 412005}, NULL) = 0 futex(0x80a8918, FUTEX_WAKE, 1) = 0 read(3, 0x4003a000, 4096) = -1 EAGAIN (Resource temporarily unavailable) gettimeofday({1150099428, 412478}, NULL) = 0 futex(0x80a8918, FUTEX_WAKE, 1) = 0 read(3, 0x4003a000, 4096) = -1 EAGAIN (Resource temporarily unavailable) gettimeofday({1150099428, 412950}, NULL) = 0 futex(0x80a8918, FUTEX_WAKE, 1) = 0 read(3, 0x4003a000, 4096) = -1 EAGAIN (Resource temporarily unavailable) gettimeofday({1150099428, 413417}, NULL) = 0 futex(0x80a8918, FUTEX_WAKE, 1) = 0 read(3, 0x4003a000, 4096) = -1 EAGAIN (Resource temporarily unavailable) futex(0x80a8918, FUTEX_WAKE, 1) = 0 gettimeofday({1150099428, 413991}, NULL) = 0 futex(0x80a8918, FUTEX_WAKE, 1) = 0 read(3, 0x4003a000, 4096) = -1 EAGAIN (Resource temporarily unavailable) gettimeofday({1150099428, 414557}, NULL) = 0 futex(0x80a8918, FUTEX_WAKE, 1) = 0 read(3, 0x4003a000, 4096) = -1 EAGAIN (Resource temporarily unavailable) gettimeofday({1150099428, 415029}, NULL) = 0 futex(0x80a8918, FUTEX_WAKE, 1) = 0 read(3, 0x4003a000, 4096) = -1 EAGAIN (Resource temporarily unavailable) gettimeofday({1150099428, 415507}, NULL) = 0 futex(0x80a8918, FUTEX_WAKE, 1) = 0 read(3, 0x4003a000, 4096) = -1 EAGAIN (Resource temporarily unavailable) gettimeofday({1150099428, 415979}, NULL) = 0 futex(0x80a8918, FUTEX_WAKE, 1) = 0 read(3, 0x4003a000, 4096) = -1 EAGAIN (Resource temporarily unavailable) gettimeofday({1150099428, 416451}, NULL) = 0 futex(0x80a8918, FUTEX_WAKE, 1) = 0 read(3, 0x4003a000, 4096) = -1 EAGAIN (Resource temporarily unavailable) gettimeofday({1150099428, 416923}, NULL) = 0 futex(0x80a8918, FUTEX_WAKE, 1) = 0 read(3, 0x4003a000, 4096) = -1 EAGAIN (Resource temporarily unavailable) futex(0x80a8918, FUTEX_WAKE, 1) = 0 gettimeofday({1150099428, 417517}, NULL) = 0 futex(0x80a8918, FUTEX_WAKE, 1) = 0 read(3, 0x4003a000, 4096) = -1 EAGAIN (Resource temporarily unavailable) gettimeofday({1150099428, 418024}, NULL) = 0 futex(0x80a8918, FUTEX_WAKE, 1) = 0 read(3, "\6~7\1\4", 4096) = 5 <<<<<<<<<< [This looks like the echo from external hardware] gettimeofday({1150099428, 568654}, NULL) = 0 gettimeofday({1150099428, 568830}, NULL) = 0 futex(0x80a8918, FUTEX_WAKE, 1) = 0 gettimeofday({1150099428, 569357}, NULL) = 0 gettimeofday({1150099428, 624793}, NULL) = 0 futex(0x80a8918, FUTEX_WAKE, 1) = 0 read(4, 0x80adbf8, 8192) = -1 EAGAIN (Resource temporarily unavailable) gettimeofday({1150099428, 625385}, NULL) = 0 futex(0x80a8918, FUTEX_WAKE, 1) = 0 gettimeofday({1150099428, 667735}, NULL) = 0 gettimeofday({1150099428, 667898}, NULL) = 0 futex(0x80a8918, FUTEX_WAKE, 1) = 0 futex(0x80a8918, FUTEX_WAKE, 1) = 0 _llseek(3, -3, 0xbfbc05c4, SEEK_CUR) = -1 ESPIPE (Illegal seek) <<<<<<<[This is where it breaks] write(2, "Traceback (most recent call last"..., 35) = 35 open("portofile.py", O_RDONLY|O_LARGEFILE) = 8 write(2, " File \"portofile.py\", line 232,"..., 38) = 38 fstat64(8, {st_mode=S_IFREG|0777, st_size=7949, ...}) = 0 mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x4003b000 read(8, "#!/usr/bin/python\n#\tModule to re"..., 4096) = 4096 read(8, "num):\t\t\t\t# see if we know him\n\t\t"..., 4096) = 3853 write(2, " ", 4) = 4 write(2, "ret_val = main_routine(port, pol"..., 48) = 48 close(8) = 0 munmap(0x4003b000, 4096) = 0 open("portofile.py", O_RDONLY|O_LARGEFILE) = 8 write(2, " File \"portofile.py\", line 90, "..., 48) = 48 fstat64(8, {st_mode=S_IFREG|0777, st_size=7949, ...}) = 0 mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x4003b000 read(8, "#!/usr/bin/python\n#\tModule to re"..., 4096) = 4096 write(2, " ", 4) = 4 write(2, "s, ret_val\t= poll_one(port, addy"..., 68) = 68 close(8) = 0 munmap(0x4003b000, 4096) = 0 open("/home/hvr/Polling/lib/readerpoll.py", O_RDONLY|O_LARGEFILE) = 8 write(2, " File \"/home/hvr/Polling/lib/re"..., 67) = 67 fstat64(8, {st_mode=S_IFREG|0644, st_size=6691, ...}) = 0 mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x4003b000 read(8, "#!/usr/bin/python\n#\tModule to ke"..., 4096) = 4096 write(2, " ", 4) = 4 write(2, "port.flush()\t\t\t\t\t\t\t# make sure i"..., 39) = 39 close(8) = 0 munmap(0x4003b000, 4096) = 0 write(2, "IOError", 7) = 7 write(2, ": ", 2) = 2 write(2, "[Errno 29] Illegal seek", 23) = 23 write(2, "\n", 1) = 1 rt_sigaction(SIGINT, {SIG_DFL}, {0x400e7680, [], 0}, 8) = 0 futex(0x80a8918, FUTEX_WAKE, 1) = 1 close(4) = 0 futex(0x80a8918, FUTEX_WAKE, 1) = 0 close(6) = 0 futex(0x80a8918, FUTEX_WAKE, 1) = 0 close(5) = 0 futex(0x80a8918, FUTEX_WAKE, 1) = 0 _llseek(3, -3, 0xbfbc0c44, SEEK_CUR) = -1 ESPIPE (Illegal seek) close(3) = 0 munmap(0x4003a000, 4096) = 0 write(2, "close failed: [Errno 29] Illegal"..., 38) = 38 futex(0x80a8918, FUTEX_WAKE, 1) = 0 futex(0x80a8918, FUTEX_WAKE, 1) = 0 futex(0x8061488, FUTEX_WAKE, 1) = 0 futex(0x80a8918, FUTEX_WAKE, 1) = 0 close(7) = 0 futex(0x804a198, FUTEX_WAKE, 1) = 0 futex(0x804a198, FUTEX_WAKE, 1) = 0 futex(0x804a198, FUTEX_WAKE, 1) = 0 futex(0x804a198, FUTEX_WAKE, 1) = 0 munmap(0x40039000, 4096) = 0 exit_group(1) = ? ------------------------------------end of trace output ----------------------- for what its worth, the code that reportedly failed this time, looks like this: 8<------------(snip) port.write(poll) # write the poll string out <<<<<<[ This is the write referred to above] port.flush() # make sure it goes <<<<<<[ This is the reported point of failure] start_time = time.time() <<<<<<[ But we got here ] s = '' gotchar = 3 # assume nothing will happen - no answer while (time.time() - start_time < timeout): <<<<<<[ and we got here too] s, ret_val =read_char(port, s) # if ret_val == 2: continue # nothing there if ret_val != 0: # kbd int and other rubbish return s, ret_val if s == '': # empty srring is nfg continue if s == eot: # report on eot gotchar = 2 return s, gotchar if s == poll: # eat echoed poll string <<<<<<[ And this looks true above too - the echoed string] s = '' gotchar = 2 # nothing there yet start_time = time.time() continue start_time = time.time() # we had a char - restart time out gotchar = 0 # note the fact that there was something return s, gotchar # time out return, with or without something in string come to think of it - when isolated like that - the failures have consistently been of the same form - a write followed immediately by a flush - could there be timing issues here? remember that we are talking about a serial port at 9600 - it takes about 1 Millisec to transmit a char - but then - if you dont follow the write with a flush, then nothing happens unless there is a line feed char in the string - that seems to force a real transmit... But I am already reading, looking for the echo, before the first char has even gone out... But the failing flush (if that is it) does not show up in the strace until much later.... Any help would be greatly appreciated - I am stuck! - Hendrik From johnjsal at NOSPAMgmail.com Mon Jun 5 16:01:33 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 05 Jun 2006 20:01:33 GMT Subject: GUI Program Error In-Reply-To: <920hg.2238$No6.47697@news.tufts.edu> References: <1149536396.375285.319390@y43g2000cwc.googlegroups.com> <920hg.2238$No6.47697@news.tufts.edu> Message-ID: John Salerno wrote: > What is dir(), btw? Is it a > class for creating the application? Heh heh, how quickly I forget about built-ins. :) Try something like this: import Tkinter as tk root = tk.Tk() label = tk.Label(root, text='Hello world!') label.pack() root.mainloop() From shejo284 at gmail.com Fri Jun 23 03:40:34 2006 From: shejo284 at gmail.com (Sheldon) Date: 23 Jun 2006 00:40:34 -0700 Subject: OverflowError: math range error... In-Reply-To: References: <1150965908.354492.239230@i40g2000cwc.googlegroups.com> Message-ID: <1151048434.349731.99390@i40g2000cwc.googlegroups.com> Thanks for the tips! I am going to look into this some more. I am not used to using Numeric and the logical functions. I didn't think about what you pointed out and somewhere the returned values from these logical methods are not what I expect. I will rewrite the whole thing using alltrue instead. /Sheldon Robert Kern skrev: > Sheldon wrote: > > Hi, > > > > I have a written a script that will check to see if the divisor is zero > > before executing but python will not allow this: > > > > ?if statistic_array[0:4] > 0.0: > > statistic_array[0,0:4] = > > int(multiply(divide(statistic_array[0,0:4],statistic_array \ > > [0,4]),10000.0))/100.0 > > > > Does anyone know why Python is complaining: > > > > "statistic_array[0,0:4] = > > int(multiply(divide(statistic_array[0,0:4],statistic_array[0,4]),10000.0))/100.0 > > > > OverflowError: math range error" > > > > and how do I get around this problem? This stupid because there is a if > > statement preventing this "dividing by zero". > > What kind of arrays are you using? If it's Numeric (and I think it is because > numarray and numpy would throw an error at the if: statement), then your test is > incorrect. > > Comparisons yield arrays of boolean values. When a Numeric boolean array is used > as a truth value (like in an if: statement), then it will return True is *any* > of the values are True. Use Numeric.alltrue(statistic_array[:4] > 0.0) instead. > > Both numarray and numpy throw an exception when one attempts to use arrays as > truth values since the desired meaning (alltrue or sometrue) is ambiguous. > > -- > 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 From gh at ghaering.de Fri Jun 2 19:05:15 2006 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Sat, 03 Jun 2006 01:05:15 +0200 Subject: Using pysqlite2 In-Reply-To: <4480a5c8$1@news.uni-ulm.de> References: <1149276702.992801.247640@j55g2000cwa.googlegroups.com> <4480a5c8$1@news.uni-ulm.de> Message-ID: <4480C42B.2030106@ghaering.de> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Dennis Benzinger wrote: > lolmcbride at googlemail.com wrote: >> Is it possible to use this for sending triggers to a sqlite db?Could >> someone provide me with an example of how to do this please? >> Thanks > > Do you want to implement a trigger for a SQLite database in Python? > > That won't work. Triggers in SQLite can only contain UPDATE, INSERT, > DELETE and SELECT statements http://sqlite.org/lang_createtrigger.html>. Yes, but you can fake it. You can create a new SQL function using pysqlite's create_function, and then just call that function in the trigger. In that Python function from the trigger, you can then even access SQLite again. I've attached a quick-and-dirty example. Note that exceptions in functions get ignored currently, so you better implement a try-except with some kind of logging during development, otherwise you will wonder why nothing happens. Also, older pysqlite releases won't provide useful error messages if you have errors in the SQL you send to executescript(). Using a recent pysqlite release is recommended if you plan to use executescript(). - -- Gerhard -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2.2 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFEgMQrdIO4ozGCH14RArFaAKCU8lgwidMoNQ0GGKVwJ2GV9xPF8ACfTDhv QVHvudLfoDGiIyFgHe5w6L4= =bfUa -----END PGP SIGNATURE----- -------------- next part -------------- A non-text attachment was scrubbed... Name: trigger_example.py Type: text/x-python Size: 702 bytes Desc: not available URL: From ullrich at math.okstate.edu Fri Jun 2 05:30:20 2006 From: ullrich at math.okstate.edu (David C. Ullrich) Date: Fri, 02 Jun 2006 04:30:20 -0500 Subject: shuffling elements of a list References: <1149045499.212967.13120@f6g2000cwb.googlegroups.com> <1149051212.139046.155340@c74g2000cwc.googlegroups.com> <1149105576.321676.131600@j55g2000cwa.googlegroups.com> <69ft72516amvri3up8fop5rf543s6en1lg@4ax.com> Message-ID: On Thu, 01 Jun 2006 03:25:23 -0700, Erik Max Francis wrote: >David C. Ullrich wrote: > >> Good example, because we know that EMF is not dumb. I've seen >> the same algorithm many times - the best example is ... > >Man, an error made _six years ago_ and people are still bringing it up ... Sorry. Happens to me on sci.math all the time. The point really wasn't that you were so dumb, the point was just the opposite. (_I_ didb't bring it up, btw - I would never have known about it if FL hadn't pointed it out.) ************************ David C. Ullrich From miki.tebeka at gmail.com Wed Jun 21 01:00:55 2006 From: miki.tebeka at gmail.com (Miki) Date: 20 Jun 2006 22:00:55 -0700 Subject: need all python dialog equivalent In-Reply-To: References: Message-ID: <1150866055.048937.217350@b68g2000cwa.googlegroups.com> Hello Eric, > Is there anything like an all Python dialog equivalent floating around? http://www.pythonware.com/library/tkinter/introduction/ HTH, -- Miki http://pythonwise.blogspot.com/ From jdc at uwo.ca Tue Jun 13 13:23:02 2006 From: jdc at uwo.ca (Dan Christensen) Date: Tue, 13 Jun 2006 13:23:02 -0400 Subject: numeric/numpy/numarray In-Reply-To: References: <1150188484.888977.189510@y43g2000cwc.googlegroups.com> Message-ID: <87pshdynpl.fsf@uwo.ca> Bryan writes: > on the python wiki > "NumArray is the current reimplementation of NumPy." > http://wiki.python.org/moin/NumArray > > so, was Numarray written *before* NumPY, or was it a reimplementation of NumPy > which implies it came *after* NumPy? I clarified that wiki page to use the name "Numeric" for the old version, and to point out that there is "Numpy" which is even newer than numarray. Dan From cfc at shell01.TheWorld.com Sat Jun 24 15:11:58 2006 From: cfc at shell01.TheWorld.com (Chris F Clark) Date: 24 Jun 2006 15:11:58 -0400 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> Message-ID: Chris Smith writes: > I thought about this in the context of reading Anton's latest post to > me, but I'm just throwing out an idea. I think there is some sense of convergence here. In particular, I reason about my program using "unsound types". That is, I reason about my program using types which I can (at least partially) formalize, but for which there is no sound axiomatic system. Now, these types are locally sound, i.e. I can prove properties that hold for regions of my programs. However, the complexity of the programs prevent me from formally proving the entire program is correct (or even entirely type-safe)--I generally work in a staticly, but weakly-typed language. Sometimes, for performance reasons, the rules need to be bent--and the goal is to bend the rules, but not break them. At other times, I want to strenghten the rules, make parts of the program more provably correct. How does this work in practice? Well, there is a set of ideal types, I would like to use in my program. Those types would prove that my program is correct. However, because there are parts of the program that for perfomnace reasons need me to widen the ideal types to something less tight, pragmatic types. The system can validate that I have not broken the pragmatic types. That is not tight enough to prove the program correct, but it provides some level of security. To improve my confidence in the program, I borrow the tagging concept to supplement the static type system. At key points in the program I can check the type tag to ensure that the data being manipulated actual matches the unprovable ideal type system. If it doesn't, I have a witness to the error in my reasoning. It is not perfect, but it is better than nothing. Why am I in this state, because I believe that most interesting programs are beyond my ability to formally prove them, or at least prove them in "reasonable" time bounds. Therefore, I prove (universally quantify) some properties of my programs, but many other (and most of the "interesting") properties, I can only existentially quantify--it worked in the cases that it was tested on. It is a corrolary of this, that most programs have bugs--places where the formal reasoning was incomplete (did not reason down to relevant interesting property) and the informal reasoning was wrong. Thus, the two forms of reasoning, static typing to check the formal properties that it can, and dynamic tagging to catch the errors that it missed work like a belt and suspenders system. I would like the static type system to catch more errors, but I need it to express more to do so, and many of the properties that are interesting require n-squared operations to validate. Equally important, the dynamic tags help when working in an essentially untrustworthy world. Not only do our own programs have bugs, so do the systems we run them on, both hardware and software. Moreover, alpha radiation and quantum effects can change "constants" in a program (some of my work has to do with soft-error rates on chips where we are trying to guarantee that the chip will have a reasonable MBTF for certain algorithms). That's not to ignore the effects of malware and other ways your program can be made less reliable. Yes, I want a well-proven program, but I also want some guarantee that the program is actually executing the algorithm specified. That requires a certain amount of "redundant" run-time checks. Knuth had a quote about a program only being proven and not tested that reflects the appropriate cynicism. I consider any case where a program gives a function outside of its domain a "type error", because an ideal (but unacheivable) type system would have prevented it. That does not make all errors, type errors, because if I give a program an input within its domain and it mis-computes the result, that is not a type error. -Chris From jcarlson at uci.edu Thu Jun 15 17:11:50 2006 From: jcarlson at uci.edu (Josiah Carlson) Date: Thu, 15 Jun 2006 14:11:50 -0700 Subject: [Python-Dev] The baby and the bathwater (Re: Scoping, augmented assignment, 'fast locals' - conclusion) In-Reply-To: References: <20060614093042.F2D7.JCARLSON@uci.edu> Message-ID: <20060615124945.F32B.JCARLSON@uci.edu> Boris Borcic wrote: > [this is bytes of an oversized put-all-into-it intervention. A possibly expanded > version will be submitted on clp with local followup before a couple days] > > Josiah Carlson wrote: > > [BB] > >> I'd say a first step in convincing me I am wrong would be to show me > examples of > >> object methods of the standard library that are recursive, and cut out for > >> recursion. > > [JC] > > Actually, I don't believe that is necessary. I've shown that you would > > get better performance with a non-recursive function and passing two > > arguments, than you would passing one argument with scoping tricks to > > get the second. > > Assuming my aim was purely performance clearly stretches the hints I gave that I > wasn't unconcerned by it. Taking ground on this to unwarrantedly suppose that my > methodology was deficient, rectify it, and then dictate the "necessary" > conclusions I find... er, preposterous seems balanced, "thought police" not > totally unwarranted. In my initial and later readings of your messages, I read 2 reasons why you were using a closure rather than some other method to perform this particular operation: 1. Minimal code change. 2. It was faster than using an object with a particular interface. If there were other reasons, then I obviously missed them. However, since no one else has responded substantively to your postings, other than Terry and Guido's 'not gonna change', I can only presume that others have found that your desired result (augmented assignments for names not previously existing in the current scope, but existing in a parent lexical scope, be performed on the object bound to a parent scope name), is undesireable for Python 2.5 . The fact that no one has suggested that you write a PEP, or start the discussion _after_ 2.5 comes out, is a sign to me that the feature is generally undesireable. Without proof to the contrary (a group of core Python developers coming out in support of the feature), I can only go by my own opinion: I don't believe the utility of this particular feature is worthwhile enough to change how Python works, considering the possibility for execution errors. [snip] > This said, first : I deny you have or ever had real ground to refuse legitimacy, > motivation, efficiency or methodological soundness to my approach. In a portion of your message that I've cut out, you described how the goal of your current programming project was to write a sudoku solver in fewer than 60 lines and that ran in fewer than 10ms for arbitrary problems. Great, wonderful, I wish you luck; I will not question or "refuse legitimacy, motivation, efficiency or methodological soundness" of your approach when using the Python programming language. However, you are offering a series of reasons as to why the Python programming language should be changed. I'm questioning your reasoning. You may find it insufficient, misinformed, prejudiced, nonsense, mean-spirited, or even that I'm a loony who should be in your killfile. My purpose here isn't to convince _you_ that you are wrong about this feature, as arguing via email has never been my strong suit, but instead to offer at least one valid reason why your change could or would hurt some Python users, and/or the effectiveness of their code. I will mention that the lack of _any_ public support in python-dev likely says far more about the unliklihood of acceptance than anything you or I have probably typed in the last few days. [snip] > [JC] > > when it was an > > actual error (a not uncommon case), > > I guess your insistence on the rightful methodology entitles me to enquire in > turn on your choice of tool to establish the relative frequency of said case ? My measurement is quite subjective. Have I ever made that mistake, or do I know of anyone who has made that mistake? In this case, I have made the mistake I mention, both in personal code, as well as code I was writing as I was tutoring. I'm not aware of significant problems in user code, usually because the moment the code is run, the programmer fixes it. Here are two questions for you: 1. Do you have any proof showing that the error I claim exists (not uncommonly was my description), is in fact so rare, that I am essentially the only one who has made the mistake? 2. Do lexically nested augmented assignments happen so often as to make this problem a "must solve" for any Python revision? > [JC] > > which is a bit of a no-no, > > What I would have believed a /bit/ of a no-no for Python, is to turn away from > the "consenting adults" spirit to go the way of so many other programming languages. > > Picture of the latter way : - As a matter of course, to place the virtue of > catching errors early, before the virtue of following programmers' legitimate > intentions. - Designing for assumed chronic lusers in need of being protected by > the compiler from shooting themselves in the foot. Do skilled programmers make errors? Yes. Do skilled programmers make errors when they are first using a programming language? Yes. It has always been my experience with Python that it seeks to be reasonable to use for both newcomers to programming and long-time "skilled" programmers. In my statements regarding possible errors related to augmented assignments, I merely believe that people can and will make mistakes. I further believe that if I manage to make a particular mistake, that someone else has, because while I'm not the most brilliant programmer out there, I'm also certainly not the worst, and I would guess that I lack the creativity to generate a completely new class of mistakes. You talk about "Designing for assumed chronic lusers", I'm talking about designing for human beings, some of whom are new to the language. - Josiah From serge.orlov at gmail.com Tue Jun 27 19:34:14 2006 From: serge.orlov at gmail.com (Serge Orlov) Date: Tue, 27 Jun 2006 16:34:14 -0700 Subject: Python UTF-8 and codecs In-Reply-To: References: <5Hgog.627$Gv.173@fed1read09> Message-ID: On 6/27/06, Mike Currie wrote: > Well, not really. It doesn't affect the result. I still get the error > message. Did you get a different result? Yes, the program succesfully wrote text file. Without magic abilities to read the screen of your computer I guess you now get exception in print statement. It is because you use legacy windows console (I use unicode-capable console of lightning compiler to run snippets of code). You can either change console or comment out print statement or change your program to print unicode representation: print repr(filteredLine) From digitalorganics at gmail.com Sun Jun 25 16:59:46 2006 From: digitalorganics at gmail.com (digitalorganics at gmail.com) Date: 25 Jun 2006 13:59:46 -0700 Subject: Mix-In Class Methods At Run-Time In-Reply-To: <1151193767.589325.158820@m73g2000cwd.googlegroups.com> References: <1151191406.755252.210300@i40g2000cwc.googlegroups.com> <1151193767.589325.158820@m73g2000cwd.googlegroups.com> Message-ID: <1151269186.710343.41210@c74g2000cwc.googlegroups.com> This looks excellent bearophile, but I'm having trouble understanding some things. Perhaps you can help wipe clean my ignorance. Firstly, I thought __classes__ was a read-only attribute? Secondly, what is a "dictproxy object" and why won't the following code work: class Cat: def meow(self): print "meow" def MixIn(object, *classes): temp = type('ClassPie', (object.__class__,) + classes, {}) temp.__dict__.update([object.__dict__]) NewClass = MixIn(Cat(), C, D) test = NewClass() __dict__, to my understanding, is suppose to be a dictionary, but Python keeps telling me it's a 'dictproxy' object and that it has no attribute 'update'. Why is this? Thanks. bearophileHUGS at lycos.com wrote: > I think it's possible, most of such kind of things are possible with > Python. > I'm not an expert yet in such kind of things, so this can be a starting > point for you (note the shadowing of m2, the class docstrings, etc). > Other people can give you something better or more correct. > > class A: > def m1(self): return "m1" > def m2(self): return "m2" > > class B: > def m3(self): return "m3" > > class P: > def m2(self): return "m2b" > def m4(self): return"m4" > > def mixin(object, *classes): > class NewClass(object.__class__): > pass > for C in classes: > NewClass.__dict__.update(C.__dict__) > object.__class__ = NewClass > > foo = P() > print "Before:" > print "foo.__class__.__dict__.keys():", foo.__class__.__dict__.keys() > print "P.__dict__.keys():", P.__dict__.keys() > print "foo.m2():", foo.m2() > print "foo.m4():", foo.m4(), "\n" > > mixin(foo, A, B) > > print "After:" > print "foo.__class__.__dict__.keys():", foo.__class__.__dict__.keys() > print "P.__dict__.keys():", P.__dict__.keys() > print "foo.m1():", foo.m1() > print "foo.m2():", foo.m2() > print "foo.m3():", foo.m3() > print "foo.m4():", foo.m4() > > Bye, > bearophile From notsew-reversePreceedingAndRemoveThis at canncentral.org Thu Jun 22 02:17:53 2006 From: notsew-reversePreceedingAndRemoveThis at canncentral.org (weston) Date: 21 Jun 2006 23:17:53 -0700 Subject: Can PyObjC be used on shared Mac OS X hosting? Message-ID: <1150957073.204624.4600@r2g2000cwb.googlegroups.com> Does anyone have experience with (or failing that, theoretical knowledge about) installing using the PyObjC bridge on a Mac OS X machine in a context where one doesn't have root/admin access (and therefore can't install things in conventional locations)? Can such a thing be done? From grflanagan at yahoo.co.uk Sun Jun 18 08:45:23 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 18 Jun 2006 05:45:23 -0700 Subject: mapping None values to '' In-Reply-To: <1150632320.443681.42640@r2g2000cwb.googlegroups.com> References: <1150632320.443681.42640@r2g2000cwb.googlegroups.com> Message-ID: <1150634723.506242.227390@h76g2000cwa.googlegroups.com> micklee74 at hotmail.com wrote: > hi > i wish to map None or "None" values to "". > eg > a = None > b = None > c = "None" > > map( , [i for i in [a,b,c] if i in ("None",None) ]) > > I can't seem to find a way to put all values to "". Can anyone help? > thanks a = [None, 'None', None] def filtre(x): if x is None or x == 'None': return '' else: return x assert map(filtre, a) == ['', '', ''] a = [1, 2, None, 'None', 3, 4] assert map(filtre, a) == [1, 2, '', '', 3, 4] From russandheather at gmail.com Thu Jun 22 17:11:36 2006 From: russandheather at gmail.com (Russell Warren) Date: 22 Jun 2006 14:11:36 -0700 Subject: better Python IDE? Mimics Maya's script editor? In-Reply-To: <1149810048.765664.107820@i40g2000cwc.googlegroups.com> References: <1149810048.765664.107820@i40g2000cwc.googlegroups.com> Message-ID: <1151010696.719267.236060@r2g2000cwb.googlegroups.com> Check out the Wing IDE - www.wingware.com . As part of it's general greatness it has a "debug probe" which lets you execute code snippets on active data in mid-debug execution. It doesn't have precisely what you are after... you can't (yet) highlight code segments and say "run this, please", but I think it might almost have what you want for general workflow improvement. The main drawback is that it is a commercial product, albeit "cheap". The extra drawback is that the debug probe feature requires the professional version which is "less cheap", but still < $200. Well worth it for professional development IMO. They have a great demo policy... you should check it out. I tried several different IDEs (I've become accustomed to using IDEs over supe'd up text editors) and Wing was/is my favorite. From keesvanschaik at gmail.com Fri Jun 9 08:04:36 2006 From: keesvanschaik at gmail.com (KvS) Date: 9 Jun 2006 05:04:36 -0700 Subject: Short questions wrt Python & Unicode Message-ID: <1149854676.717074.309260@f6g2000cwb.googlegroups.com> Hi all, I've been reading about unicode in general and using it in Python in particular lately as this turns out to be not so straightforward actually. I wanted to aks two questions: 1) I'm writing a program that interacts with the user through wxPython (unicode build) and stores & retrieves data using PySQLite. As fas as I know now, both packages are capable of handling Python unicode objects (wxPython returns the values of text controls etc. by default as Python unicode objects and "TEXT" columns in PySQLite have unicode entries) and since of course both interface with me through Python unicode objects I should be able to use each others generated unicode objects without any fear in each other functions, right?? 2) How do I get a representation of a unic. object in terms of Unicode code points? repr() doesn't do that, it sometimes parses or encodes the code points right: >>> s=u"\u0040\u0166\u00e6" >>> s u'@\u0166\xe6' (does this latter \xe6 have to do with the internal representation of unic. objects, maybe with this UCS-2 encoding?) Thanks in advance! - Kees From iainking at gmail.com Fri Jun 2 04:10:36 2006 From: iainking at gmail.com (Iain King) Date: 2 Jun 2006 01:10:36 -0700 Subject: Trying to get FreeImagePy to work. In-Reply-To: <1149192520.959302.250840@j55g2000cwa.googlegroups.com> References: <1148651668.578852.3160@i40g2000cwc.googlegroups.com> <7fEdg.13375$cX1.201311@twister2.libero.it> <1148655611.990937.322350@j73g2000cwa.googlegroups.com> <1149166096.176405.22780@i40g2000cwc.googlegroups.com> <3PCfg.20835$cX1.315781@twister2.libero.it> <1149174938.337973.85950@g10g2000cwb.googlegroups.com> <1149192520.959302.250840@j55g2000cwa.googlegroups.com> Message-ID: <1149235836.646855.164110@i40g2000cwc.googlegroups.com> Iain King wrote: > Michele Petrazzo wrote: > > Iain King wrote: > > > However, when I'm do the > > > fipy.convertToPil(), it inverts the image? > > > > No, it not invert the image... It only return the image as is. > > > > > I've inserted a > > > fipy.invert() before the conversion as a temporary fix, but is there a > > > reason for this? > > > > If you are have a min-is-white image (fax ?) that isn't the standard, > > you will have an "inverted" image, because PIl expect a min-is-black > > image! > > > > > This is probably what is happening. I'll upload one of the images > tomorrow, and you can check it out to make sure. > > > > > relevant code: > > > > > > def getHeaders(files): > > > thumbs = [] > > > for f in files: > > > print "Adding %s" % f > > > fi = FIPY.Image(f) > > > fi.setCurrentPage(0) > > > fi.invert() #temp fix > > > thumb = fi.convertToPil() > > > thumb.thumbnail(THUMBNAIL_SIZE, Image.ANTIALIAS) > > > thumbs.append((os.path.basename(f), pilToBitmap(thumb))) > > > thumbs.sort() > > > return thumbs > > > > Just a question, why "thumbs.sort" ? Inside this list you have only > > images! > > Ah, look closer! It's a list of tuples: (filename, image) > I'll try out FIPY's resizing tomorrow too. OTOH, I have functions to > convert between PIL and wxPython, and functions to convert betweem PIL > and FIPY, but I don't see a function to convert FIPY to wxPython? > Image at: http://www.snakebomb.com/misc/example.tif Iain From zach_RemoveMe at in.tu-clausthal.de Mon Jun 12 05:03:47 2006 From: zach_RemoveMe at in.tu-clausthal.de (Gabriel Zachmann) Date: Mon, 12 Jun 2006 11:03:47 +0200 Subject: urllib behaves strangely Message-ID: Here is a very simple Python script utilizing urllib: import urllib url = "http://commons.wikimedia.org/wiki/Commons:Featured_pictures/chronological" print url print file = urllib.urlopen( url ) mime = file.info() print mime print file.read() print file.geturl() However, when i ecexute it, i get an html error ("access denied"). On the one hand, the funny thing though is that i can view the page fine in my browser, and i can download it fine using curl. On the other hand, it must have something to do with the URL because urllib works fine with any other URL i have tried ... Any ideas? I would appreciate very much any hints or suggestions. Best regards, Gabriel. -- /-----------------------------------------------------------------------\ | If you know exactly what you will do -- | | why would you want to do it? | | (Picasso) | \-----------------------------------------------------------------------/ From onurb at xiludom.gro Fri Jun 2 05:40:21 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 02 Jun 2006 11:40:21 +0200 Subject: Inheritance structure less important in dynamic languages? In-Reply-To: <447f95dc$0$1167$ba620e4c@news.skynet.be> References: <447f95dc$0$1167$ba620e4c@news.skynet.be> Message-ID: <448007f9$0$20891$626a54ce@news.free.fr> Marvin wrote: > Hi, > > It's been claimed s/claimed/observed/ In Python and Ruby, class hierarchies tends to be *really* flat when compared to Java or C++. > that inheritance structures are less important in dynamic > languages like Python. Why is that Don't you guess ?-) A very obvious point is that in a dynamically typed language, inheritence is only about implementation - it's not used for class-based polymorphism (subtyping). Also, dynamic languages are usually very strong on introspection and offer good support for automatic delegation ("DoesNotUnderstand" in Smalltalk, __getattr__ in Python, etc), which tend to lower the use of inheritence for "private inheritence" (ie: implementation reuse without any subtyping semantic). This leaves with only three real use-case for inheritence : * factoring common features of a set of related classes in an abstract base class * specialisation of an existing class (proper subclassing), * mixins. > and where can i read more about that? "duck typing", "implied interface" and "composition/delegation" could be good starting points for a google search. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From bruce.azais at cpam-alencon.cnamts.fr Fri Jun 23 09:35:15 2006 From: bruce.azais at cpam-alencon.cnamts.fr (AZAIS Bruce) Date: Fri, 23 Jun 2006 15:35:15 +0200 Subject: hard to explain for a french ;-) Message-ID: <007b01c696c9$dc8c1a40$33067a37@d11610100.cpamalencon.cnamts.fr> hi everybody, i have a problem with a script. after a research with my directory, i want to do a popup of a person's photo but i don't know the syntax (i'm a newbie) : with a javascript : Popup don't work with the function window.open : Popup don't work i try that : it's good but, it's open the photo in a large window, not in a popup. do you understand my problem ? (it's not easy to explain that in english for me) thank you for all and have a good day. Bruce ***************************************************** "Le contenu de ce courriel et ses eventuelles pi?ces jointes sont confidentiels. Ils s'adressent exclusivement ? la personne destinataire. Si cet envoi ne vous est pas destin?, ou si vous l'avez re?u par erreur, et afin de ne pas violer le secret des correspondances, vous ne devez pas le transmettre ? d'autres personnes ni le reproduire. Merci de le renvoyer ? l'?metteur et de le d?truire. Attention : L'Organisme de l'?metteur du message ne pourra ?tre tenu responsable de l'alt?ration du pr?sent courriel. Il appartient au destinataire de v?rifier que les messages et pi?ces jointes re?us ne contiennent pas de virus. Les opinions contenues dans ce courriel et ses ?ventuelles pi?ces jointes sont celles de l'?metteur. Elles ne refl?tent pas la position de l'Organisme sauf s'il en est dispos? autrement dans le pr?sent courriel." ****************************************************** -------------- next part -------------- An HTML attachment was scrubbed... URL: From michele.petrazzo at TOGLIunipex.it Fri Jun 30 10:02:37 2006 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Fri, 30 Jun 2006 14:02:37 GMT Subject: string replace Message-ID: <1aapg.21924$_J1.275201@twister2.libero.it> Hi, a lot of times I need to replace more than one char into a string, so I have to do something like value = "test" chars = "e" for c in chars: value = value.replace(c, "") A solution could be that "replace" accept a tuple/list of chars, like that was add into the new 2.5 for startswith. I don't know, but can be this feature included into a future python release? Thanks, Michele From certo at comeno.it Mon Jun 19 10:50:31 2006 From: certo at comeno.it (imho) Date: Mon, 19 Jun 2006 14:50:31 GMT Subject: mapping None values to '' In-Reply-To: References: <1150632320.443681.42640@r2g2000cwb.googlegroups.com> <0Rblg.5940$zy5.141663@twister1.libero.it> Message-ID: Roberto Bonvallet ha scritto: > imho : >> map(lambda x:"" , [i for i in [a,b,c] if i in ("None",None) ]) > > You don't need map when using list comprehensions: > > ["" for i in [a, b, c] if i in ("None", None)] > I know that... I tried to match the idiom used by the o.p. :-) From torbenm at app-3.diku.dk Wed Jun 21 05:23:18 2006 From: torbenm at app-3.diku.dk (=?iso-8859-1?q?Torben_=C6gidius_Mogensen?=) Date: 21 Jun 2006 11:23:18 +0200 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <1150809118.677124.142230@u72g2000cwu.googlegroups.com> <1150815461.210286.53120@r2g2000cwb.googlegroups.com> <1150823297.816352.75370@u72g2000cwu.googlegroups.com> Message-ID: <7zzmg6amm1.fsf@app-3.diku.dk> "Rob Thorpe" writes: > Andreas Rossberg wrote: > > > No, variables are insignificant in this context. You can consider a > > language without variables at all (such languages exist, and they can > > even be Turing-complete) and still have evaluation, values, and a > > non-trivial type system. > > Hmm. You're right, ML is no-where in my definition since it has no > variables. That's not true. ML has variables in the mathematical sense of variables -- symbols that can be associated with different values at different times. What it doesn't have is mutable variables (though it can get the effect of those by having variables be immutable references to mutable memory locations). What Andreas was alluding to was presumably FP-style languages where functions or relations are built by composing functions or relations without ever naming values. Torben From solisgb at gmail.com Fri Jun 30 08:39:23 2006 From: solisgb at gmail.com (luis) Date: 30 Jun 2006 05:39:23 -0700 Subject: conecting with a MsAcces DB by dao In-Reply-To: <1151665145.582514.262970@75g2000cwc.googlegroups.com> References: <1151650208.783778.186690@d56g2000cwd.googlegroups.com> <1151655436.083906.143380@75g2000cwc.googlegroups.com> <1151663549.731904.259030@d56g2000cwd.googlegroups.com> <1151665145.582514.262970@75g2000cwc.googlegroups.com> Message-ID: <1151671163.810358.215630@d56g2000cwd.googlegroups.com> Iain King ha escrito: > luis wrote: > > Iain King ha escrito: > > > > > luis wrote: > > > > while not rs.EOF: > > > > id=rs.Fields(colName.Value) #colName, valid column name > > > > ... > > > > rs.MoveNext() > > > > rs.Close() > > > > conn.Close() > > > > > > I don't know if it's the problem your asking about, but your > > > rs.MoveNext() should be inside the while loop, no? > > Yes, is inside > > > > > You mean, it is inside the while loop in your code, but you made a > mistake copying it into your post? In the code you posted it is not > inside the while loop - it would have to be indented one more level for > that. > > Iain this is te correct identation def append_from_Access(self): try: import ... conn = win32com.client.Dispatch(r'ADODB.Connection') DSN = "PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=C:/Afile.mdb;" conn.Open(DSN) except Exception, inst: ... try: sql_statement='SELECT * FROM Mytable' rs = win32com.client.Dispatch(r'ADODB.Recordset') rs.Open(sql_statement, conn, 1, 3) while not rs.EOF: id=rs.Fields(colName.Value) #colName, valid column name ... rs.MoveNext() rs.Close() conn.Close() except Exception, inst: ... I think my problem must be with ado and dao. Now I have run makepy utility and select Microsoft ActiveX Data Objects 2.5 Library, perhaps I must also select Microsoft DAO3.5 Object Library and write win32com.client.Dispatch("DAO.DBEngine.35") for Access 97 or win32com.client.Dispatch(r'ADODB.Connection') for Acess 2000 Do you know is it possible ? luis From cdsmith at twu.net Fri Jun 23 11:19:51 2006 From: cdsmith at twu.net (Chris Smith) Date: Fri, 23 Jun 2006 09:19:51 -0600 Subject: Saying "latently-typed language" is making a category mistake References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <86Qmg.10725$o4.1907@newsread2.news.pas.earthlink.net> Message-ID: Patricia Shanahan wrote: > Vesa Karvonen wrote: > ... > > An example of a form of informal reasoning that (practically) every > > programmer does daily is termination analysis. There are type systems > > that guarantee termination, but I think that is fair to say that it is not > > yet understood how to make a practical general purpose language, whose > > type system would guarantee termination (or at least I'm not aware of such > > a language). It should also be clear that termination analysis need not > > be done informally. Given a program, it may be possible to formally prove > > that it terminates. > > To make the halting problem decidable one would have to do one of two > things: Depend on memory size limits, or have a language that really is > less expressive, at a very deep level, than any of the languages > mentioned in the newsgroups header for this message. Patricia, perhaps I'm misunderstanding you here. To make the halting problem decidable is quite a different thing than to say "given a program, I may be able to prove that it terminates" (so long as you also acknowledge the implicit other possibility: I also may not be able to prove it in any finite bounded amount of time, even if it does terminate!) The fact that the halting problem is undecidable is not a sufficient reason to reject the kind of analysis that is performed by programmers to convince themselves that their programs are guaranteed to terminate. Indeed, proofs that algorithms are guaranteed to terminate even in pathological cases are quite common. Indeed, every assignment of a worst-case time bound to an algorithm is also a proof of termination. This is, of course, a very good reason to reject the idea that the static type system for any Turing-complete language could ever perform this same kind analysis. -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation From timr at probo.com Mon Jun 19 23:59:12 2006 From: timr at probo.com (Tim Roberts) Date: Tue, 20 Jun 2006 03:59:12 GMT Subject: USB support References: <1150222139.721785.268830@f14g2000cwb.googlegroups.com> <1150664445.317749.305880@u72g2000cwu.googlegroups.com> Message-ID: "rodmc" wrote: > >Thanks for this, I have managed to build PyUSB and install it in the >relevant directory. However I get bus errors when I try the PlugUSB.py >example. Does anyone know why this is likely to be the case? > >I am using Macpython 2.4, Libusb 0.1.12 and PyUSB 0.3.3 on an Intel >based mac. It is my understanding that OS/X does not support the /proc filesystem. Without /proc, libusb cannot operate. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From fredrik at pythonware.com Tue Jun 20 03:15:41 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 20 Jun 2006 09:15:41 +0200 Subject: code is data References: <1150574111.415068.255900@p79g2000cwp.googlegroups.com><1150606118.456390.262620@y41g2000cwy.googlegroups.com><1150626424.563673.175060@c74g2000cwc.googlegroups.com><1150650852.275956.249340@p79g2000cwp.googlegroups.com><1150658597.272001.171840@r2g2000cwb.googlegroups.com><1150772934.314520.165200@p79g2000cwp.googlegroups.com> <1150779608.479611.44120@g10g2000cwb.googlegroups.com> Message-ID: Kay Schluehr wrote: > If it is just a different kind of representation of common data > structures but how do you know ? From rune.strand at gmail.com Mon Jun 26 13:45:50 2006 From: rune.strand at gmail.com (Rune Strand) Date: 26 Jun 2006 10:45:50 -0700 Subject: Beginner Programmer Question In-Reply-To: <1151343759.716134.169950@c74g2000cwc.googlegroups.com> References: <1151342733.742416.180370@r2g2000cwb.googlegroups.com> <1151343383.139891.219270@u72g2000cwu.googlegroups.com> <1151343641.509435.245210@u72g2000cwu.googlegroups.com> <1151343759.716134.169950@c74g2000cwc.googlegroups.com> Message-ID: <1151343949.958134.257960@b68g2000cwa.googlegroups.com> kydavis77 at gmail.com wrote: > Rune Strand wrote: > > > > > > I am doing alot of reading, and the problem didnt come with an answer. > > > I dont understand how to get it to continually input numbers and add > > > all those together > > > > Use while, raw_input, sys.argv[1] and int() and break the loop when the > > sum is above 100. > > > > ;-) > > thanks for the help..but i am extremley new and what you said makes no > sense to me In the code you posted above here: Move the input into the while loop. You may prefer raw_input() to input(). I don't want to write the code for you ;-) From fredrik at pythonware.com Thu Jun 22 17:48:35 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 22 Jun 2006 23:48:35 +0200 Subject: Is Queue.Queue.queue.clear() thread-safe? In-Reply-To: <1f7befae0606221440p619c9865y66e4b404fcd142c1@mail.gmail.com> References: <1151008374.303940.251300@c74g2000cwc.googlegroups.com> <1f7befae0606221440p619c9865y66e4b404fcd142c1@mail.gmail.com> Message-ID: Tim Peters wrote: >> I'm guessing no, since it skips down through any Lock semantics, > > Good guess :-) It's also unsafe because some internal conditions must > be notified whenever the queue becomes empty (else you risk deadlock). "also" ? if it weren't for the other things, the clear() call itself would have been atomic enough, right ? From duncan.booth at invalid.invalid Fri Jun 23 10:12:27 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 23 Jun 2006 14:12:27 GMT Subject: * in Python References: <1151061836.557835.295820@p79g2000cwp.googlegroups.com> <1151065046.668902.23010@g10g2000cwb.googlegroups.com> <449beca5$0$13891$626a54ce@news.free.fr> Message-ID: Bruno Desthuilliers wrote: >> so * basically means that args is a list > > A tuple IIRC In a function definition * means that any remaining position arguments will be passed in as a tuple. In a function call the * means that any sequence will be unpacked as positional arguments: it doesn't have to be a list or a tuple. From oliver at first.in-berlin.de Sun Jun 25 18:54:04 2006 From: oliver at first.in-berlin.de (Oliver Bandel) Date: Mon, 26 Jun 2006 00:54:04 +0200 Subject: languages with full unicode support In-Reply-To: <1151251736.590910.36050@u72g2000cwu.googlegroups.com> References: <1151251736.590910.36050@u72g2000cwu.googlegroups.com> Message-ID: <1151276031.641318@elch.in-berlin.de> ????? Xah-Lee san ;-) Xah Lee wrote: > Languages with Full Unicode Support > > As far as i know, Java and JavaScript are languages with full, complete > unicode support. That is, they allow names to be defined using unicode. Can you explain what you mena with the names here? > (the JavaScript engine used by FireFox support this) > > As far as i know, here's few other lang's status: > > C ? No. Well, is this (only) a language issue? On Plan-9 all things seem to be UTF-8 based, and when you use C for programming, I would think that C can handle this also. But I only have read some papers about Plan-9 and did not developed on it.... Only a try to have a different view on it. If someone knows more, please let us know :) Ciao, Oliver From siona at chiark.greenend.org.uk Wed Jun 28 06:46:32 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 28 Jun 2006 11:46:32 +0100 (BST) Subject: Immutability References: Message-ID: <4Qj*cEjkr@news.chiark.greenend.org.uk> Nick Maclaren wrote: >Georg Brandl writes: >|> [ attributions lost ] >|> > Thanks very much. And, what's more, I have even found its documentation! >|> > Whatsnew2.2. The 2.4.2 reference is, er, unhelpful. >|> Is it? >|> http://docs.python.org/lib/built-in-funcs.html >|> documents "property" quite well. >Sigh. No. It's terrible. What it documents is the use of the property >FUNCTION. It does not document what properties ARE, and how they interact >with the rest of the language. Until you know that, it is so ambiguous >as to be almost totally useless - and it is THAT information that needs to >be in the reference manual, but is only in whatsnew2.2. Actually, there's an almost throw-away mention in http://docs.python.org/ref/descriptor-invocation.html which gives you what you need (although not, I have to say, in an easily digestible form). What I've not seen documented anywhere is the: @property def fset(self, value): ... idiom. It's not obvious from the documentation of the property function that it can be used as a decorator like this. (cf. classmethod and staticmethod.) -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From artur_spruce at yahoo.com Thu Jun 29 04:41:18 2006 From: artur_spruce at yahoo.com (AdSR) Date: 29 Jun 2006 01:41:18 -0700 Subject: Amara: Where's my attribute? Message-ID: <1151570478.731909.154790@b68g2000cwa.googlegroups.com> Hi, I'm having a problem with the Amara toolkit. Try this: >>> from amara import binderytools >>> raw = '' >>> rwd = binderytools.bind_string(raw) >>> print rwd.xml() What happened to the xmlns attribute? Does anyone know a solution to this? The only workaround I found is to: >>> rwd.test.xml_set_attribute(u'xmlns', u'http://example.com/namespace') u'xmlns' >>> print rwd.xml() but it only helps if you know what to patch. My setup: Python 2.4.3 4Suite 1.0b3 Amara 1.0 I see that people have reported similar problems with other XML toolkits, so I guess this is a general namespace ugliness. Regards, AdSR From bencvt at gmail.com Sat Jun 10 01:22:59 2006 From: bencvt at gmail.com (Ben Cartwright) Date: 9 Jun 2006 22:22:59 -0700 Subject: __getattr__ question In-Reply-To: References: Message-ID: <1149916979.821376.208960@h76g2000cwa.googlegroups.com> Laszlo Nagy wrote: > So how can I tell if 'root.item3' COULD BE FOUND IN THE USUAL PLACES, or > if it is something that was calculated by __getattr__ ? > Of course technically, this is possible and I could give a horrible > method that tells this... > But is there an easy, reliable and thread safe way in the Python > language to give the answer? Why are you trying to do this in the first place? If you need to distinguish between a "real" attribute and something your code returns, you shouldn't mix them by defining __getattr__ to begin with. If, as I suspect, you just want an easy way of accessing child objects by name, why not rename "__getattr__" in your code to something like "get"? Then instead of >>> root.item3 Use >>> root.get('item3') Alternately, make self.items an instance of a custom class with __getattr__ defined. This way, root's attribute space won't be cluttered up. >>> root.items.item3 Either way is a few more characters to type, but it's far saner than trying to distinguish between "real" and "fake" attributes. --Ben From neuruss at gmail.com Mon Jun 5 08:18:13 2006 From: neuruss at gmail.com (Neuruss) Date: 5 Jun 2006 05:18:13 -0700 Subject: C# equivalent to range() In-Reply-To: References: <1149468919.951745.163700@g10g2000cwb.googlegroups.com> <1149481675.192638.275140@c74g2000cwc.googlegroups.com> Message-ID: <1149509893.031953.19310@i40g2000cwc.googlegroups.com> Erik Max Francis wrote: > > I'm curious, who are "us"? > > The regular readers of comp.lang.python. If you don't think we haven't > seen this a zillion times before, you're kidding yourself. > > If you want help on a language, ask in that language's newsgroup/mailing > list/forum/whatever. > > It surprises me how often people don't ask useful questions, or > deliberately and knowingly ask questions in the wrong places, and then > actually _defend_ their actions after they're politely but firmly > informed how to fix the problem. You're really not making yourself look > any better by continuing this thread ... Just to finish this thread: 1) It wasn't a blunt question. I started the post apologizing for the (not entirely) off opic question. 2) I wasn't politely informed. It was pretty harshly. 3) If you mean that "us" are the zillion registered users of this mailing list, well buddy, you know a whole lot of people! 4) At least one of these people replied kindly and correctly to my question within seconds. Three of four more spent several minutes whining. The other zilion persons who were not interested (other than the four I mentioned above) silently and peacefully ignored the question on went on with their happy lifes. ? bient?t, Neuruss From iainking at gmail.com Fri Jun 30 04:09:43 2006 From: iainking at gmail.com (Iain King) Date: 30 Jun 2006 01:09:43 -0700 Subject: String Question In-Reply-To: References: <1151508909.273667.270910@x69g2000cwx.googlegroups.com> <1151509682.897441.165480@y41g2000cwy.googlegroups.com> Message-ID: <1151654983.457647.246430@y41g2000cwy.googlegroups.com> Tim Roberts wrote: > "Iain King" wrote: > > > >You probably want: > > > >s.sendto('\xff'*6 + ('\x%s\x%s\x%s\x%s\x%s\x%s' % (str01, str02, str03, > > sttr04, str05, str06))*16, ('192.168.1.255', 80)) > > You probably should TRY suggestions before you post them. That will get an > "invalid \x escape". \x must be followed by exactly two hex digits. You > can't build up an escape sequence like this. > -- > - Tim Roberts, timr at probo.com > Providenza & Boekelheide, Inc. You're right. I'd foolishly assumed that \x was just another character code, like \t or \n. Apologies. Iain From marco.wahl at gmail.com Wed Jun 28 01:37:01 2006 From: marco.wahl at gmail.com (Marco Wahl) Date: 27 Jun 2006 22:37:01 -0700 Subject: global name is not defined - error Message-ID: <1151473021.756133.173350@d56g2000cwd.googlegroups.com> "a" writes: > What I want > --------------- > I want to create a list of items from a function operating on an array > of strings Ok. > What I did > ----------------- > list=["s0","s1","s2"] > l=len(list) > for i in range(l): > d_list[i]=f.do(list[i]) > print d_list[i] Aha! > Error: > ------ > global name 'd_list' is not defined > Python c:\test.py in newClass, line 30 Just as the error message tells: 'd_list' is not defined which is an error. Try list=["s0","s1","s2"] d_list = [] l=len(list) for i in range(l): # d_list[i]=f.do(list[i]) d_list.append(f.do(list[i])) print d_list[i] This is just one suggestion there may be more elegant ways. Have you heard about list comprehension? HTH From chris.uppal at metagnostic.REMOVE-THIS.org Fri Jun 23 12:10:17 2006 From: chris.uppal at metagnostic.REMOVE-THIS.org (Chris Uppal) Date: Fri, 23 Jun 2006 17:10:17 +0100 Subject: Saying "latently-typed language" is making a category mistake References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <86Qmg.10725$o4.1907@newsread2.news.pas.earthlink.net> <4g251pF1knc6tU1@individual.net> <4g28s6F1k9npnU1@individual.net> <4g2e1bF1kmiteU1@individual.net> Message-ID: <449c1f4c$0$662$bed64819@news.gradwell.net> Pascal Costanza wrote: > Sorry, obviously I was far from being clear. ACL2 is not > Turing-complete. All iterations must be expressed in terms of > well-founded recursion. How expressive does that end up being for real problems ? I mean obviously in some sense it's crippling, but how much of a restiction would that be for non-accademic programming. Could I write an accountancy package in it, or an adventure games, or a webserver, with not too much more difficulty than in a similar language without that one aspect to its type system ? Hmm, come to think of it those all hae endless loops at the outer level, with the body of the loop being an event handler, so maybe only the handler should be required to guaranteed to terminate. -- chris From aisaac0 at verizon.net Fri Jun 30 23:42:42 2006 From: aisaac0 at verizon.net (David Isaac) Date: Sat, 01 Jul 2006 03:42:42 GMT Subject: property __doc__ Message-ID: To access the doc string of a property, I have to use the class not an instance. Why? Thanks, Alan Isaac From scott.daniels at acm.org Mon Jun 5 19:36:34 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Mon, 05 Jun 2006 16:36:34 -0700 Subject: C# equivalent to range() In-Reply-To: <1149546849.406638.83870@i39g2000cwa.googlegroups.com> References: <1149468919.951745.163700@g10g2000cwb.googlegroups.com> <1149481675.192638.275140@c74g2000cwc.googlegroups.com> <1149509893.031953.19310@i40g2000cwc.googlegroups.com> <1149545140.011616.130610@y43g2000cwc.googlegroups.com> <1149546849.406638.83870@i39g2000cwa.googlegroups.com> Message-ID: <4484bb7d$1@nntp0.pdx.net> Luis M. Gonz?lez wrote: > Fuzzyman wrote: >> FWIW I agree. If anyone didn't want to answer the question they didn't >> need to. >> >> Why be rude to someone asking a polite question. It's not as if there >> isn't much more *worse* noise on this group. > > The poster asked the question very politely, apologizing in advance for > what may be consider an off-topyc question. Beginning a post by demonstrating that you know you are violating the conventions of the group is _in_and_of_itself_ rude, and hence even the first post was not a polite question. If this were not true, then all manner of spam would be polite. --Scott David Daniels scott.daniels at acm.org From alanalan at newsgroup.nospam Thu Jun 1 09:20:09 2006 From: alanalan at newsgroup.nospam (A.M) Date: Thu, 1 Jun 2006 09:20:09 -0400 Subject: DB-API: how can I find the column names in a cursor? References: Message-ID: Thank you Fredrik for help. Would you be able to help with the second part of question: The other problem is accessing data in each row by column name. In Ruby I can say: Print row["ColName"] In Python; however, I must access to row contents by integer index, like PRINT ROW[0], which reduces my program's readability. Can I access to row's contents by column name? Thanks again, Alan "Fredrik Lundh" wrote in message news:mailman.6403.1149166487.27775.python-list at python.org... > "A.M" wrote: > >> The problem is I don't know how to find out what are the column name and >> type that comes out of query (each row in cursor). >> >> Is there any possibility that my Python code can find out the column name >> and type in each row in cursor? > >>From "cursor objects" in the DB-API documentation: > > .description > > "This read-only attribute is a sequence of 7-item > sequences. Each of these sequences contains information > describing one result column: (name, type_code, > display_size, internal_size, precision, scale, > null_ok). The first two items (name and type_code) are > mandatory, the other five are optional and must be set to > None if meaningfull values are not provided." > > The full spec is available here: http://www.python.org/dev/peps/pep-0249/ > > > > From ldanielburr at mac.com Tue Jun 6 16:27:03 2006 From: ldanielburr at mac.com (amberite) Date: 6 Jun 2006 13:27:03 -0700 Subject: how not to run out of memory in cursor.execute References: <1149447895.037396.81550@j55g2000cwa.googlegroups.com> <1149531057.098045.322960@c74g2000cwc.googlegroups.com> Message-ID: <1149625623.086956.243950@u72g2000cwu.googlegroups.com> Steve Holden wrote: > > The MySQLdb solution you give is way more complicated than it needs to > be, thereby skewing your opinion towards cx_Oracle unnecessarily. > I respectfully disagree with your assertion here. The code I presented for MySQLdb is what you *have* to do, to avoid using up too much memory. This thread is about how to avoid running out of memory when handling large resultsets, and the approach I outlined is really the only way to do that with MySQLdb's DBAPI support. > Look up the .fetchmany() method of cursors in the DB API. There is only > any need to execute a single query no matter how large the result set: > you simply need to keep calling .fetchmany(N) (where N is whatever > you've decided by testing is your optimum chunk size) until it returns > less than N rows, at which point you have exhausted the query. > .fetchmany() buys you nothing in the case of large resultsets. The memory usage will continue to climb with each call to fetchmany. This isn't the fault of MySQLdb, it is just that MySQL doesn't support cursors, so MySQLdb has to fake it. > It's very little more effort to wrap this all up as a generator that > effectively allows you to use the same solution as you quote for cx_Oracle. > Again, I respectfully disagree. Your proposed solution, while resulting in shorter code, will continue to eat memory until the entire resultset has been delivered. L. Daniel Burr From gandalf at designaproduct.biz Fri Jun 9 14:47:17 2006 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Fri, 09 Jun 2006 20:47:17 +0200 Subject: TypeError: unsubscriptable object In-Reply-To: <1149878331.500752.8170@j55g2000cwa.googlegroups.com> References: <1149874726.470436.279200@i40g2000cwc.googlegroups.com> <1149878331.500752.8170@j55g2000cwa.googlegroups.com> Message-ID: <4489C235.60506@designaproduct.biz> k.retheesh at gmail.com ?rta: > So wat should I do ?? > You should do this: print type(Function),type(Description) raise SystemExit Instead of this: print template % (ID, IID, Function[:10], Description[:10],ErrorNumber, StatusCD) Then probably you will see: instead of or something similar. (Of course in your case, it can be 'float instead of list' or 'dictionary instead of tuple' etc.) Then you should debug your program and find out why the 'Function' and 'Description' objects are not string but int. Laszlo From ken.carlino at gmail.com Thu Jun 8 22:32:24 2006 From: ken.carlino at gmail.com (ken.carlino at gmail.com) Date: 8 Jun 2006 19:32:24 -0700 Subject: Exeucte a system command in python script In-Reply-To: References: <1149815748.856808.200140@j55g2000cwa.googlegroups.com> Message-ID: <1149820344.244437.120220@g10g2000cwb.googlegroups.com> Thanks I get this error 'NameError: global name 'call' is not defined" I already import 'subprocess'. Can you pleaes tell me what am I missing? Robert Kern wrote: > ken.carlino at gmail.com wrote: > > Hi, > > > > I would like to execute a shell command like this in python: > > cmd = 'ant release -Dbuild=build_proxyonly -Drev=5.1.130f > > -Dprops=\"-MIDP20_LARGE;PUSH_FEATURE=false;MIDlet-Version=5.0;version=5.0;MIDlet-Icon=midicon15x15.png;-FOUR_WAY_NAV_FEATURE\" > > -DThree_Branding=true' > > > > Which of the execl command described here should I use? > > http://pydoc.org/1.6/os.html > > None. You should use the subprocess module in 2.4 (I really do hope that you're > not using 1.6). > > http://docs.python.org/lib/module-subprocess.html > > It also works in Pythons as old as 2.2, but you'll have to install it > separately. The website for the separate release is down at the moment, but when > it comes back up: > > http://www.lysator.liu.se/~astrand/popen5/ > > -- > 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 From remi at cherrypy.org Wed Jun 21 18:22:55 2006 From: remi at cherrypy.org (remi at cherrypy.org) Date: 21 Jun 2006 15:22:55 -0700 Subject: ANN (Screencast): Using python at WebFaction Message-ID: <1150928575.433641.149900@g10g2000cwb.googlegroups.com> Hello everyone, WebFaction (formerly Python-Hosting.com) have just released a screencast demo of their control panel. The 6 minute demo shows how you can setup some sites in a few clicks, using a variety of applications (including some Python ones such as Django and TurboGears). The one-click installer already supports all major tools, including Rails, WordPress, Django, TurboGears, Plone, Trac and Subversion, but also lightweight tools such as static HTML, CGI or PHP. The demo is available at: http://blog.webfaction.com/control-panel-demo Remi. http://www.webfaction.com - Hosting for an agile web From duncan.booth at invalid.invalid Mon Jun 26 06:01:37 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 26 Jun 2006 10:01:37 GMT Subject: style question References: Message-ID: Hari Sekhon wrote: > Since the first method does not follow python's clean and easy looking > indentation structure but the second just looks crude and ugly anyway. If you want indented and pretty is important to you: >>> from textwrap import dedent as D >>> message = D("""\ This is line1. This is line2 This is line3 """) >>> message 'This is line1.\nThis is line2\nThis is line3\n' Usually though I would just make sure that long strings are declared at module level and not indent them. The backslash after the opening quotes stops the first line being indented differently: message = """\ This is line1. This is line2 This is line3 """ From fredrik at pythonware.com Thu Jun 15 18:02:07 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 16 Jun 2006 00:02:07 +0200 Subject: Which compiler will Python 2.5 / Windows (Intel) be built with? In-Reply-To: References: <1150367139.495114.148550@g10g2000cwb.googlegroups.com> <44917535$1@nntp0.pdx.net> <1150391891.130185.4640@f6g2000cwb.googlegroups.com> <4491b9e1$1@nntp0.pdx.net> <1150406005.948538.188950@h76g2000cwa.googlegroups.com> Message-ID: Sybren Stuvel wrote: > Well, it's simply not true. I switched to Cygwin Python because then I > could use gcc to compile my extensions. and you're shipping extensions that works with a stock Python distribution ? or are we playing the "but if we ignore the context, a literal interpretation of your last sentence" game, again ? boring. From chris at kateandchris.net Tue Jun 20 11:49:43 2006 From: chris at kateandchris.net (Chris Lambacher) Date: Tue, 20 Jun 2006 11:49:43 -0400 Subject: Problem on win xp and run time error In-Reply-To: References: Message-ID: <20060620154918.GA6588@kateandchris.net> On Sat, Jun 17, 2006 at 07:32:34AM +0000, Michele Petrazzo wrote: > Chris Lambacher wrote: > > On Fri, Jun 16, 2006 at 06:11:53PM +0000, Michele Petrazzo wrote: > >> Hi list, just found in this moment that my applications stop to > >> work with win xp and receive this error: > >> > >> """ This application has requested the Runtime to terminate it in > >> an unusual way. Please contact the application's support team for > >> more information. """ > >> > >> (Note that the same application [python source code + py2exe] with > >> python 2.3.x work well!) > > Don't use the single file executatble option with py2exe and the > > problem will go away. > > > > I'm not using that option! (that has also problems on win9x with python+wx) Do you get the problem when you are not using py2exe? That will be your real clue about what the culprit is. > I'm not using any of the "bundle_files" options, but only: > zipfile = "lib/libraries.zip" Try setting that to the default value for the moment and see if it gets you anywhere. You might also want to try an older version of py2exe. I would blame an interaction between py2exe and some extension you are using, unless you can get it to happen without py2exe. From cfc at shell01.TheWorld.com Tue Jun 27 00:43:47 2006 From: cfc at shell01.TheWorld.com (Chris F Clark) Date: 27 Jun 2006 00:43:47 -0400 Subject: What is Expressiveness in a Computer Language References: <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <1151368443.491445.294480@p79g2000cwp.googlegroups.com> Message-ID: "Greg Buchholz" writes: > Chris F Clark wrote: > > Thus, as we traverse a list, the first element might be an integer, > > the second a floating point value, the third a sub-list, the fourth > > and fifth, two more integers, and so on. If you look statically at > > the head of the list, we have a very wide union of types going by. > > However, perhaps there is a mapping going on that can be discerned. > > For example, perhaps the list has 3 distinct types of elements > > (integers, floating points, and sub-lists) and it circles through the > > types in the order, first having one of each type, then two of each > > type, then four of each type, then eight, and so on. > > Sounds like an interesting problem. Although not the exact type > specified above, here's something pretty similar that I could think of > implementing in Haskell. (I don't know what a "sub-list" is, for > example). Maybe some Haskell wizard could get rid of the tuples? > > > data Clark a b c = Nil | Cons a (Clark b c (a,a)) deriving Show > > clark = (Cons 42 (Cons 3.14 (Cons "abc" > (Cons (1,2) (Cons (1.2,3.4) (Cons ("foo","bar") > (Cons ((9,8),(7,6)) (Cons ((0.1,0.2),(0.3,0.4)) Nil)))))))) > > main = print clark Very impressive. It looks right to me and simple enough to understand. I must find the time to learn a modern FP language. Can you write a fold for this that prints the data as a binary tree of triples? I have to believe it isn't that hard.... -Chris From ilitzroth at gmail.com Thu Jun 22 05:12:23 2006 From: ilitzroth at gmail.com (ilitzroth at gmail.com) Date: 22 Jun 2006 02:12:23 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: <4fv081F1jh4ifU1@individual.net> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150902275.129780.50260@p79g2000cwp.googlegroups.com> <1150918629.818145.143220@y41g2000cwy.googlegroups.com> <4fv081F1jh4ifU1@individual.net> Message-ID: <1150967543.947096.72840@g10g2000cwb.googlegroups.com> > A statically type language requires you to think about two models of > your program at the same time: the static type model and the dynamic > behavioral model. A static type system ensures that these two > _different_ (that's important!) perspectives are always in sync. I have trouble understanding your use of the wording "Model of a program". If it is a system that behaves according to the rules of your program then statements about your program should consider *all* possible models. If it is a formal system that makes statements about properties of your program than the static type system is a simplified model that is suitable for automatic analysis and your runtime model is in most cases nonexistent. Can you give a definition of a "model of a program"? Can you explain why Lisp doesn't have two (SBCL does do a lot of typechecking and gives type errors)? > This is > especially valuable in settings where you know your domain well and want > to rely on feedback by your compiler that you haven't made any mistakes > in encoding your knowledge. (A static type system based on type > inferencing doesn't essentially change the requirement to think in two > models at the same time.) It is also valuable when you don't know your domain very well and you want to rely on feedback by your compiler that you haven't made any mistakes in encoding your limited knowledge > A dynamically typed language is especially well suited when you don't > (yet) have a good idea about your domain and you want to use programming > especially to explore that domain. our domain). In the sense that you can start writing code without the compiler pointing out all but the most glaring holes in your program, I agree. Most of your arguments aren't very convincing and the thruth is that I have seem lisp programmers using the debugger to find out that you can't add a number and a hastable. The static view was not there and the dynamic view must have been too complicated so they had nothing to think about. Immanuel From jstroud at ucla.edu Mon Jun 5 17:54:37 2006 From: jstroud at ucla.edu (James Stroud) Date: Mon, 05 Jun 2006 14:54:37 -0700 Subject: Little question about Tkiner: window focus In-Reply-To: References: Message-ID: Bernard Lebel wrote: > Hello, > > I have this Tkinter window that when you click on a certain button, > another instance of Tk is created, and thus a new windows is spawned. > That second windows holds a few widgets to browse files and > directories. > > Now, as soon as I start browsing files and directories, the first > window comes back in focus. I have to click the second window to put > the focus back there. > > My question is: is there a way to force the focus of a given Tk > instance? I'm using the Toplevel widget to create those second > windows. I have looked into the "takefocus" option, but doesn't seem > to have any effect. > > I'm using Python 2.4 on Windows XP Pro SP1. > > > Thanks > Bernard You should post a code snippet so we can see if there is anything amiss. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From robert.kern at gmail.com Wed Jun 21 14:43:28 2006 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 21 Jun 2006 13:43:28 -0500 Subject: Initializing a set from a list In-Reply-To: <1150873971.810396.214000@u72g2000cwu.googlegroups.com> References: <1150869540.796459.202330@u72g2000cwu.googlegroups.com> <1150871908.281225.61880@u72g2000cwu.googlegroups.com> <1150873971.810396.214000@u72g2000cwu.googlegroups.com> Message-ID: Xiaolei wrote: > Sybren Stuvel wrote: > >>Xiaolei enlightened us with: >> >>>from pylab import * >> >>You'd better not do that. Just use "import pylab". >> >>>If I remove the first line, I correctly get: >>> >>>[1, 2, 3, 3] >>> >>>set([1, 2, 3]) >> >>Pylab shadows the built-in set name, which is one of the reasons you >>should generally use "import XXX" instead of "from XXX import *". > > Ahh. Understood. Thank you very much. It should be noted that recent versions of matplotlib's pylab module have changed that function to setp() in order to avoid this problem. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From deets at nospam.web.de Thu Jun 8 08:18:02 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 08 Jun 2006 14:18:02 +0200 Subject: Terminateable thread References: Message-ID: <4eqis5F1fnu15U1@uni-berlin.de> Laszlo Nagy wrote: > > I wote a TThread class that is 'soft terminateable'. For example: > > class MyProcessor(TThread): > def run(self): > while not self.terminated(): > self.process_one_item() > > > My question is that, do I really need to use events for this? Because of > the GIL, assignments are atomic. Is it okay to use a simple > '_terminated' attribute instead of the Event object (see below)? It > would be much better to use a simple 'mythread.terminated' attribute > instead of 'mythread.terminated()' and 'mythread.terminated=True' > instead of 'mythread.terminate()'. I do that all the time - just a simple boolean set on the instance. So far, it served me well. However, a recent discussion involving Alex Martelli [1] saying that """ You have misread the Python Language Reference -- if you can give the URL on which you have read any such promise of atomicity, I will be glad to fix the docs to make that unambiguous. There is no such promise (there may be implementation accidents in some specific implementation which happen to make some operation atomic, but NO guarantee even there that the next bugfix won't break that). """ your implementation might be the better solution. Diez [1] : http://groups.google.com/group/comp.lang.python/browse_frm/thread/bf5461507803975e/3008575be66f99c1?lnk=st&q=alex+martelli+python+GIL&rnum=2#3008575be66f99c1 From deets at nospam.web.de Wed Jun 7 07:47:06 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 07 Jun 2006 13:47:06 +0200 Subject: Python language problem References: <1149678146.681370.5130@c74g2000cwc.googlegroups.com> <1149680274.133008.167140@c74g2000cwc.googlegroups.com> Message-ID: <4enslsF1f4aohU1@uni-berlin.de> > > Thanks for your so detailed explain, I think I know you, But my Engish > is not enough > to explain. > > I create same object in Tree, I want to update Tree, when I need to > delete subtree. > If where no references, I can't do that. some thing like blow: > for i in list: > del i This makes no sense. In python, objects are garbage collected when there are no references to the anymore. What you do is - create a reference to an object by letting i point to it - remove i, such that the reference is removed. This has no effect at all -- 1 - 1 = 0 If you want to remove items from a list, do something like this: l[:] = [e for e in l if predicate(e)] This will alter the list l such that only the elements of it that fullfill the predicate are retained. In other words: your code above should work when written like this: l[:] = [] which effectively removes all elements from the list. This does NOT mean that the objects referenced to by the list are deleted! If they are referenced from anywhere else, they are kept!! Diez From michele.petrazzo at TOGLIunipex.it Fri Jun 30 07:23:35 2006 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Fri, 30 Jun 2006 11:23:35 GMT Subject: Way for see if dict has a key In-Reply-To: References: <6V6pg.21624$_J1.271925@twister2.libero.it> Message-ID: Fredrik Lundh wrote: > Michele Petrazzo wrote: > >>>> key in dict >>> new syntax (2.3 and later). >> So, following it, it can be used for the operations like len? > > what's "it" in this sentence? > It, is the thought that the new 2.3 introduce. Michele From scott at bogusaddress.com Wed Jun 28 16:08:49 2006 From: scott at bogusaddress.com (scott at bogusaddress.com) Date: Wed, 28 Jun 2006 20:08:49 GMT Subject: Passing a Cookie with httplib Message-ID: Hello, >From a shell script, I have used /usr/bin/curl to access a web site and pass a cookie (as required by the site). But, I can't seem to accomplish this task with Python. I would like to use the httplib module to do this. Any thoughts on this subject? I would like to hard code the cookie in the code so it works every time: i.e. cookie = 'auth=buster%3A12345678901234567890exZ9rzMqgtxa5A'. The question is - how do I pass it with httplib? Here is what I have so far: # Import external modules import sys import httplib # Define our site and path WP_SERVER="www.foo.com" WP_PATH='/somedir/confirmquery?value=%s' try: # Grab the command line argument uservalue = sys.argv[1] # Use the httplib module and connect conn=httplib.HTTPConnection(WP_SERVER) conn.request('GET',WP_PATH % uservalue) response=conn.getresponse() data=response.read() conn.close() print data except: print "Some stupid error occurred" sys.exit(1) Any help would be greatly appreciated, Scott From blye at telkomsa.net Thu Jun 22 14:32:57 2006 From: blye at telkomsa.net (bli) Date: 22 Jun 2006 11:32:57 -0700 Subject: win32com and name of com Message-ID: <1151001177.360087.202620@m73g2000cwd.googlegroups.com> hi all first post. I am using python to connect to dll. I have read everything I can find on com!#@! and tried all variations of the name of the dll to use in the Dispatch. I get a com error-(-2147...1005, 'Invalid class string',None,None) Do I add .Application to the name? (eg 'XXXX Control Library.Application') Any help appreciated?!? How do I get the info? I have tried the gencache lines suggested in the lit. maybe I use them wrong. (All authors are fairly sparse on the topic using Microsoft examples that are more self evident.) thanks muchly! From Bulkan at gmail.com Fri Jun 23 08:17:26 2006 From: Bulkan at gmail.com (placid) Date: 23 Jun 2006 05:17:26 -0700 Subject: * in Python In-Reply-To: References: <1151061836.557835.295820@p79g2000cwp.googlegroups.com> Message-ID: <1151065046.668902.23010@g10g2000cwb.googlegroups.com> Duncan Booth wrote: > placid wrote: > > > Hi all, > > > > Can someone tell me what * in the following code means/does a Google > > search didnt turn up anything as i dont know what the * is called > > (related to Python and i dont think Python has pointers) > > > * is for variable number of positional arguments, ** is for variable > keyword arguments. The syntax is symmetrical when defining functions and > when calling them. > > See http://docs.python.org/ref/calls.html > and http://docs.python.org/ref/function.html so * basically means that args is a list containing more arguments that can change in size, whereas ** means that args is a dictionary of key=value arguments? From usenet at local.machine Mon Jun 5 08:11:34 2006 From: usenet at local.machine (=?ISO-8859-2?Q?Dra=BEen_Gemi=E6?=) Date: Mon, 05 Jun 2006 14:11:34 +0200 Subject: John Bokma harassment In-Reply-To: References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1149083474.097849.262460@i40g2000cwc.googlegroups.com> Message-ID: Ilias Lazaridis wrote: > Xah Lee wrote: >> for whatever advice or action i can solicit. Meanwhile, if you do know >> a web hosting company that can take some 80 G of bandwidth/month for >> less than $25 a month, please let me know! (i do hope if someone here >> runs a hosting business and can host my site. I will certainly return >> the favor.) 80 Gb/month ? He intends to write a lot of spam..... DG From faik at pardus.org.tr Fri Jun 16 05:07:55 2006 From: faik at pardus.org.tr (Faik Uygur) Date: Fri, 16 Jun 2006 12:07:55 +0300 Subject: getting umask without changing it Message-ID: <200606161207.56008.faik@pardus.org.tr> Is there a python way of getting the current umask without changing it? os.umask changes it, and i dont want to use os.system("umask") - Faik From hancock at anansispaceworks.com Thu Jun 1 22:21:55 2006 From: hancock at anansispaceworks.com (Terry Hancock) Date: Fri, 02 Jun 2006 02:21:55 +0000 Subject: Best Python Editor In-Reply-To: References: Message-ID: <447FA0C3.5030904@anansispaceworks.com> Fredrik Lundh wrote: > "Manoj Kumar P" wrote: > > Can anyone tell me a good python editor/IDE? > emacs! [...] Fredrik Lundh wrote: > "Manoj Kumar P" wrote: > > Can anyone tell me a good python editor/IDE? > vim! There is much truth in this man's replies. ;-D Cheers, Terry -- Terry Hancock (hancock at AnansiSpaceworks.com) Anansi Spaceworks http://www.AnansiSpaceworks.com From kewashi at gmail.com Sat Jun 10 11:55:23 2006 From: kewashi at gmail.com (KenAggie) Date: 10 Jun 2006 08:55:23 -0700 Subject: Get my airlines boarding pass In-Reply-To: <1hgotbh.1vd74fb1qhzdziN%aleax@mac.com> References: <1hgotbh.1vd74fb1qhzdziN%aleax@mac.com> Message-ID: <1149954923.868806.87270@m38g2000cwc.googlegroups.com> Good idea - I just bought the 2nd edition of the book and it is very good. Will check it out. Ken Alex Martelli wrote: > Ken wrote: > > > rh0dium wrote: > > > Hi all, > > > > > > Has any of you fine geniuses figured out a nice python script to go to > > > the Southwest airlines website and check in, and retrieve your boarding > > > pass - automatically 24 hours in advance > > > > I just wrote such a script in python and tested it successfully. Where > > should I post it? > > Activestate's Python Cookbook sounds like a good venue for this. > > > Alex From rbonvall at gmail.com Sun Jun 18 17:00:54 2006 From: rbonvall at gmail.com (Roberto Bonvallet) Date: Sun, 18 Jun 2006 17:00:54 -0400 Subject: mapping None values to '' In-Reply-To: <0Rblg.5940$zy5.141663@twister1.libero.it> References: <1150632320.443681.42640@r2g2000cwb.googlegroups.com> <0Rblg.5940$zy5.141663@twister1.libero.it> Message-ID: <1908cb6b0606181400y39c2c50dw138ed17825a8534d@mail.gmail.com> imho : > map(lambda x:"" , [i for i in [a,b,c] if i in ("None",None) ]) You don't need map when using list comprehensions: ["" for i in [a, b, c] if i in ("None", None)] -- Roberto Bonvallet From fairwinds at eastlink.ca Fri Jun 2 17:45:24 2006 From: fairwinds at eastlink.ca (David Pratt) Date: Fri, 02 Jun 2006 18:45:24 -0300 Subject: Initializing an attribute that needs the object In-Reply-To: <20060602212819.GA2688@localdomain> References: <4480AA70.2020804@eastlink.ca> <20060602212819.GA2688@localdomain> Message-ID: <4480B174.5090403@eastlink.ca> Hi Marco. Thanks for your reply. I am providing the handler with the factory instance as I have shown. This is how my code currently works. What I am trying to figure out is how to possibly provide the handler in the constructor when it needs the factory instance. This would give me some better flexibility. ie. class Factory def __init__(self, factory): At this point I don't have self. Would super help me? Regards, David Marco Giusti wrote: > On Fri, Jun 02, 2006 at 06:15:28PM -0300, David Pratt wrote: >> Hi. I want to have different handlers to do perform logic. The problem >> is the Handler requires an instance of the factory since it will use its >> own methods in conjunction with methods of the factory. >> >> Once I have got a Factory instance I can give it a new handler (see >> below). It would be more flexible if I could provide a handle in >> constructor - but how to do this when it requires the object itself. >> Would I use a super for this sort of thing? Many thanks > > when __init__ is called the object already exists. > >> class Factory: >> >> def __init__(self): >> self.some_handler = Handler(self) >> >> f = Factory() >> f.some_handler = AnotherHandler(f) > > try this, should works: > > class Factory: > > def __init__(self): > self._some_handler = AnotherHandler(self) > > maybe a class hierarchy is good for you > > ciao > m. > From cdsmith at twu.net Tue Jun 27 18:30:50 2006 From: cdsmith at twu.net (Chris Smith) Date: Tue, 27 Jun 2006 16:30:50 -0600 Subject: What is Expressiveness in a Computer Language References: <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <1151384511.223582.305760@m73g2000cwd.googlegroups.com> <1151425350.679754.278820@i40g2000cwc.googlegroups.com> <1151432002.905190.152470@y41g2000cwy.googlegroups.com> <4gdkr6F1ldalhU4@individual.net> Message-ID: Pascal Costanza wrote: > You can ignore the #'. In Scheme this as follows: > > (define blackhole (argument) > blackhole) > > It just means that the function blackhole returns the function blackhole. So, in other words, it's equivalent to (Y (\fa.f)) in lambda calculus, where \ is lambda, and Y is the fixed point combinator? -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation From Kornkatz88 at aol.com Fri Jun 30 10:30:53 2006 From: Kornkatz88 at aol.com (Kornkatz88 at aol.com) Date: Fri, 30 Jun 2006 10:30:53 EDT Subject: No Cookie: how to implement session? Message-ID: <404.5c5f3fe.31d68f9d@aol.com> I don't understand the reason for 'Cookies'. When you are pay to belong to AOL or another network why is it necessary to set up an additional address in order to be able to have access to some information? We are not all computer talented, even at this date. Some of us only use it for convenience in our every day life, why make it more complex? -------------- next part -------------- An HTML attachment was scrubbed... URL: From paolopantaleo at gmail.com Tue Jun 20 05:56:44 2006 From: paolopantaleo at gmail.com (Paolo Pantaleo) Date: Tue, 20 Jun 2006 11:56:44 +0200 Subject: Specifing arguments type for a function Message-ID: <83e8215e0606200256k9057e38g6105c59d27d4521c@mail.gmail.com> I have a function def f(the_arg): ... and I want to state that the_arg must be only of a certain type (actually a list). Is there a way to do that? Thnx PAolo -- if you have a minute to spend please visit my photogrphy site: http://mypic.co.nr From mnot at mnot.net Fri Jun 23 13:01:54 2006 From: mnot at mnot.net (Mark Nottingham) Date: Fri, 23 Jun 2006 10:01:54 -0700 Subject: PEP 314 - requirements for Python itself Message-ID: <75C72D66-19F4-43AA-9120-09919076A4E5@mnot.net> PEP 314 introduces metadata that explains what packages are required by a particular package. Is there any way to express what version of Python itself is required? Cheers, -- Mark Nottingham http://www.mnot.net/ From invalidemail at aerojockey.com Fri Jun 23 10:13:33 2006 From: invalidemail at aerojockey.com (Carl Banks) Date: 23 Jun 2006 07:13:33 -0700 Subject: Using metaclassed to dynamically generate a class based on a parameter to the objects init function. In-Reply-To: <1151061557.682689.189440@c74g2000cwc.googlegroups.com> References: <1151018669.849641.265990@g10g2000cwb.googlegroups.com> <449bb4d6$0$32258$626a54ce@news.free.fr> <1151061557.682689.189440@c74g2000cwc.googlegroups.com> Message-ID: <1151072013.327497.257110@g10g2000cwb.googlegroups.com> sashang at gmail.com wrote: > The extra_information is used in MetaThing to tell it what attributes > to add to the class. For example: > > class MetaThing(type): > def __init__(cls, name, bases, dict, extra_information): > super(MetaThing, cls).__init__(name, bases, dict) > #setup the class based on the parameter extra_information > setattr(cls, make_name(extra_information), > make_object(extra_information)) > > Does that clarify things? Why do the extra attributes need to be part of the class? ISTM each instance has its own class; therefore there it doesn't matter whether a member is a class member or an instance member. Carl Banks From lolmcbride at googlemail.com Wed Jun 7 02:54:19 2006 From: lolmcbride at googlemail.com (xera121) Date: 6 Jun 2006 23:54:19 -0700 Subject: Using pysqlite2 In-Reply-To: References: <1149276702.992801.247640@j55g2000cwa.googlegroups.com> <4480a5c8$1@news.uni-ulm.de> Message-ID: <1149663259.756749.99440@h76g2000cwa.googlegroups.com> Many thanks Gerhard - the solution you offer is workable in the scope of my project. Gracias muchacho Xera121 From fredrik at pythonware.com Thu Jun 1 12:09:32 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 1 Jun 2006 18:09:32 +0200 Subject: New to Python: Do we have the concept of Hash in Python? References: Message-ID: "A.M" wrote: > I am new to Python, with C#/Java background that's not really much of an excuse for not reading *any* Python tutorial before you jump in... > I am asking this because I learned that DB-API in Python doesn't offer access to cursor columns by > name. The only option is access by index. I hope that I've got it wrong! several people have already told you how to deal with this in Python. please see the followups to your earlier post. > I learned Ruby perfectly supports that. Ruby's DB interface, perhaps. Python's standard DB-API doesn't support this by default, for portability and performance reasons. that doesn't mean that Python don't have "hashes", just that the DB-API doesn't provide dictionary-style access to columns. see the followups to your earlier post for more details, and ways to handle this. (a much better way to deal with this is of course to *name* the variables in your select statements, so 1) the database engine can spot errors early on, and 2) it won't have to fetch data that you don't really need). From belred at gmail.com Tue Jun 13 09:58:17 2006 From: belred at gmail.com (Bryan) Date: Tue, 13 Jun 2006 06:58:17 -0700 Subject: numeric/numpy/numarray In-Reply-To: <1150188484.888977.189510@y43g2000cwc.googlegroups.com> References: <1150188484.888977.189510@y43g2000cwc.googlegroups.com> Message-ID: Simon Percivall wrote: > Bryan wrote: >> hi, >> >> what is the difference among numeric, numpy and numarray? i'm going to start >> using matplotlib soon and i'm not sure which one i should use. >> >> >> this page says, "Numarray is a re-implementation of an older Python array module >> called Numeric" >> http://www.stsci.edu/resources/software_hardware/numarray >> >> this page says, "NumPy derives from the old Numeric code base and can be used as >> a replacement for Numeric." >> http://numeric.scipy.org/ >> >> i looked at the matplotlib examples today and if i remember correctly, the >> examples didn't use numarray. >> >> so i'm a bit confused. >> >> thanks, >> >> bryan > > Look again at numeric.scipy.org, and this time: read the whole page, > especially the section called "Older Array Packages". > at the end of that page, it says: "Numarray is another implementation of an arrayobject for Python written after Numeric and before NumPy. Sponsors of numarray have indicated they will be moving to NumPy as soon as is feasible for them so that eventually numarray will be phased out." on the python wiki "NumArray is the current reimplementation of NumPy." http://wiki.python.org/moin/NumArray so, was Numarray written *before* NumPY, or was it a reimplementation of NumPy which implies it came *after* NumPy? it seems clear that Numeric is the old one and i read is not being worked on anymore. so that leaves Numarray and numpy. which of these two should i use? thanks, bryan From g.brandl-nospam at gmx.net Thu Jun 15 02:08:30 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Thu, 15 Jun 2006 08:08:30 +0200 Subject: nested functions In-Reply-To: <1150344748.652441.316680@g10g2000cwb.googlegroups.com> References: <1150319279.865335.323530@u72g2000cwu.googlegroups.com> <1150344748.652441.316680@g10g2000cwb.googlegroups.com> Message-ID: George Sakkis wrote: > Ben Finney wrote: > >> "Gregory Petrosyan" writes: >> >> > I often make helper functions nested, like this: >> > >> > def f(): >> > def helper(): >> > ... >> > ... >> > >> > is it a good practice or not? >> >> You have my blessing. Used well, it makes for more readable code. > > I'm not sure it's in general more readable; I typically use nested > functions for closures only, not helper functions, so I'd read the code > twice to check if it's a closure and if not why might have been defined > locally. I prefer to define helpers at the module level, often making > them 'private' by prepending their name with a single underscore. > >> > What about performance of such constructs? >> >> What about it? Set up some examples maningful for your situation, with >> and without such constructs, and use the profiler to find out. > > It shouldn't come as a surprise if it turns out to be slower, since the > nested function is redefined every time the outer is called. That's right. However, if the outer function is only called a few times and the nested function is called a lot, the locals lookup for the function name is theoretically faster than the globals lookup. Also, in methods you can use closures, so you don't have to pass, for example, self to the inner function. Georg From greg.kujawa at gmail.com Tue Jun 6 15:28:12 2006 From: greg.kujawa at gmail.com (gregarican) Date: 6 Jun 2006 12:28:12 -0700 Subject: 10GB XML Blows out Memory, Suggestions? References: <1149594519.098115.8980@u72g2000cwu.googlegroups.com> Message-ID: <1149622092.241196.283790@c74g2000cwc.googlegroups.com> 10 gigs? Wow, even using SAX I would imagine that you would be pushing the limits of reasonable performance. Any way you can depart from the XML requirement? That's not really what XML was intended for in terms of passing along information IMHO... axwack at gmail.com wrote: > I wrote a program that takes an XML file into memory using Minidom. I > found out that the XML document is 10gb. > > I clearly need SAX or something else? > > Any suggestions on what that something else is? Is it hard to convert > the code from DOM to SAX? From roger.miller at nova-sol.com Thu Jun 22 15:59:06 2006 From: roger.miller at nova-sol.com (Roger Miller) Date: 22 Jun 2006 12:59:06 -0700 Subject: source reduction using Python References: <1150930792.758470.315110@b68g2000cwa.googlegroups.com> Message-ID: <1151006346.061874.111460@g10g2000cwb.googlegroups.com> beliavsky at aol.com wrote: > Intel has introduced something called CESR, written in Python, to aid > C, C++, and Fortran programmers in reducing the sizes of programs > included in bug reports. Here is a brief description from > http://cache-www.intel.com/cd/00/00/21/93/219320_relnotes_10.pdf : > ... > I think one needs to qualify for "Intel Premier Support" to get CESR. I > wonder if a similar open-source Python program exists. I can't answer your question, but if you are searching it may be helpful to know that the relevant phrase is probably "program slicing". From greg at cosc.canterbury.ac.nz Sat Jun 3 05:11:42 2006 From: greg at cosc.canterbury.ac.nz (greg) Date: Sat, 03 Jun 2006 21:11:42 +1200 Subject: New to Python: Do we have the concept of Hash in Python? In-Reply-To: References: <1149182265.257263.159210@f6g2000cwb.googlegroups.com> Message-ID: <4ed222F1eao0mU2@individual.net> A.M wrote: > In essence, Ruby language is the best, but Ruby platform is too young for > me. I'll give Ruby another two years and come back to it again. > > I found the Python language quite powerful and easy. With mature and strong > community support. Welcome aboard. It'll be interesting to see whether you *still* want to switch back to Ruby after getting to know Python for two years! -- Greg From levub137 at wi.rr.com Sun Jun 11 15:33:41 2006 From: levub137 at wi.rr.com (Raymond L. Buvel) Date: Sun, 11 Jun 2006 19:33:41 GMT Subject: math.pow(x,y) In-Reply-To: References: <1150049976.916474.186580@j55g2000cwa.googlegroups.com> Message-ID: Felipe Almeida Lessa wrote: > Em Dom, 2006-06-11 ?s 11:19 -0700, fl1p-fl0p escreveu: >> import math >> math.pow(34564323, 456356) >> >> will give math range error. >> >> how can i force python to process huge integers without math range >> error? Any modules i can use possibly? > > 34564323**456356 ? > I just tried this and it is taking an extremely long time even on a fast machine with 4 Gb of RAM. Killed it after a couple of minutes. This sort of calculation can be done with extended precision floating point (as long as you don't need an exact answer). For example (using defaults on a 64-bit machine), >>> from clnum import mpf >>> mpf(34564323)**456356 mpf('1.39518106833639480699862472257296396643e3440298',36) compute time is about 160 microseconds. For more information see http://calcrpnpy.sourceforge.net/clnumManual.html For calculations involving large powers, you may still be better off using logarithms. From kent at kentsjohnson.com Thu Jun 1 14:45:56 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Thu, 01 Jun 2006 14:45:56 -0400 Subject: An oddity in list comparison and element assignment In-Reply-To: <1149177617.985251.74560@c74g2000cwc.googlegroups.com> References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> Message-ID: <447f34ec$1_2@newspeer2.tds.net> michael.f.ellis at gmail.com wrote: > Hi Alex, > With all due respect to your well-deserved standing in the Python > community, I'm not convinced that equality shouldn't imply invariance > under identical operations. > > Perhaps the most fundamental notion is mathematics is that the left and > right sides of an equation remain identical after any operation applied > to both sides. Our experience of the physical world is similar. If I > make identical modifications to the engines of two identical > automobiles, I expect the difference in performance to be identical. > If my expectation is met, I would assert that either the two vehicles > were not identical to begin with or that my modifications were not > performed identically. But programming is not mathematics and assignment is not an equation. How about this: In [1]: a=3.0 In [2]: b=3 In [3]: a==b Out[3]: True In [4]: a/2 == b/2 Out[4]: False Kent From girish at cse.iitb.ac.in Tue Jun 20 05:14:53 2006 From: girish at cse.iitb.ac.in (Girish Sahani) Date: Tue, 20 Jun 2006 14:44:53 +0530 (IST) Subject: How to truncate/round-off decimal numbers? Message-ID: <39342.10.209.4.2.1150794893.squirrel@10.105.1.3> Hi, I want to truncate every number to 2 digits after the decimal point. I tried the following but it doesnt work. >>> a = 2 >>> b = 3 >>> round(a*1.0 / b,2) 0.67000000000000004 Inspite of specifying 2 in 2nd attribute of round, it outputs all the digits after decimal. From antroy at gmail.com Fri Jun 2 08:37:39 2006 From: antroy at gmail.com (Ant) Date: 2 Jun 2006 05:37:39 -0700 Subject: Selection in Tkinter Text widget. In-Reply-To: References: <1149246483.809582.8310@i39g2000cwa.googlegroups.com> Message-ID: <1149251859.630518.248760@y43g2000cwc.googlegroups.com> Fredrik Lundh wrote: ... > it does, but by default, the selection is only shown for widgets that has the key- > board focus. if you add an explicit focus_set() call, you'll see the selection. > > Perfect! Thanks Fredrik. Strange behaviour though (IMHO), that the selection is only shown if the widget has focus. I just tried adding another component to the test, and switching from widget to widget does indeed stop the selection showing! Cheers, -- Ant... From edeveaud at pasteur.fr Fri Jun 30 12:09:03 2006 From: edeveaud at pasteur.fr (Eric Deveaud) Date: Fri, 30 Jun 2006 16:09:03 +0000 (UTC) Subject: Way for see if dict has a key References: <6V6pg.21624$_J1.271925@twister2.libero.it> <44a5041f$0$29637$636a55ce@news.free.fr> <4F7pg.21676$_J1.272665@twister2.libero.it> <1151666867.604260.116320@h44g2000cwa.googlegroups.com> <44a51f34$0$6794$626a54ce@news.free.fr> <44a5409c$0$8389$626a54ce@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > Fredrik Lundh wrote: > > Bruno Desthuilliers wrote: > > > >>> on my machine, "key in dict" is about twice as fast as the full > > > >>> try/getitem construct when the key is present in the dict, > > > >> > >> Doesn't it depends on the number of keys in the dict ? > > > > > > why would it depend on the number of keys in the dict ? > > > > > > Seems that if "key in dict" do a simple linear search, it depends on the > number of keys in dict (and the position of the searched key etc...). > > And if I'm missing the point and you it and you know why, it would be > simple to explain than to answer my question with another question. maybee we can imagine that key in dict just perform try: dict[key] return True except KeyError: return False If I understand correctly, it will be time constant no ?? just the needed time to compute the hash for the key Eric From kylotan at gmail.com Fri Jun 30 05:28:59 2006 From: kylotan at gmail.com (Ben Sizer) Date: 30 Jun 2006 02:28:59 -0700 Subject: No error while sending via TCP Socket In-Reply-To: References: Message-ID: <1151659739.850068.287190@d56g2000cwd.googlegroups.com> Martin B?rkle wrote: > I have writen a programm using TCP sockets. After i get the connection > to another socket I cut the Ethernet cable. Then I send a message. > The program doesnt raise any exception. Can somebody tell me why and > give me a hint how to get an exception Have you tried waiting 30 seconds or so? The connection may just take a while to time out. -- Ben Sizer From yairchu at gmail.com Tue Jun 6 07:25:05 2006 From: yairchu at gmail.com (yairchu at gmail.com) Date: 6 Jun 2006 04:25:05 -0700 Subject: is it possible to find which process dumped core In-Reply-To: <1149514829.032643.193890@h76g2000cwa.googlegroups.com> References: <1149514829.032643.193890@h76g2000cwa.googlegroups.com> Message-ID: <1149593104.974354.166060@y43g2000cwc.googlegroups.com> if your core is from a python program you can check what file/function was running use this gdb macro: define pbt set $i = 0 set $j = 0 while $i < 1000 select $i if $eip >= &PyEval_EvalFrame if $eip < &PyEval_EvalCodeEx echo c frame # p $i echo py frame # p $j set $j = $j+1 x/s ((PyStringObject*)f->f_code->co_filename)->ob_sval x/s ((PyStringObject*)f->f_code->co_name)->ob_sval echo line # p f->f_lineno end end set $i = $i+1 end end document pbt show python backtrace macro by yairchu based on pyframe macro by jeremy hylton end works on python2.4 here but not 100% sure it will always work. it has some nasty hack. you can also see where each of the threads was by choosing the wanted thread in gdb I'll post my useful gdb macros to the web sometime soon From iainking at gmail.com Thu Jun 1 08:48:16 2006 From: iainking at gmail.com (Iain King) Date: 1 Jun 2006 05:48:16 -0700 Subject: Trying to get FreeImagePy to work. In-Reply-To: References: <1148651668.578852.3160@i40g2000cwc.googlegroups.com> <7fEdg.13375$cX1.201311@twister2.libero.it> <1148655611.990937.322350@j73g2000cwa.googlegroups.com> Message-ID: <1149166096.176405.22780@i40g2000cwc.googlegroups.com> Michele Petrazzo wrote: > Iain King wrote: > > Michele Petrazzo wrote: > > > > I downloaded and installed 0.9.9.3, and it now works. Thanks! > > > > I advice you to don't use that ctypes version... Better is to use the > newest one and update freeimagepy! > > > Iain > > > > Michele OK, Ive installed the latest versions I can find, which are FreeImagePy 1.2.4 and ctypes 0.9.9.6, and I'm back to the error I had earlier. Do you know what's wrong? Iain From grante at visi.com Wed Jun 28 10:45:03 2006 From: grante at visi.com (Grant Edwards) Date: Wed, 28 Jun 2006 14:45:03 -0000 Subject: How to measure execution time of a program References: <54032.10.209.4.1.1151481158.squirrel@10.105.1.3> Message-ID: <12a55ff5fg7be3b@corp.supernews.com> On 2006-06-28, Pete Forman wrote: > "Fredrik Lundh" writes: > > simplest way: > > > > t0 = time.time() > > You can get better resolution by using time.clock() instead of > time.time(). Oh really? When I do it, time.clock() is worse: ------------------------------timeit.py------------------------------ import time for i in range(5): t0 = time.time() print "hi there" print time.time()-t0 for i in range(5): t0 = time.clock() print "hi there" print time.clock()-t0 ------------------------------timeit.py------------------------------ hi there 0.000149011611938 hi there 4.10079956055e-05 hi there 3.981590271e-05 hi there 3.981590271e-05 hi there 3.88622283936e-05 hi there 0.0 hi there 0.0 hi there 0.0 hi there 0.0 hi there 0.0 -- Grant Edwards grante Yow! I'm a nuclear at submarine under the visi.com polar ice cap and I need a Kleenex! From bj_666 at gmx.net Fri Jun 16 04:15:21 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Fri, 16 Jun 2006 10:15:21 +0200 Subject: list of polynomial functions References: <1150390140.459461.169900@i40g2000cwc.googlegroups.com> <4491AA55.7030200@tim.thechases.com> <4491c005$1@nntp0.pdx.net> Message-ID: In , Tim Chase wrote: > My understanding is that the lambda-defined functions are not > called until the actual application thereof, with the > > mypolys = make_polys(8) > mypolys[5](2) #the lambda call happens here, no? Yes, that's right. > 's original statement read like a koan...there was more in it > than I was getting out of it. There seem to be several concepts > I've not yet wrapped my head around. My understanding (likely > wrong) was that "lambda" was sort of like defining a function > inline, along the lines of > > def f(x): > return x+5 > > being somewhat equiv to > > k = lambda x: x+5 > > you could then do > > >>> f(20) > 25 > >>> j = f > >>> j(20) > 25 > >>> k(20) > 25 > >>> j = k > >>> j(20) > 25 > > There does seem to be some subtle difference, as > > >>> f > > >>> k > at 0xb7d8c0d4> > > "k" clearly knows it's a just as "f" knows its an "f" > (whether asked for by the aliased name or not). That understanding is mostly correct. Just that there's no subtile difference. `k` doesn't know it's a lambda function, it's just an ordinary function at this point which happens to have the name ''. That's somewhat unusual but it behaves like any ``def``-ed function. > [lightbulb begins to go on...sorta] > > However, in the OP's example, slightly modified, it seems that > polys, even when it doesn't exist in the calling scope, it > doesn't matter. > > >>> def mp(n): > ... p = lambda x: 1 > ... polys = [p] > ... for i in range(n): > ... polys.append(lambda x: polys[i](x)*x) > ... return polys > ... > >>> f = mp(5) > >>> polys > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'polys' is not defined > >>> for p in f: print p(3) > ... > 1 > Traceback (most recent call last): > File "", line 1, in ? > File "", line 5, in > : > : > : > > I'm curious why the very first attempt to call p(3) doesn't bomb > out with the NameError that "polys" wasn't defined before it even > got to the point of attempting to call it. Well, because `polys` does not exist in the module scope. But it exists in the local scope of the functions in `f`. An example: In [2]:def outer(a): .2.: b = 42 .2.: def inner(c): .2.: print a, b, c .2.: print locals() .2.: .2.: return inner .2.: In [3]:f = outer(1) In [4]:f(2) 1 42 2 {'a': 1, 'c': 2, 'b': 42} If `outer` returns `inner` the inner function still has a reference to the locals of the enclosing function. So they won't go away if the outer function returns. `a` and `b` are looked up when `f` is called. That's a problem if you create more than one function in `outer` and use a name from outer's locals that changes: In [7]:def pitfall(): .7.: functions = list() .7.: for i in range(3): .7.: functions.append(lambda: i) .7.: print 'pitfall: i=%d' % i .7.: return functions .7.: In [8]:for function in pitfall(): .8.: print function() .8.: pitfall: i=2 2 2 2 At the time the list with the functions is returned `i` is 2. So if you call any of the functions it looks up this `i`. Ciao, Marc 'BlackJack' Rintsch From bdesth.quelquechose at free.quelquepart.fr Fri Jun 2 20:21:37 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 03 Jun 2006 02:21:37 +0200 Subject: after del list , when I use it again, prompt 'not defined'.how could i delete its element,but not itself? In-Reply-To: <1149235087.256704.309360@g10g2000cwb.googlegroups.com> References: <1149235087.256704.309360@g10g2000cwb.googlegroups.com> Message-ID: <4480a683$0$935$626a54ce@news.free.fr> python a ?crit : > after del list , when I use it again, prompt 'not defined'.how could i > delete its element,but not itself? > except list.remove(val) ,are there other ways to delete list 's > elements? > > and , I wrote: > > list1=[] > def method1(): Why naming a function "method" ? > global list1 globals are evil. > list1=['a','b','c','d'] > def method2(): > list2=list1 this makes list2 point to the same object as list1. > list2.remove['a'] > main(): > global list1 > method1() > method2() > print list1[0] > > it prints 'b'. Of course. Python's "variable" are really just names referencing objects. Making two names pointing to the same object does'nt make two different objects, just two references to one object. > > How could I keep the list1 not to change when remove list2's elements? Copy the list. From mike_mp at zzzcomputing.com Mon Jun 26 01:48:56 2006 From: mike_mp at zzzcomputing.com (Michael Bayer) Date: Mon, 26 Jun 2006 01:48:56 -0400 Subject: queue deadlock possibility Message-ID: Hi - i was just going through this thread: http://mail.python.org/ pipermail/python-list/2006-April/336948.html , where it is suggested that the Lock instance used by Queue.Queue should be publically configurable. I have identified another situation where a Queue can be deadlocked, one which is also alleviated by configuring the type of Lock used by the Queue (or just changing it to an RLock). The scenario arises when the Queue is operated upon within the __del__ method of an object; since __del__ can be called at somewhat unpredictable times, I have observed that it is in fact possible, in extremely rare circumstances, for put() to be called within a get() or possibly vice versa; since both methods lock on the same underlying mutex object which is an instance of threading.Lock, a deadlock occurs. The issue can be fixed by substituting a threading.RLock for the threading.Lock object that Queue instantiates by default. The scenario this has arisen within is a database connection pool, which puts connections in a Queue, returns them via get() within a wrapper object, and the wrapper object automatically returns the connection to the Queue via put() within its __del__ method (an explicit close() method is available as well). While I cant reproduce it locally, one of my users experiences it regularly. I had him install the "threadframe" module to trace it out, and it reveals that all threads are hung within Queue on the acquiring of the "not_empty" and "not_full" Conditionals, and the offending stack trace within it looks like this: File "build/bdist.linux-i686/egg/sqlalchemy/pool.py", line 84, in connect File "build/bdist.linux-i686/egg/sqlalchemy/pool.py", line 130, in __init__ File "build/bdist.linux-i686/egg/sqlalchemy/pool.py", line 102, in get File "build/bdist.linux-i686/egg/sqlalchemy/pool.py", line 226, in do_get File "/usr/lib/python2.4/Queue.py", line 116, in get raise Empty File "build/bdist.linux-i686/egg/sqlalchemy/pool.py", line 157, in __del__ File "build/bdist.linux-i686/egg/sqlalchemy/pool.py", line 163, in _close File "build/bdist.linux-i686/egg/sqlalchemy/pool.py", line 99, in return_conn File "build/bdist.linux-i686/egg/sqlalchemy/pool.py", line 216, in do_return_conn File "/usr/lib/python2.4/Queue.py", line 71, in put self.not_full.acquire() this is a simplified version of the logic, the actual version is the pool.py module in the SQLAlchemy package: import Queue pool = Queue.Queue(maxsize=10) class ConnectionWrapper(object): def __init__(self, connection): self.connection = connection def __del__(self): pool.put_nowait(self) # fill up the pool with 10 connections for x in range(0,10): pool.put_nowait(database.connect()) def connect(): return ConnectionWrapper(pool.get()) At the moment I am modifying the Queue's mutex to be a threading.RLock to fix the problem; what does the community think of either making the Queue's Lock instance public or changing it to an RLock ? - mike From meng.yan at gmail.com Fri Jun 2 01:01:08 2006 From: meng.yan at gmail.com (Mike Meng) Date: 1 Jun 2006 22:01:08 -0700 Subject: Are there something like "Effective Python"? Message-ID: <1149224468.481470.74580@i39g2000cwa.googlegroups.com> Hi all, I just finished reading Learning Python 3rd ed, and am doing my first Python application, which retrieves and process text and XML documents from Web. Python helped me to write the application in a few hours, I'm very happy with its productivity. But the performance is not satisfactory. I decide to optimized it in Python before trying C/C++ extensions. But I don't know Python much and have no clu to tune my program. Also, I don't know what Pythonist's preferred styles. Are there any books/documents which play the similar role for Python as 'Effective C++' does for C++? For example, one of my friends read my program and suggest me to move the re.compile() out of a for-loop, since the regular pattern is fixed, and re.compile() is slow. I want to find more such advice, where can I find them? Thank you. Mike From timr at probo.com Fri Jun 30 02:57:01 2006 From: timr at probo.com (Tim Roberts) Date: Fri, 30 Jun 2006 06:57:01 GMT Subject: String Question References: <1151508909.273667.270910@x69g2000cwx.googlegroups.com> <1151509682.897441.165480@y41g2000cwy.googlegroups.com> Message-ID: "Iain King" wrote: > >You probably want: > >s.sendto('\xff'*6 + ('\x%s\x%s\x%s\x%s\x%s\x%s' % (str01, str02, str03, > sttr04, str05, str06))*16, ('192.168.1.255', 80)) You probably should TRY suggestions before you post them. That will get an "invalid \x escape". \x must be followed by exactly two hex digits. You can't build up an escape sequence like this. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From sudheerb at netapp.com Wed Jun 7 19:44:30 2006 From: sudheerb at netapp.com (Sudheer Gupta) Date: Wed, 07 Jun 2006 19:44:30 -0400 Subject: Using C struct in Python In-Reply-To: <4487613A.8050502@lexicon.net> References: <4487613A.8050502@lexicon.net> Message-ID: <448764DE.6020708@netapp.com> Hi, Thanks a lot for your responses. It cleared up a lot for me !! Its a superglue developed and used in house and cannot be revealed .. sorry for that !! I am only extending to the existing glue. Have contacted the author regarding the problem. Sorry for confusion -Sudheer John Machin wrote: > On 8/06/2006 7:35 AM, Sudheer Gupta wrote: >> Hi, > > Hi. > > Your later "correction" doesn't clear up the confusion below. Quick > eye-balling revealed no difference. If you have to correct a minor > typo in a posting, please consider saying "change X to Y" instead of > reposting the whole thing. > >> >> I am having trouble using C struct in python. Hope anyone can help me >> out ... >> >> Say, I have my C struct as >> >> typedef struct call >> { >> struct call *next; >> // ..... >> >> } call_t; >> >> I have a global variable, namely call_pool, which is of type call_t * > > You really need to explain what sort of glue you have between your > Python code and your C code. > > 1. Are you the author of the glue? If not, better ask the author. > 2. Are you extending Python with a module written in C, or are you > embedding Python in a C program? > 3. If extending, what's your glue? SWIG? something else? hand-crafted? > >> >> My python program: >> >> cp = call_pool # no error doing this, means that call_pool is >> accessable > > Acessible from where? How do you bind the name "call_pool" to an object? > >> >> while cp: >> print cp >> print cp.next >> >> >> This is giving me error: " There is no member or method name c_next" > > Not a Python error message. Must be coming from inside your extension > module. > >> >> Now, If I just do: >> >> print cp >> print cp.next >> >> there is no problem. > > Sorry, I don't understand. Above you said it was "giving me error". > >> But I am seeing a difference in the way python is looking at the struct: >> >> print cp -> (call_t*) 0xb0... >> print cp.next -> (struct call *) 0xb0... > > If they are actual results from a Python print statement, then I can > only assume the extension module defines types which have (in effect) > str() and/or repr() methods which produce such output. > > Python does not know that the C type of cp is (call_t*) and that of > cp.next is (struct call *). In fact it doesn't care, and it shouldn't > care. The extension module could be written in assembly language or > APL or even INTERCAL if it obeys the conventions, which don't include > exposing a C type for each object. Another way of looking at it: > methods in extension modules are mostly expected to behave like > methods written in Python. > > I get the impression that you are using some "superglue" that parses C > declarations and writes (parts of) Python extension modules in C. Do > you think you could possibly tell us what the name of this superglue is? > >> Is python not intelligent enough to diagnose the next pointer ?? > > > To the extent to which I can understand what your question means, the > answer is: It by design makes no attempt to be what you are calling > intelligent. > > Python does only limited inspection of the tables of methods that an > extension type says it supports. It uses only the very basic > information: is the pointer to method X NULL? > > I hope some of the above helps you amplify your question. > > Cheers, > John From pc at p-cos.net Tue Jun 20 13:14:33 2006 From: pc at p-cos.net (Pascal Costanza) Date: Tue, 20 Jun 2006 19:14:33 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <4fpvbvF1keed1U1@individual.net> Message-ID: <4fqonoF1kfkapU1@individual.net> Matthias Blume wrote: > Pascal Costanza writes: > >> - In a dynamically typed language, you can run programs successfully >> that are not acceptable by static type systems. > > This statement is false. The example I have given is more important than this statement. > For every program that can run successfully to completion there exists > a static type system which accepts that program. Moreover, there is > at least one static type system that accepts all such programs. > > What you mean is that for static type systems that are restrictive > enough to be useful in practice there always exist programs which > (after type erasure in an untyped setting, i.e., by switching to a > different language) would run to completion, but which are rejected by > the static type system. No, that's not what I mean. >> Here is an example in Common Lisp: >> >> ; A class "person" with no superclasses and with the only field "name": >> (defclass person () >> (name)) >> >> ; A test program: >> (defun test () >> (let ((p (make-instance 'person))) >> (eval (read)) >> (slot-value p 'address))) >> >> (slot-value p 'address) is an attempt to access the field 'address in >> the object p. In many languages, the notation for this is p.address. >> >> Although the class definition for person doesn't mention the field >> address, the call to (eval (read)) allows the user to change the >> definition of the class person and update its existing >> instances. Therefore at runtime, the call to (slot-value p 'adress) >> has a chance to succeed. > > I am quite comfortable with the thought that this sort of evil would > get rejected by a statically typed language. :-) This sort of feature is clearly not meant for you. ;-P Pascal -- 3rd European Lisp Workshop July 3 - Nantes, France - co-located with ECOOP 2006 http://lisp-ecoop06.bknr.net/ From david.reitter at gmail.com Thu Jun 15 20:03:34 2006 From: david.reitter at gmail.com (david.reitter at gmail.com) Date: 15 Jun 2006 17:03:34 -0700 Subject: a good programming text editor (not IDE) In-Reply-To: References: <1150411969.535331.43840@g10g2000cwb.googlegroups.com> Message-ID: <1150416213.955557.117500@r2g2000cwb.googlegroups.com> Slawomir Nowaczyk wrote: > #> That's true, but even emacs and xemacs don't offer simple automatic > #> word wrap (i.e. wrap a line without splitting words or putting an eol > #> or hard carriage return at the end of every line). > > Of course it does... there is longlines.el and longlines-mode in my > copy of GNU Emacs: > > ,-------------------------------------------------- > | Toggle Long Lines mode. > | In Long Lines mode, long lines are wrapped if they extend beyond > | `fill-column'. The soft newlines used for line wrapping will not > | show up when the text is yanked or saved to disk. > `------------------------------------------------- Not quite. Longlines Mode actually inserts real carriage returns into the buffer, which you will notice in a lot of situations. For example, text does not get rewrapped when you resize the frame to a different width. Also, searching for two words (with a space in between them) won't work when the target text happens to wrap them just there (happens to me all the time when editing LaTeX). Thirdly, you'll find that when you load a file, its lines won't automatically wrap at the frame (actually, the window) width position. All of these things don't bother long-time Emacs people, because most of them tend to see a GUI as a way to display many terminals (something like that has been said by someone else before in this thread), and most of them rely on traditional Unix tools such as grep which work line-by-line. I have advocated seeing lines (with a CR and/or LF) as paragraphs, and making the display of lines a matter of the particular display, not the original data. That is much more natural for wrapped text, i.e. real text rather than computer-parseable files. A patch to Emacs 22 has been produced after that discussion, but sadly, it isn't mature enough to make it into the final Emacs 22 release. But I am confident we're going to see this in GNU Emacs 23, or at least in Aquamacs Emacs in a little while. From manuelg at gmail.com Mon Jun 19 14:29:09 2006 From: manuelg at gmail.com (manuelg at gmail.com) Date: 19 Jun 2006 11:29:09 -0700 Subject: copyfile avoiding overwrites and race conditions References: <1150494450.684069.104490@h76g2000cwa.googlegroups.com> <4496AD5D.1040309@websafe.com> Message-ID: <1150741749.864857.247530@y41g2000cwy.googlegroups.com> Larry Bates wrote: > I guess my approach would be different. To eliminate any race > conditions, I would keep a small text file that always contained > the next filename that is to be written. Something like: > > nextfiletowrite=/path/filename006.dat > > I would try to get a lock on this file, read it, extract next > filename, increment the counter portion of the filename, > write it back out and unlock it. Now I have the name of the > file to write that is unique to my instance and I can write it > without worrying about other processes. Yes, that would work as well but I get the feeling that 1) most people don't write to an automatically incrementing filename 2) the few who do don't sweat the race condition Thanks for your reply Manuel From deets at nospam.web.de Wed Jun 28 16:10:47 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 28 Jun 2006 22:10:47 +0200 Subject: Generator naming convention? In-Reply-To: <1151520720.749818.131460@i40g2000cwc.googlegroups.com> References: <1151520720.749818.131460@i40g2000cwc.googlegroups.com> Message-ID: <4gg61vF1lumumU1@uni-berlin.de> aurora00 at gmail.com schrieb: > I use generators a lot. E.g. > > > def gen_words(text) > ... parse text ... > yield each word in text > > for word in gen_words(text): > print word > > > I don't like the name gen_xxx() very much. Looking for some inspiration > to name generators. Here are some of my ideas: > > enumerate_words > gen_words > generate_words > parse_words > walk_words > > Any idea? Do you have a naming convention for generators? No. From my POV, a generator is not different from any other method returning a list. I don't care if the implementation is def words(): return ["dies", "ist", "das", "Haus", "vom", "Nikolaus"] or def words(): for w in ["dies", "ist", "das", "Haus", "vom", "Nikolaus"]: yield w Regards, Diez From deets at nospam.web.de Mon Jun 26 04:50:19 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 26 Jun 2006 10:50:19 +0200 Subject: Interactive debugging References: <1151296785.275841.294080@y41g2000cwy.googlegroups.com> Message-ID: <4g9lebF1minr8U1@uni-berlin.de> 63q2o4i02 at sneakemail.com wrote: > Hi, is there a way in python to place some sort of keyboard() type > statement which stops the script and puts you back at the console? I'm > looking for something like in matlab, where you place a keyboard() > command (I think), then you're in debug mode in the console, and you > type continue to re-enter the script where you left off. While you're > in the debugger/console you're at the scope where the keyboard() call > was and you can manipulate variables, etc. Is there something like > this in python? I've been using winpdb, which is great, but sometimes > I need more interactivity. Is this what pdb is about? Use import pdb pdb.set_trace() The line where the set_trace() is invoked puts you back in the interpreter. Diez From __peter__ at web.de Thu Jun 1 03:52:25 2006 From: __peter__ at web.de (Peter Otten) Date: Thu, 01 Jun 2006 09:52:25 +0200 Subject: shuffling elements of a list References: <1149045499.212967.13120@f6g2000cwb.googlegroups.com> <1149147164.012044.66960@u72g2000cwu.googlegroups.com> Message-ID: Gerard Flanagan wrote: > Ben Finney wrote: >> pile_index = 0 >> for card in deck: >> piles[pile_index].append(card) >> pile_index = (pile_index + 1) % numpiles >> > > no need to maintain an index ;-) > > piles = [ list() for _ in range(n) ] > for i, card in enumerate(deck): > piles[i % numpiles].append(card) No need to maintain an index ;-) piles = [deck[start::numpiles] for start in range(numpiles)] Assuming deck is a list, that is. Peter From bdesth.quelquechose at free.quelquepart.fr Mon Jun 5 21:58:14 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 06 Jun 2006 03:58:14 +0200 Subject: Adding attribute to objetcs In-Reply-To: <1149542058.273735.259150@u72g2000cwu.googlegroups.com> References: <1149542058.273735.259150@u72g2000cwu.googlegroups.com> Message-ID: <4484b193$0$14843$626a54ce@news.free.fr> faulkner a ?crit : (please, don't top-post - corrected) > > Miguel Galves wrote: > >>Hello, >> >>I`m starting to learn python, and I hava a very good background in Java >>and C/C++ programming. I was reading Dive into python chapter about >>OO and I saw that in python we can do the following: >> >>class Person: Do yourself a favor : use new-style classes class Person(object): >> pass >> >>joe = new Person() joe = Person() No 'new' keyword needed - Python classes are callable objects acting as factory. >>joe.name = "Joe" >>joe.age = 13 >> >>It seems that it is possible to add attributes to any object instance >>in run time, as in Javascript. Yes, unless you used __slots__ in your class. >> It seems to me that it can be a source >>of errors. Almost never happened to me in 7+ years of Python programming. > One that come in my mind is the follwing: >> >>class Person: >> name = "" This creates a class attribute (ie: shared by all instances of the class). For an instance attribute, you want this: class Person(object): def __init__(self, name="") self.name = name >>joe = new Person() >>joe.nome = "Joe" >> >>The code above adds an attribute called nome, but the programmer may think >>it's name. Then he haven't read it's code !-) >>What is the real interest of this feature ? Doing things you can't even dream of in Java or C++. Now if this scares you, what about dynamically adding/replacing a method to/of a whole class or on a per-instance basis, or changing the class of an object at runtime ?-) > Is there a way to block this >>kind of error ? If you're serious, you use automated unit tests, and you'll notice the error pretty quickly. Even if you don't use automated unit-tests, the test/code cycle in Python is so fast that you'll still notice the problem pretty soon. And also, there are tools like pylint that may help you catch a lot of typos. Now in practice, I can assure you this is nothing to worry about. Since Python doesn't get in the way, one usually stay very focused on the actual code being written instead of fighting with boiler-plate. > when you set an attribute of an object, python secretly calls that > objects __setattr__ method. > class test: *please* use new-style classes. > def __setattr__(self, attr_name, attr_value): > print self, attr_name, attr_value stdout is for normal program outputs. Trace etc should go either to a log and/or to stderr. > self.__dict__[attr_name] = attr_value # do what the original > __setattr__ method does. And ? How will this "block this kind of error" ? Are you suggesting to test for names in __setattr__ ? This would be totally stupid IMHO. Python *is* dynamic. period. Better to go with the language than to try to force it into a brain-dead mockup of Java. From fredrik at pythonware.com Thu Jun 22 10:57:21 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 22 Jun 2006 16:57:21 +0200 Subject: The code that could not be... In-Reply-To: <1150936844.874347.163060@r2g2000cwb.googlegroups.com> References: <1150936844.874347.163060@r2g2000cwb.googlegroups.com> Message-ID: Alex A. Naanou wrote: > To mention several tasks that can be made trivial using this technique > are, for instance zope-like acquisitions, various ACLs, interfaces and > other namespace manipulation patterns. eh ? why not use Python's OO mechanisms for this, like everyone else is doing... From R.Brodie at rl.ac.uk Tue Jun 27 10:01:48 2006 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Tue, 27 Jun 2006 15:01:48 +0100 Subject: Having problems with strings in HTML References: Message-ID: "Sion Arrowsmith" wrote in message news:gLB*BXekr at news.chiark.greenend.org.uk... >>By the way, you _do_ realize that your "&" characters should be escaped >>as "&", don't you? > > No they shouldn't. They part of the url, which is (IIRC) a CDATA > attribute of the A element, not PCDATA. It is CDATA but ampersands still need to be escaped. From nospam at nospam.com Wed Jun 21 12:10:08 2006 From: nospam at nospam.com (3c273) Date: Wed, 21 Jun 2006 09:10:08 -0700 Subject: OS specific command in Python References: <1150781429.090359.148560@c74g2000cwc.googlegroups.com> <44979b35$0$8390$626a54ce@news.free.fr> <1150823140.295590.307390@i40g2000cwc.googlegroups.com> <4498d973$0$25496$626a54ce@news.free.fr> Message-ID: "Avell Diroll" wrote in message news:4498d973$0$25496$626a54ce at news.free.fr... > ##Python Script : > from subprocess import Popen > p1 = Popen(["dmesg"], stdout=PIPE) > p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) > output = p2.communicate()[0] I was just trying to learn how to use .communicate() and all of the examples I see have [0] after .communicate(). What is the significance of the [0]? Thanks for your help. Louis From amorgan at xenon.Stanford.EDU Sun Jun 4 01:12:52 2006 From: amorgan at xenon.Stanford.EDU (Alan Morgan) Date: Sat, 3 Jun 2006 22:12:52 -0700 (PDT) Subject: Python less error-prone than Java References: <3Vtgg.2967$ap3.12@news-server.bigpond.net.au> Message-ID: In article <3Vtgg.2967$ap3.12 at news-server.bigpond.net.au>, Neil Hodgson wrote: >Alan Morgan wrote: > >> Since Java doesn't allow function overloading that clearly can't be >> the way. J2SE 5.0 allows generic classes and functions that operate >> on generic containers. There are some gotchas, but it's not drastically >> more complex than the original int-only java code. > > Doesn't Java restrict generics to only operate on reference types so >you can't produce a generic binary search that operates on arrays where >the item type may be int? Yup, you have to wrap int (and double and float and...). Blame type erasure. Alan -- Defendit numerus From martin.witte at gmail.com Fri Jun 23 11:38:38 2006 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 23 Jun 2006 08:38:38 -0700 Subject: what exceptions may file() and read() throw? In-Reply-To: References: Message-ID: <1151077118.742687.277010@p79g2000cwp.googlegroups.com> Daniel Sch?le wrote: > Hello, > > currently I am using this instance method > > def getFilecontent(self, filename): > try: > return file(filename).read() > except IOError, err_msg: > print err_msg > sys.exit(1) > except: > print "unknown exception in PackageParser" > sys.exit(1) > > I tried to open a file for which I don't have the permissions to read > (etc/shadow) > and I tried to open a file which doesn't exist > in both cases I got IOError exception, so my question is > does it make sence to have > > except: > print "unknown exception in PackageParser" > sys.exit(1) > > or is it a dead code? > are there some good reference sources to see what file() and read() > may throw, IMHO it's OS dependent. > > Regards, Daniel You also could do something like def getFilecontent(self, filename): try: return file(filename).read() except IOError, err_msg: print err_msg sys.exit(1) except Exception ,e: print e.__class__, str(e) Then the next tiome this happens you have more information on what happened From diffuser78 at gmail.com Thu Jun 22 16:55:16 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 22 Jun 2006 13:55:16 -0700 Subject: Network Programming in Python In-Reply-To: <449affdd$0$32633$626a54ce@news.free.fr> References: <1151002934.586359.174540@m73g2000cwd.googlegroups.com> <1151006542.682915.83500@c74g2000cwc.googlegroups.com> <449affdd$0$32633$626a54ce@news.free.fr> Message-ID: <1151009716.570612.37790@c74g2000cwc.googlegroups.com> I got it ...initially sourceforge page linked all old libraries..later then got this link to twistedmatrix. Thanks. Bruno Desthuilliers wrote: > diffuser78 at gmail.com a ?crit : > > I have Python 2.4.2 on windows and Linux both. I got an import error. > > how can we obtain the twisted libraries ? > > Is google down ? From ms at cerenity.org Sun Jun 25 07:28:18 2006 From: ms at cerenity.org (Michael) Date: Sun, 25 Jun 2006 12:28:18 +0100 Subject: PEP thought experiment: Unix style exec for function/method calls Message-ID: <449e72ec$0$3530$ed2619ec@ptn-nntp-reader01.plus.net> Hi, [ I'm calling this PEP thought experiment because I'm discussing language ideas for python which if implemented would probably be quite powerful and useful, but the increased risk of obfuscation when the ideas are used outside my expected/desired problem domain probably massively outweigh the benefits. (if you're wondering why, it's akin to adding a structured goto with context) However I think as a thought experiment it's quite useful, since any language feature can be implemented in different ways, and I'm wondering if anyone's tried this, or if it's come up before (I can't find either if they have...). ] I'm having difficulty finding any previous discussion on this -- I keep finding people either having problems calling os.exec(lepev), or with using python's exec statement. Neither of which I mean here. Just for a moment, let's just take one definition for one of the os.exec* commands: execv(...) execv(path, args) Execute an executable path with arguments, replacing current process. path: path of executable file args: tuple or list of strings Also: Note that execv inherits the system environment. Suppose we could do the same for a python function - suppose we could call the python function but either /without/ creating a new stack frame or /replacing/ the current stack frame with the new one. Anyway, I've been thinking recently that the same capability in python would be useful. However, almost any possible language feature: * Has probably already been discussed to death in the past * There's often a nice idiom working around the lack of said feature. So I'm more on an exploratory forage than asking for a language change here ;) Since os.exec* exists and "exec" already exists in python, I need to differentiate what I mean by a unix style exec from python. So for convenience I'll call it "cexe". Now, suppose I have: ---------- def set_name(): name = raw_input("Enter your name! > ") cexe greet() def greet(): print "hello", name cexe set_name() print "We don't reach here" ---------- This would execute, ask for the user's name, say hello to them and then exit - not reaching the final print "We don't reach here" statement. Let's ignore for the moment that this example sucks (and is a good example of the danger of this as a language feature), what I want to do here is use this to explain the meaning of "cexe". There's two cases to consider: cexe some_func_noargs() This transfers execution to the function that would normally be called if I simply called without using "cexe" some_func_noargs() . However, unlike a function call, we're /replacing/ the current thread of execution with the thread of execution in some_func_noargs(), rather than stacking the current location, in order to come back to later. ie, in the above this could also be viewed as "call without creating a new return point" or "call without bothering to create a new stack frame". It's this last point why in the above example "name" leaks between the two function calls - due to it being used as a cexe call. Case 2: given... def some_func_withargs(colour,tone, *listopts, **dictopts) consider... cexe some_func_withargs(foo,bar, *argv, **argd) This would be much the same as the previous case, except in the new execution point, the name colour & tone map to the values foo & bar had in the original context, whilst listopts and dictopts map the values that argv & argd had in the original content) One consequence here though is that in actual practice the final print statement of the code above never actually gets executed. (Much like if that was inside a function, writing something after "return foo", wouldn't be executed) The reason I'm curious here about previous discussion is because conceptually there's obviously other semantics you can apply - such as the current stack frame is /replaced/ by the new stack frame. This is perhaps a more accurate mapping to the Unix exec call. If that was the case, it would mean that locals would not "leak" between functions (which is desirable), and our example above could be rewritten as follows: ---------- def get_and_use_value_from_user(tag, callforward): somevalue = raw_input(tag) cexe callforward(name) def greet(name): print "hello", name cexe get_and_use_value_from_user("Enter your name! > ", greet) print "We don't reach here" ---------- OK, so this probably seems pretty pointless to many people, but I'm curious about improving the tools to deal with state machines. Often people use switch statements in other languages to deal with them, and for certain classes of state machines you can use replace them with generators. But that's not appropriate for everything... My particular thought that started all this off actually stems from this: Essentially by doing a cexe we're actually creating a composite function out of disparate functions (perhaps shared or not shared local context). ie ... ---------- def count(): print "Counting to 3!" cexe one() def one(): print "one!" cexe two() def two(): print "two!" cexe three() def three(): print "three!" count() # Note I'm not doing cexe count() here ---------- ... essentially dynamically constructs an execution context similar to a single function, ie the above collapses to something like: ---------- def count(): print "Counting to 3!" print "one!" print "two!" print "three!" count() # Note I'm not doing cexe count() here ---------- It's this recognition that made me wonder this: This works well for state machines, and generators are a nice model for dealing with resumable things (and a state machine can be viewed as a resumable "thing"). Now suppose we take all that one stage further and provide said composite generator, with some additional context in the way we do with Kamaelia - cf http://kamaelia.sf.net/MiniAxon/ , we could potentially do this: (choosing something relatively substantial to show I'm not just being whimsical, and to provide somthing perhaps more "real") class TCP_StateMachine(Axon.Component.component): def CLOSED(self): if not self.anyReady(): yield self.pause() event = self.recv("inbox") if "appl passive open" == event.type: cexe self.LISTEN() if "active open" == event.type: self.send(SYN(event.payload), "network") cexe self.SYN_SENT() def LISTEN(self): if not self.anyReady(): yield self.pause() event = self.recv("inbox") if "recv syn" == event.type: self.send( , "network") cexe self.SYN_RCVD() if "appl send data" == event.type: self.send( , "network") cexe self.SYN_SENT() def SYN_RCVD(self): if not self.anyReady(): yield self.pause() event = self.recv("inbox") if "recv rst" == event.type: cexe self.LISTEN() if "recv ack" == event.type: cexe self.ESTABLISHED() if "appl close" == event.type: self.send(FIN(event.payload), "network") cexe self.FIN_WAIT1() def SYN_SENT(self): if not self.anyReady(): yield self.pause() event = self.recv("inbox") if "appl close" == event.type: cexe self.CLOSED() if "timeout" == event.type: cexe self.CLOSED() if "recv syn-ack" == event.type: self.send(ACK(event.payload), "network") cexe self.ESTABLISHED() def ESTABLISHED(self): # more complex than others, so skipped, has its own data transfer # state etc, so would make more sense to model as a subcomponent. def FIN_WAIT_1(self): if not self.anyReady(): yield self.pause() event = self.recv("inbox") if "recv ack" == event.type: cexe self.FIN_WAIT_2() if "recv fin" == event.type: self.send(ACK(event.payload), "network") cexe self.CLOSING() if "recv fin, ack" == event.type: self.send(ACK(event.payload), "network") cexe self.TIME_WAIT() def FIN_WAIT_2(self): if not self.anyReady(): yield self.pause() event = self.recv("inbox") if "recv fin" == event.type: self.send(ACK(event.payload), "network") cexe self.TIME_WAIT() def CLOSING(self): if not self.anyReady(): yield self.pause() event = self.recv("inbox") if "recv ack" == event.type: cexe self.TIME_WAIT() def TIME_WAIT(self): if not self.anyReady(): yield self.pause() event = self.recv("inbox") if "timeout 2MSL" == event.type: cexe self.CLOSED() Now obviously that's not particularly pretty, but the clear definition of states as methods, and clear transitions between states via the cexe calls, is relatively easy to follow through. ie it's fairly clear it's implementing the standard TCP state machine. (Incidentally if you're wondering what relevance this has outside of just TCP, this sort of thing could be useful in games for modelling complex behaviours) What is less clear about this is that I'm working on the assumption that as well as the language change making "cexe" work, is that this also allows the above set of methods to be treated as if it's one large generator that's split over multiple function definitions. This is conceptually very similar to the idea that cexe would effectively "join" functions together, as alluded to above. This has a number of downsides for the main part of the language, so I wouldn't suggest that these changes actually happen - consider it a thought experiment if you like. (I think the single function/no wrapping of yield IS actually a good thing) However, I feel the above example is quite a compelling example of how a unix style exec for python method calls could be useful, especially when combined with generators. (note this is a thought experiment ;) It also struck me that any sufficiently interesting idea is likely to have already been implemented, though perhaps not looking quite like the above, so I thought I'd ask the questions: * Has anyone tried this sort of thing? * Has anyone tried simply not creating a new stack frame when doing a function call in python? (or perhaps replacing the current one with a new one) * Has anyone else tried modelling the unix system exec function in python? If so what did you find? * Since I can't find anything in the archives, I'm presuming my searching abilities are bust today - can anyone suggest any better search terms or threads to look at? * Am I mad? :) BTW, I'm aware that this has similarities to call with continuation, and that you can use statesaver.c & generators to achieve something vaguely similar to continuations, but I'm more after this specific approach, rather than that general approach. (After all, even ruby notes that their most common use for call/cc is to obfuscate code - often accidentally - and I'm not particularly interested in that :) Whereas the unix style exec is well understood by many people, and when it's appropriate can be extremely useful. My suspicion is that my ideasabove actually maps to a common idiom, but I'm curious to find that commonidiom. I'm fairly certain something like this could be implemented using greenlets, and also fairly certain that Stackless has been down this route in the past, but I'm not able to find something like this exec style call there. (Which is after all more constrained than your usual call with continuation approach) So, sorry for the length of this, but if anyone has any thoughts, I'd be very interested. If they don't, I hope it was interesting :) Regards, Michael. From tenax.raccoon at gmail.com Tue Jun 20 17:07:01 2006 From: tenax.raccoon at gmail.com (Jason) Date: 20 Jun 2006 14:07:01 -0700 Subject: Python with Eclipse In-Reply-To: References: Message-ID: <1150837621.358208.296610@u72g2000cwu.googlegroups.com> PyDev Eclipse keeps around the python interpreter unless it gets removed. I think part of the point is to keep around failed runs so the user can investigate the stack. Eclipse doesn't keep this around if you Run you script, but it will keep the interpreter alive if you Debug your script, regardless of how it exits. (It may dispose of the interpreter if your program exits with a normal error code.) Anyway, in the Debug View, you can see a list of all the python interpreters that PyDev and Eclipse are keeping alive. There's a set of debugging-related buttons just above: step into, step over, step return, continue, and others. One of the buttons there looks like a couple of "X" symbols. This button officially shuts down a python interpreter. (Be careful and don't actually click the "X" symbol that closes the debug area!) --Jason Stan Cook wrote: > I've been trying to use Eclipse with Python on Linux for a > while and have noticed something odd. After running the > code or debugging a few times, its responsiveness gets > really bad. Upon checking the equivalent of the task > manager, I find several instances of Python running. When I > kill these instances, the responsiveness comes back. I'm > not sure if there is a better place to post this, but it is > Python related. Is this just an issue with Eclipse or is > there something else I should inspect? > > Any help would be appreciated. > > Regards, > > S Cook From luc.saffre at gmail.com Thu Jun 22 13:36:17 2006 From: luc.saffre at gmail.com (luc.saffre at gmail.com) Date: 22 Jun 2006 10:36:17 -0700 Subject: Standard names for common keyboard events Message-ID: <1150997777.416199.30210@i40g2000cwc.googlegroups.com> Hello, I thought that I should ask here for comments on a blog entry that I wrote some weeks ago. I am sure that other people have been thinking about this, but I didn't yet find them. The Python standard library unfortunately doesn't provide a module that gives unique names to common keyboard events. Even Tkinter had to write a complex parser to find out which keyboard event the programmer actually means. The parser literally plays a guessing game. If you want an event to happen when the user presses for example the key combination Shift-F7, then you (the programmer) are free to call this key S-F7, Sh-F7, Shift+F7,... and many more. Tkinter will understand you! This is artificial intelligence! At run-time, while the user is waiting! What a strange approach! wxPython is also funny. Here is an excerpt from the wxMenu::Append() documentation: The item string for the normal menu items (not submenus or separators) may include the accelerator which can be used to activate the menu item from keyboard. The accelerator string follows the item label and is separated from it by a TAB character ('\t'). Its general syntax is any combination of "CTRL", "ALT" and "SHIFT" strings (case doesn't matter) separated by either '-' or '+' characters and followed by the accelerator itself. The accelerator may be any alphanumeric character, any function key (from F1 to F12) or one of the special characters listed in the table below (again, case doesn't matter): wxPython has a lot of constants to name common key events. For example the ?page down? key is called wx.WXK_PAGEDOWN. But if you specify PAGEDOWN in a wxMenu::Append() string, it won't work. Because for wxMenu::Append() you must call this key PGDN. I don't blame neither Tkinter nor wxPython, but these funny observations show that a standard method to speak about keyboard events would be useful. I agree that the subject is not trivial, and that there are more than one possible ways to implementat such a module. But as long as I don't find a better solution I'll use my selfmade module: http://svn.berlios.de/wsvn/lino/trunk/src/lino/forms/keyboard.py?op=file&rev=0&sc=0 (Original entry is at http://lino.saffre-rumma.ee/news/356.html) Luc From slawomir.nowaczyk.847 at student.lu.se Thu Jun 1 18:40:47 2006 From: slawomir.nowaczyk.847 at student.lu.se (Slawomir Nowaczyk) Date: Fri, 02 Jun 2006 00:40:47 +0200 Subject: An oddity in list comparison and element assignment In-Reply-To: <1149199942.955228.281950@u72g2000cwu.googlegroups.com> References: <1149199942.955228.281950@u72g2000cwu.googlegroups.com> Message-ID: <20060602002705.FC33.SLAWOMIR.NOWACZYK.847@student.lu.se> On Thu, 01 Jun 2006 15:12:23 -0700 michael.f.ellis at gmail.com wrote: #> I believe that 'is' tests equality of reference, such that #> #> >>> a = range(1,3) #> >>> b = range(1,3) #> >>> a is b #> False #> #> The 'is' operator tells you whether a and b refer to the same object. #> What I've been discussing is whether == should test for "structural" #> equality so that a and b remain equivalent under parallel mutations #> (and also under single mutations to common references) What does "parallel mutations" mean? In particular, what should be the results of each of the following three comparisons: x, y, z = [1],[1],[1] a, b = [x,y], [y,z] c, d = [[1],[1]], [[1],[1]] a == b c == d a[0].remove(1) b[0].remove(1) a == b So, do I understand correctly that you would like first comparison (a==b) to return "False" and second comparison (c==d) to return "True"? -- Best wishes, Slawomir Nowaczyk ( Slawomir.Nowaczyk at cs.lth.se ) Living on Earth may be expensive, but it includes an annual free trip around the Sun. From cdsmith at twu.net Sun Jun 25 16:28:22 2006 From: cdsmith at twu.net (Chris Smith) Date: Sun, 25 Jun 2006 14:28:22 -0600 Subject: What is Expressiveness in a Computer Language References: <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <34aj92h0g7tqi9amhh7k3ieq5n568t0e6f@4ax.com> Message-ID: George Neuner wrote: > >Undecidability can always be avoided by adding annotations, but of > >course that would be gross overkill in the case of index type widening. > > Just what sort of type annotation will convince a compiler that a > narrowing conversion which could produce an illegal value will, in > fact, never produce an illegal value? The annotation doesn't make the narrowing conversion safe; it prevents the narrowing conversion from happening. If, for example, I need to subtract two numbers and all I know is that they are both between 2 and 40, then I only know that the result is between -38 and 38, which may contain invalid array indices. However, if the numbers were part of a pair, and I knew that the type of the pair was , then I would know that the difference is between 0 and 38, and that may be a valid index. Of course, the restrictions on code that would allow me to retain knowledge of the form [pair of numbers, 2 through 40, a > b] may be prohibitive. That is an open question in type theory, as a matter of fact; whether types of this level of power may be inferred by any tractable procedure so that safe code like this may be written without making giving the development process undue difficulty by requiring ten times as much type annotations as actual code. There are attempts that have been made, and they don't look too awfully bad. -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation From chris.uppal at metagnostic.REMOVE-THIS.org Thu Jun 22 10:49:57 2006 From: chris.uppal at metagnostic.REMOVE-THIS.org (Chris Uppal) Date: Thu, 22 Jun 2006 15:49:57 +0100 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> Message-ID: <449aaea0$1$656$bed64819@news.gradwell.net> I wrote: > It would be interesting to see what a language designed specifically to > support user-defined, pluggable, and perhaps composable, type systems > would look like. Since writing that I've come across some thoughts by Gilad Bracha (a Name known to Java and Smalltalk enthusiasts alike) here: http://blogs.sun.com/roller/page/gbracha?entry=a_few_ideas_on_type and a long, and occasionally interesting, related thread on LtU: http://lambda-the-ultimate.org/node/1311 Not much discussion of concrete language design, though. -- chris From gregpinero at gmail.com Tue Jun 6 17:50:46 2006 From: gregpinero at gmail.com (=?ISO-8859-1?Q?Gregory_Pi=F1ero?=) Date: Tue, 6 Jun 2006 17:50:46 -0400 Subject: tempfile Question Message-ID: <312cfe2b0606061450xe855e76r426ee757829c06fb@mail.gmail.com> Hey group, I have a command line tool that I want to be able to call from a Python script. The problem is that this tool only writes to a file. So my solution is to give the tool a temporary file to write to and then have Python read that file. I figure that's the safest way to deal with this sort of thing. (But I'm open to better methods). Here's my code so far, could anyone tell me the proper way to use tempfile. This code won't let the tool write to the file because Python has it locked. But I'm worried that if I close the file then windows might take it away? I have no idea. PDFTOTEXTPATH=r'C:\xpdf-3.01pl2-win32\xpdf-3.01pl2-win32\pdftotext.exe' def read_pdf_text(filepath): outfile=tempfile.NamedTemporaryFile() outfilename=outfile.name command=r'"%s" "%s" "%s"' % (PDFTOTEXTPATH,filepath,outfilename) result=os.popen(command).read() pdftext=outfile.read() outfile.close() return pdftext Much thanks! -- Gregory Pi?ero Chief Innovation Officer Blended Technologies (www.blendedtechnologies.com) From faulkner612 at comcast.net Fri Jun 2 21:43:03 2006 From: faulkner612 at comcast.net (faulkner) Date: 2 Jun 2006 18:43:03 -0700 Subject: check for dictionary keys In-Reply-To: <1149298230.864123.8320@u72g2000cwu.googlegroups.com> References: <1149298230.864123.8320@u72g2000cwu.googlegroups.com> Message-ID: <1149298983.720797.8460@i39g2000cwa.googlegroups.com> def all(s): for x in s: if not x: return False return True bad_combos = [['-A', '-B'], ['-A', '-C'], ...] for bad_combo in bad_combos: assert not all([bad_elem in a for bad_elem in bad_combo]) micklee74 at hotmail.com wrote: > hi > in my code, i use dict(a) to make to "a" into a dictionary , "a" comes > from user input, so my program does not know in the first place. Then > say , it becomes > > a = { '-A' : 'value1' , '-B' : "value2" , "-C" : "value3" , '-D' : > 'value4' } > > somewhere next in my code, i will check for these..: > > 1) -A and -B cannot exist together > 2) -A and -C cannot exist together > 3) -A and -B and -D cannot exist together > 4) and lots of other combinations to check for.... > > how can i efficiently check for the above? At first as i do simple > checks , i use if and else. > But as i began to check for more combinatoiuns, it gets messy.... > > thanks. From andre.roberge at gmail.com Tue Jun 6 18:12:18 2006 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: 6 Jun 2006 15:12:18 -0700 Subject: newbie: python application on a web page In-Reply-To: <9PSdnTgkR_-HehjZnZ2dnUVZ_qidnZ2d@is.co.za> References: <1149615269.695229.88820@j55g2000cwa.googlegroups.com> <1149624046.762779.225240@h76g2000cwa.googlegroups.com> <9PSdnTgkR_-HehjZnZ2dnUVZ_qidnZ2d@is.co.za> Message-ID: <1149631938.190738.130070@g10g2000cwb.googlegroups.com> Max wrote: > puzz wrote: > > sorry about the missunderstanding... > > > > but my question is "how" and not "where" to put it online > > and that's where the "newbie" comes from > > > > P M > > If you just want to make it available for download, that's easy. If you > want to make it open source, you could upload it to > planet-source-code.com (I used to put a lot there; don't know if they > have a python section) or SourceForge depending on your "market". > > But what I think you want is a web interface (where a user goes to your > site and uses it in the browser window). This is more tricky, but you're > almost certainly going to have to abandon Tkinter. You could try doing > an applet in Jython (which compiles Python to Java bytecode so you could > in theory do a Java-style applet). > > The alternative is to have the curve drawn server-side, so you would > have an HTML form on the page, and on clicking a button, load the graph > (into an "iframe" or something perhaps [I have a feeling iframes have > been deprecated - check first]). In which case you'd want to look up > CGI, AJAX, etc. > I'd suggest drawing curves in a ; supported by Firfox, Safari, Opera ... and, if you use Google's "excanvas", it can be supported by IE. Andr? > --Max From onurb at xiludom.gro Thu Jun 29 08:06:35 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Thu, 29 Jun 2006 14:06:35 +0200 Subject: Python decompiler In-Reply-To: References: Message-ID: <44a3c24b$0$7134$626a54ce@news.free.fr> subramanian2003 wrote: > Hello All, > > I have some compiled python 2.4 scripts. If anyone has python decompiler, pls send me. > Do you have the right to decompile them ? Usually, open source softwares - as the name imply - are ditributed with the sources, or have an available source distribution. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From steve at holdenweb.com Sat Jun 10 08:36:24 2006 From: steve at holdenweb.com (Steve Holden) Date: Sat, 10 Jun 2006 13:36:24 +0100 Subject: wxPython: Should you use a master sizer object? In-Reply-To: References: Message-ID: John Salerno wrote: > Sorry for posting here again. I tried the wxPython list but I'm not sure > I'm sending to the right email address! It bounced back. Besides, your > opinions are too good to pass up. ;) > > My question was: > > I was wondering, is it recommended to always have a top-level sizer in > which you place all other sizers, or is it acceptable to have mulitple > sizers that are not grouped together? You should definitely create a master sizer, and then add sub-sizers to it. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From david.nospam.hopwood at blueyonder.co.uk Wed Jun 28 17:33:05 2006 From: david.nospam.hopwood at blueyonder.co.uk (David Hopwood) Date: Wed, 28 Jun 2006 21:33:05 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <1151199196.870389.81960@p79g2000cwp.googlegroups.com> <_xrng.108673$H71.2451@newssvr13.news.prodigy.com> Message-ID: Anton van Straaten wrote: > Chris Smith wrote: > >> What makes static type systems interesting is not the fact that these >> logical processes of reasoning exist; it is the fact that they are >> formalized with definite axioms and rules of inference, performed >> entirely on the program before execution, and designed to be entirely >> evaluatable in finite time bounds according to some procedure or set >> of rules, so that a type system may be checked and the same conclusion >> reached regardless of who (or what) is doing the checking. All that, >> and they still reach interesting conclusions about programs. > > There's only one issue mentioned there that needs to be negotiated > w.r.t. latent types: the requirement that they are "performed entirely > on the program before execution". More below. > >> If informal reasoning about types doesn't meet these criteria (and it >> doesn't), then it simply doesn't make sense to call it a type system >> (I'm using the static terminology here). It may make sense to discuss >> some of the ways that programmer reasoning resembles types, if indeed >> there are resemblances beyond just that they use the same basic rules >> of logic. It may even make sense to try to identify a subset of >> programmer reasoning that even more resembles... or perhaps even is... >> a type system. It still doesn't make sense to call programmer >> reasoning in general a type system. > > I'm not trying to call programmer reasoning in general a type system. > I'd certainly agree that a programmer muddling his way through the > development of a program, perhaps using a debugger to find all his > problems empirically, may not be reasoning about anything that's > sufficiently close to types to call them that. But "latent" means what > it implies: someone who is more aware of types can do better at > developing the latent types. So these "latent types" may in some cases not exist (in any sense), unless and until someone other than the original programmer decides how the program could have been written in a typed language? I don't get it. > As a starting point, let's assume we're dealing with a disciplined > programmer who (following the instructions found in books such as the > one at htdp.org) reasons about types, writes them in his comments, and > perhaps includes assertions (or contracts in the sense of "Contracts for > Higher Order Functions[1]), to help check his types at runtime (and I'm > talking about real type-checking, not just tag checking). > > When such a programmer writes a type signature as a comment associated > with a function definition, in many cases he's making a claim that's > provable in principle about the inputs and outputs of that function. This is talking about a development practice, not a property of the language. It may (for the sake of argument) make sense to assign a term such as latent typing to this development practice, but not to call the language "latently-typed". -- David Hopwood From david.nospam.hopwood at blueyonder.co.uk Wed Jun 21 13:24:42 2006 From: david.nospam.hopwood at blueyonder.co.uk (David Hopwood) Date: Wed, 21 Jun 2006 17:24:42 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: <1150904475.363283.234730@y41g2000cwy.googlegroups.com> References: <7zpshbsvjy.fsf@app-1.diku.dk><4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <1150809118.677124.142230@u72g2000cwu.googlegroups.com> <1150815461.210286.53120@r2g2000cwb.googlegroups.com> <1150823297.816352.75370@u72g2000cwu.googlegroups.com> <7zzmg6amm1.fsf@app-3.diku.dk> <1150904475.363283.234730@y41g2000cwy.googlegroups.com> Message-ID: Marshall wrote: > Torben ?gidius Mogensen wrote: > >>That's not true. ML has variables in the mathematical sense of >>variables -- symbols that can be associated with different values at >>different times. What it doesn't have is mutable variables (though it >>can get the effect of those by having variables be immutable >>references to mutable memory locations). > > While we're on the topic of terminology, here's a pet peeve of > mine: "immutable variable." > > immutable = can't change > vary-able = can change > > Clearly a contradiction in terms. But one that is at least two hundred years old [*], and so unlikely to be fixed now. In any case, the intent of this usage (in both mathematics and programming) is that different *instances* of a variable can be associated with different values. [*] introduced by Leibniz, according to , but that was presumably in Latin. The first use of "variable" as a noun recorded by the OED in written English is in 1816. -- David Hopwood From sysfault at zetafunc.net Fri Jun 9 15:41:57 2006 From: sysfault at zetafunc.net (Anthony Greene) Date: Fri, 09 Jun 2006 15:41:57 -0400 Subject: Pychecker References: <1149878819.556169.270020@u72g2000cwu.googlegroups.com> Message-ID: On Fri, 09 Jun 2006 11:46:59 -0700, Matt Good wrote: > Anthony Greene wrote: >> Howdy, I had the impression that pychecker caught and reported such >> dynamic syntactical errors. >> >> #!/usr/bin/env python >> >> >> def add(i): >> i += 10 >> >> status = 3 >> >> if 1 == 1: >> statuss = 15 >> >> add(status) >> >> ======================= >> >> exalted sysfault$ pychecker foo.py >> Processing foo... >> >> Warnings... >> >> None >> >> ======================= >> >> Hence the mispelling of status (statuss), which was done purposely to test >> if pychecker will acknowledge and report the error. Do i need to enable >> some type of pychecker option in order for it to pick up the error? I know >> that it is syntactically correct in python, however it's likely that >> 'status' is meant. Am i wishing that pychecker will replace a statically >> typed language mechanism? > > That's a functional error, not a syntactical one. Analyzing the > spelling of variables for similarity would lead to a lot of incorrect > warnings since pychecker has no way to tell this apart from intentional > similar spellings such as: > > values = [1, 2, 3] > value = values[0] > > However, when the misspelling is made inside a local scope, rather than > at the module level a warning is reported "test.py:8: Local variable > (statuss) not used": > > def add(i): > i += 10 > > def test(): > status = 3 > if 1 == 1: > statuss = 15 > add(status) > > > This is why tools like pychecker (or pyflakes, pylint, or even a static > code compiler) aren't a substitute for unit tests. They can definitely > help catch common mistakes, but they can't ensure your code does what > you intended. Thanks guys, exactly what was needed. -- A wise man knows he knows nothing. From webraviteja at gmail.com Mon Jun 19 17:35:23 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 19 Jun 2006 14:35:23 -0700 Subject: code is data In-Reply-To: References: <1150574111.415068.255900@p79g2000cwp.googlegroups.com> <1150606118.456390.262620@y41g2000cwy.googlegroups.com> Message-ID: <1150752923.917182.302630@h76g2000cwa.googlegroups.com> BJ?rn Lindqvist wrote: > > > > community has no interest in it. When I absolutely need macros, I will > > > > go elsewhere. > > I *like* 1..5 (ada, ruby) instead of range(5). If I had macros, I would > > have done it myself for *my* code. > I think this example more is a symptom of a childish need to get > things your way than of a deficiency in Python. I thought I had enough asterisks in there to indicate that it is a preference that I will not be defending on rational grounds. I had a better argument before it in the same post. But you had to choose only the trivial one to dismiss me as childish. Didn't you? :-) > BTW, range(5) = 0..4 in Ada and Ruby. My bad. I usually write range(1, 5 + 1) to get 1..5. I could write range(1, 6). But I would like to see the upper bound explicitly. Of course, I could write a function to wrap that up. > You said "when I absolutely need macros" but none of your examples > demonstrate any "absolute need." I can't see your point. Did you miss the word - *WHEN*? I don't need them absolutely now. And I know, that I won't get them here. And just so you don't misinterpret, I don't call that a "deficiency". Just a mismatch between the personal and the community mindset. BTW, the recent language changes - decorators, conditional expressions and with statements are not absolute either. That did not stop them from being welcome additions. From steve at holdenweb.com Thu Jun 29 08:54:17 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 29 Jun 2006 13:54:17 +0100 Subject: Execute Commands on Remote Computers over Network In-Reply-To: References: <1151378614.481850.271340@c74g2000cwc.googlegroups.com> <1151443795.343874.290790@u72g2000cwu.googlegroups.com> Message-ID: Lawrence D'Oliveiro wrote: > In article <1151443795.343874.290790 at u72g2000cwu.googlegroups.com>, > "dylpkls91" wrote: > > >>Lawrence D'Oliveiro wrote: >> >>>In article <1151378614.481850.271340 at c74g2000cwc.googlegroups.com>, >>> "dylpkls91" wrote: >>> >>> >>>>I have been researching this topic and come up with some code to make >>>>it work. It uses SSL and requires the 3rd party package Paramiko (which >>>>requires PyCrypto). >>> >>>Why not just spawn an invocation of SSH? >> >>Can you explain what this means, and how I could do it in Python? > > > SSH is the standard means of remotely executing commands on one *nix > system from another . It is included with all > self-respecting *nix systems these days. You can set up a trust > relationship between particular accounts on two systems, so one can > connect to the other without a password. All communication is encrypted > to lock out eavesdroppers. Also note that Cygwin gives you openssh in a Unix-shell-like environment. Has its own Python too, though you don't do things in Cygwin for performance, usually. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From rbonvall at gmail.com Sat Jun 3 21:06:12 2006 From: rbonvall at gmail.com (Roberto Bonvallet) Date: Sat, 3 Jun 2006 21:06:12 -0400 Subject: reordering elements of a list In-Reply-To: <1149382009.640607.217470@y43g2000cwc.googlegroups.com> References: <1149382009.640607.217470@y43g2000cwc.googlegroups.com> Message-ID: <1908cb6b0606031806g5a98cbdax6c73c2ce1915bc3d@mail.gmail.com> 3 Jun 2006 17:46:49 -0700, greenflame : > Suppose the main list is: mainlist = list('qwertyuiop') > > Suppose the ordering list is: orderinglist = [3, 4, 2, 1] > > Then I am looking for a function that will take mainlist and > orderinglist as arguments and return the following list: > > ['e', 'r', 'w', 'q', 't', 'y', 'u', 'i', 'o', 'p'] >>> mainlist = list('qwertyuiop') >>> orderinglist = [3, 4, 2, 1] >>> [mainlist[i - 1] for i in orderinglist] + mainlist[len(orderinglist):] ['e', 'r', 'w', 'q', 't', 'y', 'u', 'i', 'o', 'p'] Best regards. -- Roberto Bonvallet From rhymes at myself.com Wed Jun 21 18:21:04 2006 From: rhymes at myself.com (Lawrence Oluyede) Date: Thu, 22 Jun 2006 00:21:04 +0200 Subject: Is it possible to split a class definition? References: <1150927868.807640.45760@c74g2000cwc.googlegroups.com> Message-ID: <1hhb4ui.b1cklg1qvuja4N%rhymes@myself.com> wrote: > Is it possible to split a Class definition over two or more text files? > (if so, how:) There's no partial types like in .NET 2.0 but since Python is dynamic you can add members at runtime :-) -- Lawrence - http://www.oluyede.org/blog "Nothing is more dangerous than an idea if it's the only one you have" - E. A. Chartier From serge.orlov at gmail.com Wed Jun 21 15:07:45 2006 From: serge.orlov at gmail.com (Serge Orlov) Date: Wed, 21 Jun 2006 12:07:45 -0700 Subject: Porting python to a TI Processor (C64xx) In-Reply-To: References: Message-ID: On 6/21/06, Roland Geibel wrote: > > Dear all. > > We want to make python run on DSP processors (C64xx family of TI). I don't know what C64xx is, but I believe python needs general purpose CPU to run I've already tried to ask mickey at vanille.de (about his "Python for > arm-Linux"), > but didn't get an answer so far. > Neither could I find it in the Python tree at sourceforge. What are you trying to find in the sources? Python is just a C program and you port it just like any C program. -------------- next part -------------- An HTML attachment was scrubbed... URL: From piet at cs.uu.nl Fri Jun 23 07:37:25 2006 From: piet at cs.uu.nl (Piet van Oostrum) Date: Fri, 23 Jun 2006 13:37:25 +0200 Subject: What is Expressiveness in a Computer Language References: <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <1150809118.677124.142230@u72g2000cwu.googlegroups.com> <1150815461.210286.53120@r2g2000cwb.googlegroups.com> <1150823297.816352.75370@u72g2000cwu.googlegroups.com> <7zzmg6amm1.fsf@app-3.diku.dk> <1150904475.363283.234730@y41g2000cwy.googlegroups.com> Message-ID: >>>>> "Marshall" (M) wrote: >M> Torben ?gidius Mogensen wrote: >>> >>> That's not true. ML has variables in the mathematical sense of >>> variables -- symbols that can be associated with different values at >>> different times. What it doesn't have is mutable variables (though it >>> can get the effect of those by having variables be immutable >>> references to mutable memory locations). >M> While we're on the topic of terminology, here's a pet peeve of >M> mine: "immutable variable." >M> immutable = can't change >M> vary-able = can change >M> Clearly a contradiction in terms. I would say that immutable = 'can't *be* changed' rather than 'can't change'. But I am not a native English speaker. Compare with this: the distance of the Earth to Mars is variable (it varies), but it is also immutable (we can't change it). -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From benjamin.franksen at bessy.de Wed Jun 21 21:40:48 2006 From: benjamin.franksen at bessy.de (Benjamin Franksen) Date: Thu, 22 Jun 2006 03:40:48 +0200 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <4fpvbvF1keed1U1@individual.net> <4fqonoF1kfkapU1@individual.net> <1150824752.799997.206210@p79g2000cwp.googlegroups.com> <4fqt33F1kfd1jU1@individual.net> <2N3mg.462963$xt.331923@fe3.news.blueyonder.co.uk> <4fsbivF1jqb81U1@individual.net> <4fsu9dF1k21c9U1@individual.net> Message-ID: Pascal Costanza wrote: > There is, of course, room for research on performing static type checks > in a running system, for example immediately after or before a software > update is applied, or maybe even on separate type checking on software > increments such that guarantees for their composition can be derived. > However, I am not aware of a lot of work in that area, maybe because the > static typing community is too focused on compile-time issues. Not everyone is. For instance, Don Stewart has been enormously successful in deploying such a system for Haskell (very much a statically typed language) in a practically usable way. It is called hs-plugins (see http://www.cse.unsw.edu.au/~dons/hs-plugins/), a framework for run-time loading and re-loading of Haskell modules (in source form or already compiled, giving different levels of security). Far from being a purely academic exercise, there are interesting applications, including yi, an extensible editor, and lambdabot, an IRC bot, both available from the above same home page. Cheers, Ben From marshall.spight at gmail.com Mon Jun 19 20:58:22 2006 From: marshall.spight at gmail.com (Marshall) Date: 19 Jun 2006 17:58:22 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: <1150761004.928251.318340@h76g2000cwa.googlegroups.com> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> Message-ID: <1150765102.867144.12590@h76g2000cwa.googlegroups.com> Joe Marshall wrote: > > They *do* have a related meaning. Consider this code fragment: > (car "a string") > [...] > Both `static typing' and `dynamic typing' (in the colloquial sense) are > strategies to detect this sort of error. The thing is though, that putting it that way makes it seems as if the two approaches are doing the same exact thing, but just at different times: runtime vs. compile time. But they're not the same thing. Passing the static check at compile time is universally quantifying the absence of the class of error; passing the dynamic check at runtime is existentially quantifying the absence of the error. A further difference is the fact that in the dynamically typed language, the error is found during the evaluation of the expression; in a statically typed language, errors are found without attempting to evaluate the expression. I find everything about the differences between static and dynamic to be frustratingly complex and subtle. (To be clear, I do know that Joe understands these issues quite well.) So I kind of agree with Chris, insofar as I think the terminology plays a role in obscuring rather than illuminating the differences. On the other hand I agree with Joe in that: > I mean that this has been argued time and time again in comp.lang.lisp > and probably the other groups as well. You may not like the fact that > we say that Lisp is dynamically typed, but *we* are not confused by > this usage. In fact, we become rather confused when you say `a > correctly typed program cannot go wrong at runtime' because we've seen > plenty of runtime errors from code that is `correctly typed'. Yes; as I said ealier, the horse has left the barn on this one. The conversation I would *really* like to have is the one where we discuss what all the differences are, functionally, between the two, and what the implications of those differences are, without trying to address which approach is "right" or "better", because those are dependent on the problem domain anyway, and because I can make up my own mind just fine about which one I prefer. The comp.lang.functional and comp.lang.lisp people are probably two of the smartest groups on usenet. (I do not consider myself a member of either group.) You wouldn't *think* that conversation would be *so* hard to have. Marshall From rogue_pedro at yahoo.com Wed Jun 28 18:46:45 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 28 Jun 2006 15:46:45 -0700 Subject: for and while loops References: <1151531527.496772.65130@i40g2000cwc.googlegroups.com> Message-ID: <1151534805.568766.19050@y41g2000cwy.googlegroups.com> kydavis77 at gmail.com wrote: > i was wondering if anyone could point me to some good reading about the > for and while loops > > i am trying to write some programs > "Exercise 1 > > Write a program that continually reads in numbers from the user and > adds them together until the sum reaches 100. Write another program > that reads 100 numbers from the user and prints out the sum. " > > but im not quite grasping those functions.. > > please bear im mind i am an extreme newbie at this...thanks in advance while loops test a condition every time through the loop and keep running as long as it's true. for loops run through a finite (usually) set of things and do something "for" each thing. Check out one or more python tutorials such as http://docs.python.org/tut/tut.html (and especially this part http://docs.python.org/tut/node6.html), a quick search an google can turn up more. (Hint: you're probably gonna want to use a while loop for the first program and a for loop for the second.) Hope that helps, ~Simon From maric at aristote.info Tue Jun 6 03:11:28 2006 From: maric at aristote.info (Maric Michaud) Date: Tue, 6 Jun 2006 09:11:28 +0200 Subject: OT: unix newbie questions In-Reply-To: References: <20060606035507.XHEA21801.mta9.adelphia.net@AT119L38513> Message-ID: <200606060911.29010.maric@aristote.info> Le Mardi 06 Juin 2006 08:36, Fredrik Lundh a ?crit?: > > *26. You observed that some of your group members are fiddling with your > > file ?"myfile" and you wanted to remove the read permission to your > > group. How do you do? (1) > > ?>>> os.chmod("myfile.txt", 0404) rather, >>> os.chmod("myfile.txt", 0400) I guess. or maybe you want something like this : import os, stat os.chmod("myfile.txt", os.stat("myfile.txt").st_mode - stat.S_IRGRP) -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From william.xwl at gmail.com Thu Jun 15 23:33:31 2006 From: william.xwl at gmail.com (William Xu) Date: Fri, 16 Jun 2006 11:33:31 +0800 Subject: BeautifulSoup error Message-ID: <871wtpdbas.fsf@www.williamxu.com> Hi, all, This piece of code used to work well. i guess the error occurs after some upgrade. >>> import urllib >>> from BeautifulSoup import BeautifulSoup >>> url = 'http://www.google.com' >>> port = urllib.urlopen(url).read() >>> soup = BeautifulSoup() >>> soup.feed(port) Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.3/sgmllib.py", line 94, in feed self.rawdata = self.rawdata + data UnicodeDecodeError: 'ascii' codec can't decode byte 0xb8 in position 565: ordinal not in range(128) >>> Any ideas to solve this? version info: Python 2.3.5 (#2, Mar 7 2006, 12:43:17) [GCC 4.0.3 20060212 (prerelease) (Debian 4.0.2-9)] on linux2 python-beautifulsoup: 3.0.1-1 -- William "I'd love to go out with you, but I have to floss my cat." From alanalan at newsgroup.nospam Fri Jun 9 11:16:05 2006 From: alanalan at newsgroup.nospam (A.M) Date: Fri, 9 Jun 2006 11:16:05 -0400 Subject: Win XP: Problem with shell scripting in Python References: Message-ID: > I dare hardly suggest this, but might it not be better to use Python's > database functionality to perform the task? The language can access both > databases, and you might find it quicker. Then again, if your database > experience is limited, you may not ... > > regards > Steve > -- > Steve Holden +44 150 684 7255 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Love me, love my blog http://holdenweb.blogspot.com > Recent Ramblings http://del.icio.us/steve.holden > Hi Steven, Based on my experience, the fastest possible way to import raw data into Oracle is SQL*Loader. Similarly, the fastest way to extract raw data from SQL server is BCP. My script transfers 40,000,000 records (actually big records) from sql server to oracle in 20 Min. I tried ODBC to do the same work. I turned off all record locking and transactions through query hints. The actual program was a C# program. After 12 hours, I just stopped the program. I created DOS batch files to control BCP and SQL*Loader steps. It is faster than any fancy GUI tools. Now I am using Python. I am thinking to add comprehensive logging to the ETL (extract transform load) process. All details command line outputs will be stored in database. System administrators can query database and watch how the ETL job is working. At this point I have quite challenge with capturing BCP's stdout/stderr output to string variables in Python program. I'll post the final outcome here. Regards, Alan From onurb at xiludom.gro Wed Jun 21 06:34:03 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Wed, 21 Jun 2006 12:34:03 +0200 Subject: What's the best way to wrap a whole script in try..except? In-Reply-To: References: Message-ID: <4499209c$0$9929$636a55ce@news.free.fr> Hari Sekhon wrote: > I want to wrap a whole script in try ... except. What is the best way of > doing this? > > Consider the following: - > > try: > import > > > > def notifyme(traceback): > code to tell me there is a problem > > except Exception, traceback: > notifyme(traceback) > > > Would this code not work because if any part of encounters an > exception then it won't reach the notifyme() function definition and > therefore the whole thing won't work and I won't get notified when a > traceback occurs, in fact the call to notifyme() under except will > itself probably trace back as well! Yes. > Do I have to instead do: > > import > def notifyme(): > code to tell me there is a problem > > try: > > > except Exception, traceback: > notifyme(traceback) > Would work, but... > How you you handle this? I don't put the main logic at the top level - I use a main() function. import def notifyme(e): # code here... def main(*args): try: # code here return 0 except Exception, e: notifyme(e) return if __name__ == '__main__': import sys sys.exit(main(*sys.argv)) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From Serge.Orlov at gmail.com Thu Jun 1 14:18:46 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 1 Jun 2006 11:18:46 -0700 Subject: struct: type registration? In-Reply-To: References: <447e4b98$1@news.eftel.com> Message-ID: <1149185926.636174.48970@y43g2000cwc.googlegroups.com> Giovanni Bajo wrote: > John Machin wrote: > > I am an idiot, so please be gentle with me: I don't understand why you > > are using struct.pack at all: > > Because I want to be able to parse largest chunks of binary datas with custom > formatting. Did you miss the whole point of my message: > > struct.unpack("3liiSiiShh", data) Did you want to write struct.unpack("Sheesh", data) ? Seriously, the main problem of struct is that it uses ad-hoc abbreviations for relatively rarely[1] used functions calls and that makes it hard to read. If you want to parse binary data use pyconstruct [1] Relatively to regular expression and string formatting calls. From lolmcbride at googlemail.com Fri Jun 2 15:31:43 2006 From: lolmcbride at googlemail.com (lolmcbride at googlemail.com) Date: 2 Jun 2006 12:31:43 -0700 Subject: Using pysqlite2 Message-ID: <1149276702.992801.247640@j55g2000cwa.googlegroups.com> Is it possible to use this for sending triggers to a sqlite db?Could someone provide me with an example of how to do this please? Thanks From wescpy at gmail.com Fri Jun 23 20:43:15 2006 From: wescpy at gmail.com (w chun) Date: Fri, 23 Jun 2006 17:43:15 -0700 Subject: pyuno and oootools with OpenOffice 2.0 Message-ID: <78b3a9580606231743p29f64189o72fddc420719c5fe@mail.gmail.com> > Subject: pyuno and oootools with OpenOffice 2.0 > From: "Sells, Fred" > Date: Thu May 4 17:37:35 CEST 2006 > > I'm using windows xp and OpenOffice 2.0 and doing my first project with > pyuno. > > I've got the basics to work,. An example I googled at > http://blogs.nuxeo.com/sections/aggregators/openoffice_org/blogaggregator_view?b_start:int=0 > imported an ootools module. When I try to import it, it does not exist, > > Does anyone know where this exists, or why I cannot import it. the oootools.py module is referenced in this blog entry: http://blogs.nuxeo.com/sections/blogs/laurent_godard/2006_04_13_testing-pyuno-programs-with-doctests the direct link to download this file is: http://blogs.nuxeo.com/sections/blogs/laurent_godard/2006_04_13_testing-pyuno-programs-with-doctests/downloadFile/attachedFile_1_f0/oootools.py HTH, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From eval.apply at gmail.com Mon Jun 19 19:50:04 2006 From: eval.apply at gmail.com (Joe Marshall) Date: 19 Jun 2006 16:50:04 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> Message-ID: <1150761004.928251.318340@h76g2000cwa.googlegroups.com> Chris Smith wrote: > Joe Marshall wrote: > > > > Chris Smith wrote: > > > > > > Knowing that it'll cause a lot of strenuous objection, I'll nevertheless > > > interject my plea not to abuse the word "type" with a phrase like > > > "dynamically typed". > > > > Allow me to strenuously object. The static typing community has its > > own set of > > terminology and that's fine. However, we Lisp hackers are not used to > > this terminology. > > It confuses us. *We* know what we mean by `dynamically typed', and we > > suspect *you* do, too. > > I know what you mean by types in LISP. The phrase "dynamically typed," > though, was explicitly introduced as a counterpart to "statically > typed" in order to imply (falsely) that the word "typed" has related > meanings in those two cases. They *do* have a related meaning. Consider this code fragment: (car "a string") Obviously this code is `wrong' in some way. In static typing terms, we could say that we have a type error because the primitive procedure CAR doesn't operate on strings. Alternatively, we could say that since Lisp has one universal type (in static type terms) the code is correctly statically typed - that is, CAR is defined on all input, but it's definition is to raise a runtime exception when passed a string. But regardless of which way you want to look at it, CAR is *not* going to perform its usual computation and it is *not* going to return a value. The reason behind this is that you cannot take the CAR of a string. A string is *not* a valid argument to CAR. Ask anyone why and they will tell you `It's the wrong type.' Both `static typing' and `dynamic typing' (in the colloquial sense) are strategies to detect this sort of error. > Nevertheless, I did not really object, > since it's long since passed into common usage, Exactly. And you are far more likely to encounter this sort of usage outside of a type theorist's convention. > until Torben attempted > to give what I believe are rather meaningless definitions to those > words, in terms of some mythical thing called "type violations" that he > seems to believe exist apart from any specific type systems. It's hardly mythical. (car "a string") is obviously an error and you don't need a static type system to know that. > > > This cleaner terminology eliminates a lot of confusion. > > > > Hah! Look at the archives. > > I'm not sure what you mean here. You would like me to look at the > archives of which of the five groups that are part of this conversation? > In any case, the confusion I'm referring to pertains to comparison of > languages, and it's already been demonstrated once in the half-dozen or > so responses to this branch of this thread. I mean that this has been argued time and time again in comp.lang.lisp and probably the other groups as well. You may not like the fact that we say that Lisp is dynamically typed, but *we* are not confused by this usage. In fact, we become rather confused when you say `a correctly typed program cannot go wrong at runtime' because we've seen plenty of runtime errors from code that is `correctly typed'. > > > If types DON'T mean a compile-time method for proving the > > > absence of certain program behaviors, then they don't mean anything at > > > all. > > > > Nonsense. > > Please accept my apologies for not making the context clear. I tried to > clarify, in my response to Pascal, that I don't mean that the word > "type" can't have any possible meaning except for the one from > programming language type theory. I should modify my statement as > follows: > > An attempt to generalize the definition of "type" from programming > language type theory to eliminate the requirement that they are > syntactic in nature yields something meaningless. Any concept of > "type" that is not syntactic is a completely different thing from > static types. Agreed. That is why there is the qualifier `dynamic'. This indicates that it is a completely different thing from static types. > Basically, I start objecting when someone starts comparing "statically > typed" and "dynamically typed" as if they were both varieties of some > general concept called "typed". They aren't. I disagree. There is clearly a concept that there are different varieties of data and they are not interchangable. In some languages, it is up to the programmer to ensure that mistakes in data usage do not happen. In other languages, the computer can detect such mistakes and prevent them. If this detection is performed by syntactic analysis prior to running the program, it is static typing. Some languages like Lisp defer the detection until the program is run. Call it what you want, but here in comp.lang.lisp we tend to call it `dynamic typing'. > Furthermore, these two > phrases were invented under the misconception that that are. If you > mean something else by types, such as the idea that a value has a tag > indicating its range of possible values, then I tend to think it would > be less confusing to just say "type" and then clarify the meaning it > comes into doubt, rather than adopting language that implies that those > types are somehow related to types from type theory. You may think it would be less confusing, but if you look at the archives of comp.lang.lisp you would see that it is not. We're all rubes here, so don't try to educate us with your high-falutin' technical terms. From theller at python.net Sun Jun 11 13:01:59 2006 From: theller at python.net (Thomas Heller) Date: Sun, 11 Jun 2006 19:01:59 +0200 Subject: import hook In-Reply-To: <1hgrdu7.1djmypwdlt2uN%aleax@mac.com> References: <1hgrdu7.1djmypwdlt2uN%aleax@mac.com> Message-ID: Alex Martelli wrote: > Jeremy Sanders wrote: > >> Hi - Is it possible to override the import process so that if in my program >> I do >> >> import foo.bar >> >> Python will look for bar in a directory which isn't called foo? >> >> I want my module/program to be able to be run without being installed in >> site-packages, so by doing "import foo.bar", it should start looking for >> bar in the current directory which could be called "foo-0.43". >> >> I've tried overriding __import__, chopping out "foo." from package names, >> but that tends to break. I've also tried overriding imp.find_module() but >> Python never appears to use my version. >> >> Any ideas? > > Yes, PEP 302 (which despite being marked as "draft" has in fact been > already mostly implemented, since it's used by the zipimport mechanism) > allows you to perform such feats. Study it at > ... There are also other ways. You could extend __path__ of foo, and the pkgutil module might also be useful. Thomas From deets at nospam.web.de Wed Jun 21 18:45:41 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 22 Jun 2006 00:45:41 +0200 Subject: Is it possible to split a class definition? In-Reply-To: <1150927868.807640.45760@c74g2000cwc.googlegroups.com> References: <1150927868.807640.45760@c74g2000cwc.googlegroups.com> Message-ID: <4fu0ggF1kt6v5U1@uni-berlin.de> jerry.levan at gmail.com schrieb: > Hi, > > Is it possible to split a Class definition over two or more text files? > (if so, how:) Not in that sense. But if you must, you can use several classes and then a resulting class that inherits from all of these. Diez From nmm1 at cus.cam.ac.uk Thu Jun 29 12:43:30 2006 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 29 Jun 2006 16:43:30 GMT Subject: Bug reporting impossible References: <1151598979.369897.140770@x69g2000cwx.googlegroups.com> Message-ID: In article <1151598979.369897.140770 at x69g2000cwx.googlegroups.com>, "Simon Forman" writes: |> Nick Maclaren wrote: |> ... |> > Create a file called '' in your current directory containing |> > 'print "Oh, yeah?\n"' and then import a module that doesn't exist. |> > Don't include the single quotes. |> |> Why would you have a file named '' in your current directory? Why would Python search for one? :-) In both cases, the normal answer is "Someone made a mistake" but, if you have a script that creates a files of the same names specified in the current directory, what name should it use if you specify stdin? It is one of the standard conventions, which is (after all) why Python is searching for it. Anyway, I have now reported the bug - but this bug is more amusing than serious. Regards, Nick Maclaren. From gyows at sbcglobal.net Thu Jun 15 14:04:23 2006 From: gyows at sbcglobal.net (Ransom) Date: 15 Jun 2006 11:04:23 -0700 Subject: occasional win32com error Message-ID: <1150394663.125760.231580@f6g2000cwb.googlegroups.com> Hey folks... Newbie here. I'm working with win32com launching, closing and re-launching Excel grabbing output and doing stuff. Well, on some occasions, I get the following error: Traceback (most recent call last): File "checkrates.py", line 95, in ? newdata = getNewData(testcases1) File "checkrates.py", line 62, in getNewData excel.Workbooks.Open(docdir + 'TOSrat2006_09.xls') File "C:\Python24\lib\site-packages\win32com\client\dynamic.py", line 496, in __getattr__ raise AttributeError, "%s.%s" % (self._username_, attr) AttributeError: Excel.Application.Workbooks Sometimes the code runs fine. Sometimes I get this error. The code in question is: import string from win32com.client import Dispatch docdir = 'E:\\scripts\\Python\\RSAutomation\\' def getOldData(testcases): #open excel excel = Dispatch("Excel.Application") excel.Workbooks.Open(docdir + 'TOSrat2006_07.xls') oldoutputlist = [] for rsinput in testcases.xreadlines(): inputlist = string.split(rsinput, ',') # iterate through and update spreadheet input cellx = range(3,51) values = range(0,48) for i,r in zip(cellx, values): excel.ActiveSheet.Cells(i,2).Value = inputlist[r] #read spreadsheet output and cat to outputlist premium = excel.ActiveSheet.Cells(32,6).Value oldoutputlist.append(premium) # close up excel excel.ActiveWorkbook.Close(SaveChanges=0) excel.Quit() del excel return oldoutputlist def getNewData(testcases): # open excel excel = Dispatch("Excel.Application") excel.Workbooks.Open(docdir + 'TOSrat2006_09.xls') newoutputlist = [] for rsinput in testcases.xreadlines(): inputlist = string.split(rsinput, ',') # iterate through and update spreadsheet input cellx = range(3,51) values = range(0,48) for i,r in zip(cellx, values): excel.ActiveSheet.Cells(i,2).Value = inputlist[r] # read ratesheet output and cat to outputlist premium = excel.ActiveSheet.Cells(32,6).Value newoutputlist.append(premium) excel.ActiveWorkbook.Close(SaveChanges=0) excel.Quit() del excel return newoutputlist if __name__ == "__main__": testcases = open('arse_testcases.csv','r') testcases1 = open('arse_testcases.csv','r') olddata = getOldData(testcases) newdata = getNewData(testcases1) print olddata print newdata It seems like Python or COM is having a hard time freeing up (or closing down) excel prior to the "getNewData" function running and it is stepping on itself. I thought the stuff I'm doing at the end of getOldData should successfully shut down excel. Any advice, criticism, flames are appreciated. Cheers! From marshall.spight at gmail.com Sat Jun 24 13:46:49 2006 From: marshall.spight at gmail.com (Marshall) Date: 24 Jun 2006 10:46:49 -0700 Subject: Saying "latently-typed language" is making a category mistake In-Reply-To: <0neng.213767$8W1.1948@fe1.news.blueyonder.co.uk> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <86Qmg.10725$o4.1907@newsread2.news.pas.earthlink.net> <0neng.213767$8W1.1948@fe1.news.blueyonder.co.uk> Message-ID: <1151171209.684163.143410@c74g2000cwc.googlegroups.com> David Hopwood wrote: > > A type system that required an annotation on all subprograms that do not > provably terminate, OTOH, would not impact expressiveness at all, and would > be very useful. Interesting. I have always imagined doing this by allowing an annotation on all subprograms that *do* provably terminate. If you go the other way, you have to annotate every function that uses general recursion (or iteration if you swing that way) and that seems like it might be burdensome. Further, it imposes the annotation requirement even where the programer might not care about it, which the reverse does not do. Marshall From bj_666 at gmx.net Fri Jun 23 13:31:46 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Fri, 23 Jun 2006 19:31:46 +0200 Subject: Opening a file with system default application References: <1151077662.598370.214490@c74g2000cwc.googlegroups.com> <1151080343.917275.296520@g10g2000cwb.googlegroups.com> <1151080644.805513.257140@r2g2000cwb.googlegroups.com> <1151081172.418493.190730@i40g2000cwc.googlegroups.com> Message-ID: In <1151081172.418493.190730 at i40g2000cwc.googlegroups.com>, BartlebyScrivener wrote: >>> It would probably break like mad under *nix > > I bet it would work the same way on linux or os x; it's the equivalent > of double-clicking on the file. No it doesn't work. Double clicking is not an OS thing but a a GUI thing. Ciao, Marc 'BlackJack' Rintsch From hshore at 1st-spot.net Thu Jun 22 21:43:42 2006 From: hshore at 1st-spot.net (Harold Shore) Date: Fri, 23 Jun 2006 01:43:42 GMT Subject: Using SQLite3 with python 2.5 beta Message-ID: >From the release notes I read that "If you're compiling the Python source yourself, note that the source tree doesn't include the SQLite code, only the wrapper module. You'll need to have the SQLite libraries and headers installed before compiling Python, and the build process will compile the module when the necessary headers are available." I do have SQLite3 installed on my system, but after doing a plain vanilla compilation of the the 2.5 beta and trying the SQLite code given in the release notes I get the message "NameError: name 'sqlite3' is not defined". I wonder what the requirement means that "when the necessary headers are available"? How would they need to be made available? Does anyone have any success with this? From bborcic at gmail.com Thu Jun 8 13:59:10 2006 From: bborcic at gmail.com (Boris Borcic) Date: Thu, 08 Jun 2006 19:59:10 +0200 Subject: How to generate k+1 length strings from a list of k length strings? In-Reply-To: <1149785331.109164.208340@i39g2000cwa.googlegroups.com> References: <44883789$1_4@news.bluewin.ch> <1149785331.109164.208340@i39g2000cwa.googlegroups.com> Message-ID: <4488658e$1_5@news.bluewin.ch> bearophileHUGS at lycos.com wrote: > Boris Borcic: >> I'd favor the following, that I find most readable >> sets = map(set,list_of_strings) >> res = set(''.join(sorted(s1|s2)) for s1 in sets for s2 in sets if len(s1^s2)==2) > > I think there can be written more readable code. readability, of course, is in the eye of the beholder... and I find this code *much* easier to recognize as a realisation of the description made by the OP, than the code he himself offered - if you care to take a look at both. For my programs I > usually prefer simpler code, I challenge you to write simpler code to do the equivalent. > that (if possible) even a children can > understand. what child ? one that is trained just like *you* think children should start, I guess. > So I can debug, modify and improve it better & faster. Sure, but the case is we each were *distinct* children. > > Bye, > bearophile > From groupstudy2001 at yahoo.co.uk Mon Jun 26 18:23:05 2006 From: groupstudy2001 at yahoo.co.uk (groupstudy2001 at yahoo.co.uk) Date: 26 Jun 2006 15:23:05 -0700 Subject: Can I load and run modules inside threads.... Message-ID: <1151360585.064451.312740@y41g2000cwy.googlegroups.com> .... and is it a good idea??? I am thinking of writing a controlling module - call it a postmaster if you will - that will start submodules and pass them work via queues - one input queue per module. The modules will send their results back to the postmaster via its queue. The postmaster will then read the incoming message and, if necessary, pass it on to another thread. The problem is that I want the submodules NOT to be known by or part of the original module. So I have to load them as the need is seen, probably by name, and tie them to queues. Can anyone see a problem with this or some good way to do it? Maybe, modname = ....... #Module name a variable exec("import %s as mod" % modname) module_input_queue = Queue.Queue() new_thread = mod.classname( my_queue, module_input_queue, parms) new_thread.start() From 3dbernard at gmail.com Thu Jun 1 16:45:44 2006 From: 3dbernard at gmail.com (Bernard Lebel) Date: Thu, 1 Jun 2006 16:45:44 -0400 Subject: Tkinter: select multiple entries in Listbox widget? In-Reply-To: References: Message-ID: <61d0e2b40606011345jfa64a17i12e6825fd75d87e0@mail.gmail.com> Oh, thanks a lot Rob. Bernard On 6/1/06, Rob Williscroft wrote: > Bernard Lebel wrote in news:mailman.6413.1149178158.27775.python- > list at python.org in comp.lang.python: > > > Hello, > > > > Is there an option or a way to allow the selection of multiple entries > > in the Listbox widget? I could not find any, and would like to allow > > the end user to select multiple entries. > > > > > > When configuring use: > > selectmode = "multiple" > > e.g.: > > import Tkinter as tk > > root = tk.Tk() > > a = tk.Listbox( root, selectmode = "multiple" ) > for i in range(10): > a.insert( i, str(i) + " item" ) > > a.pack() > root.mainloop() > > I found the answer here: > > http://www.python.org/doc/life-preserver/ClassListbox.html > > Though I had to guess the `= "multiple"` part. > > Rob. > -- > http://www.victim-prime.dsl.pipex.com/ > -- > http://mail.python.org/mailman/listinfo/python-list > From sekhon.hari at googlemail.com Wed Jun 21 06:59:21 2006 From: sekhon.hari at googlemail.com (Hari Sekhon) Date: Wed, 21 Jun 2006 11:59:21 +0100 Subject: memory error with zipfile module In-Reply-To: <446e51e6$0$6831$636a55ce@news.free.fr> References: <446e07ab$0$12795$636a55ce@news.free.fr> <1148072514.207383.26370@j55g2000cwa.googlegroups.com> <446e51e6$0$6831$636a55ce@news.free.fr> Message-ID: On 20/05/06, Bruno Desthuilliers wrote: > > Roger Miller a ?crit : > > The basic problem is that the zipfile interface only reads and writes > > whole files, so it may perform poorly or fail on huge files. At one > > time I implemented a patch to allow reading files in chunks. However I > > believe that the current interface has too many problems to solve by > > incremental patching, > > Yeps, that was the general tone of some thread on python-dev. And from > what I saw of the source code, it may effectively not be the cleanest > part of the stdlib. But what, it does what it was written for at first : > provide working support for zipped packages. > > > and that a zipfile2 module is probably warranted. > > (Is anyone working on this?) > > Seems like Bob Ippolito was on the rank, but I guess you'll get better > answers on python-dev. > > > In the meantime I think the best solution is often to just run an > > external zip/unzip utility to do the heavy lifting. > > Indeed !-) > > But while having zip/unzip installed OOTB on a unix-like system is close > to warrented, it may not be the case on Windows. > -- > http://mail.python.org/mailman/listinfo/python-list > Shame, I would like to try to improve this but seeing as Roger Miller has already submitted a patch I don't know how much I can do for this. In the end I resorted to using an external zip utility via os.system(). I'll be interested to know if there is any work done on improving this as I'm in favour of native python usage, rather than using os.system() and relying on the operating system having a zip command, which I'm not convinced is the case on all windows machines, and also, I'm sure gentoo installs don't have zip by default, since I had to emerge it on a server for this script to work. Is it me or is having to use os.system() all the time symtomatic of a deficiency/things which are missing from python as a language? Not that I'm complaining, I'm just curious... I'm a fledgeling programmer so I don't mind being gently corrected by any veterans around. Hari -------------- next part -------------- An HTML attachment was scrubbed... URL: From ptmcg at austin.rr._bogus_.com Wed Jun 28 05:20:19 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 28 Jun 2006 09:20:19 GMT Subject: Help Installing smartypants.py References: <1151466836.227516.40540@d56g2000cwd.googlegroups.com> Message-ID: "Scott McCracken" wrote in message news:1151466836.227516.40540 at d56g2000cwd.googlegroups.com... > I just got Python 2.4 setup locally (Mac OS X) and am trying to extend > it by installing both the markdown and smartypants plugins. Ultimately > I'd like to be able use both in a custom CMS I'm building with Django. > > Installing markdown was a snap by following the instructions at > http://www.freewisdom.org/projects/python-markdown/, but I cannot > figure out what to do for smartypants. I have found: > http://web.chad.org/projects/smartypants.py/, but cannot make any sense > of it. After reading Jeff Croft's wonderful site, I know it's possible > - and when I asked him in one of his posts he gave me the following > response: > > > As for SmartyPants -- there is a Python port. I've found it to be not quite as perfect as the original >Perl version, but it basically works. Just Google for it. You'd install it the same way (drop >smartypants.py in your Python path). > > Does anyone know what port he's talking about? Is it the smartypants.py > file referenced above? And if so, any quick tips for a clueless UNIX > user on how to drop smartypants.py in my Python path? Many thanks in > advance! > Go to the bottom of http://web.chad.org/projects/smartypants.py/ and you will see a number of links to various versions of this .py module. If you right-click/Save As to smartypants.py, and then save this file to a directory in your Pythonpath, then this will make this module accessible to you. -- Paul From johnjsal at NOSPAMgmail.com Thu Jun 15 15:59:03 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 15 Jun 2006 19:59:03 GMT Subject: a good programming text editor (not IDE) In-Reply-To: References: <_xgkg.2317$No6.48542@news.tufts.edu> <1150393919.514359.55580@h76g2000cwa.googlegroups.com> Message-ID: Larry Bates wrote: > Nope, no Java knowledge necessary. Jython just compiles Python code > to java bytecode instead of python bytecode. Once it is in java bytecode > the JVM doesn't know where it came from. Well that's good to know. I guess there's not much of a point in writing pure Python code with Jython, but at least now I know it works that way! From flippa at flippac.org Sun Jun 11 00:35:09 2006 From: flippa at flippac.org (Philippa Cowderoy) Date: Sun, 11 Jun 2006 05:35:09 +0100 Subject: Xah Lee network abuse In-Reply-To: References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148495974.975395.12920@i40g2000cwc.googlegroups.com> <1149998343.493200.144990@h76g2000cwa.googlegroups.com> Message-ID: On Sat, 10 Jun 2006, Erik Max Francis wrote: > Philippa Cowderoy wrote: > > > Rather a lot depends on which legal system you're in, for a start. Including > > the standards of proof and who the onus is on. > > Oh, no doubt. But I don't think there's any modern legal system in which it's > a crime, rather than a tort. Is there? > I'm not aware of a current legal system where it's the case, but I don't know the details of many of them. -- flippa at flippac.org A problem that's all in your head is still a problem. Brain damage is but one form of mind damage. From M.Waack at gmx.de Tue Jun 6 08:03:58 2006 From: M.Waack at gmx.de (Mathias Waack) Date: Tue, 06 Jun 2006 12:03:58 GMT Subject: 10GB XML Blows out Memory, Suggestions? References: <1149594519.098115.8980@u72g2000cwu.googlegroups.com> Message-ID: axwack at gmail.com wrote: > I wrote a program that takes an XML file into memory using Minidom. I > found out that the XML document is 10gb. > > I clearly need SAX or something else? More memory;) Maybe you should have a look at pulldom, a combination of sax and dom: it reads your document in a sax-like manner and expands only selected sub-trees. > Any suggestions on what that something else is? Is it hard to convert > the code from DOM to SAX? Assuming a good design of course not. Esp. if you only need some selected parts of the document SAX should be your choice. Mathias From ilias at lazaridis.com Sat Jun 10 14:41:01 2006 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Sat, 10 Jun 2006 21:41:01 +0300 Subject: CONSTRUCT - Python's way of Ruby's "alias_method" In-Reply-To: References: Message-ID: Maric Michaud wrote: > Le Vendredi 09 Juin 2006 20:06, Ilias Lazaridis a ?crit : >> the code below works, but has the limitation that I cannot import the >> syncdb_hook within "django.core.management". > > In [4]: from b import CONS > > In [5]: import b > > In [6]: b.CONS = 3 > > In [7]: CONS > Out[7]: 5 > > In [8]: from b import CONS > > In [9]: CONS > Out[9]: 3 > > So, if you change one module name, a function or a class or a constant, you > must do it before it is imported, or you must reload modules using it. But > either are not always possible, and the later is not what you want to achieve > here as it will re-execute all initialisation code in those modules. > > But think of that, a function is hopefully an object in python, hmmm : > > In [1]: from temp import func > > In [2]: func(5) > Out[2]: 5 > > In [3]: def g(s) : return s*2 > ...: > > In [4]: func.func_code = g.func_code > > In [5]: func(5) > Out[5]: 10 > > hey, that should work ! Great Construct! Much flexibility! I'll try the implementation tomorrow. - The actual Versions of the hooks can be found here: http://case.lazaridis.com/browser/django/rework/syncdb_hook.py?rev=7 http://case.lazaridis.com/browser/django/rework/startproject_hook.py?rev=13 This construct has helped to simplify nearly all simplification goals: http://case.lazaridis.com/wiki/DjangoSchemaEvolution . -- http://lazaridis.com From skip at pobox.com Sun Jun 4 06:55:43 2006 From: skip at pobox.com (skip at pobox.com) Date: Sun, 4 Jun 2006 05:55:43 -0500 Subject: Pyrex list/array In-Reply-To: <1149415140.458073.65310@c74g2000cwc.googlegroups.com> References: <1149360983.373137.200740@i39g2000cwa.googlegroups.com> <448239EB.6010706@lexicon.net> <1149415140.458073.65310@c74g2000cwc.googlegroups.com> Message-ID: <17538.48175.243802.549777@montanaro.dyndns.org> >> 5. Does your architecture support psyco? If so, have you tried that >> and what were the results? Jim> Already using psyco. Is it substantially faster with psyco than without? If psyco is performing its magic on the critical section of code already, you are going to lose that when switching to Pyrex. Skip From david.nospam.hopwood at blueyonder.co.uk Wed Jun 28 12:25:22 2006 From: david.nospam.hopwood at blueyonder.co.uk (David Hopwood) Date: Wed, 28 Jun 2006 16:25:22 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <7zy7vt1mz2.fsf@app-3.diku.dk> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <1151384511.223582.305760@m73g2000cwd.googlegroups.com> <4gdkmiF1ldalhU3@individual.net> <4gfcclF1mpbg7U1@individual.net> <6gwog.488405$xt.80841@fe3.news.blueyonder.co.uk> Message-ID: Andreas Rossberg wrote: > David Hopwood wrote: > >> (In the case of eval, OTOH, >> the erroneous code may cause visible side effects before any run-time >> error occurs.) > > Not necessarily. You can replace the primitive eval by compile, which > delivers a function encapsulating the program, so you can check the type > of the function before actually running it. Eval itself can easily be > expressed on top of this as a polymorphic function, which does not run > the program if it does not have the desired type: > > eval ['a] s = typecase compile s of > f : (()->'a) -> f () > _ -> raise TypeError What I meant was, in the case of eval in an untyped ("dynamically typed") language. The approach you've just outlined is an implementation of staged compilation in a typed language. -- David Hopwood From rupole at hotmail.com Wed Jun 14 21:26:07 2006 From: rupole at hotmail.com (Roger Upole) Date: Wed, 14 Jun 2006 21:26:07 -0400 Subject: Screen capturing on Windows References: <1150192149.757557.163820@y43g2000cwc.googlegroups.com> Message-ID: <1150334439_5618@sp6iad.superfeed.net> "Rune Strand" wrote in message news:1150192149.757557.163820 at y43g2000cwc.googlegroups.com... > > Is it possible by use of pyWin32 or ctypes to make a screen capture of > an inactive, or a hidden window if the hwnd/WindowName/ClassName is > known? I've seen dedicated screen capture software do this. While > PIL.ImageGrab.grab() is excellent, it will only capture the foreground > of the desktop. I've tried for hours, but I soon get helplessly lost in > the labyrinths of the Win32API. > This will restore a minimized window, bring it to the top and save a bmp. import time import win32gui, win32ui, win32con, win32api def window_capture(window_title): hwnd=win32gui.FindWindow(None, window_title) if not hwnd: raise 'Window not found' print hwnd win32gui.ShowWindow(hwnd,win32con.SW_RESTORE) win32gui.SetForegroundWindow(hwnd) time.sleep(0.1) l,t,r,b=win32gui.GetWindowRect(hwnd) h=b-t w=r-l hwndDC = win32gui.GetWindowDC(hwnd) mfcDC=win32ui.CreateDCFromHandle(hwndDC) saveDC=mfcDC.CreateCompatibleDC() saveBitMap = win32ui.CreateBitmap() saveBitMap.CreateCompatibleBitmap(mfcDC, w, h) saveDC.SelectObject(saveBitMap) saveDC.BitBlt((0,0),(w, h) , mfcDC, (0,0), win32con.SRCCOPY) temp_dir=win32api.GetTempPath() bmpname=win32api.GetTempFileName(temp_dir,'wc')[0]+'.bmp' saveBitMap.SaveBitmapFile(saveDC, bmpname) return bmpname Roger From ldo at geek-central.gen.new_zealand Thu Jun 8 17:55:05 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 09 Jun 2006 09:55:05 +1200 Subject: Large Dictionaries References: <1147699064.107490@teuthos> <1147772420.405097@teuthos> <1147818548.532882.94180@i39g2000cwa.googlegroups.com> <1147874585.728471@teuthos> <1148514158.790760.205630@i40g2000cwc.googlegroups.com> <447af556$1@nntp0.pdx.net> <1149517720.086866.3510@j55g2000cwa.googlegroups.com> Message-ID: In article <1149517720.086866.3510 at j55g2000cwa.googlegroups.com>, "Iain King" wrote: >Lawrence D'Oliveiro wrote: >> In article <447af556$1 at nntp0.pdx.net>, >> Scott David Daniels wrote: >> >> >For example, time timsort (Python's internal sort) on pre-sorted >> >data; you'll find it is handled faster than random data. >> >> But isn't that how a reasonable sorting algorithm should behave? Less >> work to do if the data is already sorted? > >An already sorted list can be pathological for Quicksort, depending on >how you code it. I did say "reasonable". :) From yumagene at gmail.com Fri Jun 16 11:13:42 2006 From: yumagene at gmail.com (genea) Date: 16 Jun 2006 08:13:42 -0700 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> Message-ID: <1150470822.647000.323290@i40g2000cwc.googlegroups.com> Torben ?gidius Mogensen wrote: > There are several aspects relevant to this issue, some of which are: > - Compactness: How much do I have to type to do what I want? ...... > - Naturality: How much effort does it take to convert the concepts of > my problem into the concepts of the language? > - Feedback: Will the language provide sensible feedback when I write > nonsensical things? > - Reuse: How much effort does it take to reuse/change code to solve a > similar problem? ..... I am fairly new to Haskell, but the compactness of the language and the way you can express a lot in a very small amount of real estate is very important.. I used to program back in the 80's in forth a lot.... okay I'm a dinosaur!, but "good" definitions were usually very short, and sweet. Unicon/Icon that I used {still do!} in the imperative world, very compact. I will give an example that covers compact, reusable, and because of static typing when will give back mis-type info when you load a new "a or xs" into it to form a new function. -- what is happening below is a is being replaced with the curried lambda: ((++) 3) and -- xs a list: [1..6], so when that definition of f is used it is type checked to see if the -- elements in xs match the type of a, so if this were going to be compiled, it would -- checked and guaranteed to work. Prelude> :t f f :: forall a b. (Show b) => (a -> b) -> [a] -> IO () Prelude> let f a xs = putStr $ foldr (++) "\n" $ map (((++) "\n"). show . a ) xs Prelude> f ((*) 3) [1..6] 3 6 9 12 15 18 Prelude> another substitution of parameters.. using the same definition of f allowed by the the polymorphic parameters allowed in Haskell add to the versatility and reusability angle: Prelude> f sqrt [0.5,1.0..4] 0.7071067811865476 1.0 1.224744871391589 1.4142135623730951 1.5811388300841898 1.7320508075688772 1.8708286933869707 2.0 Same function 'f" now used with a different type.. [0.5,1.0..4] :: forall a. (Fractional a, Enum a) => [a] I don't know, but this just makes programming fun, for me anyway, and if it is fun, it is expressive.. I've heard this statement made about Ruby and Unicon, to name a few... some would say Python.. but it really applies to the functional languages too, with all their strict typing, with the type inference mechanisms, it isn't usually that big a deal.. If you just get into it, and can learn to take some constructive criticism from your compiler, well hey, it is a really patient teacher... you might get frustrated at times.. but the compiler will happily remind you of the same type mis-matches, until you get a handle on some concept and never once complain... Happy Programming to all! -- gene From david.huard at gmail.com Wed Jun 21 09:58:25 2006 From: david.huard at gmail.com (David Huard) Date: Wed, 21 Jun 2006 09:58:25 -0400 Subject: How to override the doc of an object instance. References: <200606211539.02663.maric@aristote.info> Message-ID: On Wed, 21 Jun 2006 15:39:02 +0200, Maric Michaud wrote: > This is w.__class__.x.__doc__. Thanks, So in order to implement what I want, I should rather consider an ipython hack to print w.__class__.x.__doc__ when it exists, instead of w.x.__doc_ ? Does this makes sense or it will ruin the standard behaviour? David From olsongt at verizon.net Fri Jun 30 12:26:43 2006 From: olsongt at verizon.net (olsongt at verizon.net) Date: 30 Jun 2006 09:26:43 -0700 Subject: Reddit broke - should have remained on Lisp? In-Reply-To: <1151662812.571023.205500@d56g2000cwd.googlegroups.com> References: <1151626961.232761.255550@d56g2000cwd.googlegroups.com> <1151662301.891275.166300@d56g2000cwd.googlegroups.com> <1151662812.571023.205500@d56g2000cwd.googlegroups.com> Message-ID: <1151684803.210502.68450@d56g2000cwd.googlegroups.com> Kay Schluehr wrote: > > Please, since this is a Python+Lisp cross-thread and you seem to have > background info: can you explain why Lisp hackers have turned > themselves into Python newbies for Reddit impl. and finally complain > about the language switch? What was cause for their decision to use > Python in the first place? Basically, it was the same complaint everyone else has about common lisp. It's an awesome language, but there are no reliable standard crossplatform (and free) libraries for threading and sockets. They were using FreeBSD as a server, and (trying to) use powerbooks as a dev platform, and that seriously restricted viable CL implemenations. http://redditblog.blogspot.com/2005/12/night-of-living-python.html http://redditblog.blogspot.com/2005/12/on-lisp.html From onurb at xiludom.gro Fri Jun 2 05:24:07 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 02 Jun 2006 11:24:07 +0200 Subject: Conditional Expressions in Python 2.4 In-Reply-To: References: Message-ID: <4480042b$0$29879$636a55ce@news.free.fr> A.M wrote: > Hi, > > > > I am using Python 2.4. I read the PEP 308 at: > > http://www.python.org/dev/peps/pep-0308/ > > I tried the statement: > > a= "Yes" if 1==1 else "No" > > but the interpreter doesn't accept it. > > Do we have the conditional expressions in Python 2.4? No, AFAIK they'll be in for 2.5 In the meanwhile, there are (sometime tricky? ways to get the same result: a = 1 == 1 and "Yes" or "No" a = ("No", "Yes")[1 == 1] -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From jo at durchholz.org Sun Jun 25 13:58:27 2006 From: jo at durchholz.org (Joachim Durchholz) Date: Sun, 25 Jun 2006 19:58:27 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: <1151252226.104247.62960@b68g2000cwa.googlegroups.com> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150908952.804184.218990@r2g2000cwb.googlegroups.com> <1150991074.705803.211570@m73g2000cwd.googlegroups.com> <1151244628.566060.40500@p79g2000cwp.googlegroups.com> <1151252226.104247.62960@b68g2000cwa.googlegroups.com> Message-ID: rossberg at ps.uni-sb.de schrieb: > Gabriel Dos Reis wrote: >> | >> | (Unfortunately, you can hardly write interesting programs in any safe >> | subset of C.) >> >> Fortunately, some people do, as living job. > > I don't think so. Maybe the question is what a "safe subset" consists > of. In my book, it excludes all features that are potentially unsafe. Unless you define "safe", *any* program is unsafe. Somebody could read the program listing, which could trigger a traumatic childhood experiece. (Yes, I'm being silly. But the point is very serious. Even with less silly examples, whether a language or subset is "safe" entirely depends on what you define to be "safe", and these definitions tend to vary vastly across language communities.) Regards, Jo From maric at aristote.info Thu Jun 15 07:01:52 2006 From: maric at aristote.info (Maric Michaud) Date: Thu, 15 Jun 2006 13:01:52 +0200 Subject: __lt__ slowing the "in" operator even if not called In-Reply-To: <1150318630.203249.191250@r2g2000cwb.googlegroups.com> References: <1150318630.203249.191250@r2g2000cwb.googlegroups.com> Message-ID: <200606151301.53298.maric@aristote.info> Le Mercredi 14 Juin 2006 22:57, Emanuele Aina a ?crit?: > Here you can see that even with only the __lt__ method it goes 10x > slower, but __lt__ is never called as "Foo" is not printed. No, that is not what it shows. The only thing it shows is that in operator is slow for lists, and as it iterates over the entire list untill it find an element, it is much slower when it fails a lot. Use dict in operator instead. Here is a program to show this in details : import timing class State(object): def __init__(self, value): self.v = value class StateEQ(State): def __eq__ (self, other): if isinstance(other, State) : return self.v == other.v else : return self.v == other class StateLT(State) : def __lt__ (self, other): if isinstance(other, State) : return self.v < other.v else : return self.v < other class StateLTEQ(StateEQ, StateLT) : pass def test(state_cls): num_elem = 3*10**4 print print state_cls l = [state_cls(0)] for i in xrange(num_elem): l.append(state_cls(i+1)) print print "in operator at the beginning of list:", timing.start() for i in xrange(300): i in l timing.finish() print timing.milli() print "in operator at the end of list:", timing.start() for i in xrange(num_elem-300, num_elem): i in l timing.finish() print timing.milli() print print "converting to dict :", timing.start() d = {}.fromkeys(l) timing.finish() print timing.milli() print "in operator for a dict for %s elements:" % (num_elem*2), timing.start() for i in xrange(num_elem, num_elem*2): i in d timing.finish() print timing.milli() if __name__ == '__main__': test(State) test(StateLT) test(StateEQ) test(StateLTEQ) for which the output is : in operator at the beginning of list: 1983 in operator at the end of list: 2011 converting to dict : 82 in operator for a dict for 60000 elements: 12 in operator at the beginning of list: 3866 in operator at the end of list: 3871 converting to dict : 332 in operator for a dict for 60000 elements: 50 in operator at the beginning of list: 173 in operator at the end of list: 28249 converting to dict : 79 in operator for a dict for 60000 elements: 14 in operator at the beginning of list: 202 in operator at the end of list: 30472 converting to dict : 68 in operator for a dict for 60000 elements: 50 Every classes that define the __eq__ operator will find quickly the elements if they are at the beginning of the list. If they are at the end, the in oprerator is slower in these classes because of the overhead of function calls (in StateLt there is also an overhead due to internal lookup, IMO). Converting to dicts and looking for keys is *really* and equally fast in all cases, it does not depend on success or failure. -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From fredrik at pythonware.com Tue Jun 27 09:12:08 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 27 Jun 2006 15:12:08 +0200 Subject: how to do -vv for very verbose? References: <44A12872.9030104@gmail.com> Message-ID: Hari Sekhon wrote: > I'm using optparse.Optionparser to take switches for a script I'm > writing, but I can't see how to give it -vv for very verbose. > > the option for -v is simply set to True by the option parser if present, > whereas I really want a numeric value, 1 if there is -v and 2 if there > is -vv. action="count" ? From rpdooling at gmail.com Mon Jun 19 21:35:09 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 19 Jun 2006 18:35:09 -0700 Subject: Newbie Question References: <1150750938.973049.114780@y41g2000cwy.googlegroups.com> <129e55eahc35f00@corp.supernews.com> <1150753085.332654.283270@f6g2000cwb.googlegroups.com> Message-ID: <1150767309.831092.188530@h76g2000cwa.googlegroups.com> Saint Malo wrote: > If the program searches for blue, i just want it to print blue Huh? Tell it to print whatever you want. for line in file: if 'blue' in line: print 'blue' for line in file: if 'brown' in line: print 'brown' for line in file: if 'red' in line: print 'weasels rip my flesh' From sturnfie at gmail.com Thu Jun 1 16:08:44 2006 From: sturnfie at gmail.com (sturnfie at gmail.com) Date: 1 Jun 2006 13:08:44 -0700 Subject: Best Python Editor In-Reply-To: References: Message-ID: <1149192524.269902.46240@f6g2000cwb.googlegroups.com> In a windows enviroment, I am a big fan of conTEXT http://www.context.cx/ . Very powerful syntax highlighting for many, many languages . project workspace support . code template support . great file browsing and favorites support . good search/replace support across all open files In a unix enviroment, i use eclipse or vim -- lucas Manoj Kumar P wrote: > Hi, > > Can anyone tell me a good python editor/IDE? > It would be great if you can provide the download link also. > > Thank You, > -Manoj- From jstroud at ucla.edu Fri Jun 16 16:56:44 2006 From: jstroud at ucla.edu (James Stroud) Date: Fri, 16 Jun 2006 13:56:44 -0700 Subject: Pycrypto In-Reply-To: References: <1150446904.527285.255170@g10g2000cwb.googlegroups.com> <1150458752.342042.189650@h76g2000cwa.googlegroups.com> <1150462237.224431.213020@c74g2000cwc.googlegroups.com> Message-ID: Laszlo Nagy wrote: > >> Not in this implementation: >> py> from Crypto.Cipher import AES >> py> crypt = AES.new('abcdefghijklmnop', AES.MODE_CBC) >> py> c = crypt.encrypt('1') >> Traceback (most recent call last): >> File "", line 1, in ? >> ValueError: Input strings must be a multiple of 16 in length >> > > This is strange. In theory, any ECB mode cipher can be used to create a > CBC mode cipher. > AFAIK, CBC creates one encrypted block, and uses the one byte from the > plain text to xor it > with the last encrypted byte. Finally it shifts the encrypted block. > This way each input byte will > have a corresponding output byte, and there is no size limit for the > plain text. > > Frankly, I could write the CBC mode cipher using the (already existing) > ECB cipher. Why we have this limitation? > > Laszlo > > CBC mode is cipher block chaining, so it still works as a block cipher, which means that it must be that len(text) % block_size == 0. In other words, CBC does not shift by one byte but by block_size bytes. See: http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From mw.visenso at googlemail.com Wed Jun 14 09:59:33 2006 From: mw.visenso at googlemail.com (Marco Wahl) Date: 14 Jun 2006 06:59:33 -0700 Subject: Where is documentation for += In-Reply-To: References: <1150292372.337690.25290@y41g2000cwy.googlegroups.com> Message-ID: <1150293572.954032.263170@u72g2000cwu.googlegroups.com> > > [...] I can't find any documentation for +=. > > Any hints? > http://docs.python.org/ref/augassign.html That's it. Thank you very much. From cdsmith at twu.net Wed Jun 21 14:33:16 2006 From: cdsmith at twu.net (Chris Smith) Date: Wed, 21 Jun 2006 12:33:16 -0600 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> Message-ID: Joachim Durchholz wrote: > Assume a language that > a) defines that a program is "type-correct" iff HM inference establishes > that there are no type errors > b) compiles a type-incorrect program anyway, with an establishes > rigorous semantics for such programs (e.g. by throwing exceptions as > appropriate). So the compiler now attempts to prove theorems about the program, but once it has done so it uses the results merely to optimize its runtime behavior and then throws the results away. I'd call that not a statically typed language, then. The type-checking behavior is actually rather irrelevant both to the set of valid programs of the language, and to the language semantics (since the same could be accomplished without the type checking). It is only relevant to performance. Obviously, the language probably qualifies as dynamically typed for most common definitions of that term, but I'm not ready to accept one definition and claim to understand it, yet, so I'll be cautious about classsifying the language. > The compiler might actually refuse to compile type-incorrect programs, > depending on compiler flags and/or declarations in the code. Then those compiler flags would cause the compiler to accept a different language, and that different language would be a statically typed language (by which I don't mean to exclude the possibility of its also being dynamically typed). > Typed ("strongly typed") it is, but is it statically typed or > dynamically typed? So my answer is that it's not statically typed in the first case, and is statically typed in the second case, and it intuitively appears to be dynamically typed at least in the first, and possibly in the second as well. -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation From nospam at nospam.com Tue Jun 13 13:23:06 2006 From: nospam at nospam.com (3c273) Date: Tue, 13 Jun 2006 10:23:06 -0700 Subject: Customized Boot Manager in Python References: <1150209056.507195.81430@y43g2000cwc.googlegroups.com> Message-ID: wrote in message news:1150209056.507195.81430 at y43g2000cwc.googlegroups.com... > Now, I have to create a visual interface for such kind of small > program. > > I have 2 questions > (i) How can we use operating system specific commands like ssh within > the python program (ii) Which grphics library (wxPython or any other) > would be the fastest with least learning curve to get this thing done. > > Thanks (i)Check out the subprocess module. (ii)If you are just looking to put a couple of buttons on a gui, I learned to do this pretty quickly using Tkinter and one of the online tutorials. Louis From rabkinDELETE at mweb.co.za Sun Jun 4 07:58:26 2006 From: rabkinDELETE at mweb.co.za (Max) Date: Sun, 04 Jun 2006 13:58:26 +0200 Subject: if not CGI: In-Reply-To: <447f722b$0$30312$626a54ce@news.free.fr> References: <447f722b$0$30312$626a54ce@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > Max a ?crit : (snip) > > RoR is not bad, but really over-hyped. There's no shortage of at least > as good solutions in Python. You may want to look at Django, Turbogears, > Pylons, web.py etc. for fullstack MVC frameworks. That's what I thought! (snip) > > So the problem is not "are there good solutions", but "which one to > choose" !-) The answer of course depends on what you want and what you > like, but taking a few days to play with Turbogears, Django and Pylons > might be a good idea. Good stuff. I'm downloading them now. Thanks. --Max From walter at livinglogic.de Fri Jun 16 10:44:26 2006 From: walter at livinglogic.de (=?ISO-8859-1?Q?Walter_D=F6rwald?=) Date: Fri, 16 Jun 2006 16:44:26 +0200 Subject: a good programming text editor (not IDE) In-Reply-To: <1150430810.039713.262660@f6g2000cwb.googlegroups.com> References: <_xgkg.2317$No6.48542@news.tufts.edu> <1150430810.039713.262660@f6g2000cwb.googlegroups.com> Message-ID: <4492C3CA.7050700@livinglogic.de> josiah.carlson at gmail.com wrote: > John Salerno wrote: > [snip] >> Thanks for any suggestions, and again I'm sorry if this feels like the >> same question as usual (it's just that in my case, I'm not looking for >> something like SPE, Komodo, Eric3, etc. right now). > > I was taking a peek at c.l.py to check for replies in another thread > and couldn't help notice your asking about editors. Please pardon the > personal pimping, but have you looked at PyPE (pype.sf.net)? I tried it out and the first problem I noticed is that on Windows opening a file from a Samba drive doesn't seem to work, as PyPE converts the filename to lowercase. Servus, Walter From pc at p-cos.net Thu Jun 22 03:47:12 2006 From: pc at p-cos.net (Pascal Costanza) Date: Thu, 22 Jun 2006 09:47:12 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150902275.129780.50260@p79g2000cwp.googlegroups.com> <1150918629.818145.143220@y41g2000cwy.googlegroups.com> Message-ID: <4fv081F1jh4ifU1@individual.net> David Hopwood wrote: > Marshall wrote: >> Chris Smith wrote: >>> Marshall wrote: >>> >>>> I think what this highlights is the fact that our existing terminology >>>> is not up to the task of representing all the possible design >>>> choices we could make. Some parts of dynamic vs. static >>>> a mutually exclusive; some parts are orthogonal. >>> Really? I can see that in a strong enough static type system, many >>> dynamic typing features would become unobservable and therefore would be >>> pragmatically excluded from any probable implementations... but I don't >>> see any other kind of mutual exclusion between the two. >> Well, it strikes me that some of what the dynamic camp likes >> is the actual *absence* of declared types, or the necessity >> of having them. > > So why aren't they happy with something like, say, Alice ML, which is > statically typed, but has a "dynamic" type and type inference? I mean > this as a serious question. Note: I haven't yet worked with such a language, but here is my take anyway. A statically type language requires you to think about two models of your program at the same time: the static type model and the dynamic behavioral model. A static type system ensures that these two _different_ (that's important!) perspectives are always in sync. This is especially valuable in settings where you know your domain well and want to rely on feedback by your compiler that you haven't made any mistakes in encoding your knowledge. (A static type system based on type inferencing doesn't essentially change the requirement to think in two models at the same time.) A dynamically typed language is especially well suited when you don't (yet) have a good idea about your domain and you want to use programming especially to explore that domain. Some static typing advocates claim that static typing is still suitable for exploring domains because of the compiler's feedback about the preliminary encoding of your incomplete knowledge, but the disadvantages are a) that you still have to think about two models at the same time when you don't even have _one_ model ready and b) that you cannot just run your incomplete program to see what it does as part of your exploration. A statically typed language with a dynamic type treats dynamic typing as the exception, not as the general approach, so this doesn't help a lot in the second setting (or so it seems to me). A language like Common Lisp treats static typing as the exception, so you can write a program without static types / type checks, but later on add type declarations as soon as you get a better understanding of your domain. Common Lisp implementations like CMUCL or SBCL even include static type inference to aid you here, which gives you warnings but still allows you to run a program even in the presence of static type errors. I guess the feedback you get from such a system is probably not "strong" enough to be appreciated by static typing advocates in the first setting (where you have a good understanding of your domain). Pascal -- 3rd European Lisp Workshop July 3 - Nantes, France - co-located with ECOOP 2006 http://lisp-ecoop06.bknr.net/ From bdesth.quelquechose at free.quelquepart.fr Fri Jun 2 19:58:33 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 03 Jun 2006 01:58:33 +0200 Subject: integer to binary... In-Reply-To: <1149190940.548582.27200@h76g2000cwa.googlegroups.com> References: <1149189570.376091.319890@j55g2000cwa.googlegroups.com> <127ugf9jgu7av18@corp.supernews.com> <1149190940.548582.27200@h76g2000cwa.googlegroups.com> Message-ID: <4480a11b$0$6172$626a54ce@news.free.fr> nicolasg at gmail.com a ?crit : > Grant Edwards wrote: > >>On 2006-06-01, nicolasg at gmail.com wrote: >> >> >>>does anyone know a module or something to convert numbers like integer >>>to binary format ? >> >>They _are_ in binary format. >> >> >>>for example I want to convert number 7 to 0111 so I can make some >>>bitwise operations... >> >>Just do it: >> >> >>>>>7 & 3 >> >>3 >> >>>>>7 | 8 >> >>15 >> >> >>-- > > I know I can do that but I need to operate in every bit separeted. Could you explain the difference ? From peace.is.our.profession at gmx.de Fri Jun 23 04:11:08 2006 From: peace.is.our.profession at gmx.de (Mirco Wahab) Date: Fri, 23 Jun 2006 10:11:08 +0200 Subject: map() return of flat tuple list In-Reply-To: <1151017077.211517.47940@u72g2000cwu.googlegroups.com> References: <1151017077.211517.47940@u72g2000cwu.googlegroups.com> Message-ID: Thus spoke bearophileHUGS at lycos.com (on 2006-06-23 00:57): > Maybe you want something like this (but this doesn't use map): > [(r,c) for r, row in enumerate(m) for c in xrange(len(row))] Ahh, its a 'list comprehension', nice. Now, lets see how the decorate/undecorate sort turns out to look in Python: arr = [ [3,3,3,3], [3,3,3,1], [3,3,3,3] ] print \ sorted( [ (j,i) for j, row in enumerate(arr) for i in xrange(len(row)) ], lambda a,b: (arr[a[0]][a[1]] - arr[b[0]][b[1]]) )[ 0 ] ==> prints indices: (1,3) He, this looks more like Haskell than like Python (for me, it looks awful ;-) I'll try to come up with at least one map inside the comprehension, if that works - just to avoid the dual for ;-) Reagrds and thanks Mirco From tim.leeuwvander at nl.unisys.com Thu Jun 22 04:20:13 2006 From: tim.leeuwvander at nl.unisys.com (Tim N. van der Leeuw) Date: 22 Jun 2006 01:20:13 -0700 Subject: wxPython GUI designer In-Reply-To: <1150664728.435902.210930@y41g2000cwy.googlegroups.com> References: <1150661348.837969.46870@r2g2000cwb.googlegroups.com> <1150664728.435902.210930@y41g2000cwy.googlegroups.com> Message-ID: <1150964413.849754.130180@i40g2000cwc.googlegroups.com> diffuser78 at gmail.com wrote: > Are there any good commercial project built with wx ? I am a newbie and > a have to write a small application in Python. I was wondering which > optin would be best for me in terms of least learning curve and getting > the final product ASAP. > > Thanks > It's not a commercial project, but the current BitTorrent beta's (versions 4.9.x) are written with wx ... To me, the appearant lack of a good and easy-to-use multi-column tree widget was a showstopper to diving deeper into wxPython, though. I decided to use PyGTK for now, which I'm a bit more familiar already and which I know has a multi-column tree good enough for me (and I found it easy to add inline-editing too). I don't know how good PyQT is on windows; other than that, in my opinion PyGTK gives the best / most complete GUI for Python with reasonable ease-of-programming. Cheers, --Tim From tim.leeuwvander at nl.unisys.com Sat Jun 24 13:27:49 2006 From: tim.leeuwvander at nl.unisys.com (Tim N. van der Leeuw) Date: 24 Jun 2006 10:27:49 -0700 Subject: PyGTK and Py2Exe troubles In-Reply-To: <1151169308.365744.108440@u72g2000cwu.googlegroups.com> References: <1151141748.172141.285890@p79g2000cwp.googlegroups.com> <1151169308.365744.108440@u72g2000cwu.googlegroups.com> Message-ID: <1151170069.457557.298100@p79g2000cwp.googlegroups.com> riqu... at gmail.com wrote: > Tim N. van der Leeuw ha scritto: > > > I tried to create a windows executable of a pygtk program. My first > > attempt worked, kinda, except that no themes were applied and no > > readable fonts were found by pango; so all letters where just empty > > squares. But the program worked. > > > > I looked up some docs, found the following recipe on the PyGTK Wiki > > site: > > http://starship.python.net/crew/theller/moin.cgi/Py2exeAndPyGTK > > > > I followed those instructions to convert my setup.py file; everything > > still worked the same as before. > > versions of python,gtk,pygtk? wich windows? > wich installer of gtk have you used? > did you install pycairo too? > > try again with these one, if different from yours > gtk -> http://gladewin32.sourceforge.net > pygtk/pycairo -> http://www.mapr.ucl.ac.be/~gustin/win32_ports/ > > bye, > Riccardo Riccardo, Thanks for your reply; sorry for omitting all the relevant details! Python: 2.4.3 from python.org Windows XP SP2 GTK 2.8.18 from gladewin32 pygtk & pycairo from Gustin's ports. py2exe: 0.6.5 The program works when run under the interpreter; but crashes when using py2exe and all shared files mentioned, are copied to the same dir as the exe. (When I don't copy all those files, pango complains about missing fonts and shows only empty squares for all leters. but the program doesn't crash. It only crashes when GTK's shared files are with the program) Thanks, --Tim From python.list at tim.thechases.com Wed Jun 7 13:05:01 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 07 Jun 2006 12:05:01 -0500 Subject: printing backslash In-Reply-To: <1149698793.422979.148770@i40g2000cwc.googlegroups.com> References: <1149698793.422979.148770@i40g2000cwc.googlegroups.com> Message-ID: <4487073D.3090603@tim.thechases.com> > i want to print something like this > > |\| > > first i tried it as string > > a = "|\|" > > it prints ok > > but when i put it to a list > > a = ["|\|"] > > it gives me '|\\|' .there are 2 back slashes...i only want one.. how > can i properly escape it? > I have tried [r"|\|"] , [r'\\'] but they do not work... You omit how you're printing matters. >>> s1 = '|\|' >>> s2 = r'|\|' >>> s3 = '|\\|' >>> print repr(s1), '->', s1 '|\\|' -> |\| >>> print repr(s2), '->', s2 '|\\|' -> |\| >>> print repr(s3), '->', s3 '|\\|' -> |\| There's a difference between the repr() of a string (which escapes items that need to be escaped) and printing items. All three *print* the item as you request it. All three represent the item with the proper backslashes. The preferred form of putting backslashes in a string is the s2 or s3 form, as the s1 form can have some "unpredictable"(*) results: "\|" happens not to be a recognized escape sequence "\t" is, so you get things like >>> s = '\t\|' >>> s '\t\\|' -tkc (*) "unpredictable" defined as, "predictable, if you happen to have memorized the exact set of characters that do or don't need to beescaped" From marc.t.davies at gmail.com Tue Jun 20 08:54:05 2006 From: marc.t.davies at gmail.com (MTD) Date: 20 Jun 2006 05:54:05 -0700 Subject: Iteration over recursion? Message-ID: <1150808045.539887.291180@i40g2000cwc.googlegroups.com> Hello all, I've been messing about for fun creating a trial division factorizing function and I'm naturally interested in optimising it as much as possible. I've been told that iteration in python is generally more time-efficient than recursion. Is that true? Here is my algorithm as it stands. Any suggestions appreciated! from math import * def factorize(x): """ Return factors of x """ factors = [] lim = int(sqrt(x)) y = divmod(x,2) if y[1] == 0: # x is even factors = factors + [2] + factorize(y[0]) else: # x is odd i = 3 while i <= lim: y = divmod(x,i) if y[1] == 0: factors = factors + [i] + factorize(y[0]) i = lim+1 else: i += 2 if factors == []: # necessary step for correct recursion factors = [x] return factors From eval.apply at gmail.com Mon Jun 26 12:25:16 2006 From: eval.apply at gmail.com (Joe Marshall) Date: 26 Jun 2006 09:25:16 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: <1151115244.951029.56060@g10g2000cwb.googlegroups.com> References: <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150761004.928251.318340@h76g2000cwa.googlegroups.com> <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <1150908952.804184.218990@r2g2000cwb.googlegroups.com> <1150991074.705803.211570@m73g2000cwd.googlegroups.com> <1151083239.829296.33030@i40g2000cwc.googlegroups.com> <1151083931.162325.268050@g10g2000cwb.googlegroups.com> <1151086320.564736.272500@y41g2000cwy.googlegroups.com> <1151100483.057344.310970@g10g2000cwb.googlegroups.com> <1151115244.951029.56060@g10g2000cwb.googlegroups.com> Message-ID: <1151339115.942653.59210@c74g2000cwc.googlegroups.com> Marshall wrote: > > I stand corrected: if one is using C and writing self-modifying > code, then one *can* zip one's pants. Static proofs notwithstanding, I'd prefer a dynamic check just prior to this operation. I want my code to be the only self-modifying thing around here. From trentm at activestate.com Mon Jun 19 20:16:26 2006 From: trentm at activestate.com (Trent Mick) Date: Mon, 19 Jun 2006 17:16:26 -0700 Subject: Active Python versions In-Reply-To: <2hElg.41514$mF2.19600@bgtnsc04-news.ops.worldnet.att.net> References: <2hElg.41514$mF2.19600@bgtnsc04-news.ops.worldnet.att.net> Message-ID: <44973E5A.5030909@activestate.com> Tom Del Rosso wrote: > Can I ask you about alternative environments? How do Active Python and IDLE > from python.org compare? Both ActivePython and the Python installers from python.org install IDLE. They should not differ at all (AFAIK). Trent -- Trent Mick trentm at activestate.com From luismgz at gmail.com Fri Jun 2 01:36:13 2006 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 1 Jun 2006 22:36:13 -0700 Subject: C# equivalent to range() References: <1149214153.359809.288610@i39g2000cwa.googlegroups.com> <1149214491.034665.29030@j55g2000cwa.googlegroups.com> <1149217547.618703.209770@i39g2000cwa.googlegroups.com> Message-ID: <1149226573.446484.17340@c74g2000cwc.googlegroups.com> Erik Max Francis wrote: > Yeah, what jerks. They actually wanted to talk about Python, not some > random other language that you're trying to learn that has nothing to do > with it ... There are thousands of threads to choose from in this forum. If they didn't like this question, they could have picked any other one to discuss. There's no need to be disagreeable :-) Luis From fredrik at pythonware.com Fri Jun 30 07:01:00 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 30 Jun 2006 13:01:00 +0200 Subject: delete first line in a file References: <44a4f854$0$12942$91cee783@newsreader02.highway.telekom.at> <44a50151$0$12935$91cee783@newsreader02.highway.telekom.at> Message-ID: Juergen Huber wrote: > ok...i thought as much, that i have to copy this file! > > how will i do that?! > how will i fix this file => delete the first line?! > > with which commands could i do that?! start here: http://docs.python.org/tut/node9.html#SECTION009200000000000000000 From kay.schluehr at gmx.net Wed Jun 21 03:03:44 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 21 Jun 2006 00:03:44 -0700 Subject: Iteration over recursion? In-Reply-To: <1150808045.539887.291180@i40g2000cwc.googlegroups.com> References: <1150808045.539887.291180@i40g2000cwc.googlegroups.com> Message-ID: <1150873424.345733.165730@m73g2000cwd.googlegroups.com> You might use a separate prime generator to produce prime factors. The factorize algorithm becomes quite simple and configurable by prime generators. For demonstration purposes I use the eratosthenes sieve. def eratosthenes(): memo = {} q = 2 while True: p = memo.pop(q, None) if p is None: yield q memo[q*q] = q else: x = p + q while x in memo: x += p memo[x] = p q+=1 def factorize(n, sieve = eratosthenes): if n <= 1: return [n] factors = [] primes = sieve() for q in primes: while n % q == 0: factors.append(q) n //= q if n == 1: return factors Regards, Kay From sjmachin at lexicon.net Thu Jun 1 20:04:45 2006 From: sjmachin at lexicon.net (John Machin) Date: 1 Jun 2006 17:04:45 -0700 Subject: New to Python: Do we have the concept of Hash in Python? In-Reply-To: References: Message-ID: <1149206685.768210.71990@i39g2000cwa.googlegroups.com> A.M wrote: > The application is not mission critical system. It is just a simple > reporting tool. Famous last words. From geoffschmidt at gmail.com Tue Jun 20 03:23:24 2006 From: geoffschmidt at gmail.com (geoffschmidt at gmail.com) Date: 20 Jun 2006 00:23:24 -0700 Subject: Bus error in PyGILState_Release (callbacks from other threads) Message-ID: <1150788204.188239.55450@g10g2000cwb.googlegroups.com> [Note: I don't check the mailbox in the header. Please send any correspondence to the address listed below.] I'm trying to write an extension in C that delivers callbacks to Python. The C code starts several threads, and I'd like one of the new threads that is started to be able to deliver callbacks to Python. I thought I could do this by wrapping the callback function in PyGILState_Ensure / PyGILState_Release. When I do this, the Python code in the callback in between those two calls certainly works, but when PyGILState_Release is called, the process dies with a bus error! Is this supposed to work, or am I doing something terribly wrong? (Code attached below.) This is the official Python 2.4.3 build for OS X; I'm running OS X 10.4.6. My examination of the source suggests that head_mutex in pystate.c is becoming 0x20, which is not so good, since it is supposed to be a pointer. (in pystate.c: PyGILState_Release calls PyThreadState_DeleteCurrent, which calls tstate_delete_common, which calls HEAD_UNLOCK, which calls PyThread_release_lock in thread_pthread.h; this function's first action is to call pthread_mutex_lock, which dies on a bus error because the value of head_mutex that HEAD_UNLOCK got and passed to PyThread_release_lock pointed off into outer space. This is educated guesswork -- gdb's not reporting a whole lot in the call stack.) Interestingly, the prior call to HEAD_LOCK in tstate_delete_common succeeds, so it sort of looks like memory is being corrupted in between the HEAD_LOCK at around pystate.c:245 and the HEAD_UNLOCK around pystate.c:254. HEAD_LOCK(); // <-- guess: this is succeeding for (p = &interp->tstate_head; ; p = &(*p)->next) { if (*p == NULL) Py_FatalError( "PyThreadState_Delete: invalid tstate"); if (*p == tstate) break; } *p = tstate->next; HEAD_UNLOCK(); // <-- guess: this is resulting in a bus error Here's some Pyrex code that crashes 100% of the time for me: --- snip (foo.pyx) --- cdef extern from "stdio.h": int printf(char *str, ...) cdef extern from "Python.h": ctypedef int PyGILState_STATE PyGILState_STATE PyGILState_Ensure() void PyGILState_Release(PyGILState_STATE gstate) cdef extern from "pthread.h": ctypedef void *pthread_t # it'll do int pthread_create(pthread_t *thread, void *attr, void *(*start_routine)(void *), void *arg) cdef extern void *func(void *x): printf("Entering func(%p)\n", x) cdef PyGILState_STATE st printf("PyGILState_Ensure\n") st = PyGILState_Ensure() printf("PyGILState_Release\n") PyGILState_Release(st) printf("Leaving func\n") def callFuncDirectly(): func(NULL) def callFuncInThread(): cdef pthread_t thr pthread_create(&thr, NULL, func, NULL); --- snip (setup.py) --- from distutils.core import setup from distutils.extension import Extension from Pyrex.Distutils import build_ext setup( name = 'foo', ext_modules = [Extension("foo", ["foo.pyx"])], cmdclass = {'build_ext': build_ext}, ) --- end --- I ran 'python setup.py build_ext --inplace', then started python in that directory, did 'import foo', and then 'foo.callFuncDirectly()'. No crash. Then I called 'foo.callFuncInThread()'. Prints 'PyGILState_Release' and then falls over. Program received signal EXC_BAD_ACCESS, Could not access memory. Reason: KERN_PROTECTION_FAILURE at address: 0x00000020 [Switching to process 25649 thread 0x313] 0x900017dc in pthread_mutex_lock () (gdb) bt #0 0x900017dc in pthread_mutex_lock () #1 0x002be654 in PyThread_release_lock (lock=0x20) at /Volumes/Data/Users/ronald/Universal/python24-fat/Python/thread_pthread.h:439 #2 0x00045600 in func (__pyx_v_x=0x0) at foo.c:72 #3 0x9002ba68 in _pthread_body () Any help (or even just confirmation along the lines of "this is supposed to work, file a bug") would be greatly appreciated. thanks, Geoff Schmidt gschmidt [[a t]] gschmidt [[d o t]] org (send correspondence here, not the address in the header) From anton.vredegoor at gmail.com Thu Jun 1 15:54:45 2006 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Thu, 01 Jun 2006 21:54:45 +0200 Subject: integer to binary... In-Reply-To: <1149189570.376091.319890@j55g2000cwa.googlegroups.com> References: <1149189570.376091.319890@j55g2000cwa.googlegroups.com> Message-ID: <447f4610@news.henrynet.se> nicolasg at gmail.com wrote: > does anyone know a module or something to convert numbers like integer > to binary format ? > > for example I want to convert number 7 to 0111 so I can make some > bitwise operations... >>> def bits(i,n): return tuple((0,1)[i>>j & 1] for j in xrange(n-1,-1,-1)) >>> bits(7,4) (0, 1, 1, 1) Anton From josef.cihal at siemens.com Fri Jun 30 08:30:21 2006 From: josef.cihal at siemens.com (Cihal Josef) Date: Fri, 30 Jun 2006 14:30:21 +0200 Subject: Can't connect to Oracle DB via DCOracle2 as sysdba Message-ID: <94CEBD2AC72A3D478BC8381A196FD7CCA0083E@vie012.at.sat-automation.com> Hi, how can I connect please to DB Oracle9i via DCOracle.Connect as SYSDBA? >>> dbc = DCOracle2.connect(user='', password= ' as sysdba' ) u,p2: sys,'p Traceback (most recent call last): File "", line 1, in ? File "C:\Program Files\Python21\lib\DCOracle2\DCOracle2\DCOracle2.py", line 18 6, in connect #print "Created new DCO2 connection %s" % conn dco2.DatabaseError: (1017, 'ORA-01017: invalid username/password; logon denied') How can I connect via DCOracle2 in Python to Database? as usually mit sqlplus in command line: sqlplus "/ as sysdba" Thanks for every idea! Josef -------------- next part -------------- An HTML attachment was scrubbed... URL: From paddy3118 at netscape.net Fri Jun 2 15:09:54 2006 From: paddy3118 at netscape.net (Paddy) Date: 2 Jun 2006 12:09:54 -0700 Subject: Sampling a population References: Message-ID: <1149275394.499808.31460@i39g2000cwa.googlegroups.com> Brian Quinlan wrote: > This is less a Python question and more a optimization/probability > question. Imaging that you have a list of objects and there frequency in > a population e.g. > > lst = [(a, 0.01), (b, 0.05), (c, 0.50), (d, 0.30), (e, 0.04), (f, 0.10)] > > and you want to drawn n items from that list (duplicates allowed), with > that probability distribution. > > The fastest algorithm that I have been able to devise for doing so is: > O(n * log(len(lst))). Can anyone think or a solution with a better time > complexity? If not, is there an obviously better way to do this > (assuming n is big and the list size is small). > Any way I tried to slice and dice it, I could not get any faster. draw2 and draw 3 generate code on the fly. draw4 sneakily tries to trade memory and accuracy for speed but is even slower! First the times, then the code: $ ./timeit.py 'from probDistribution import draw as draw; draw(10000, [0.01, 0.05, 0.50, 0.30, 0.04, 0.10])' 100 loops, best of 3: 13.4 msec per loop $ ./timeit.py 'from probDistribution import draw2 as draw; draw(10000, [0.01, 0.05, 0.50, 0.30, 0.04, 0.10])' 100 loops, best of 3: 15.2 msec per loop $ ./timeit.py 'from probDistribution import draw3 as draw; draw(10000, [0.01, 0.05, 0.50, 0.30, 0.04, 0.10])' 100 loops, best of 3: 16.2 msec per loop $ ./timeit.py 'from probDistribution import draw4 as draw; draw(10000, [0.01, 0.05, 0.50, 0.30, 0.04, 0.10])' 10 loops, best of 3: 30.5 msec per loop === CODE probDistribution.py === from random import random, randrange from bisect import bisect def draw(n, lst): ps = [] last = 0 for p in lst: ps.append(last + p) last += p # ps = [0.01, 0.06, 0.56, 0.86, 0.90, 1.00] chosen = [0] * len(lst) # track frequency for i in range(n): r = random() chosen[bisect(ps, r)] += 1 # binary search and increment result = [] # rescale probability based on frequency for c in chosen: result.append(float(c) / n) return result def draw2(n, lst): """ uses dynamicc code generation of this form: chosen = [0] * 6 for i in xrange(10000): r = random() if r < 0.01: chosen[0]+=1 elif r < 0.06: chosen[1] +=1 ... elif r < 0.90: chosen[4] +=1 else chosen[5]+=1 """ assert len(lst)>1, "Corner case NOT covered" codestr = 'chosen = [0] * %i\n' % (len(lst),) codestr += 'for i in xrange(%i):\n r = random()\n' % (n,) last = 0.0 lstmax = len(lst)-1 for i,p in enumerate(lst): last += p if i==0: codestr += ' if r < %g: chosen[%i] +=1\n' % (last, i) elif i==lstmax: codestr += ' else: chosen[%i] +=1\n' % (i,) else: codestr += ' elif r < %g: chosen[%i] +=1\n' % (last, i) exec codestr result = [] # rescale probability based on frequency for c in chosen: result.append(float(c) / n) return result def draw3(n, lst): """ uses dynamicc code generation of this form: chosen = [0] * 6 for i in xrange(10000): r = random() chosen[-1+ ( ((r<0.01) and 1) or ((r<0.06) and 2) ... or ((r<0.90) and 5) or 6 )] +=1 """ assert len(lst)>1, "Corner case NOT covered" codestr = 'chosen = [0] * %i\n' % (len(lst),) codestr += 'for i in xrange(%i):\n r = random()\n' % (n,) codestr += ' chosen[-1+ (\n' last = 0.0 lstmax = len(lst)-1 for i,p in enumerate(lst): last += p if i==0: codestr += ' ((r<%g) and 1)\n' % (last) elif i==lstmax: codestr += ' or %i\n )] +=1\n' % (i+1,) else: codestr += ' or ((r<%g) and %i)\n' % (last, i+1) #return codestr exec codestr result = [] # rescale probability based on frequency for c in chosen: result.append(float(c) / n) return result def draw4(n, lst, precision = 0.01, maxbins=10000): """ Memory/speed tradeoff by coarse quantizing of frequency values. """ assert len(lst)>1, "Corner case NOT covered" assert 0.0 < precision < 1.0 and (1.0/precision) < maxbins binmax = int(1.0/precision) chosenbin = [0] * binmax for i in xrange(n): chosenbin[randrange(binmax)] +=1 left, right = 0, 0 # extract bin range for summation chosen = [0] * len(lst) last = 0.0 for i,p in enumerate(lst): last += p right = int(last/precision) chosen[i] = sum( chosenbin[left:right] ) left = right result = [] # rescale probability based on frequency for c in chosen: result.append(float(c) / n) return result === END CODE === From mumarathe at gmail.com Fri Jun 9 16:38:45 2006 From: mumarathe at gmail.com (Manish Marathe) Date: Fri, 9 Jun 2006 13:38:45 -0700 Subject: Killing a thread Message-ID: <7c8a9a970606091338t174fbcb0wc73cdb8b385f8ccd@mail.gmail.com> Hello, I am creating threads using my self defined class which inherits the threading.Thread class. I want to know how can I kill the threads which are being created by the object of my self defined class. Thanks -- Manish Marathe SpikeSource, Inc. http://developer.spikesource.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From s99999999s2003 at yahoo.com Wed Jun 7 02:18:57 2006 From: s99999999s2003 at yahoo.com (s99999999s2003 at yahoo.com) Date: 6 Jun 2006 23:18:57 -0700 Subject: assign operator as variable ? Message-ID: <1149661137.454954.234390@u72g2000cwu.googlegroups.com> hi in python is there any way to do this op = "<" a = 10 b = 20 if a op b : print "a is less than b" ?? thanks From scott.daniels at acm.org Tue Jun 20 11:58:04 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Tue, 20 Jun 2006 08:58:04 -0700 Subject: [PIL]: Image size in runtime In-Reply-To: References: Message-ID: <4498161d$1@nntp0.pdx.net> Andrea Gavana wrote: > I am using PIL to load and display some pictures (via wxPython) in a > GUI. I have added the ability for the user to change the linear > dimensions of the image (in pixels) and the quality of the image in > order for the image to be saved in another file. > I was wondering if is there a way to know in advance, based on the > pixel dimensions specified by the user and by the image quality, which > file size (in > bytes) I will obtain for the new image (approximatively). Is there a > way to obtain such result without actually saving the image? The answer is really no, since it depends on the complexity of the picture. A solid square of one color is highly compressible, and a photo of a tall ship's rigging is relatively hard to compress. You can compress to a cStringIO file (and so not have to actually hit the disk) to get a size, ten discard the cStringIO object. -- --Scott David Daniels scott.daniels at acm.org From email at christoph-haas.de Wed Jun 14 13:56:17 2006 From: email at christoph-haas.de (Christoph Haas) Date: Wed, 14 Jun 2006 19:56:17 +0200 Subject: Correctly reading stdout/stderr from subprocess In-Reply-To: <200606141556.16856.maric@aristote.info> References: <20060613222002.GB5153@workaround.org> <200606141314.14587.maric@aristote.info> <200606141556.16856.maric@aristote.info> Message-ID: <20060614175617.GB5018@workaround.org> On Wed, Jun 14, 2006 at 03:56:16PM +0200, Maric Michaud wrote: > I did it just to validate my point and because i don't use threads very often > in python, some exercises can't hurt :) Since you are familiar with threads I believe that my excercises are a tad bit more low-level compared to yours. :) > def run(command): > > import subprocess > > run = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, > stderr=subprocess.PIPE) > > # Wait for the process to return > import thread, threading > out, err = [], [] > out_ended, err_ended = threading.Event(), threading.Event() > > def getOutput(output, lines, ended_event) : > for i in output.readlines() : lines.append(i.rstrip('\n')) > ended_event.set() > > out_thread = thread.start_new_thread(getOutput, (run.stdout, out, > out_ended)) > err_thread = thread.start_new_thread(getOutput, (run.stderr, err, > err_ended)) > > out_ended.wait() > err_ended.wait() > > returncode = run.wait() > > return returncode, out, err Quite interesting. I dived into /usr/lib/python2.4/subprocess.py and found out that the "communicate()" method actually works similarly. I might even prefer your version because I get the returncode from run.wait() what "communicate()" does not. Great work. Thanks for your time. Kindly Christoph From thorsten at thorstenkampe.de Wed Jun 7 12:09:32 2006 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Wed, 7 Jun 2006 17:09:32 +0100 Subject: CENSORSHIP - Django Project (Schema Evolution Support) References: <4486B9FB.9030804@lazaridis.com> Message-ID: <1mbzvhr7j0x99.qlcv3kw259m6.dlg@40tude.net> * Ilias Lazaridis (2006-06-07 12:35 +0000) > [posted publicly to comp.lang.python, with email notification to 6 > recipients relevant to the topic] I think I have a deja-vu... Did someone say "Xah"?! T. From python.list at tim.thechases.com Thu Jun 1 16:02:59 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 01 Jun 2006 15:02:59 -0500 Subject: integer to binary... In-Reply-To: <1149190940.548582.27200@h76g2000cwa.googlegroups.com> References: <1149189570.376091.319890@j55g2000cwa.googlegroups.com> <127ugf9jgu7av18@corp.supernews.com> <1149190940.548582.27200@h76g2000cwa.googlegroups.com> Message-ID: <447F47F3.2030505@tim.thechases.com> >>> for example I want to convert number 7 to 0111 so I can make some >>> bitwise operations... >> Just do it: >> >>>>> 7 & 3 >> 3 >>>>> 7 | 8 >> 15 > I know I can do that but I need to operate in every bit separeted. I suppose there might be other operations for which having them as strings could be handy. E.g. counting bits: bitCount = len([c for c in "01001010101" if c=="1"]) or parity checking with those counted bits...sure, it can be done with the raw stuff, but the operations often tend to be more obscure. Other reasons for wanting an arbitrary integer in binary might be for plain-old-display, especially if it represents bitmap data. If you just want to operate on each bit, you can iterate over the number of bits and shift a single bit to its position: >>> target = 10 >>> shift = 0 >>> while 1 << shift <= target: ... print "Bit %i is %i" % (shift, ... (target & (1 << shift)) >> shift) ... shift += 1 ... Bit 0 is 0 Bit 1 is 1 Bit 2 is 0 Bit 3 is 1 It's ugly, but it works... -tkc From alf at merlin.fayauffre.org Tue Jun 13 09:30:36 2006 From: alf at merlin.fayauffre.org (Alexandre Fayolle) Date: Tue, 13 Jun 2006 13:30:36 +0000 (UTC) Subject: pylab doesn't find numpy on Windows References: <1150205073.203361.304190@f14g2000cwb.googlegroups.com> Message-ID: Le 13-06-2006, timw.google nous disait: > Hi all. > > I installed matplotlib 0.87.3 under Python 2.4 on both Linux (FC3) and > Windows XP Pro. On the linux install, I can import pylab, but when I > try to do the same thing on the Windows installation, I get > >>>> from pylab import * > > ImportError: No module named Numeric > > I have numpy 0.9.8 installed in both places too. it is trying to load Numeric python. You need to configure matplotlib to use numpy by saying numerix : numpy in the matplotlibrc file. -- Alexandre Fayolle LOGILAB, Paris (France) Formations Python, Zope, Plone, Debian: http://www.logilab.fr/formations D?veloppement logiciel sur mesure: http://www.logilab.fr/services Python et calcul scientifique: http://www.logilab.fr/science From antroy at gmail.com Mon Jun 19 06:52:48 2006 From: antroy at gmail.com (Ant) Date: 19 Jun 2006 03:52:48 -0700 Subject: Simple script to make .png thumbnails from .zip archive... In-Reply-To: <1150713530.440037.54650@y41g2000cwy.googlegroups.com> References: <1150660266.413889.217280@c74g2000cwc.googlegroups.com> <1150664094.345764.280030@u72g2000cwu.googlegroups.com> <1150713530.440037.54650@y41g2000cwy.googlegroups.com> Message-ID: <1150714367.931689.202100@u72g2000cwu.googlegroups.com> Try adapting the other posters example with something like: import Image, StringIO zip=zipfile.ZipFile(inURL,mode="r") picture=zip.read("00.jpg") image = Image.open(StringIO(picture)) image.thumbnail ((128,128), Image.ANTIALIAS) image.save (file + '.thumb.png') I haven't tested it, but something like this should work. From larry at theclapp.org Fri Jun 30 16:14:57 2006 From: larry at theclapp.org (Larry Clapp) Date: Fri, 30 Jun 2006 20:14:57 GMT Subject: Reddit broke - should have remained on Lisp? References: <1151626961.232761.255550@d56g2000cwd.googlegroups.com> <1151627462.297352.205150@i40g2000cwc.googlegroups.com> Message-ID: On 2006-06-30, Luis M. Gonz?lez wrote: > Alok wrote: >> While posting a comment on http://www.reddit.com I got an error >> page with the following curious statement on it. >> >> "reddit broke (sorry)" >> "looks like we shouldn't have stopped using lisp..." >> >> See screenshot at >> http://photos1.blogger.com/blogger/1773/1980/1600/reddit-broke.jpg >> >> Whether they truly repent not using lisp or otherwise, their site >> appears to be 3 times slower ... > > I don't know if this is true or not, but blaming a language for a > poor development is a little bit ridiculous... You've obviously never used Taskmate. Ick. ;) -- L From steve at holdenweb.com Thu Jun 15 10:25:11 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 15 Jun 2006 15:25:11 +0100 Subject: GUI in Python using wxGlade In-Reply-To: <1150380251.279150.73620@u72g2000cwu.googlegroups.com> References: <1150380251.279150.73620@u72g2000cwu.googlegroups.com> Message-ID: <44916DC7.50201@holdenweb.com> diffuser78 at gmail.com wrote: > I recently tried a hand at wxGlade and was happy to see it designs a > GUI for you in minutes. I am a newbie Python coder. I am not completely > aware of GUI programming. > > I can easily make menubars etc but I am not too sure sure how to get > more windows poppping to get more information. I mean when you click > something, a new windows would open and ask for input like that. Since > I am using wxGlade and wxPython....can you suggest me a quick tutorial > for GUI programming. > > Every help is appreciate, > Without having time to go into a full, the way to proceed with Glade (unless I am mistaken) is to design each window independently of the others, and to use a button press in one window to create an instance of another type of window. Good luck! regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From fabiofz at gmail.com Tue Jun 20 21:53:06 2006 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Tue, 20 Jun 2006 22:53:06 -0300 Subject: Another Eclipse Question with Python In-Reply-To: References: Message-ID: On 6/20/06, Stan Cook wrote: > > I followed the help instructions to set a watchpoint for a > variable, or at lest I tried. When I hilight the variable > and go to the run menu, the "toggle watchpoint" is grayed > out and can't be selected as specified. Is this Python > related only? Just wondering, I want to use the software > with all of the features it allows if possible. Which help instructions? Have you checked the getting started at: http://fabioz.com/pydev/manual_101_root.html? (This can happen if your perspective is not well configured...) -------------- next part -------------- An HTML attachment was scrubbed... URL: From invalidemail at aerojockey.com Wed Jun 28 20:21:08 2006 From: invalidemail at aerojockey.com (Carl Banks) Date: 28 Jun 2006 17:21:08 -0700 Subject: Numeric help! References: <1151510615.139278.167520@j72g2000cwa.googlegroups.com> Message-ID: <1151540468.434688.242530@75g2000cwc.googlegroups.com> Sheldon wrote: > Hi, > > I have the following loop that I think can be written to run faster in > Numeric. I am currently using Numeric. > range_va = [60,61,62,63,64,65,66,67,68,69,70,71,72] > main.xsize= 600 > main.ysize= 600 > #msgva is an (600x600) Numeric array with mutiple occurrences of the > values in range_va > #sat_id is an (600x600) Numeric array with values ranging from -2 to 2 > for z in range_va: > count = 0 > mbias = 0 > for i in range(main.xsize): > for j in range(main.ysize): > if msgva[i,j] == z: > mbias += sat_id[i,j] # take the sum of the > values > count += 1 # count the occurrences > tmp_array[0,index] = round(mbias/count,1) # store the mean > tmp_array[1,index] = z > index += 1 > > Any help would be greatly appreciated! I'm not sufficiently sure this isn't a homework problem, so here's a partial answer. Your intuition is correct--there's almost always a faster way to do it when you're cycling through Numeric array indices in a Python for loop. Numeric and successors exist mostly to get rid of them. Given z, you can calculate mbias in one line: mbias = Numeric.sum( Numeric.ravel(Numeric.where(msgva==z,sat_id,0))) Here, the Numeric.where function allows you to filter out entries: it returns an array with the elements of sat_id, but only where the corresponding element of msvga==z; otherwise the entry is zero. Numeric.ravel flattens an multidimensional array into one dimension, and, of course, Numeric.sum adds up all the elements in the array. How to get count and to work this into your loop are left as an exercise. Carl Banks From david.nospam.hopwood at blueyonder.co.uk Wed Jun 28 10:21:54 2006 From: david.nospam.hopwood at blueyonder.co.uk (David Hopwood) Date: Wed, 28 Jun 2006 14:21:54 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: <4gfcclF1mpbg7U1@individual.net> References: <7zy7vt1mz2.fsf@app-3.diku.dk> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <1151384511.223582.305760@m73g2000cwd.googlegroups.com> <4gdkmiF1ldalhU3@individual.net> <4gfcclF1mpbg7U1@individual.net> Message-ID: <6gwog.488405$xt.80841@fe3.news.blueyonder.co.uk> Pascal Costanza wrote: > David Hopwood wrote: >> Pascal Costanza wrote: >>> David Hopwood wrote: >>>> Marshall wrote: >>>> >>>>> The real question is, are there some programs that we >>>>> can't write *at all* in a statically typed language, because >>>>> they'll *never* be typable? >>>> >>>> In a statically typed language that has a "dynamic" type, all >>>> dynamically typed programs are straightforwardly expressible. >>> >>> What about programs where the types change at runtime? >> >> Staged compilation is perfectly compatible with static typing. >> Static typing only requires that it be possible to prove absence >> of some category of type errors when the types are known; it >> does not require that all types are known before the first-stage >> program is run. > > Can you change the types of the program that is already running, or are > the levels strictly separated? In most staged compilation systems this is intentionally not permitted. But this is not a type system issue. You can't change the types in a running program because you can't change the program, period. And you can't do that because most designers of these systems consider directly self-modifying code to be a bad idea (I agree with them). Note that prohibiting directly self-modifying code does not prevent a program from specifying another program to *replace* it. >> There are, however, staged compilation systems that guarantee that >> the generated program will be typeable if the first-stage program >> is. > > ...and I guess that this reduces again the kinds of things you can express. Yes. If you don't want that, use a system that does not impose this restriction/guarantee. >> (It's clear that to compare the expressiveness of statically and >> dynamically typed languages, the languages must be comparable in >> other respects than their type system. Staged compilation is the >> equivalent feature to 'eval'.) > > If it is equivalent to eval (i.e., executed at runtime), and the static > type checker that is part of eval yields a type error, then you still > get a type error at runtime! You can choose to use a system in which this is impossible because only typeable programs can be generated, or one in which non-typeable programs can be generated. In the latter case, type errors are detected at the earliest possible opportunity, as soon as the program code is known and before any of that code has been executed. (In the case of eval, OTOH, the erroneous code may cause visible side effects before any run-time error occurs.) I don't know what else you could ask for. -- David Hopwood From joncle at googlemail.com Tue Jun 13 17:09:58 2006 From: joncle at googlemail.com (Jon Clements) Date: 13 Jun 2006 14:09:58 -0700 Subject: "groupby" is brilliant! In-Reply-To: <1150189681.614913.218500@f6g2000cwb.googlegroups.com> References: <1150180151.643245.148210@y43g2000cwc.googlegroups.com> <1150189681.614913.218500@f6g2000cwb.googlegroups.com> Message-ID: <1150232998.479794.105820@i40g2000cwc.googlegroups.com> Not related to itertools.groupby, but the csv.reader object... If for some reason you have malformed CSV files, with embedded newlines or something of that effect, it will raise an exception. To skip those, you will need a construct of something like this: raw_csv_in = file('filenamehere.csv') for raw_line in raw_csv_in: try: # Do something to rawline here maybe if necessary to "clean it up" row = csv.reader( [raw_line] ).next() # Do your stuff here except csv.Error: pass # or do something more appropriate if the record is important May not be applicable in your case, but has stung me a few times... All the best, Jon. Frank Millman wrote: > Paul McGuire wrote: > > > > > > reader = csv.reader(open('trans.csv', 'rb')) > > > rows = [] > > > for row in reader: > > > rows.append(row) > > > > > > > This is untested, but you might think about converting your explicit "for... > > append" loop into either a list comp, > > > > rows = [row for row in reader] > > > > or just a plain list constructor: > > > > rows = list(reader) > > > > Neh? > > > > -- Paul > > > > Yup, they both work fine. > > There may be times when you want to massage the data before appending > it, in which case you obviously have to do it the long way. Otherwise > these are definitely neater, the last one especially. > > You could even do it as a one-liner - > rows = list(csv.reader(open('trans.csv', 'rb'))) > > It still looks perfectly readable to me. > > Thanks > > Frank From jes at nl.demon.net Mon Jun 5 16:15:27 2006 From: jes at nl.demon.net (Jim Segrave) Date: Mon, 05 Jun 2006 20:15:27 -0000 Subject: Large Dictionaries References: <1147699064.107490@teuthos> <1288rq2mkj9r40b@corp.supernews.com> Message-ID: <128946vm56t7627@corp.supernews.com> In article , Tim Peters wrote: >[Jim Segrave] >> Actually, presorted lists are not a bad case for heapsort - it's quite >> immune to any existing order or lack thereof, > >Write a heapsort and time it. It's not a difference in O() behavior, >but more memory movement is required for a sorted list because >transforming the list into a max-heap at the start requires shuffling >the largest elements from the end of the list to its start. Initially >reverse-sorted is a "good case" for heapsort in the same sense >(because the list is already a max-heap then; initially sorted is as >far from being a max-heap as is possible). "good" and "bad" are both >O(N log N) here, though. I did implement a crude heapsort before posting this and measured the number of comparisions and the number of swaps. ================================================== #!/usr/local/bin/python import random class HeapSorter(object): def __init__(self, seq): self.compares = 0 self.swaps = 0 self.length = len(seq) self.seq = seq def __sift(self, i): while True: j = 2 * i + 1 if j + 1 < self.length: self.compares += 1 if self.seq[j + 1] > self.seq[j]: j = j + 1 if j >= self.length: return self.compares += 1 if self.seq[i] > self.seq[j]: return self.swaps += 1 self.seq[i], self.seq[j] = (self.seq[j], self.seq[i]) i = j def __makeheap(self): for i in range(self.length / 2, -1, -1): self.__sift(i) def sort(self): self.__makeheap() for i in range(self.length - 1, -1, -1): self.swaps += 1 self.seq[i], self.seq[0] = (self.seq[0], self.seq[i]) self.length -= 1 self.__sift(0) if __name__ == '__main__': s = list(range(100000)) random.shuffle(s) heap = HeapSorter(s) heap.sort() print "Random list: comapres %d, swaps %d" % \ (heap.compares, heap.swaps) heap = HeapSorter(s) heap.sort() print "Sorted list: comapres %d, swaps %d" % \ (heap.compares, heap.swaps) s.reverse() heap = HeapSorter(s) heap.sort() print "Reverse Sorted list: comapres %d, swaps %d" % \ (heap.compares, heap.swaps) ================================================== Which gave the following results: /usr/home/jes% python ./heapsort Random list: comapres 3019969, swaps 1575263 Sorted list: comapres 3112517, swaps 1650855 Reverse Sorted list: comapres 2926640, swaps 1497435 Assuming compares and swaps dominate other bookkeeping, then heapsort is quite stable in its performance, although the constant in the O(N log N) is much larger than for other sorts. -- Jim Segrave (jes at jes-2.demon.nl) From fredrik at pythonware.com Thu Jun 15 04:09:52 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 15 Jun 2006 10:09:52 +0200 Subject: nested functions References: <1150319279.865335.323530@u72g2000cwu.googlegroups.com> <1150344748.652441.316680@g10g2000cwb.googlegroups.com> Message-ID: George Sakkis wrote: > It shouldn't come as a surprise if it turns out to be slower, since the > nested function is redefined every time the outer is called. except that it isn't, really: all that happens is that a new function object is created from prebuilt parts, and assigned to a local variable. it's not slower than, say, a method call. From dev at null.com Tue Jun 27 14:48:43 2006 From: dev at null.com (Mike Currie) Date: Tue, 27 Jun 2006 11:48:43 -0700 Subject: Python UTF-8 and codecs Message-ID: I'm trying to write out files that have utf-8 characters 0x85 and 0x08 in them. Every configuration I try I get a UnicodeError: ascii codec can't decode byte 0x85 in position 255: oridinal not in range(128) I've tried using the codecs.open('foo.txt', 'rU', 'utf-8', errors='strict') and that doesn't work and I've also try wrapping the file in an utf8_writer using codecs.lookup('utf8') Any clues? Thanks Mike From fredrik at pythonware.com Fri Jun 2 07:32:14 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 2 Jun 2006 13:32:14 +0200 Subject: import confused by contents of working directory References: <1149244708.049852.153980@i39g2000cwa.googlegroups.com> Message-ID: "Jon" wrote: > Would somebody please explain how to know what is going on when an > import statement is ambiguous? there is no ambiguity: python searches through a list of directories, in a given order. the list is stored in the sys.path list, which you can inspect and modify freely. also see the section "The Module Search Path" in the Modules chapter in the tutorial: http://pytut.infogami.com/node8.html > If the interpreter has several choices about what to import then which one is > chosen? the first one on the path. From esj at harvee.org Tue Jun 13 19:18:47 2006 From: esj at harvee.org (Eric S. Johansson) Date: Tue, 13 Jun 2006 19:18:47 -0400 Subject: question on dict subclassing and overriding __setitems__ Message-ID: I apologize if this is an FAQ but googling has not turned up anything, at least to my keywords. I need to parse a configuration file from an existing application and I'm treating it as a dictionary. I created my class with a parent class of dict. Everything works okay except I discover I need to force keys to uppercase when setting a value. I override __setitems__ and, as you'd expect, I get a recursive loop. I'm obviously missing a clue on how to break the recursion. My admittedly simpleminded method overloading looks like: def __setitem__ (self, index, value): """force keys to uppercase""" self[index.upper()] = value thanks for any pointers. From alex.nanou at gmail.com Thu Jun 22 13:24:10 2006 From: alex.nanou at gmail.com (Alex A. Naanou) Date: 22 Jun 2006 10:24:10 -0700 Subject: The code that could not be... In-Reply-To: References: <1150936844.874347.163060@r2g2000cwb.googlegroups.com> Message-ID: <1150997049.940777.326290@b68g2000cwa.googlegroups.com> Steven Bethard wrote: > Alex A. Naanou wrote: > > The object's __dict__ can only be a dict derivative and at that none of > > the Python's mapping API will be used (the dict is accessed directly). > [snip] > > I wrote a patch some time back, it appears rather stable and is being > > production tested. > > > > you can download it here: > > http://pli.sourceforge.net/object_dict_interface_use_fix.patch > > Could you post this to Python's sourceforge tracker[1]? You're likely > to get more reviewers that way. > > BTW, I too would like to see this happen -- thanks so much for providing > an implementation! > > [1] http://sourceforge.net/tracker/?group_id=5470&atid=105470 > > STeVe I do not recomend using this code yet.... (there are several bugs here that were found today :) ) From bignose+hates-spam at benfinney.id.au Wed Jun 14 20:57:15 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 15 Jun 2006 10:57:15 +1000 Subject: Bundling an application with third-party modules References: <1150285229.237626.36440@y41g2000cwy.googlegroups.com> <1150330824.653252.212300@f6g2000cwb.googlegroups.com> Message-ID: <87u06nkzh0.fsf@benfinney.id.au> "Serge Orlov" writes: > Ben Finney wrote: > > That's a large part of my question. How can I lay out these > > modules sensibly during installation so they'll be easily > > available to, but specific to, my application? > > Put them in a directory "lib" next to the main module and start the > main module with the following blurb: > ------------------------------------------------ > import sys, os > sys.path.insert(1, os.path.join(sys.path[0],"lib")) > ------------------------------------------------ The application consists of many separate programs to perform various tasks, some larger than others. There's no sensible place for a "main module". There probably will be a library directory for common code, though. Are you suggesting that the third-party libraries should go within the application-native library? What's a good way to get from upstream source code (some of which is eggs, some of which expects 'distutils' installation, and some of which is simple one-file modules) to a coherent set of application library code, that is automatable in an install script? I could muddle through and hack something together, of course. I'm asking what are the ways that have already been found to work well. -- \ "Friendship is born at that moment when one person says to | `\ another, 'What! You too? I thought I was the only one!'" -- | _o__) C.S. Lewis | Ben Finney From python.list at tim.thechases.com Wed Jun 7 12:29:25 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 07 Jun 2006 11:29:25 -0500 Subject: creating and naming objects In-Reply-To: <1149696358.065614.76150@h76g2000cwa.googlegroups.com> References: <1149696358.065614.76150@h76g2000cwa.googlegroups.com> Message-ID: <4486FEE5.8090403@tim.thechases.com> > def createStudent(): > foo = Student() > /add stuff > > Now, suppose that I want to create another Student. Do I need > to name that Student something other than foo? What happens > to the original object? If you want to keep the old student around, you have to keep a reference to it somewhere. This can be saving the reference before you tromp on foo, or make foo a list and keep a list of students (which is what it seems like you want to do). >>> foo = Student() # foo is a Student >>> bar = foo # bar now refers to the same student >>> foo is bar True >>> bar.setName("George") >>> foo.name #altering "the thing refered to by bar" changes foo because they both refer to the same object 'George' >>> foo = Student() # make foo refer to a new student >>> foo is bar False >>> foo.name '' >>> bar.name 'George' >>> students = [] >>> students.append(Student()) >>> students.append(Student()) >>> students[0].setName("Alice") >>> students[1].setName("Bob") >>> students[0].name 'Alice' >>> students[1].name 'Bob' >>> students[0] is students[1] False Hopefully the above gives you some ideas as to -how references work -how to store multiple students (use a list) > I hope that I am clear about what I am asking. I hope I am clear in explaining what I understand that you are asking. :) -tkc From onurb at xiludom.gro Thu Jun 8 13:54:41 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 08 Jun 2006 19:54:41 +0200 Subject: follow-up to FieldStorage In-Reply-To: References: <4484b428$0$29635$636a55ce@news.free.fr> Message-ID: <44886462$0$10267$636a55ce@news.free.fr> Tim Roberts wrote: > John Salerno wrote: > > >>Bruno Desthuilliers wrote: >> >>>John Salerno a ?crit : >>> >>>>If I want to get all the values that are entered into an HTML form and >>>>write them to a file, is there some way to handle them all at the same >>>>time, or must FieldStorage be indexed by each specific field name? >>> >>>AFAIK, FieldStorage is a somewhat dict-like object, but I'm not sure it >>>supports the whole dict interface. At least, it does support keys(), so >>>you should get by with: >>> >>>for k in fs.keys(): >>> print >> myfile, k, ":", fs[k] >>> >>>But reading the doc may help... >> >>Thanks. The cgi docs don't seem to get into too much detail, unless I >>wasn't thorough enough. But your method seems like it might work well if >>I can't find something after another read through. > > > On the other hand, 45 seconds with the source code shows that "class > FieldStorage" has member functions called "keys()" and "has_key()". > > Use the source, Luke. To me, that's one of the big beauties of Python. FWIW, reading the source is not even needed to know this: Python 2.4.3 (#1, Jun 3 2006, 17:26:11) [GCC 3.4.6 (Gentoo 3.4.6-r1, ssp-3.4.5-1.0, pie-8.7.9)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import cgi >>> dir(cgi.FieldStorage) ['FieldStorageClass', '_FieldStorage__write', '__contains__', '__doc__', '__getattr__', '__getitem__', '__init__', '__iter__', '__len__', '__module__', '__repr__', 'bufsize', 'getfirst', 'getlist', 'getvalue', 'has_key', 'keys', 'make_file', 'read_binary', 'read_lines', 'read_lines_to_eof', 'read_lines_to_outerboundary', 'read_multi', 'read_single', 'read_urlencoded', 'skip_lines'] >>> -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From gbsuar at gmail.com Wed Jun 28 20:16:49 2006 From: gbsuar at gmail.com (Gabriel) Date: Wed, 28 Jun 2006 21:16:49 -0300 Subject: USB Message-ID: <91906ddf0606281716h1e884a30l69e38f2ddcbe8d44@mail.gmail.com> ?Alguien conoce alg?n m?dulo para python con el que se pueda tener acceso a los puertos USB y que sea multiplataforma? -- Gabriel From g.brandl-nospam at gmx.net Thu Jun 29 03:37:16 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Thu, 29 Jun 2006 09:37:16 +0200 Subject: Generator naming convention? In-Reply-To: <1151520720.749818.131460@i40g2000cwc.googlegroups.com> References: <1151520720.749818.131460@i40g2000cwc.googlegroups.com> Message-ID: aurora00 at gmail.com wrote: > I use generators a lot. E.g. > > > def gen_words(text) > ... parse text ... > yield each word in text > > for word in gen_words(text): > print word > > > I don't like the name gen_xxx() very much. Looking for some inspiration > to name generators. Here are some of my ideas: > > enumerate_words > gen_words > generate_words > parse_words > walk_words > > Any idea? Do you have a naming convention for generators? If it's not a short one where you can see the whole body immediately, I think it's more important to mention the generator-ness in the docstring. Georg From kay.schluehr at gmx.net Tue Jun 6 12:02:59 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 6 Jun 2006 09:02:59 -0700 Subject: 10GB XML Blows out Memory, Suggestions? In-Reply-To: <1149594519.098115.8980@u72g2000cwu.googlegroups.com> References: <1149594519.098115.8980@u72g2000cwu.googlegroups.com> Message-ID: <1149609779.575723.50190@g10g2000cwb.googlegroups.com> axwack at gmail.com wrote: > I wrote a program that takes an XML file into memory using Minidom. I > found out that the XML document is 10gb. > > I clearly need SAX or something else? > > Any suggestions on what that something else is? Is it hard to convert > the code from DOM to SAX? If your XML files grow so large you might rethink the representation model. Maybe you give eXist a try? http://exist.sourceforge.net/ Regards, Kay From tim.peters at gmail.com Tue Jun 20 16:57:56 2006 From: tim.peters at gmail.com (Tim Peters) Date: Tue, 20 Jun 2006 16:57:56 -0400 Subject: need helping tracking down weird bug in cPickle In-Reply-To: <449833A4.7000905@mvista.com> References: <449833A4.7000905@mvista.com> Message-ID: <1f7befae0606201357x62f6d42atb42b2bd91d0133e0@mail.gmail.com> [Carl J. Van Arsdall] > Hey everyone, cPickle is raising an ImportError that I just don't quite > understand. When that happens, the overwhelmingly most likely cause is that the set of modules on your PYTHONPATH has changed since the pickle was first created, in ways such that a module _referenced_ inside the pickle can no longer be found. For example, here's file resourcepmdb.py on my box: def f(): print "hi" Here's a bit of Python code that uses it: import cPickle import resourcepmdb pf = open("junk.pik", "wb") pickler = cPickle.Pickler(pf) pickler.dump([resourcepmdb.f]) pf.close() Pickle stores module globals like user-defined classes and module functions (the case above) not by saving the code they contain, but _just_ by saving strings recording the module's name and the global's name. The unpickling process creates an import out of those strings. So long as resourcepmdb stays on my PYTHONPATH, unpickling junk.pik works fine. For example, this code: import cPickle pf = open("junk.pik", "rb") pickler = cPickle.Unpickler(pf) whatever = pickler.load() pf.close() print whatever prints something like [] But if resourcepmdb gets off my path (for example, resourcepmdb.py gets deleted, renamed, or moved -- or PYTHONPATH itself changes), that same code dies with exactly the error you reported: Traceback (most recent call last): File "pik2.py", line 5, in ? whatever = pickler.load() ImportError: No module named resourcepmdb > ... > I've done some research and it looks like cPickle tries to load some > modules as some kind of test. That's unlikely ;-) > From what I can tell the module that cPickle is trying to load is a > concatenation of the module that it exists in and part of the string > that was sent in the orignal request. Sorry, can't tell from here. > It looks like something where memory is getting overwritten, but I'm not > really doing anything too fancy, so i'm not sure how to approach this > problem. I'm using python2.2. Does anyone know how I might go about > trying to troubleshoot something like this? Is there a good tool or a > better method of error handling I can use to try and track this down? > Or is it better to give up troubleshooting and just upgrade to 2.4? You could at least _install_ a recent Python so you could use the newer pickletools module. pickletools.dis() displays a readable "disassembly" of a pickle, so that there's no need to guess about what the pickle _thinks_ it's trying to do. pickletools won't have any problem working with pickles created by an older Python. > ... > Here's the traceback: > > Traceback (most recent call last): > File "/home/build/bin/resourceManager/resourceQueue.py", line 50, in > initQueue > pickledList = cPickle.load(queueFPtr) > ImportError: No module named resourcepmdb' See above for the most obvious way to get an error like that. From alet at librelogiciel.com Fri Jun 2 17:30:17 2006 From: alet at librelogiciel.com (Jerome Alet) Date: Fri, 02 Jun 2006 23:30:17 +0200 Subject: [ANN] pkipplib v0.04 is out Message-ID: Hi there, I'm pleased to announce pkipplib v0.04 This GPLed Python library allows you to create, manage or parse IPP (Internet Printing Protocol) requests. In addition, it exposes a CUPS() class which allows one to interact with a CUPS print server (or an IPP printer). Written in pure Python, there's no need to link with the CUPS' libraries, and it doesn't even require any CUPS related software to work. The mid to long term goal is to support all of the CUPS' IPP API. Summary of changes : - Support for HTTP Basic authentication when connecting to a CUPS server was added. - General reliability was improved. To learn more about it, see examples of use, or download it : http://www.pykota.com/software/pkipplib/ Thank you for reading. Jerome Alet From claird at lairds.us Thu Jun 1 20:57:06 2006 From: claird at lairds.us (Cameron Laird) Date: Fri, 2 Jun 2006 00:57:06 +0000 Subject: Tkinter - changing existing Dialog? References: Message-ID: <20f4l3-nga.ln1@lairds.us> In article , Michael Yanowitz wrote: >Hello: > > > I have a Tkinter GUI Dialog with many buttons and labels and text >widgets. >What I would like to do is, can I: > >1) Disable/deactivate/hide a button, text widget that is already drawn (and > of course the opposite enable/activate/show it)? . . . import Tkinter root = Tkinter.Tk() def actions(): print "Someone pushed the button." b.configure(state = Tkinter.DISABLED) b = Tkinter.Button(root, text = "Push me", command = actions) b.pack() root.mainloop() From steve at holdenweb.com Tue Jun 27 12:30:28 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 27 Jun 2006 17:30:28 +0100 Subject: Unbound Local error? How? In-Reply-To: <44A15215.5060101@gmail.com> References: <44a14f72$0$16244$636a55ce@news.free.fr> <44A15215.5060101@gmail.com> Message-ID: <44A15D24.9030000@holdenweb.com> Hari Sekhon wrote: > Bruno Desthuilliers wrote: > >>Hari Sekhon wrote: >> >> >>>I've got some code as follows: >>> >>>import re >>>re_regexname = re.compile('abc') >>> >>>..... >>>..... various function defs >>>..... >>> >>>def func1(): >>> ... >>> func2() >>> ... >>> >>>def func2(): >>> if re_regexname.match('abc'): >>> >>> >>>if __name__ == '__main__': >>> func1() >>> >>> >>>but this returns the Traceback: >>> >>>UnboundLocalError: local variable 're_regexname' referenced before >>>assignment >>> >>> >> >>this is *not* the traceback. This is only the error message. The >>traceback contains all needed informations (or at least all possible >>information at this point) to know what happened. But you did not post >>the traceback. Nor did you post the minimal runnable code snippet >>producing this error. >> >> >> >>>How? >>> >>> >> >>How could we know ? >> >> >> >> > > sorry, I know it looks like I was being stingy but the traceback was not > that helpful, not without seeing more a huge amount more of the code. I > was trying to abbreviate. > > Traceback (most recent call last): > File "./backup.py", line 649, in ? > backup(machine,share) > File "./backup.py", line 364, in backup > backupdir(source,destination) > File "./backup.py", line 398, in backupdir > (dirlist,filelist) = getdirlisting( source ) > File "./backup.py", line 445, in getdirlisting > if re_skip_dirs.match(x): > UnboundLocalError: local variable 're_skip_dirs' referenced before > assignment > > This doesn't really show that much, I figured the problem was the following: > > def getdirlisting(): > re_skip_dirs = re_skip_top_dirs #Here's the culprit > > where both these regex compiled objects were declared at the top level, > it seems that the assignment is trying to use the local variable > re_skip_top_dirs which doesn't exist, that's why I'm getting a > traceback, commenting out this line it runs fine. > > -h > > The error is simply that you are making an assignment *somewhere* inside your function body, so the compiler is treating the variable as local, masking the module-level global name. Consequently when you try to read its value you are told that the local variable has not yet been bound to a value. A "global" statement inside the function body will fix the problem. You could also add a keyword argument (never used except to set a default for it in the "def" statement). regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From sjdevnull at yahoo.com Fri Jun 2 14:12:00 2006 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 2 Jun 2006 11:12:00 -0700 Subject: How do you practice Python? In-Reply-To: <1149150517.034409.292530@g10g2000cwb.googlegroups.com> References: <1149150517.034409.292530@g10g2000cwb.googlegroups.com> Message-ID: <1149271920.917381.112910@u72g2000cwu.googlegroups.com> Ray wrote: > In our field, we don't always get to program in the language we'd like > to program. So... how do you practice Python in this case? Write code. Lots of it. Work on a project at home, contribute to something open source, use it to write support scripts at work, whatever. Figure out a way to write code. From tdw at tdw.net Tue Jun 13 05:46:16 2006 From: tdw at tdw.net (Tim Williams) Date: Tue, 13 Jun 2006 10:46:16 +0100 Subject: [*SPAM*] Python open proxy honeypot In-Reply-To: References: Message-ID: <9afea2ac0606130246m7274211g4baa7f83c0d25c0d@mail.gmail.com> On 13/06/06, Alex Reinhart wrote: > > Is running Python's built-in smtpd, pretending to accept and forward all > messages, enough to get me noticed by a spammer, or do I have to do > something else to "advertise" my script as an open proxy? This will get you noticed by crawlers that scan the Internet looking for SMTP open-relays on port 25, its not an open-proxy :):) This will work as planned, but you should also have some email addresses using this server for a full range of spam hits. A single domain is cheap and you can use it just for incoming spam - seed a few addresses around the internet and wait Things you should be aware of: a) You may be breaking your ISP's T&Cs and AUPs b) your ISP connection must have port 25 open c) Be prepared for potentially huge numbers of connections in intermittent but sustained batches which may make your connection unusable. d) point c might get you noticed in relation to point a. HTH :) From onurb at xiludom.gro Thu Jun 1 04:50:53 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 01 Jun 2006 10:50:53 +0200 Subject: How do you practice Python? In-Reply-To: <1149150517.034409.292530@g10g2000cwb.googlegroups.com> References: <1149150517.034409.292530@g10g2000cwb.googlegroups.com> Message-ID: <447eaae0$0$20867$636a55ce@news.free.fr> Ray wrote: > In our field, we don't always get to program in the language we'd like > to program. So... how do you practice Python in this case? Say you're > doing J2EE right now. Hopefully not ! > How do you practice Python to keep your skills > sharp? How *would* I do ? Well, perhaps I'd use Jython ? -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From bearophileHUGS at lycos.com Fri Jun 9 04:32:31 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 9 Jun 2006 01:32:31 -0700 Subject: How to generate k+1 length strings from a list of k length strings? In-Reply-To: <44892d49$1_2@news.bluewin.ch> References: <44883789$1_4@news.bluewin.ch> <1149785331.109164.208340@i39g2000cwa.googlegroups.com> <4488658e$1_5@news.bluewin.ch> <1149800459.244528.220790@u72g2000cwu.googlegroups.com> <44892d49$1_2@news.bluewin.ch> Message-ID: <1149841951.219910.206100@g10g2000cwb.googlegroups.com> Boris Borcic: > > I don't do challenges. > > Pfff... and you don't do real debates either. Different nations have different values and different cultures, in mine challenges are often seen as things for children, and a waste of time for adults (probably in USA challenges are appreciated more). Bye, bearophile From icebear at northpole.gov Sat Jun 24 11:29:01 2006 From: icebear at northpole.gov (icebear) Date: Sat, 24 Jun 2006 15:29:01 GMT Subject: dragging with Boa Constructor References: Message-ID: <1Tcng.1678$il.776@trnddc03> icebear wrote: > There's some non-obvious trick to being able to drag widgets around on a > frame screen using Boa Constructor. I'd appreciate hearing from anybody > who knows what it is. Seeeeem to have figured it out myself here.... the REAL widgets can be dragged, and the ones which can't seem to correspond to base classes which you don't want to be putting on a form anyhow.... Straaaaange...... From onurb at xiludom.gro Fri Jun 9 12:19:03 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 09 Jun 2006 18:19:03 +0200 Subject: regexp questoin In-Reply-To: <1149868825.331142.280180@f6g2000cwb.googlegroups.com> References: <1149868825.331142.280180@f6g2000cwb.googlegroups.com> Message-ID: <44899f78$0$5714$626a54ce@news.free.fr> micklee74 at hotmail.com wrote: > hi > > i created a script to ask user for an input that can be a pattern > right now, i use re to compile that pattern > pat = re.compile(r"%s" %(userinput) ) #userinput is passed from > command line argument > if the user key in a pattern , eg [-] , and my script will search some > lines that contains [-] > > pat.findall(lines) > > but the script produce some error: sre_constants.error: unexpected end > of regular expression If you feed re.compile() something that is not a valid regexp, it will choke. > how can i successful catch patterns such as "[-]" in my regexp > compilation where input is unknown...? If what you want is to validate that the input is a valid regexp, just try to compile it. In your case (cli argument), there's not much you can do if the arg is not a valid regexp, except printing a message to stderr and sys.exit()ing with a non-zero value. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From rgelfand2 at hotmail.com Wed Jun 28 17:17:39 2006 From: rgelfand2 at hotmail.com (Roman) Date: 28 Jun 2006 14:17:39 -0700 Subject: Building Web Site Using Python Message-ID: <1151529459.322632.261870@b68g2000cwa.googlegroups.com> I am new to python. I am looking to read in a 12mb csv file, parse it, generate web pages, summarize on a column and make drop down bottons. Where would I be able to find sample code that does something similar to this? Also, I know that microsoft has put out .net beta version of it. If I am using windows server, I am confined to use iron python? or are there alternatives? Perhaps, there are python web packages that have their own web server engine? Thanks in advance, From eval.apply at gmail.com Fri Jun 23 12:33:01 2006 From: eval.apply at gmail.com (Joe Marshall) Date: 23 Jun 2006 09:33:01 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: <1151028214.668765.182330@p79g2000cwp.googlegroups.com> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <449b07bb$0$11073$9b4e6d93@newsread4.arcor-online.net> <1151028214.668765.182330@p79g2000cwp.googlegroups.com> Message-ID: <1151080381.150026.236440@r2g2000cwb.googlegroups.com> Marshall wrote: > Timo Stamm wrote: > > > > This is actually one of the most interesting threads I have read in a > > long time. If you ignore the evangelism, there is a lot if high-quality > > information and first-hand experience you couldn't find in a dozen books. > > Hear hear! This is an *excellent* thread. The evangelism is at > rock-bottom > and the open exploration of other people's way of thinking is at what > looks to me like an all-time high. What are you, some sort of neo-static pseudo-relational object-disoriented fascist? From kiana.toufighi at utoronto.ca Mon Jun 26 14:49:44 2006 From: kiana.toufighi at utoronto.ca (Kiana Toufighi) Date: Mon, 26 Jun 2006 14:49:44 -0400 Subject: Having problems with reading file in Python CGI Message-ID: <44A02C48.8020400@utoronto.ca> Hi, I have a simple CGI program that allows that user to upload a file. However, since accessing the the value of the uploaded file using the value attribute or the getvalue() method reads the entire file in memory as a string which is not what I want I'm making use of the file module. The problem is that all the my checks including "assert fileStream.file in not None" return true however readline() does not return the next line of the fileStream.file object! What am I doing wrong? Here's my code: Here's my code: caller: dataFile = form['data_file'] fileproc = redrev.FileStreamProcessor() dataLines = fileproc.readStream(dataFile) callee: def readStream(self, fileStream): '''readStream: reads a stream of input returns a list of lines''' # list to hold data lines fileLines = [] # make sure that the stream has been provided try: assert fileStream.file is not None except Exception, e: "No input to process" # use filestream object to get uploaded file's lines one by one if fileStream.file: while 1: line = fileStream.file.readline() if not line: break # process and store the line line.strip() fileLines.append(line) return fileLines Thanks, Kiana From steve at holdenweb.com Thu Jun 29 03:28:43 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 29 Jun 2006 08:28:43 +0100 Subject: Immutability In-Reply-To: References: <4Qj*cEjkr@news.chiark.greenend.org.uk> Message-ID: Georg Brandl wrote: > Nick Maclaren wrote: > >>In article , >>"Fredrik Lundh" writes: >>|> >>|> identical? you only applied @property to one of the methods, and then you're >>|> surprised that only one of the methods were turned into a property? >> >>I wasn't expecting EITHER to be turned INTO a property - I was expecting >>both methods to be the same, but one would have non-default properties >>attached to it. > > > That's another sign that property isn't intended to be used as a decorator. > Normally, decorators wrap functions with other functions. property doesn't > return a function but a descriptor object. > OK, I still think the docs need updating, but to explain the above as the reason *why* property's use as a decorator is not advised. Or is it stylistically and semantically acceptable in the case of a read-only property? Would it make sense, in the single argument case, to default the doc value to fget.__doc__ to support that use case, or should we just not create read-only properties by using property as a decorator? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From scott.daniels at acm.org Mon Jun 26 13:25:18 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Mon, 26 Jun 2006 10:25:18 -0700 Subject: style question In-Reply-To: References: Message-ID: <44a01364@nntp0.pdx.net> Claudio Grondi wrote: <<>> > When necessary to skip first line _and_ indentation: > message = """ > This is line 1 > This is line 2 > This is line 3 > """.replace('\n ', '\n')[1:] # adjust here '\n ' to indentation Riffing on this idea: message = """ This is line 1 This is line 2 This is line 3 """.replace(""" """, '\n')[1:] --Scott David Daniels scott.daniels at acm.org From ole.nielsby at snailmail.dk Tue Jun 27 17:00:01 2006 From: ole.nielsby at snailmail.dk (Ole Nielsby) Date: Tue, 27 Jun 2006 23:00:01 +0200 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150998222.352746.65520@i40g2000cwc.googlegroups.com> <1151026856.064429.36460@c74g2000cwc.googlegroups.com> <1151079774.429512.68840@c74g2000cwc.googlegroups.com> <1151098655.828408.286630@y41g2000cwy.googlegroups.com> Message-ID: <44a19c52$0$15784$14726298@news.sunsite.dk> David Hopwood <...nospam....uk> wrote: > A good debugger is invaluable regardless of your attitude > to type systems. I found that certain language features help greatly in pinning the errors, when programming in my own impure fp language (PILS). Originally, I implemented a single-stepping debugger for the language, but I trashed it for three reasons, of which two are rather uninteresting here: it messed up the GUI system, and the evaluation order of PILS made single-stepping a confusing experience. The interesting reason is: I didn't need single-stepping, partly because the programming system is unit-test friendly, partly because of language features that seem to mimick the concept of taking responsibility. Basically, the PILS execution mechanism is pessimistic. When a function is called, the assumption is it won't work, and the only way the function can return a result is by throwing an exception. So, if a function call doesn't throw an exception, it has failed and execution will stop unless the function call is explicitly marked as fault tolerant, as in f (x) else "undefined" This has been merged with tail call flattening - rather than throwing the result, an (expression, binding) thing is thrown (I guess .NET'ers would call it an anonymous parameterless delegate), and the expression is then evaluated after the throw. Mimickally speaking, when a function body performs this throw, it takes responsibility for getting the job done, and if it fails, it will suffer the peril of having its guts exposed in public by the error message window - much like certain medieval penal systems. I will spare you for the gory details, just let me add that to honor the demands of modern bureaucracy, I added a "try the other office" feature so that there are ways of getting things done without ever taking responsibility. Strangely, this all started 20 years ago as I struggled implementing an early PILS version on an 8-bit Z80 processor, at a blazing 4 MHz. I needed a fast way of escaping from a failing pattern match, and it turned out the conditional return operation of this particular processor was the fastest I could get. Somehow, the concept of "if it returns, it's bad" crept into the language design. I was puzzled by its expressiveness and the ease of using it, only years later did I realize that its ease of use came from the mimicking of responsibility. I'm still puzzled that the notion of mimicking a cultural/ social concept came from a microprocessor instruction. It seems like I - and perhaps computer language designers in general - have a blind spot. We dig physical objects and mathematical theories, and don't take hints from the "soft sciences"... Perhaps I'm over-generalizing, it just strikes me that the dispute always seems to stand between math versus object orientation, with seemingly no systematic attempts at utilizing insigts from the study of languages and cultural concepts. It's like as if COBOL and VB scared us from ever considering the prospect of making programming languages readable to the uninitiated. From tdelaney at avaya.com Mon Jun 26 18:12:38 2006 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Tue, 27 Jun 2006 08:12:38 +1000 Subject: queue deadlock possibility Message-ID: <2773CAC687FD5F4689F526998C7E4E5FF1E79A@au3010avexu1.global.avaya.com> Michael Bayer wrote: > i was just going through this thread: http://mail.python.org/ > pipermail/python-list/2006-April/336948.html , where it is suggested > that the Lock instance used by Queue.Queue should be publically > configurable. I have identified another situation where a Queue can > be deadlocked, one which is also alleviated by configuring the type > of Lock used by the Queue (or just changing it to an RLock). > > The scenario arises when the Queue is operated upon within the > __del__ method of an object; since __del__ can be called at somewhat > unpredictable times, I have observed that it is in fact possible, in > extremely rare circumstances, for put() to be called within a get() > or possibly vice versa; since both methods lock on the same > underlying mutex object which is an instance of threading.Lock, a > deadlock occurs. > > The issue can be fixed by substituting a threading.RLock for the > threading.Lock object that Queue instantiates by default. Please a patch on SourceForge, and send an email to python-dev to alert people of this issue (SourceForge isn't sending notification emails). Tim Delaney From sekhon.hari at googlemail.com Tue Jun 27 08:45:38 2006 From: sekhon.hari at googlemail.com (Hari Sekhon) Date: Tue, 27 Jun 2006 13:45:38 +0100 Subject: how to do -vv for very verbose? Message-ID: <44A12872.9030104@gmail.com> I'm using optparse.Optionparser to take switches for a script I'm writing, but I can't see how to give it -vv for very verbose. the option for -v is simply set to True by the option parser if present, whereas I really want a numeric value, 1 if there is -v and 2 if there is -vv. Any ideas on how to do this? I think I'll have to stop using action="store_true". -h From ldo at geek-central.gen.new_zealand Thu Jun 22 04:52:50 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 22 Jun 2006 20:52:50 +1200 Subject: Cycles between package imports References: <1150633514.024828.95330@g10g2000cwb.googlegroups.com> Message-ID: In article , "Martin Blais" wrote: >On 18 Jun 2006 05:25:14 -0700, John Roth wrote: > >> The general rule is: don't do that. It doesn't work, and the >> hoops you have to go through to force it to work are so >> complex and bizzare that they're not worth it. Redesign >> the modules so you don't have cyclic dependencies. > >This is a matter completely aside the question. No it isn't. I agree with John Roth. >Whether it's worth it >or not depends on the specific case --not included in the example-- >and in the case where it shows up in my code, removing the cycle >actually made sense (it does, most of the time, but not always). See, even you are unable to come up with an example where a cyclic import makes sense. In general, the complications they introduce are simply not worth it. This was discovered decades ago, during the development of languages like Ada and Modula-2 which could do automatic initialization and finalization of library modules arranged by the compiler/linker system. From wahab at chemie.uni-halle.de Sat Jun 17 17:16:10 2006 From: wahab at chemie.uni-halle.de (Mirco Wahab) Date: Sat, 17 Jun 2006 23:16:10 +0200 Subject: Python is fun (useless social thread) ;-) In-Reply-To: References: <1150573961.441575.270110@r2g2000cwb.googlegroups.com> Message-ID: Thus spoke Sybren Stuvel (on 2006-06-17 22:01): > Rune Strand enlightened us with: >> But back on university, I met a very, very pretty C++ girl who said >> many favourable things about Python. > > Rrrrrr a very, very pretty girl that likes C++ and Python. > Does it get better? It does: http://www.cafepress.com/buy/python/-/pv_design_prod/p_stickem.23651835/pNo_23651835/id_7539588/ Regards Mirco From maric at aristote.info Fri Jun 9 04:33:51 2006 From: maric at aristote.info (Maric Michaud) Date: Fri, 9 Jun 2006 10:33:51 +0200 Subject: Importing again and again In-Reply-To: <1149796920.757115.290840@h76g2000cwa.googlegroups.com> References: <1149796920.757115.290840@h76g2000cwa.googlegroups.com> Message-ID: <200606091033.52699.maric@aristote.info> Le Jeudi 08 Juin 2006 22:02, abcd a ?crit?: > > def foo(): > import bar > bar.printStuff() > > foo() > foo() > foo() > foo() > > ...will that re-import bar 4 times...or just import it once? is this a > big performance hit? Import a module more than once doesn't execute the code of this module more than once. I don't know what's your need but as some have spoke of reload I just want to warn you, reload a module means that you want invalidate the code of this and replace it by a new one, this is not like a normal but deeper import. Also, you'll have to deal yourself wiith references to your old code. Hmmm, the following example should be clear than my explanations :) n [1]: import temp In [2]: class a(temp.Base temp.Base In [2]: class a(temp.Base temp.Base In [2]: class a(temp.Base temp.Base In [2]: class a(temp.Base) : pass ...: In [3]: reload(temp) Out[3]: In [4]: class b(temp.Base) : pass ...: In [7]: b.__base__, a.__base__, b.__base__ is a.__base__ Out[7]: (, , False) In [8]: isinstance(a(), temp.Base), isinstance(b(), temp.Base) Out[8]: (False, True) -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From webraviteja at gmail.com Tue Jun 13 16:30:29 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 13 Jun 2006 13:30:29 -0700 Subject: Combining The Best Of Python, Ruby, & Java?????? In-Reply-To: <1150222373.368622.121050@h76g2000cwa.googlegroups.com> References: <1150181049.815883.138580@c74g2000cwc.googlegroups.com> <4f7todF1har97U1@uni-berlin.de> <1150222373.368622.121050@h76g2000cwa.googlegroups.com> Message-ID: <1150230629.136320.45210@u72g2000cwu.googlegroups.com> Luis M. Gonz?lez wrote: > Diez B. Roggisch wrote: > > > But semantically it is a proper functional language. The features may > > > not attract Python users who might prefer Boo/Jython/IronPython. But it > > > does offer something to disillusioned Groovy users. > > > > Are they disillusioned? Just wondering. > > > > Diez > > Whay talking about disillutioned programmers? > These are tools, not religions... > I love python, and I like it more everyday. And with the advent of > Pypy, its future looks brighter than ever. > But I also find very interesting these new options that are coming up. > Although I'm not a professional programmer (not even a serious > aficionado), I love to be able to translate my python skills very > easily to .NET through Boo, for example. > I even find it more appealing than Ironpython, because it was created > from the ground up to take advantage of the CLR. > On the other hand, porting pure python to .NET is in many aspects like > trying to fit a square on a circle (I don't know if this sentence makes > sense in english...). > Because many of the design choices taken by GvR back in the early > nineties were surely conditioned by the platform he chose to write > python, which is the c language. > The good thing is that python is having a lot of influence in these new > languages. > As far as I could see, even C# 3.0 is showing up some pythonic traits. I did not realize the flame potential of that remark. Just to clarify, I have no criticism of any kind on Groovy. I mentioned Groovy since Scala, the original topic of the thread addresses the needs of the same group (a modern language with a Java friendly syntax). I am not a language bigot. Note that I am defending Scala, a new language, in this thread so far. I do not want this thread to break into a language war from my remark. I hope that Python gets some of the features listed in my above post in it's own unique Pythonic way eventually. The discussion perhaps is more constructive if we can see some good in Scala that is worth adopting. From sjmachin at lexicon.net Wed Jun 7 17:17:45 2006 From: sjmachin at lexicon.net (John Machin) Date: Thu, 08 Jun 2006 07:17:45 +1000 Subject: Convert Date to Short formate In-Reply-To: <1149709855.899702.89100@c74g2000cwc.googlegroups.com> References: <1149709855.899702.89100@c74g2000cwc.googlegroups.com> Message-ID: <44874279$1@news.eftel.com> On 8/06/2006 5:50 AM, aqmaiya wrote: > Hello, > there is string value 'Dec 06, 2000' I want to convert that string > date to SHORT FORMAT like '2000-12-06-. Please help me how do I do > that? I'm new in Jython. > Thanks, > aqmaiya > Two ways (at least): (1) check out the strptime and strftime (p == parse, f == format) functions in the time module In general, the datetime module is much to be preferred for working with dates and times -- unless of course you need to mimic functions from the C time.h library -- however the datetime module won't be getting a strptime until version 2.5, which is still in alpha test. (2) As you are new to Python, you might like to try your skills with basic parts from the Python toolkit, like dictionaries and slicing, and write a function yourself, specialised to that particular format. Here are some hints: # example Dec 06, 2000 # ruler 0123456789012 mpart = data[0:3] # similarly: dpart, ypart month_dict = {'jan': 1, ....., 'dec': 12} month_num = month_dict[mpart.lower()] # will work with Dec, dec, DEC result = '%s-%02d-%s' % (ypart, month_num, dpart) How much validation you do is up to you :-) HTH, John From maric at aristote.info Mon Jun 12 04:41:01 2006 From: maric at aristote.info (Maric Michaud) Date: Mon, 12 Jun 2006 10:41:01 +0200 Subject: Function to remove elements from a list not working (corrected) In-Reply-To: <49543.10.209.4.1.1150100717.squirrel@10.105.1.3> References: <49543.10.209.4.1.1150100717.squirrel@10.105.1.3> Message-ID: <200606121041.01792.maric@aristote.info> Le Lundi 12 Juin 2006 10:25, Girish Sahani a ?crit?: > Hi, > I am trying to modify a list of pairs (l4) by removing those > pairs which are not present in a third list called pairList. > The following is a simplified part of the routine i have written. However > it does not give the correct output. Please help! > Its possible i have made a trivial mistke since i am a newbie. > > def getl5(): > l5 = [] > pairList = [[1,2],[3,4],[3,5],[3,6],[9,7],[8,9],[8,7],[7,9],[11,10]] > l4 = > [[4,2],[4,7],[4,10],[4,12],[9,2],[9,7],[9,10],[9,12],[11,2],[11,7]] for > pair in l4: > if pair not in pairList: > l4.remove(pair) > print "l4 is",l4 > You are trying to modify a list while iterating over it, never do that ! > The output given is: > l4 is [[4, 7], [4, 12], [9, 7], [9, 12], [11, 7]] Is this work in your case ? def getl5(): pairList = [[1,2],[3,4],[3,5],[3,6],[9,7],[8,9],[8,7],[7,9],[11,10]] l4 = [[4,2],[4,7],[4,10],[4,12],[9,2],[9,7],[9,10],[9,12],[11,2],[11,7]] l4 = [ e for e in l4 if e in pairList ] print "l5 is", l4 -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From jo at durchholz.org Wed Jun 28 05:39:16 2006 From: jo at durchholz.org (Joachim Durchholz) Date: Wed, 28 Jun 2006 11:39:16 +0200 Subject: languages with full unicode support In-Reply-To: References: <1151251736.590910.36050@u72g2000cwu.googlegroups.com> Message-ID: Tim Roberts schrieb: > "Xah Lee" wrote: >> C ? No. > > This is implementation-defined in C. A compiler is allowed to accept > variable names with alphabetic Unicode characters outside of ASCII. Hmm... that could would be nonportable, so C support for Unicode is half-baked at best. Regards, Jo From grante at visi.com Fri Jun 23 14:08:10 2006 From: grante at visi.com (Grant Edwards) Date: Fri, 23 Jun 2006 18:08:10 -0000 Subject: Network Programming in Python References: <1151002934.586359.174540@m73g2000cwd.googlegroups.com> <1151067757.353199.238420@g10g2000cwb.googlegroups.com> <129o2p1l3149579@corp.supernews.com> Message-ID: <129obgarkdma51a@corp.supernews.com> On 2006-06-23, Cameron Laird wrote: > In article <129o2p1l3149579 at corp.supernews.com>, > Grant Edwards wrote: >>On 2006-06-23, diffuser78 at gmail.com wrote: >> >>> How will Pyon help my cause ? >> >>What's Pyon? > . > . > . > A misreading of "Pyro". Pyro , > of course, is yet another communications layer, but, as was suggested, > one that might particularly suit Mr. Johnson. Ah! I think I've always mixed up pyrex and pyro and psco, and never actually new what Pyro really was. I've got it straight now (how long I'll keep the three of them striaght in my head is another question). -- Grant Edwards grante Yow! BARBARA STANWYCK at makes me nervous!! visi.com From paddy3118 at netscape.net Thu Jun 1 18:59:40 2006 From: paddy3118 at netscape.net (Paddy) Date: 1 Jun 2006 15:59:40 -0700 Subject: grouping a flat list of number by range In-Reply-To: <127urvnrbvjgr07@corp.supernews.com> References: <1149196642.001466.53990@c74g2000cwc.googlegroups.com> <1149201416.196975.123370@c74g2000cwc.googlegroups.com> <127urvnrbvjgr07@corp.supernews.com> Message-ID: <1149202780.780252.242110@f6g2000cwb.googlegroups.com> Jim Segrave wrote: > In article <1149201416.196975.123370 at c74g2000cwc.googlegroups.com>, > Paddy wrote: > >=== interv2 === > >>>> def interv2(inlist): > >... for i,val in enumerate(inlist): > >... if i==0: > >... tmp = val > >... elif val != valinc: > >... yield [tmp, valinc] > >... tmp = val > >... valinc = val+1 > >... yield [tmp, valinc] > >... > >>>> list(interv2(inlist)) > >[[3, 4], [6, 9], [12, 14], [15, 16]] > > > >=== END interv2 === > > This doesn't actually run, changing it to make it do so: > > def interv2(inlist): > tmp = valinc = 0 > for i,val in enumerate(inlist): > if i==0: > tmp = val > valinc = val + 1 > elif val != valinc: > yield [tmp, valinc] > tmp = val > valinc = val+1 > yield [tmp, valinc] > > it now works, but returns [0, 0] when passed an empty list, when it > should return nothing at all > -- > Jim Segrave (jes at jes-2.demon.nl) Jim, I had tabs/spaces indent problems when cut-n-pasting. What I ran was more like the version below, but i did a quick separation of the line that has the ';' in it and goofed. >>> def interv2(inlist): ... for i,val in enumerate(inlist): ... if i==0: ... tmp = val ... elif val != valinc: ... yield [tmp, valinc]; tmp = val ... valinc = val+1 ... yield [tmp, valinc] ... >>> list(interv2(inlist)) [[3, 4], [6, 9], [12, 14], [15, 16]] From kkylheku at gmail.com Sun Jun 4 04:13:44 2006 From: kkylheku at gmail.com (Kaz Kylheku) Date: 4 Jun 2006 01:13:44 -0700 Subject: Python less error-prone than Java In-Reply-To: References: Message-ID: <1149408824.174844.178010@u72g2000cwu.googlegroups.com> Ilpo Nyyss?nen wrote: > This is one big thing that makes code > less error-prone: using existing well made libraries. > You can find binary search from python standard library too (but actually the API > in Java is a bit better, see the return values). > Well, you can say that the binary search is a good example and in real > code you would use the stuff from the libraries. The trouble with your point is that Christoph's original posting refers to an article, which, in turn, at the bottom, refers to a bug database which shows that the very same defect had been found in Sun's Java library! Buggy library code is what prompted that article. > I'd say it is not > good example: How often will you write such algorithms? Very rarely. > > Integer overflows generally are not those errors you run into in > programs. Except when you feed those programs inputs which are converted to integers which are then fed as domain values into some operation that doesn't fit into the range type. Other than that, you are okay! Like when would that happen, right? > The errors happening most often are from my point of view: > > 1. null pointer errors > 2. wrong type (class cast in Java, some weird missing attribute in python) > 3. array/list index out of bounds > > First and third ones are the same in about every language. ... other than C and C++, where their equivalents just crash or stomp over memory, but never mind; who uses those? ;) > The second > one is one where the typing can make a difference. Actually, the first one is also where typing can make a difference. Instead of this stupid idea of pointers or references having a null value, you can make a null value which has its own type, and banish null pointers. So null pointer errors are transformed into type errors: the special value NIL was fed into an operation where some other type was expected. And by means of type polymorphism, an operation can be extended to handle the case of NIL. From peter.maas at somewhere.com Fri Jun 30 16:18:15 2006 From: peter.maas at somewhere.com (Peter Maas) Date: Fri, 30 Jun 2006 22:18:15 +0200 Subject: Import bug: Module executed twice when imported! In-Reply-To: References: Message-ID: Michael Abbott wrote: > In article , > Michael Abbott wrote: > >> --- test.py --- >> import imptest >> execfile('subtest.py', dict(__name__ = 'subtest.py')) >> --- imptest.py --- >> print 'Imptest imported' >> --- subtest.py --- >> import imptest >> --- >> >> $ python test.py >> Imptest imported >> Imptest imported >> $ > > I claim this as an unreported (and highly obscure) Python bug. The docs tell us (http://www.python.org/doc/2.4.2/lib/built-in-funcs.html): ------------------------- begin ------------------------------- execfile(filename[, globals[, locals]]) This function is similar to the exec statement, but parses a file instead of a string. It is different from the import statement in that it does not use the module administration -- it reads the file unconditionally and does not create a new module. ------------------------- end --------------------------------- I claim this as a well documented (and thus exspectable) Python behaviour. execfile() just executes a file unconditionally without searching in sys.modules. That's its purpose, otherwise it would be a synonym of the import statement. Peter Maas, Aachen From cdsmith at twu.net Sun Jun 25 12:32:59 2006 From: cdsmith at twu.net (Chris Smith) Date: Sun, 25 Jun 2006 10:32:59 -0600 Subject: What is Expressiveness in a Computer Language References: <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <0%Wlg.3521$MF6.947@tornado.socal.rr.com> <44992e6c$0$664$bed64819@news.gradwell.net> <1151010139.960608.122470@b68g2000cwa.googlegroups.com> Message-ID: Joachim Durchholz wrote: > Sorry, I have to insist that it's not me who's stretching terms here. > > All textbook definitions that I have seen define a type as the > set/operations/axioms triple I mentioned above. > No mention of immutability, at least not in the definitions. The immutability comes from the fact (perhaps implicit in these textbooks, or perhaps they are not really texts on formal type theory) that types are assigned to expressions, and the program is not likely to change as it executes. Even such oddities as "self-modifying code" are generally formally modeled as a single program, which reduces to other programs as it evaluates just like everything else. The original program doesn't change in the formal model. Hence the common (and, I think, meaningless) distinction that has been made here: that static type systems assign types to expressions (sometimes I hear variables, which is limiting and not really correct), while dynamic type systems do so to values. However, that falls apart when you understand what formal type systems mean by types. What they mean, roughly, is "that label which we attach to an expressions according to fixed rules to help facilitate our proofs". Since dynamic type systems don't do such proofs, I'm having trouble understanding what could possibly be meant by assigning types to values, unless we redefine type. That's what I've been trying to do. So far I've had only limited success, although there is definite potential in one post by Chris Uppal and another by Chris Clark (or maybe I'm just partial to other people named Chris). -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation From robert.thorpe at antenova.com Wed Jun 21 05:50:42 2006 From: robert.thorpe at antenova.com (Rob Thorpe) Date: 21 Jun 2006 02:50:42 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <7zpshbsvjy.fsf@app-1.diku.dk><4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <1150809118.677124.142230@u72g2000cwu.googlegroups.com> <1150815461.210286.53120@r2g2000cwb.googlegroups.com> <1150822150.701434.296460@u72g2000cwu.googlegroups.com> Message-ID: <1150883442.498308.226730@b68g2000cwa.googlegroups.com> Matthias Blume wrote: > "Rob Thorpe" writes: > > > I think we're discussing this at cross-purposes. In a language like C > > or another statically typed language there is no information passed > > with values indicating their type. > > You seem to be confusing "does not have a type" with "no type > information is passed at runtime". > > > Have a look in a C compiler if you don't believe me. > > Believe me, I have. In a C compiler the compiler has no idea what the values are in the program. It knows only their type in that it knows the type of the variable they are contained within. Would you agree with that? > > No it doesn't. Casting reinterprets a value of one type as a value of > > another type. > > There is a difference. If I cast an unsigned integer 2000000000 to a > > signed integer in C on the machine I'm using then the result I will get > > will not make any sense. > > Which result are you getting? What does it mean to "make sense"? Well the right one actually, bad example. But, if I cast an unsigned int 2500000000 to signed I get -1794967296. From trentm at activestate.com Mon Jun 19 15:58:15 2006 From: trentm at activestate.com (Trent Mick) Date: Mon, 19 Jun 2006 12:58:15 -0700 Subject: Using Komodo 3.5 - Setting breakpoints in multiple *.py files In-Reply-To: <1149611297.071477.32300@j55g2000cwa.googlegroups.com> References: <1149611297.071477.32300@j55g2000cwa.googlegroups.com> Message-ID: <449701D7.90401@activestate.com> jeem wrote: > I am using ActiveState Komodo 3.5 to work on a large python 2.4 > application with an extensive UI... I am attempting to debug the > application and am setting breakpoints in 4 different *.py files.. > Breakpoints in the main file are working OK, but any breakpoints in > imported files are not... The three imported files are open in Komodo > and are in the same local directory as the main file (in the > python24/Lib/site-packages tree)... The code sections I am trying to > debug are invoked by some UI events... When I start the debugging > section and navigate to the features I am trying to debug, the > breakpoint are ignored... I can execute a "Break now" command and the > IDE is smart enough to find and display imported *.py resources... but > normal breakpoints are ignored... It works for me in a trivial example: C:\trentm\tmp\foo>cat foo.py print "hi from foo" import bar bar.bar() print "bye from foo" C:\trentm\tmp\foo>cat bar.py def bar(): print "hi from bar.bar()" print "bye from bar.bar()" I set breakpoints on the "import bar" line in foo.py and on the 'print "hi...' line in "bar.py". Started debugging "foo.py" and the debugger breaks on both breakpoints. If you step into the "import" statements in your debug session, are the imported modules the ones you expect? I.e. in my example the breakpoint would not have worked if "bar.py" had been imported from another location on my sys.path. Note: this might be better discussed on the komodo-discuss mailing list. (http://listserv.activestate.com/mailman/mysubs) Cheers, Trent -- Trent Mick trentm at activestate.com From onurb at xiludom.gro Fri Jun 9 12:26:29 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 09 Jun 2006 18:26:29 +0200 Subject: Error in Chain of Function calls (Code Attached) In-Reply-To: References: <448930f1$0$10302$636a55ce@news.free.fr> Message-ID: <4489a136$0$16558$636a55ce@news.free.fr> Girish Sahani wrote: >>Girish Sahani wrote: >> (snip) >>>Before the >>>main function, i have defined the other functions such as >>>genColocations,genTableInstances,etc. Output of genColocations is to be >>>given to the next function genTableInstances,output of this function to >>>tiCount and findPI, and so on. >>>However i am getting an error at the line marked with ***. >> >>Which error ? How do you hope us to be of any help here if you don't *at >>least* provide the full traceback ? FWIW, the canonical way to do things >>is to: >>- provide minimal *runnable* code exposing the problem >>- explain what you hoped to get >>- explain what you got instead (including full traceback) >> >>As a matter of fact, it's often the case that one solves the problem >>when working on the first point !-) >> >>(snip) > > Ohh...I was thinking that posting the whole code would not be a good idea. It's *not* a good idea - unless the code is *very* short and has no dependencies on anything else than the stdlib. Please re-read *carefully* the first point : - provide minimal *runnable* code exposing the problem and notice the use of the word "minimal". I *never* suggested that you post the *whole* code. > The error i get above is: > line 266, in colocationMiner > prunedNew = genColocations(prunedK) This is *not* the error. It's a line number (which is totally useless if you don't have the corresponding file). Please re-read what I wrote about posting *the full traceback*. Tracebacks are not here to be beautiful on your screen, there here to give you as much possible informations about what went wrong. > Anyways, i've attached the file colocations.py. Don't attach files. Reduce your code to the *minimal* *runnable* code snippet reproducing the problem. (snip a few hundred lines of code I won't certainly take time to read unless I'm being paid for fixing 'em) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From felipe.lessa at gmail.com Sun Jun 11 14:52:55 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Sun, 11 Jun 2006 15:52:55 -0300 Subject: math.pow(x,y) In-Reply-To: <1150049976.916474.186580@j55g2000cwa.googlegroups.com> References: <1150049976.916474.186580@j55g2000cwa.googlegroups.com> Message-ID: <1150051975.13193.0.camel@kenshin.CASA> Em Dom, 2006-06-11 ?s 11:19 -0700, fl1p-fl0p escreveu: > import math > math.pow(34564323, 456356) > > will give math range error. > > how can i force python to process huge integers without math range > error? Any modules i can use possibly? 34564323**456356 ? -- Felipe. From tjreedy at udel.edu Mon Jun 5 14:48:23 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 5 Jun 2006 14:48:23 -0400 Subject: [twisted] PyOpenSSL and PyCrypto are outdated! References: <1149524697.220261.73510@c74g2000cwc.googlegroups.com> Message-ID: "Mike Meng" wrote in message news:1149524697.220261.73510 at c74g2000cwc.googlegroups.com... > I'm learning Twisted and downloaded pyOpenSSL and pycrypto win32 > installer on http://twisted.sourceforge.net/contrib/ . But I find the > lastest version are for Python 2.3. I try to rebuild pyOpenSSL from > source, but get lots of compile errors. Are these two packages > obsolated? Where can I find updated version? Did you try Google? This question has been asked before. From jmcmonagle at velseis.com.au Tue Jun 6 19:36:23 2006 From: jmcmonagle at velseis.com.au (John McMonagle) Date: Wed, 07 Jun 2006 09:36:23 +1000 Subject: tkinter: making widgets instance or not? In-Reply-To: <1149636457.26711.41.camel@kuepper.vels-int.com.au> References: <1149636457.26711.41.camel@kuepper.vels-int.com.au> Message-ID: <1149636983.26711.42.camel@kuepper.vels-int.com.au> On Wed, 2006-06-07 at 09:27 +1000, John McMonagle wrote: > On Tue, 2006-06-06 at 19:42 +0000, John Salerno wrote: > > Fredrik Lundh wrote: > > > > > however, if you need to access a widget later on, it might be a good > > > idea to save a reference to it somewhere... > > > > To follow up on that point, I have the following code now. I have two > > questions about it: > > > > 1. Can I somehow make the passing of 'master' to the draw_entry method > > automatic, so I don't have to type it each time I call the function? > > > > 2. Related to your comment, the obvious problem here is that it doesn't > > save references to the text box names, so I can't access them later. Is > > there still a way to automate the process like I've done, but have each > > entry field have a separate name? > > > > Thanks. > > > > --------------- > > > > import Tkinter as tk > > > > > > class App: > > > > def __init__(self, master): > > self.draw_entry(master, 'First Name:') > > self.draw_entry(master, 'Last Name:') > > > > def draw_entry(self, master, label_text): > > frame = tk.Frame(master, bd=4) > > frame.pack() > > self.label = tk.Label(frame, text=label_text, width=10) > > self.label.pack(side=tk.LEFT) > > self.entry = tk.Entry(frame) > > self.entry.pack(side=tk.LEFT) > > > > > > root = tk.Tk() > > app = App(root) > > root.resizable(width=False, height=False) > > root.mainloop() > > -- > > > Try this: > > import Tkinter as tk > > class App: > > def __init__(self, master): > self.parent = master > self.entry1 = self.draw_entry('First Name:') > self.entry2 = self.draw_entry('Last Name:') > > def draw_entry(self, label_text): > frame = tk.Frame(self,parent, bd=4) Sorry - typo. Should reas self.parent not self,parent > frame.pack() > label = tk.Label(frame, text=label_text, width=10) > label.pack(side=tk.LEFT) > entry = tk.Entry(frame) > entry.pack(side=tk.LEFT) > return entry > > root = tk.Tk() > app = App(root) > root.resizable(width=False, height=False) > root.mainloop() > > > > -- > This message has been scanned for viruses and > dangerous content by MailScanner, and is > believed to be clean. > -- This message has been scanned for viruses and dangerous content by MailScanner, and is believed to be clean. From jimburton1 at gmail.com Thu Jun 15 06:08:12 2006 From: jimburton1 at gmail.com (jimburton) Date: 15 Jun 2006 03:08:12 -0700 Subject: distutils `requires' tag Message-ID: <1150366092.188588.57940@g10g2000cwb.googlegroups.com> Hi, I'm using python 2.3.5 and want to use distutils to distribute a module that depends on another - is there any way to specify that? Something like: setup(name='aimspy', ... requires = { 'jpype': '*'}, ) Thanks From cdsmith at twu.net Wed Jun 21 21:55:54 2006 From: cdsmith at twu.net (Chris Smith) Date: Wed, 21 Jun 2006 19:55:54 -0600 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150902275.129780.50260@p79g2000cwp.googlegroups.com> <1150918629.818145.143220@y41g2000cwy.googlegroups.com> Message-ID: Marshall wrote: > Well, it strikes me that some of what the dynamic camp likes > is the actual *absence* of declared types, or the necessity > of having them. At the very least, requiring types vs. not requiring > types is mutually exclusive. So you're saying, then, that while static typing and dynamic typing are not themselves mutually exclusive, there are people whose concerns run as much in the "not statically typed" direction as in the "dynamically typed" direction? I agree that this is undoubtedly true. That (not statically typed) seems to be what gets all the attention, as a matter of fact. Most programmers in modern languages assume, though, that there will be some kind of safeguard against writing bad code with unpredictable consequences, so in practice "not statically typed" correlates strongly with "dynamically typed". Nevertheless, the existence of languages that are clearly "both" suggests that they should be considered separately to at least some extent. -- Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation From fredrik at pythonware.com Tue Jun 6 05:28:51 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 06 Jun 2006 11:28:51 +0200 Subject: Checking var is a number? In-Reply-To: <1149583700.145737.170720@j55g2000cwa.googlegroups.com> References: <1149583700.145737.170720@j55g2000cwa.googlegroups.com> Message-ID: dav.phillips at ntlworld.com wrote: > I am very new to all this and need to know how to check > a variable to see if it is a number or not. assuming that "variable" means "string object" and "number" means "integer", you can use the isdigit predicate: if var.isdigit(): print "all characters in", var, "are digits" if you want to check for anything that can be converted to a float, the best way is to do the conversion and trap any ValueError that may occur: try: value = float(var) except ValueError: print "not a valid float" if you want an integer instead, replace "float" with "int". if you had something else in mind, let us know. > Also can anyone recommend a reference book apart from dive into python > preferably a reference with good examples of how to impliment code. you can find an extensive list of available books here: http://wiki.python.org/moin/PythonBooks some on-line code collections: http://aspn.activestate.com/ASPN/Python/Cookbook/ http://effbot.org/zone/librarybook-index.htm and don't forget the core references: http://docs.python.org/lib/ http://docs.python.org/ref/ From max at alcyone.com Sun Jun 11 03:11:01 2006 From: max at alcyone.com (Erik Max Francis) Date: Sun, 11 Jun 2006 00:11:01 -0700 Subject: Xah Lee network abuse In-Reply-To: References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148495974.975395.12920@i40g2000cwc.googlegroups.com> <1149998343.493200.144990@h76g2000cwa.googlegroups.com> Message-ID: EJP wrote: > Many states have criminal as well as civil libel. > http://en.wikipedia.org/wiki/Slander_and_libel The idea of using Wikipedia to back up a legal point is rather amusing ... but still, none of the relevant parties involved live in countries which have any form of criminal libel. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis To perceive is to suffer. -- Aristotle From grante at visi.com Wed Jun 14 12:17:52 2006 From: grante at visi.com (Grant Edwards) Date: Wed, 14 Jun 2006 16:17:52 -0000 Subject: Numerics, NaNs, IEEE 754 and C99 References: <12904mjhl493t49@corp.supernews.com> <1290aik50hmk94a@corp.supernews.com> <4490329e$0$12356$636a55ce@news.free.fr> Message-ID: <1290dlgfqnf79ca@corp.supernews.com> On 2006-06-14, Christophe wrote: > Grant Edwards a ?crit : >> The division by zero trap is really annoying. In my world the >> right thing to do is to return Inf. > > Your world is flawed then, this is a big mistake. NaN is the > only aceptable return value for a division by zero. You're probably right if you're talking about math, but I'm not doing math. I'm doing engineering. In all of the situations I've ever encountered, Inf was a much better choice. Aside from Python, every FP library or processor I've ever used returned Inf for divide by zero (which is the behavior required by IEEE 754). I need my Python programs to work the same way as everything else. http://standards.ieee.org/reading/ieee/interp/754-1985.html In IEEE Std 754-1985, subclause 7.2- Division by Zero, it says: "If the divisor is zero and the dividend is a finite nonzero number, then the division by zero shall be signaled. The result, when no trap occurs, shall be a correctly signed (infinity symbol)(6.3)." While this is apparently the convention decided on by the committee, it is mathematically incorrect and it seems as if it should have been designated as Not-a-Number, since division by zero is mathematically undefined and implies that 0*infinity=1, which is patently absurd. Why was this convention chosen instead of NaN, since it leads to a further degradation of our children's math abilities, given that the IEEE floating-point standard would be considered to be authoritative on this subject, yet produces an erroneous results. Interpretation for IEEE Std 754-1985 When a non-zero number is divided by a zero number, that is a divide by zero. It is interpreted as an attempt to take a limit of the ratio of two numbers as the denominator becomes too small to be represented in the number system while the numerator remains representable. Such a limit is best represented by an infinity of the appropriate sign. When zero is divided by zero, no such extrapolation can be made. If it is caused by an attempt to take the limit of the ratio of two numbers when both become two small to be represented, then the limit cannot be determined. If it is caused by some mistake in the programming, then no limit exists. Thus, this case is thought to be invalid and a NaN of appropriate sign is returned. (The sign is the only bit of information that can be determined.) While counter examples to the mathematical interpretation of both of these results can be constructed they tend to be either the result of extreme scaling or an attempt to evaluate a non-analytic function. The former can be resolved by rescaling. But, as the latter involve functions that cannot (formally) be evaluated on a computer (without extreme effort anyway) in the region of their non-analyticity, usually no good solution exists. -- Grant Edwards grante Yow! I represent a at sardine!! visi.com From tactics40 at gmail.com Mon Jun 26 13:49:37 2006 From: tactics40 at gmail.com (tac-tics) Date: 26 Jun 2006 10:49:37 -0700 Subject: Freezing Python with jythonc Message-ID: <1151344176.995788.297350@u72g2000cwu.googlegroups.com> I've got a nice jython application that I wish to freeze. After playing around with flag settinsg on jythonc, I managed to get it to compile without warnings or errors, but when I try to run my main class file, I keep getting the error: Exception in "main" thread, NoClassDefFoundError. When I just use "java gui" (gui.class is the bytecode file), it flags an error on org.python.core.PyObject. If add jython.jar to the classpath, it gives me the same error on my gui instead of PyObject. I figured that testing out jythonc on such a large project, I should have expected it to fail. So I wrote a one-liner hello world print "Hello world" saved it to test.py in a different directory, and tried again to jythonc it. However, I keep getting the same errors. What am I doing wrong? From popat2006 at gmail.com Fri Jun 23 00:29:48 2006 From: popat2006 at gmail.com (pythonfreak) Date: 22 Jun 2006 21:29:48 -0700 Subject: Python Position Available Message-ID: <1151036988.430042.201000@p79g2000cwp.googlegroups.com> http://seeker.dice.com/jobsearch/servlet/JobSearch?op=101&dockey=xml/2/d/2df860112e8687e5964d1896a9adde11 at activejobs0&c=1&source=1 From find at my.address.elsewhere Thu Jun 22 12:50:53 2006 From: find at my.address.elsewhere (Matthias Blume) Date: Thu, 22 Jun 2006 11:50:53 -0500 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150902275.129780.50260@p79g2000cwp.googlegroups.com> <1150918629.818145.143220@y41g2000cwy.googlegroups.com> <4fv081F1jh4ifU1@individual.net> <1150967543.947096.72840@g10g2000cwb.googlegroups.com> <4fv84rF1kp06kU1@individual.net> <4fvfuiF1kncqtU1@individual.net> <87ejxh9xoq.fsf@thalassa.informatimago.com> <87ac859m1p.fsf@thalassa.informatimago.com> Message-ID: Pascal Bourguignon writes: > Matthias Blume writes: > >> Pascal Bourguignon writes: >> >>> Moreover, a good proportion of the program and a good number of >>> algorithms don't even need to know the type of the objects they >>> manipulate. >>> >>> For example, sort doesn't need to know what type the objects it sorts >>> are. It only needs to be given a function that is able to compare the >>> objects. >> >> Of course, some statically typed languages handle this sort of thing >> routinely. >> >>> Only a few "primitive" functions need specific types. >> >> Your sort function from above also has a specific type -- a type which >> represents the fact that the objects to be sorted must be acceptable >> input to the comparison function. > > Well, not exactly. What do you mean by "not exactly". > sort is a higher level function. The type of its > arguments is an implicit parameter of the sort function. What do you mean by "higher-level"? Maybe you meant "higher-order" or "polymorphic"? [ rest snipped ] You might want to look up "System F". >>> So basically, you've got a big black box of applicaition code in the >>> middle that doesn't care what type of value they get, and you've got a >>> few input values of a specific type, a few processing functions >>> needing a specific type and returning a specific type, and a few >>> output values that are expected to be of a specific type. At anytime, >>> you may change the type of the input values, and ensure that the >>> needed processing functions will be able to handle this new input >>> type, and the output gets mapped to the expected type. >> >> ...or you type-check your "black box" and make sure that no matter how >> you will ever change the type of the inputs (in accordance with the >> interface type of the box) you get a valid program. > > When? When what? From istvan.albert at gmail.com Thu Jun 15 17:24:22 2006 From: istvan.albert at gmail.com (Istvan Albert) Date: 15 Jun 2006 14:24:22 -0700 Subject: a good programming text editor (not IDE) References: <_xgkg.2317$No6.48542@news.tufts.edu><44919668$1@nntp0.pdx.net> Message-ID: <1150406662.900552.46650@u72g2000cwu.googlegroups.com> Scott David Daniels wrote: > To paraphrase someone else (their identity lost in my mental fog) about > learning VI: > "The two weeks you'll spend hating vi (or vim) as you learn it will > be repaid in another month, ad the rest is pure profit." Time and again I hear this (no shortage of Vim fans, same with Emacs), and I know I should know better but always believe them yet again. Invariably I download Vim play with it for an hour, get increasingly frustrated and give up. Most likely I'm greatly spoiled by using EditPlus (Windows only), it just makes it so easy to do the basic programming tasks that I need, everywhere else I turn I see far more functionality but at the price of not being able to do basic tasks as efficiently as I need them. Say I want to be able to execute the python program I'm currently editing. Nothing simpler in EditPlus, Tools->Configure Tools->Add Tool then specify which program you want to run, what parameters it takes and whether to capture the output or not ... total time it took me first time I wanted to do this ... about 3 minutes ... from now on pressing Ctrl-1 while editing the source will execute the python on the current source *and* it displays the output in a lower pane as it runs *and* it allows me to simultanously edit the file *while* the program is running. Outstanding. Yet after searching and reading stuff for more than an hour I was unable to accomplish the same thing in Vim though I'm already familiar enough with basic editing and setup (through my previous trials and tribulations) ... I have a few solutions that end up doing something similar but are quite a few keypresses longer both to invoke or to get back to the source that I'm writing, or I lose editing control while the program is running ... etc... So if the OP is on windows just head over and get EditPlus (UltraEdit and TextPad seem to be similar), and just accept the fact that you are already using an editor that as good as an editor can get ... I know I'd pay that registration once again for an editor that works the same way on Linux... i. From pjb at informatimago.com Thu Jun 22 12:45:22 2006 From: pjb at informatimago.com (Pascal Bourguignon) Date: Thu, 22 Jun 2006 18:45:22 +0200 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150902275.129780.50260@p79g2000cwp.googlegroups.com> <1150918629.818145.143220@y41g2000cwy.googlegroups.com> <4fv081F1jh4ifU1@individual.net> <1150967543.947096.72840@g10g2000cwb.googlegroups.com> <4fv84rF1kp06kU1@individual.net> <4fvfuiF1kncqtU1@individual.net> <87ejxh9xoq.fsf@thalassa.informatimago.com> Message-ID: <87ac859m1p.fsf@thalassa.informatimago.com> Matthias Blume writes: > Pascal Bourguignon writes: > >> Moreover, a good proportion of the program and a good number of >> algorithms don't even need to know the type of the objects they >> manipulate. >> >> For example, sort doesn't need to know what type the objects it sorts >> are. It only needs to be given a function that is able to compare the >> objects. > > Of course, some statically typed languages handle this sort of thing > routinely. > >> Only a few "primitive" functions need specific types. > > Your sort function from above also has a specific type -- a type which > represents the fact that the objects to be sorted must be acceptable > input to the comparison function. Well, not exactly. sort is a higher level function. The type of its arguments is an implicit parameter of the sort function. (sort "Hello World" (function char<=)) --> " HWdellloor" (sort '(52 12 42 37) (function <=)) --> (12 37 42 52) (sort (list (make-instance 'person :name "Pascal") (make-instance 'unit :name "Pascal") (make-instance 'programming-language :name "Pascal")) (lambda (a b) (string<= (class-name (class-of a)) (class-name (class-of b))))) --> (# # #) In Common Lisp, sort is specified to take a parameter of type SEQUENCE = (or vector list), and if a list it should be a proper list, and a function taking two arguments (of any type) and returning a generalized boolean (that is anything can be returned, NIL is false, something else is true) So you could say that: (sort (sequence element-type) (function (element-type element-type) boolean)) --> (sequence element-type) but element-type is not a direct parameter of sort, and can change for all calls event at the same call point: (mapcar (lambda (s) (sort s (lambda (a b) (<= (sxhash a) (sxhash b))))) (list (vector 52 12 42 37) (list 52 12 42 37) (list "abc" 'def (make-instance 'person :name "Zorro") 76))) --> (#(12 37 42 52) (12 37 42 52) (76 # DEF "abc")) >> So basically, you've got a big black box of applicaition code in the >> middle that doesn't care what type of value they get, and you've got a >> few input values of a specific type, a few processing functions >> needing a specific type and returning a specific type, and a few >> output values that are expected to be of a specific type. At anytime, >> you may change the type of the input values, and ensure that the >> needed processing functions will be able to handle this new input >> type, and the output gets mapped to the expected type. > > ...or you type-check your "black box" and make sure that no matter how > you will ever change the type of the inputs (in accordance with the > interface type of the box) you get a valid program. When? At run-time? All the modifications I spoke of can be done at run-time in Lisp. -- __Pascal Bourguignon__ http://www.informatimago.com/ The mighty hunter Returns with gifts of plump birds, Your foot just squashed one. From uval at rz.uni-karlsruhe.de Fri Jun 23 10:44:09 2006 From: uval at rz.uni-karlsruhe.de (Daniel Schüle) Date: Fri, 23 Jun 2006 16:44:09 +0200 Subject: what exceptions may file() and read() throw? References: Message-ID: Hi > You can't easily list the exceptions that your code could throw. There are > some obvious ones apart from IOError: say filename was an int (or even > certain strings) you would get TypeError, or you might get MemoryError or > KeyboardInterrupt. More obscurely, if you reused file as a global variable > you could generate any exception at all. I undestand now, so it would be better to let it in the code in case it's triggered (I triggered it by passing int instead of str, as you said) I would at least know where to look I wouldn't call it "dead code" then ... dead code is more like if False: do_something() thank you Regards, Daniel From osv at javad.com Fri Jun 16 04:48:03 2006 From: osv at javad.com (Sergei Organov) Date: Fri, 16 Jun 2006 12:48:03 +0400 Subject: a good programming text editor (not IDE) References: <_xgkg.2317$No6.48542@news.tufts.edu> Message-ID: John Salerno writes: > I know there's a request for a good IDE at least once a week on the ng, > but hopefully this question is a little different. I'm looking for > suggestions for a good cross-platform text editor (which the features > for coding, such as syntax highlighting, etc.) but not a full IDE with > all the fancy jazz (GUI developer, UML diagrams, etc.). > > Ideally, it would be something I could even put on a flash drive and > move from computer to computer, but this isn't necessary. Just something > I can immediately use in either Windows or Linux (or Mac, if > necessary). These days one can put entire OS to a flash drive, not only an editor. [...] > And naturally there are Emacs and Vim, but I just don't know if I need > to invest *that* much time into learning one of them (probably Vim, > since I hear it's lighter and faster). >From this thread you can easily see that people that never look for another editor are either Emacs or Vim users. I think you have two options here: either spend some time to master one of them, or spend the rest of your life looking for a good editor ;) [I compose this reply in XEmacs, yes] -- Sergei. From skip at pobox.com Tue Jun 6 10:27:32 2006 From: skip at pobox.com (skip at pobox.com) Date: Tue, 6 Jun 2006 09:27:32 -0500 Subject: 10GB XML Blows out Memory, Suggestions? In-Reply-To: <2Qfhg.18186$0v4.787@tornado.texas.rr.com> References: <1149594519.098115.8980@u72g2000cwu.googlegroups.com> <2Qfhg.18186$0v4.787@tornado.texas.rr.com> Message-ID: <17541.37076.898344.96365@montanaro.dyndns.org> Paul> You clearly need something instead of XML. Amen, brother... +1 QOTW. Skip From blais at furius.ca Tue Jun 20 20:04:21 2006 From: blais at furius.ca (Martin Blais) Date: Tue, 20 Jun 2006 20:04:21 -0400 Subject: [Announce] haddoc and haddoc.el Message-ID: <8393fff0606201704j3441bf75yeab5b89d9de44447@mail.gmail.com> Description =========== Haddoc is a simple tool that allows an emacs user to search the Python HTML documentation indexes and to bring a web browser to an index term page. Motivation ---------- Even though I have the Python TexInfo documentation installed from my Emacs, somehow I always end up browsing the documentation from a web browser. Most of the time I start from either the Python Library Reference or from the index. I wanted to be able to bring up the documentation from within Emacs. This does it. With haddoc, you invoke the elisp function ``haddoc-lookup`` (I type ``C-c .``), enter some search terms, and the matches from the Python indexes are shown in a buffer, from which you can select to direct your external web browser to. I like to drive an external Firefox with it. Design ------ I took the simple approach and wrote a combination of Emacs-LISP and Python code to implement this: * ``haddoc-update``: a Python script that will parse the HTML documentation indexes and generate a mapping of the index entries to the HTML pages in a DBM database (in ``/var/lib/haddoc/haddoc.db`` by default) * ``haddoc-lookup``: a Python script that does a lookup of search terms (potentially incomplete) on the index keys and returns the page references for each of the search terms on stdout * ``haddoc.el``: an Emacs-LISP package that can query the results of ``haddoc-lookup`` and spawn a webbrowser to the appropriate pages. Download at: http://furius.ca/downloads/haddoc/releases/ Cheers, From kay.schluehr at gmx.net Sun Jun 18 17:09:33 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 18 Jun 2006 14:09:33 -0700 Subject: Seeking regex optimizer References: <1150650439.651839.38180@y41g2000cwy.googlegroups.com> <1150662655.541745.174430@u72g2000cwu.googlegroups.com> Message-ID: <1150664973.879328.228330@y41g2000cwy.googlegroups.com> Paddy wrote: > Kay Schluehr wrote: > > I have a list of strings ls = [s_1,s_2,...,s_n] and want to create a > > regular expression sx from it, such that sx.match(s) yields a SRE_Match > > object when s starts with an s_i for one i in [0,...,n]. There might > > be relations between those strings: s_k.startswith(s_1) -> True or > > s_k.endswith(s_1) -> True. An extreme case would be ls = ['a', 'aa', > > ...,'aaaa...ab']. For this reason SRE_Match should provide the longest > > possible match. > > > > Is there a Python module able to create an optimized regex rx from ls > > for the given constraints? > > > > Regards, > > Kay > > A start would be: > regexp = "^(" + "|".join(sorted(ls, reverse=True)) + ")" > But the above does not work if you have special characters in your > strings. For special characters there might be a workaround using escapes. This is indeed important, but I do think one should split the problem into separate parts. > You say you want something that is optimised. What have have you tried? Sorting the list and checking for successor inclusions. Say you have ls = ['x','a', 'aa', 'aab' ,'ab'] This can be mapped to: 'x|a(?:(?:ab)?|b?|a?)' or to: '^(x|ab|aab|aa|a)' with reverse sorting as in your proposal.The naive solution is easy to generate but I'm sceptical about its cost effectiveness. On the other hand I do not want to investigate this matter if somebody else already did it thoroughly. Regards, Kay From fredrik at pythonware.com Wed Jun 7 03:14:28 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 07 Jun 2006 09:14:28 +0200 Subject: python-dev Summary for 2006-04-01 through 2006-04-15 In-Reply-To: References: Message-ID: > --------------------- > Python 2.5a1 Released > --------------------- > > Python 2.5 alpha 1 was released on April 5th. Please download it and > try it out, particularly if you are an extension writer or you embed > Python -- you may want to change things to support 64-bit sequences, > and if you have been using mismatched PyMem_* and PyObject_* > allocation calls, you will need to fix these as well. gotta do something about the lag, really ;-) for the record, 2.5 alpha 2 was released in late april; get it here: http://www.python.org/download/releases/2.5/ the rest of the summary blurb still applies; extension writers should read PEP 353: http://www.python.org/dev/peps/pep-0353 http://www.python.org/dev/peps/pep-0353/#conversion-guidelines From nicolasg at gmail.com Wed Jun 14 07:55:03 2006 From: nicolasg at gmail.com (nicolasg at gmail.com) Date: 14 Jun 2006 04:55:03 -0700 Subject: File read and writing in binary mode... Message-ID: <1150286103.249888.99610@i40g2000cwc.googlegroups.com> Hi, I'm trying to open a file (any file) in binary mode and save it inside a new text file. After that I want to read the source from the text file and save it back to the disk with its original form. The problem is tha the binary source that I extract from the text file seems to be diferent from the source I saved. Here is my code: 1) handle=file('image.gif','rb') source=handle.read() handle.close() if I save the file directly everything is well : 2A) handle=file('imageDuplicated.gif','wb') handle.write(source) handle.close() the file imageDuplicated.gif will be exactly the same as the original image.gif. But if I save the source to a text file I have porblem : 2B) handle=file('text.txt','w') handle.write(source) handle.close() handle=file('text.txt','r') source2=handle.read() handle.close() handle=file('imageDuplicated.gif','wb') handle.write(source2) handle.close() the files are completly different and I even cant display the image from the imageDuplicated.gif . something changes when I save the source in the text file because in 2B) source == source2 returns a False . I suspect that maybe the encoding is making a conflict but I don't know how to manipulate it... Every help is welcome, thanks. From aleax at mac.com Wed Jun 14 11:16:56 2006 From: aleax at mac.com (Alex Martelli) Date: Wed, 14 Jun 2006 08:16:56 -0700 Subject: convert floats to their 4 byte representation References: <1150297093.191223.152330@c74g2000cwc.googlegroups.com> Message-ID: <1hgwxgz.od7gd0160os2pN%aleax@mac.com> godavemon wrote: > I need to take floats and dump out their 4 byte hex representation. > This is easy with ints with the built in hex function or even better > for my purpose > > def hex( number, size ): > s = "%"+str(size) + "X" > return (s % number).replace(' ', '0') > > but I haven't been able to find anything for floats. Any help would be > great. floats' internal representation in Python is 8 bytes (equivalent to a C "double"). However, you can import struct and use struct.pack('f',x) to get a 4-byte ("single precision") approximation of x's 8-byte value, returned as a string of 4 bytes; you may force little-endian by using as the format 'f'; then loop on each character of the string and get its ord(c) [a number from 0 to 255] to format as you wish. For example import struct def float_hex4(f): return ''.join(('%2.2x'%ord(c)) for c in struct.pack('f', f)) or variants thereof. Alex From grflanagan at yahoo.co.uk Thu Jun 8 15:38:55 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 8 Jun 2006 12:38:55 -0700 Subject: follow-up to FieldStorage References: <4484b428$0$29635$636a55ce@news.free.fr> Message-ID: <1149795535.513230.85290@y43g2000cwc.googlegroups.com> John Salerno wrote: > Bruno Desthuilliers wrote: > > John Salerno a ?crit : > >> If I want to get all the values that are entered into an HTML form and > >> write them to a file, is there some way to handle them all at the same > >> time, or must FieldStorage be indexed by each specific field name? > > > > AFAIK, FieldStorage is a somewhat dict-like object, but I'm not sure it > > supports the whole dict interface. At least, it does support keys(), so > > you should get by with: > > > > for k in fs.keys(): > > print >> myfile, k, ":", fs[k] > > > > But reading the doc may help... > > Thanks. The cgi docs don't seem to get into too much detail, unless I > wasn't thorough enough. But your method seems like it might work well if > I can't find something after another read through. this any use: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81547 ? Gerard From jo at durchholz.org Sun Jun 25 08:12:47 2006 From: jo at durchholz.org (Joachim Durchholz) Date: Sun, 25 Jun 2006 14:12:47 +0200 Subject: What is Expressiveness in a Computer Language In-Reply-To: <1151010139.960608.122470@b68g2000cwa.googlegroups.com> References: <7zpshbsvjy.fsf@app-1.diku.dk><4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <0%Wlg.3521$MF6.947@tornado.socal.rr.com> <44992e6c$0$664$bed64819@news.gradwell.net> <1151010139.960608.122470@b68g2000cwa.googlegroups.com> Message-ID: rossberg at ps.uni-sb.de schrieb: > Joachim Durchholz wrote: >> > A type is the encoding of these properties. A type >>> varying over time is an inherent contradiction (or another abuse of the >>> term "type"). >> No. It's just a matter of definition, essentially. >> E.g. in Smalltalk and Lisp, it does make sense to talk of the "type" of >> a name or a value, even if that type may change over time. > > OK, now we are simply back full circle to Chris Smith's original > complaint that started this whole subthread, namely (roughly) that > long-established terms like "type" or "typing" should *not* be > stretched in ways like this, because that is technically inaccurate and > prone to misinterpretation. Sorry, I have to insist that it's not me who's stretching terms here. All textbook definitions that I have seen define a type as the set/operations/axioms triple I mentioned above. No mention of immutability, at least not in the definitions. Plus, I don't see any necessity on insisting on immutability for the definition of "type". Otherwise, you'd have to declare that Smalltalk objects truly don't have a type (not even an implied one), and that would simply make no sense: they do in fact have a type, even though it may occasionally change. Regards, Jo From ziga.seilnacht at gmail.com Fri Jun 2 04:28:14 2006 From: ziga.seilnacht at gmail.com (Ziga Seilnacht) Date: 2 Jun 2006 01:28:14 -0700 Subject: tp_richcompare References: Message-ID: <1149236894.705238.224090@c74g2000cwc.googlegroups.com> Sreeram Kandallu wrote: > I'm writing an extension type, for which i'd like to implement only == > and !=, but not the other comparison operators like <,<=,>,>=. > What is the right way to do this? > I currently have a tp_richcompare function, which handles Py_EQ, and > Py_NE, but raises a TypeError for the other operations. Is this the > 'right' way? Yes. This is exactly what the builtin complex type does. > Sreeram > Ziga From ghidox at gmail.com Wed Jun 21 02:14:36 2006 From: ghidox at gmail.com (Ghido) Date: 20 Jun 2006 23:14:36 -0700 Subject: separation events Message-ID: <1150870476.561722.190970@c74g2000cwc.googlegroups.com> Hi all, i'm writing a software with python and wxpython for manage the quality/environmental/security system for the my factory. I want to separate the gui structure from the events and database operations for obtain a very modular software, for this reason i start to use sqlalchemy. Unfortunately i don't understand if is possibile to have a file with only the gui structure and another file with the database operations and the events of the gui. It is possibile? the use of sqlalchemy is a good thing? Thanks a lot Ghido From fredrik at pythonware.com Tue Jun 6 02:23:29 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 06 Jun 2006 08:23:29 +0200 Subject: C# equivalent to range() In-Reply-To: <1149547304.607625.101670@j55g2000cwa.googlegroups.com> References: <1149468919.951745.163700@g10g2000cwb.googlegroups.com> <1149481675.192638.275140@c74g2000cwc.googlegroups.com> <1149509893.031953.19310@i40g2000cwc.googlegroups.com> <1149545140.011616.130610@y43g2000cwc.googlegroups.com> <1149546736.728440.74700@i39g2000cwa.googlegroups.com> <1149547304.607625.101670@j55g2000cwa.googlegroups.com> Message-ID: Fuzzyman wrote: > Well, this is true. Doesn't make it a *good* thing of course... :-) on the other hand, the rules for what works and doesn't on public forums have been finely tuned for many years. that's why "the rules don't apply to me" people like Lee, "Neuruss", and others get the kind of pushback they're getting. and frankly, their approach doesn't work in real life, so what makes you think it would work on the internet? From girish at cse.iitb.ac.in Mon Jun 12 04:25:17 2006 From: girish at cse.iitb.ac.in (Girish Sahani) Date: Mon, 12 Jun 2006 13:55:17 +0530 (IST) Subject: Function to remove elements from a list not working (corrected) Message-ID: <49543.10.209.4.1.1150100717.squirrel@10.105.1.3> Hi, I am trying to modify a list of pairs (l4) by removing those pairs which are not present in a third list called pairList. The following is a simplified part of the routine i have written. However it does not give the correct output. Please help! Its possible i have made a trivial mistke since i am a newbie. def getl5(): l5 = [] pairList = [[1,2],[3,4],[3,5],[3,6],[9,7],[8,9],[8,7],[7,9],[11,10]] l4 = [[4,2],[4,7],[4,10],[4,12],[9,2],[9,7],[9,10],[9,12],[11,2],[11,7]] for pair in l4: if pair not in pairList: l4.remove(pair) print "l4 is",l4 The output given is: l4 is [[4, 7], [4, 12], [9, 7], [9, 12], [11, 7]] From deets at nospam.web.de Wed Jun 7 07:52:52 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 07 Jun 2006 13:52:52 +0200 Subject: CENSORSHIP - Django Project (Schema Evolution Support) References: <4486B9FB.9030804@lazaridis.com> Message-ID: <4ent10F1f9d3gU1@uni-berlin.de> http://en.wikipedia.org/wiki/Ilias_Lazaridis [posted publicly to comp.lang.python, with no email notification to recipients that certainly don't consider this a relevant topic and for all those who don't know Illias] Diez From rossberg at ps.uni-sb.de Thu Jun 22 11:42:09 2006 From: rossberg at ps.uni-sb.de (rossberg at ps.uni-sb.de) Date: 22 Jun 2006 08:42:09 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <7zpshbsvjy.fsf@app-1.diku.dk><4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <0%Wlg.3521$MF6.947@tornado.socal.rr.com> <44992e6c$0$664$bed64819@news.gradwell.net> Message-ID: <1150990929.210041.198580@m73g2000cwd.googlegroups.com> Darren New schrieb: > Andreas Rossberg wrote: > > AFAICT, ADT describes a type whose values can only be accessed by a > > certain fixed set of operations. > > No. AFAIU, an ADT defines the type based on the operations. The stack > holding the integers 1 and 2 is the value (push(2, push(1, empty()))). > There's no "internal" representation. The values and operations are > defined by preconditions and postconditions. Are you sure that you aren't confusing *abstract* with *algebraic* data types? In my book, abstract types usually have an internal representation, and that can even be stateful. I don't remember having encountered definitions of ADT as restrictive as you describe it. > Both a stack and a queue could be written in most languages as "values > that can only be accessed by a fixed set of operations" having the same > possible internal representations and the same function signatures. > They're far from the same type, because they're not abstract. Different abstract types can have the same signature. That does not make them the same type. The types are distinguished by their identity. Likewise, two classes can have the same set of methods, without being the same class (at least in languages that have nominal typing, which includes almost all typed OOPLs). > I'm pretty sure in Pascal you could say > > Type Apple = Integer; Orange = Integer; > and then vars of type apple and orange were not interchangable. No, the following compiles perfectly fine (using GNU Pascal): program bla; type apple = integer; orange = integer; var a : apple; o : orange; begin a := o end. - Andreas From ibr at radix50.net Mon Jun 5 13:19:51 2006 From: ibr at radix50.net (Baurzhan Ismagulov) Date: Mon, 5 Jun 2006 19:19:51 +0200 Subject: logging In-Reply-To: <1149423835.166446.126240@i40g2000cwc.googlegroups.com> References: <1148426018.334087.124160@i40g2000cwc.googlegroups.com> <1148577240.250304.116360@j55g2000cwa.googlegroups.com> <1149005605.819519.242350@j55g2000cwa.googlegroups.com> <1149113113.083677.235570@i39g2000cwa.googlegroups.com> <1149423835.166446.126240@i40g2000cwc.googlegroups.com> Message-ID: <20060605171951.GA14461@radix50.net> Hello Vinay, On Sun, Jun 04, 2006 at 05:23:55AM -0700, Vinay Sajip wrote: > It's not propagated to the root logger (or to ancestor loggers in > general) - just to the handlers associated with ancestor loggers. ... > You can set levels on handlers as well as loggers. So if you add a > syslog handler to the root and set its level to CRITICAL, only CRITICAL > messages are sent to syslog. ... > logging.MYCUSTOMLEVEL = 25 > logging.addLevelName(logging.MYCUSTOMLEVEL, "MYCUSTOMLEVEL") Thanks much! With kind regards, Baurzhan. From digitalorganics at gmail.com Mon Jun 26 14:20:16 2006 From: digitalorganics at gmail.com (digitalorganics at gmail.com) Date: 26 Jun 2006 11:20:16 -0700 Subject: Replace Whole Object Through Object Method In-Reply-To: References: <1151337453.804750.293180@b68g2000cwa.googlegroups.com> Message-ID: <1151346016.052469.216270@p79g2000cwp.googlegroups.com> Maric Michaud wrote: ... > > def MixInto(Class, Mixin): > > if Mixin not in Class.__bases__: > > Class.__bases__ += (Mixin,) > > This doesn't work in most cases (with new style classes), better recreat a > type which inherit from Class and Mixin, or Class.__dict__ with > Mixin.__dict__. > I think I've discovered precisely what you mean about problem with new style classes. Do you know why it doesn't work for them? As I pointed out, creating a new type doesn't achieve the same thing. Any workarounds? Thanks. From noah.gift at gmail.com Wed Jun 7 19:52:11 2006 From: noah.gift at gmail.com (Noah Gift) Date: Wed, 7 Jun 2006 19:52:11 -0400 Subject: image sequence to Quicktime movie Message-ID: Hi, I am new to python and was interested in writing some python code that converts image sequences, for example tiff, into Quicktime movies, for example animation codec. Can anyone point me in the right direction to begin my research? It would be nice to not use pyobjc as I am trying to focus on doing things in pure python for now as a learning excercise. Thanks, Noah Gift -------------- next part -------------- An HTML attachment was scrubbed... URL: From laurent.pointal at limsi.fr Fri Jun 2 04:21:12 2006 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Fri, 02 Jun 2006 10:21:12 +0200 Subject: How to format datetime values In-Reply-To: References: <1149190242.446952.52180@j55g2000cwa.googlegroups.com> Message-ID: A.M a ?crit : > "BartlebyScrivener" wrote in message > news:1149190242.446952.52180 at j55g2000cwa.googlegroups.com... >> Are you trying to get banned, or what? >> >> It's the equivalent of me asking you: >> >> Hey, does Ruby have anything like dictionaries and will you teach me >> about strings? Oh, and what's an object? >> >> Go read the bleeping tutorial. >> >> rd >> > > Well, I did investigate all tutorial and google and I wasn't able to find > any built-in way for datetime formatting in Python. Really ? For time formating... have you really really looked at module... 'time'? > In fact I cannot find > any way to format a long integer into 99,999,9999 format. I know how > to format strings with C printf like formatter, but I am sure what I > am trying to do can't be done with C printf formatting. For long integer formating like your example, its not direct - maybe look at locale formating of numbers (module... 'locale'). And I recently annouce the PQRC (on clp.announce), which can gives you some directions: http://www.limsi.fr/Individu/pointal/python/pqrc/ A+ Laurent. From ursache.marius at gmail.com Tue Jun 27 10:05:58 2006 From: ursache.marius at gmail.com (Marius Ursache) Date: 27 Jun 2006 07:05:58 -0700 Subject: How do you use this list ? In-Reply-To: References: Message-ID: <1151417158.476033.297640@u72g2000cwu.googlegroups.com> Bo Yang wrote: > Hi everyone , > I have join this list for about 4 months , and everyday I receive > hundreds of > mails . There is no means to read all of them , so I just read something > interesting > for me . But if so , there are too much mails pile up in my inbox , I > want to ask > how do you use this list , reading every mail come in or just read what > you think > interesting ? > I use digest messages on a gmail account. i read the digests whenever i have time. -- M. http://marius.me.uk/ From arauzo at decsai.ugr.es Tue Jun 13 08:07:44 2006 From: arauzo at decsai.ugr.es (Antonio Arauzo Azofra) Date: Tue, 13 Jun 2006 14:07:44 +0200 Subject: Unimporting modules, memory leak? Message-ID: <448EAA90.6040007@decsai.ugr.es> Hello everybody, Probably, this is being too demanding for Python, but it may be useful to unimport modules to work with dynamic code (though not the best, one example is [2]). In fact, it is supposed to be possible[1], but I have detected it usually leaks memory. When unimported in Linux, the simple C module attached (has no functions, just the structure) leaks two memory pages To see the test you can just put the files in a directory and: python setupmod1.py install --install-lib . python testMemory.py Its output follows. First, the memory used before import. Second memory used after the import. Third the number of references to that object is checked before using del. Finally the memory used after unimporting. -- Testing mod1 -- Mem. used: 1242 (gc: 0 ) Mem. used: 1244 (gc: 0 ) Check refs (should be = 2): 2 Mem. used: 1244 (gc: 0 ) -- Testing bigModule -- Mem. used: 1244 (gc: 0 ) Mem. used: 2686 (gc: 0 ) Check refs (should be = 2): 2 Mem. used: 1244 (gc: 0 ) -- Testing random -- Mem. used: 1244 (gc: 0 ) Mem. used: 1256 (gc: 0 ) Check refs (should be = 2): 2 Mem. used: 1256 (gc: 57 ) Unimporting attached "bigmodule.py" there are no memory leaks. Unimporting python's random module it leaks some pages, but garbage collector admit it can not free them. If a module with the same name that the unimported module is imported, the pages are reused. While, if this same module is loaded with another name, they are not freed, and the program grows with each module imported/unimported Is this a Python bug? A Linux bug? Am i missing some way of freeing that memory used by C module? [1] http://mail.python.org/pipermail/python-list/1999-May/002669.html [2] http://ax5.com/antonio/orangesnns -- Saludos, Antonio Arauzo Azofra -------------- next part -------------- A non-text attachment was scrubbed... Name: bigModule.py Type: text/x-python Size: 129 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: setupmod1.py Type: text/x-python Size: 272 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: srcmod1.c Type: text/x-csrc Size: 226 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: testMemory.py Type: text/x-python Size: 690 bytes Desc: not available URL: From mgalves at gmail.com Tue Jun 6 12:00:46 2006 From: mgalves at gmail.com (Miguel Galves) Date: Tue, 6 Jun 2006 13:00:46 -0300 Subject: what are you using python language for? In-Reply-To: References: Message-ID: <52655700606060900y3dd17af9t22fa36838994ac42@mail.gmail.com> I'm using for processing genetic and biological data, anda for fun... On 6/4/06, hacker1017 wrote: > > im just asking out of curiosity. > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Miguel Galves - Engenheiro de Computa??o J? leu meus blogs hoje? Para geeks http://log4dev.blogspot.com Pra pessoas normais http://miguelgalves.blogspot.com "N?o sabendo que era imposs?vel, ele foi l? e fez..." -------------- next part -------------- An HTML attachment was scrubbed... URL: From duncanm255 at hotmail.com Thu Jun 1 10:34:23 2006 From: duncanm255 at hotmail.com (D) Date: 1 Jun 2006 07:34:23 -0700 Subject: Starting New Process Message-ID: <1149172463.881528.131290@j55g2000cwa.googlegroups.com> Hello, I need to write a server program that performs the following tasks: 1) Listens on TCP port 5555 for a connection 2) When client connects, launches application (for example, vi), then closes connection with client 3) Goes back to listening on TCP port 5555 for an incoming connection The main thing I need to make sure of is that when the server program closes, that the applications that were launched remain running (i.e. I would need to launch them independently of the server program). Any help as to how to do this would be greatly appreciated! From max at alcyone.com Sun Jun 11 02:14:21 2006 From: max at alcyone.com (Erik Max Francis) Date: Sat, 10 Jun 2006 23:14:21 -0700 Subject: Xah Lee network abuse In-Reply-To: References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148495974.975395.12920@i40g2000cwc.googlegroups.com> <1149998343.493200.144990@h76g2000cwa.googlegroups.com> Message-ID: Mike Schilling wrote: > If I were to write, say, that Tony Blair's tax policy will lead to higher > deficits, I could be convicted of libel? Even if that's true, it's not a > priori provable. I think what he was getting at is that, unlike many jurisdictions, writing something factually true is _not_ in and of itself a defense against a libel suit in the UK. As for the reverse side of the issue, in jurisdictions where it _is_ a defense, if one were to accuse him of being a pedophile but couldn't prove it, that would certainly be an actionable offense. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Twenty-four hours a day, three-hundred sixty-five days a year as Secretary of Defense, I lived the Cold War. -- Robert S. McNamara From qcd.apprentice at gmail.com Tue Jun 27 12:54:03 2006 From: qcd.apprentice at gmail.com (QCD Apprentice) Date: Tue, 27 Jun 2006 11:54:03 -0500 Subject: What is Expressiveness in a Computer Language In-Reply-To: <1151425350.679754.278820@i40g2000cwc.googlegroups.com> References: <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <1151384511.223582.305760@m73g2000cwd.googlegroups.com> <1151425350.679754.278820@i40g2000cwc.googlegroups.com> Message-ID: Joe Marshall wrote: > Marshall wrote: >> Yes, an important question (IMHO the *more* important question >> than the terminology) is what *programs* do we give up if we >> wish to use static typing? I have never been able to pin this >> one down at all. > > It would depend on the type system, naturally. > > It isn't clear to me which programs we would have to give up, either. > I don't have much experience in sophisticated typed languages. It is > rather easy to find programs that baffle an unsophisticated typed > language (C, C++, Java, etc.). > > Looking back in comp.lang.lisp, I see these examples: > > (defun noisy-apply (f arglist) > (format t "I am now about to apply ~s to ~s" f arglist) > (apply f arglist)) > > (defun blackhole (argument) > (declare (ignore argument)) > #'blackhole) > > But wait a sec. It seems that these were examples I invented in > response to the same question from you! > > >> The real question is, are there some programs that we >> can't write *at all* in a statically typed language, because >> they'll *never* be typable? > > Certainly! As soon as you can reflect on the type system you can > construct programs that type-check iff they fail to type-check. Sorry, but can you elaborate on this last point a little? I think I missed something. From david.nospam.hopwood at blueyonder.co.uk Tue Jun 20 23:46:11 2006 From: david.nospam.hopwood at blueyonder.co.uk (David Hopwood) Date: Wed, 21 Jun 2006 03:46:11 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> Message-ID: <7i3mg.204167$8W1.155367@fe1.news.blueyonder.co.uk> Chris Smith wrote: > Chris Uppal wrote: > >>>I'm unsure whether to consider explicitly stored array lengths, which >>>are present in most statically typed languages, to be part of a "type" >>>in this sense or not. >> >>If I understand your position correctly, wouldn't you be pretty much forced to >>reject the idea of the length of a Java array being part of its type ? > > I've since abandoned any attempt to be picky about use of the word "type". I think you should stick to your guns on that point. When people talk about "types" being associated with values in a "latently typed" or "dynamically typed" language, they really mean *tag*, not type. It is remarkable how much of the fuzzy thinking that often occurs in the discussion of type systems can be dispelled by insistence on this point (although much of the benefit can be obtained just by using this terminology in your own mind and translating what other people are saying to it). It's a good example of the weak Sapir-Whorf hypothesis, I think. -- David Hopwood From johnjsal at NOSPAMgmail.com Tue Jun 13 14:29:47 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 13 Jun 2006 18:29:47 GMT Subject: wxpython: how do i write this without the id parameter? In-Reply-To: <448e430d$1@nntp0.pdx.net> References: <448e430d$1@nntp0.pdx.net> Message-ID: Scott David Daniels wrote: > def __init__(self, parent=None, id=-1, title=__file__): I get that __file__ is not defined. From zefirek at Speacock.Pau.Apoznan.Mpl Fri Jun 23 08:06:43 2006 From: zefirek at Speacock.Pau.Apoznan.Mpl (zefciu) Date: Fri, 23 Jun 2006 14:06:43 +0200 Subject: Reuseable iterators - which is better? Message-ID: In the tutorial there is an example iterator class that revesrses the string given to the constructor. The problem is that this class works only once, unlike built-in types like string. How to modify it that it could work several times? I have tried two approaches. They both work, but which of them is stylistically better? class Reverse: #original one "Iterator for looping over a sequence backwards" def __init__(self, data): self.data = data self.index = len(data) def __iter__(self): return self def next(self): if self.index == 0: raise StopIteration self.index = self.index - 1 return self.data[self.index] class Reverse: #1st approach "Reuseable Iterator for looping over a sequence backwards" def __init__(self, data): self.data = data self.index = len(data) def __iter__(self): return self def next(self): if self.index == 0: self.index = len(self.data) #Reset when previous # iterator goes out raise StopIteration self.index = self.index - 1 return self.data[self.index] class Reverse: #2nd approach "Reuseable Iterator for looping over a sequence backwards" def __init__(self, data): self.data = data def __iter__(self): self.index = len(self.data) #Reset as a part of iterator # creation return self def next(self): if self.index == 0: raise StopIteration self.index = self.index - 1 return self.data[self.index] From jsfrank.chen at msa.hinet.net Mon Jun 19 02:45:19 2006 From: jsfrank.chen at msa.hinet.net (Thomas Moore) Date: Mon, 19 Jun 2006 14:45:19 +0800 Subject: pyfcp References: Message-ID: <000d01c6936b$ef79abb0$2c8cfea9@Thomas> > http://www.python.org/pyfcp > It gets me to Error 404. From chris.uppal at metagnostic.REMOVE-THIS.org Fri Jun 23 08:32:31 2006 From: chris.uppal at metagnostic.REMOVE-THIS.org (Chris Uppal) Date: Fri, 23 Jun 2006 13:32:31 +0100 Subject: What is a type error? References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <7i3mg.204167$8W1.155367@fe1.news.blueyonder.co.uk> <44992e6c$2$664$bed64819@news.gradwell.net> <%Igmg.464974$xt.353729@fe3.news.blueyonder.co.uk> <449aaea0$2$656$bed64819@news.gradwell.net> Message-ID: <449bde60$0$663$bed64819@news.gradwell.net> Chris Smith wrote: [me:] > > I think we're agreed (you and I anyway, if not everyone in this thread) > > that we don't want to talk of "the" type system for a given language. > > We want to allow a variety of verification logics. So a static type > > system is a logic which can be implemented based purely on the program > > text without making assumptions about runtime events (or making > > maximally pessimistic assumptions -- which comes to the same thing > > really). I suggest that a "dynamic type system" is a verification > > logic which (in principle) has available as input not only the program > > text, but also the entire history of the program execution up to the > > moment when the to-be-checked operation is invoked. > > I am trying to understand how the above statement about dynamic types > actually says anything at all. So a dynamic type system is a system of > logic by which, given a program and a path of program execution up to > this point, verifies something. We still haven't defined "something", > though. That was the point of my first sentence (quoted above). I take it, and I assumed that you shared my view, that there is no single "the" type system -- that /a/ type system will yield judgements on matters which it has been designed to judge. So unless we either nominate a specific type system or choose what judgements we want to make (today) any discussion of types is necessarily parameterised on the class(es) of . So, I don't -- can't -- say /which/ judgements my "dynamic type systems" will make. They may be about nullablity, they may be about traditional "type", they may be about mutability... When we look at a specific language (and its implementation), then we can induce the logic(s) that whatever dynamic checks it applies define. Alternatively we can consider other "dynamic type systems" which we would like to formalise and mechanise, but which are not built into our language of choice. > We also haven't defined what happens if that verification > fails. True, and a good point. But note that it only applies to systems which are actually implemented in code (or which are intended to be so). As a first thought, I suggest that a "dynamic type system" should specify a replacement action (which includes, but is not limited to, terminating execution). That action is taken /instead/ of the rejected one. E.g. we don't actually read off the end of the array, but instead a signal is raised. (An implementation might, in some cases, find it easier to implement the checks by allowing the operation to fail, and then backtracking to "pretend" that it had never happened, but that's irrelevant here). The replacement action must -- of course -- be valid according to the rules of the type system. Incidentally, using that idea, we get a fairly close analogy to the difference between strong and weak static type systems. If the "dynamic type system" doesn't specify a valid replacement action, or if that action is not guaranteed to be taken, then it seems that the type system or the language implementation is "weak" in very much the same sort of way as -- say -- the 'C' type system is weak and/or weakly enforced. I wonder whether that way of looking at it -- the "error" never happens since it is replaced by a valid operation -- puts what I want to call dynamic type systems onto a closer footing with static type systems. Neither allows the error to occur. (Of course, /I/ -- the programmer -- have made a type error, but that's different thing.) > In other words, I think that everything so far is essentially just > defining a dynamic type system as equivalent to a formal semantics for a > programming language, in different words that connote some bias toward > certain ways of looking at possibilities that are likely to lead to > incorrect program behavior. I doubt that will be an attractive > definition to very many people. My only objections to this are: a) I /want/ to use the word "type" to describe the kind of reasoning I do (and some of the mistakes I make) b) I want to separate the systems of reasoning (whether formal or informal, static or dynamic, implemented or merely conceptual, and /whatever/ we call 'em ;-) from the language semantics. I have no objection to being used as part of a language specification, but I don't want to restrict types to that. > > Note that not all errors that I would want to call type errors are > > necessarily caught by the runtime -- it might go happily ahead never > > realising that it had just allowed one of the constraints of one of the > > logics I use to reason about the program. What's known as an > > undetected bug -- but just because the runtime doesn't see it, doesn't > > mean that I wouldn't say I'd made a type error. (The same applies to > > any specific static type system too, of course.) > > In static type system terminology, this quite emphatically does NOT > apply. There may, of course, be undetected bugs, but they are not type > errors. If they were type errors, then they would have been detected, > unless the compiler is broken. Sorry, I wasn't clear. I was thinking here of my internal analysis (which I want to call a type system too). Most of what I was trying to say is that I don't expect a "dynamic type system" to be complete, any more than a static one. I also wanted to emphasise that I am happy to talk about type systems (dynamic or not) which have not been implemented as code (so they yield judgements, and provide a framework for understanding the program, but nothing in the computer actually checks them for me). > If you are trying to identify a set of dynamic type errors, in a way > that also applies to statically typed languages, then I will read on. Have I answered that now ? /Given/ a set of operations which I want to forbid, I would like to say that a "dynamic type system" which prevents them executing is doing very much the same job as a static type system which stops the code compiling. Of course, we can talk about what kinds of operations we want to forbid, but that seems (to me) to be orthogonal to this discussion. Indeed, the question of dynamic/static is largely irrelevant to a discussion of what operations we want to police, except insofar as certain checks might require information which isn't available to a (feasible) static theorem prover. -- chris From paddy3118 at netscape.net Thu Jun 1 01:31:15 2006 From: paddy3118 at netscape.net (Paddy) Date: 31 May 2006 22:31:15 -0700 Subject: TSV to HTML References: <1149098823.979329.9220@f6g2000cwb.googlegroups.com> <447e268a$0$3699$4d3efbfe@news.sover.net> <1149126509.984331.306530@h76g2000cwa.googlegroups.com> Message-ID: <1149139875.503669.57900@h76g2000cwa.googlegroups.com> Brian wrote: > First let me say that I appreciate the responses that everyone has > given. > > A friend of mine is a ruby programmer but knows nothing about python. > He gave me the script below and it does exactly what I want, only it is > in Ruby. Not knowing ruby this is greek to me, and I would like to > re-write it in python. > > I ask then, is this essentially what others here have shown me to do, > or is it in a different vein all together? > Leif's Python example uses the csv module which understands a lot more about the peculiarities of the CSV/TSV formats. The Ruby example prepends a block. The Ruby example splits each line to form a table row and each row on tabs, to form the cells. The thing about TSV/CSV formats is that their is no one format. you need to check how your TSV creator generates the TSV file: Does it put quotes around text fields? What kind of quotes? How does it represent null fields? Might you get fields that include newlines? - P.S. I'm not a Ruby programmer, just read the source ;-) From gandalf at designaproduct.biz Thu Jun 15 12:13:17 2006 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Thu, 15 Jun 2006 18:13:17 +0200 Subject: code folding, a unique problem to python? In-Reply-To: References: Message-ID: <4491871D.5030403@designaproduct.biz> John Salerno ?rta: > Specifically, I'm using UltraEdit and perhaps there's no way perfect way > to implement code folding with it, given how it uses its syntax > highlighting file to do so (i.e., you have to specify an "Opening" and > "Closing" character in which to enfold code, such as braces). > > But my question is more general: is it possible to implement code > folding with Python given that it has no real block delimiters? Or is > this still a matter of which particular editor/IDE you use? For my part > I've tried (as was suggested elsewhere) to use 'def' as an opening and > closing keyword, but this of course will enfold everything between two > defs, even if you have more code between your function definitons (such > as a new class definition). > > So maybe I'm stuck in UE, but I'm curious if there is some general way > to do this, or is Python just too simple and concise for its own good? :) > There are many editors that do this. For Python, folding is based on IDENT and DEDENT tokens. You can look for their definition in the Python Language Reference. For example, SPE can do this. See this screenshot: http://stani.be/python/spe/screenshots/spe-linux-blender.png Best, Laszlo From vadim.feelsgood at gmail.com Thu Jun 1 08:26:31 2006 From: vadim.feelsgood at gmail.com (vadim.feelsgood at gmail.com) Date: 1 Jun 2006 05:26:31 -0700 Subject: Best Python Editor In-Reply-To: <1149149773.999940.13500@i40g2000cwc.googlegroups.com> References: <1149149773.999940.13500@i40g2000cwc.googlegroups.com> Message-ID: <1149164791.002020.210000@c74g2000cwc.googlegroups.com> I use WingIDE too. It is very convenient. Good auto-completion feature. It is not so heavy as Komodo. WingIDE was my the second step after Komodo. Just try it and u'll understand how it is good. yairchu at gmail.com wrote: > > Can anyone tell me a good python editor/IDE? > > It would be great if you can provide the download link also. > > WingIDE is very good. > It gives very nice completions and has a nice thing called "source > assistant" that shows the help of the function you're standing on and > etc. > But I don't think it's open-source and freei if that bothers you > http://www.wingware.com/ > > Another good one is idlespoon. > this one is open-source and freei > http://idlespoon.python-hosting.com/ From marc.t.davies at gmail.com Fri Jun 30 08:00:45 2006 From: marc.t.davies at gmail.com (MTD) Date: 30 Jun 2006 05:00:45 -0700 Subject: efficiency question In-Reply-To: References: <6AD91BEE-08AF-446D-AE17-B2FB5532E7FE@math.harvard.edu> Message-ID: <1151668845.318085.276910@h44g2000cwa.googlegroups.com> For the sake of comparison: >>> def cod(x): ... tupple1 = ("abc", "def", "xyz") ... tupple2 = ("pqr", "tuv", "123") ... if x in tupple1: ... doStuff() ... elif x in tupple2: ... doOtherStuff() ... >>> dis.dis(cod) 2 0 LOAD_CONST 7 (('abc', 'def', 'xyz')) 3 STORE_FAST 2 (tupple1) 3 6 LOAD_CONST 8 (('pqr', 'tuv', '123')) 9 STORE_FAST 1 (tupple2) 4 12 LOAD_FAST 0 (x) 15 LOAD_FAST 2 (tupple1) 18 COMPARE_OP 6 (in) 21 JUMP_IF_FALSE 11 (to 35) 24 POP_TOP 5 25 LOAD_GLOBAL 3 (doStuff) 28 CALL_FUNCTION 0 31 POP_TOP 32 JUMP_FORWARD 25 (to 60) >> 35 POP_TOP 6 36 LOAD_FAST 0 (x) 39 LOAD_FAST 1 (tupple2) 42 COMPARE_OP 6 (in) 45 JUMP_IF_FALSE 11 (to 59) 48 POP_TOP 7 49 LOAD_GLOBAL 4 (doOtherStuff) 52 CALL_FUNCTION 0 55 POP_TOP 56 JUMP_FORWARD 1 (to 60) >> 59 POP_TOP >> 60 LOAD_CONST 0 (None) 63 RETURN_VALUE From johnjsal at NOSPAMgmail.com Sat Jun 10 15:59:00 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sat, 10 Jun 2006 15:59:00 -0400 Subject: wxPython: Should you use a master sizer object? In-Reply-To: References: <448b072f$0$11723$c3e8da3@news.astraweb.com> Message-ID: <448b25e4$0$9428$c3e8da3@news.astraweb.com> Steve Holden wrote: > There doesn't seem to be any really usable material to help beginners. A > recursive design approach seems best, breaking down each grouping, but I > have sometimes found it difficult to adapt a design to changes. > > Although I'm a big fan of open source I must confess that to solve this > problem I eventually bought a copy of wxDesigner, which while not > perfect does help quite a lot, and allows cut/copy and paste of design > elements. Yeah, it would be nice to use something like wxDesigner eventually, but right now I'd like to learn how to write it all by hand, so I can know what's going on. There are a couple of screencasts about using sizers with Dabo that are helpful, even though it's specific to that designer. It still shows how to layout nested sizers, for example. From wescpy at gmail.com Fri Jun 30 23:44:00 2006 From: wescpy at gmail.com (w chun) Date: Fri, 30 Jun 2006 20:44:00 -0700 Subject: pyuno and PDF output In-Reply-To: <78b3a9580606231754i7921e733l8625c14002cf6615@mail.gmail.com> References: <78b3a9580606231754i7921e733l8625c14002cf6615@mail.gmail.com> Message-ID: <78b3a9580606302044g7cfc4915h948f8f4c9b2f01fe@mail.gmail.com> On 6/23/06, w chun wrote: > > 2. use the short form to instantiate a PropertyValue > > REPLACE: > PDF = PropertyValue("FilterName", 0, "writer_pdf_Export", 0) > WITH: > PDF = PropertyValue("FilterName", "writer_pdf_Export") after trying this again, i discovered that this fails too. the only thing that worked for me was doing it the "manual" way: pdf = PropertyValue() pdf.Name = 'FilterName' pdf.Value = 'writer_pdf_Export' furthermore, if you need to specify multiple properties, then virtually duplicating these three lines up and down your code starts to get old: hdn = PropertyValue() hdn.Name = 'Hidden' hdn.Value = True pdf = PropertyValue() pdf.Name = 'FilterName' pdf.Value = 'writer_pdf_Export' ow = PropertyValue() ow.Name = 'Overwrite' ow.Value = True you can slightly improve on this with something like: props = [PropertyValue() for i in range(nprops)] props[0].Name = 'FilterName' props[0].Value = 'writer_pdf_Export' props[1].Name = 'Overwrite' props[1].Value = True props[2].Name = 'Hidden' props[2].Value = True instead, i put this all into a function, and it helped clean things up a bit: def makePropVal(x, y=True): pv = PropertyValue() pv.Name = x pv.Value = y return pv hdn = makePropVal('Hidden') pdf = makePropVal('FilterName', FTYPES[ftype]) ow = makePropVal('Overwrite') > 3. use storeToURL() as opposed to storeAsURL() > > REPLACE: > doc2.storeAsURL("file:///C:/alleclipse/OpenOffice/test2.pdf", (PDF,)) > > WITH: > doc2.storeToURL(unohelper.absolutize( > unohelper.systemPathToFileUrl('C:/alleclipse/OpenOffice/test2.pdf'), > unohelper.systemPathToFileUrl('test2.pdf')), (PDF,)) correction (should be dir path as 1st arg): unohelper.systemPathToFileUrl('C:/alleclipse/OpenOffice'), unohelper.systemPathToFileUrl('test2.pdf')), (PDF,)) -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From grante at visi.com Fri Jun 30 16:15:21 2006 From: grante at visi.com (Grant Edwards) Date: Fri, 30 Jun 2006 20:15:21 -0000 Subject: How to control permission of file? References: <12aavvb7vc58b48@corp.supernews.com> Message-ID: <12ab1ipqgdduv83@corp.supernews.com> On 2006-06-30, K.S.Sreeram wrote: > Grant Edwards wrote: >> When one open()s a file (that doesn't exist) for writing , how >> does one control that file's permissions (it's "mode" in Unix >> terms). > > Check out 'os.open' > It returns a file descriptor, and if you need a file object you can use > 'os.fdopen' on the file descriptor Thanks. I thought maybe there was a less arcane way to do it. -- Grant Edwards grante Yow! FROZEN ENTREES may at be flung by members of visi.com opposing SWANSON SECTS... From jmcmonagle at velseis.com.au Thu Jun 1 18:30:56 2006 From: jmcmonagle at velseis.com.au (John McMonagle) Date: Fri, 02 Jun 2006 08:30:56 +1000 Subject: Tkinter - changing existing Dialog? In-Reply-To: References: Message-ID: <1149201056.26711.27.camel@kuepper.vels-int.com.au> On Thu, 2006-06-01 at 08:31 -0400, Michael Yanowitz wrote: > Hello: > > > I have a Tkinter GUI Dialog with many buttons and labels and text > widgets. > What I would like to do is, can I: > > 1) Disable/deactivate/hide a button, text widget that is already drawn (and > of course the opposite enable/activate/show it)? > > 2) Change the text of a label or button that is already drawn? > > based on actions taken by the user. Can it be done without destroying > the present dialog or the objects in it and creating a new one? > > Sorry for what probably is such a trivial and basic question. I just can't > find the answer or know what the technical term for what I want to do is to > search for it myself. To disable/deactivate a button widget, use the keyword 'state'. For example, import Tkinter as Tk root = Tk.Tk() bid = Tk.Button(root, text='test', state=Tk.NORMAL) bid.pack() bid.configure(state=Tk.DISABLED) If you want to hide the button (using Pack geometry manager): bid.pack_forget() You can pack it again using bid.pack() but it may be difficult to pack it back where you originally intended. If you are using the Grid geometry manager: bid.grid_forget() To put it back simply call grid again with the same row, column. Changing the text of a label or button already drawn is simply done by a call to the configure method on the button or label's text attribute: bid.configure(text='Help') Regards, John -- This message has been scanned for viruses and dangerous content by MailScanner, and is believed to be clean. From test at test.test Wed Jun 21 20:42:02 2006 From: test at test.test (test at test.test) Date: Wed, 21 Jun 2006 19:42:02 -0500 Subject: Python to PHP Login System (HTTP Post) Message-ID: Hi everyone, I'm creating a desktop Python application that requires web-based authentication for accessing additional application features. HTTP GET is really simple. HTTP POST is not (at least for me anyway) ;) I have tried a few different sources, but I cannot get HTTP POST to successfully log in. I can login using FireFox at http://www.magnetshare.com/main.php I suggest you register a dummy login to see what I mean (don't enter your real e-mail address). Now here's some code: ------------------------------------------------------------------------------ msparams = urllib.urlencode({'user': self.components.User.text, 'pass': self.components.MagnetSharePassword.text, 'sublogin': '1'}) try: f = urllib() ***What should go here?*** fc = f.read() fc.close() except: self.statusBar.text = "Disconnected" result = dialog.alertDialog(self, 'Couldn\'t connect to MagnetShare.com! Please check your Internet connection, and then try again.') else: print fc ------------------------------------------------------------------------------- Also, could you let us know what modules we should import? Thanks for checking this out! By the way, the PHP system I'm using is super easy to set up: http://www.evolt.org/article/PHP_Login_System_with_Admin_Features/17/60384/index.html From seerhut at gmail.com Sun Jun 25 13:21:32 2006 From: seerhut at gmail.com (seerhut) Date: Mon, 26 Jun 2006 01:21:32 +0800 Subject: Eclipse IDE question In-Reply-To: <1151241922.620601.218580@r2g2000cwb.googlegroups.com> References: <1151241922.620601.218580@r2g2000cwb.googlegroups.com> Message-ID: kilnhead wrote: > I am trying to use eclipse for python development. Is it possible to > run a python script without having to name/setup a configuration? Can > eclipse be set up so that "run" loads the code into the interpreter and > goes? I don't want to create a new run config every time I want to run > a script. > try pydev , a plugin for eclipse From onurb at xiludom.gro Fri Jun 23 09:50:17 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Fri, 23 Jun 2006 15:50:17 +0200 Subject: code is data In-Reply-To: References: <44965f53$0$12743$636a55ce@news.free.fr> <4496b29f$0$27412$626a54ce@news.free.fr> <4496e9c9$0$14868$626a54ce@news.free.fr> <4fokj4F1ihat3U1@uni-berlin.de> <4497c20e$0$29656$636a55ce@news.free.fr> <4fpuh5F1i9bl1U1@uni-berlin.de> <4497d72d$0$30964$636a55ce@news.free.fr> <4fq5fkF1k346bU1@uni-berlin.de> <44982637$0$29812$626a54ce@news.free.fr> <1151013151.902103.32800@g10g2000cwb.googlegroups.com> Message-ID: <449bf199$0$1338$626a54ce@news.free.fr> Anton Vredegoor wrote: (snip) > However, I knew of the existence of such languages but I am mostly > interested in standardized code interchange, like for example with JSONP > which fetches some external javascriptcode from another server using > JSON and places the translated javascript into a webpage at the request > of the clients browser or so it seems. This is AJAX with JSON instead of XML (should we call this AJAJ ?-). It's quite handy, since it saves both the extra bits to be transfered (XML is way much verbose than JSON) and the XML to javascript parsing. > Maybe a Python webserver could > also emit pieces of javascript code by getting them from a *Python* code > library after translating Python code on the fly? If you restrict this on data, it's already done (Turbogears uses this for AJAX). > That would open up the web to Python programmers without browsers > needing to understand Python. Like Jython, but now as separately > distributed functions from different servers. > > Anton -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From erchamion.beren at gmail.com Wed Jun 14 05:14:42 2006 From: erchamion.beren at gmail.com (sinan nalkaya) Date: Wed, 14 Jun 2006 09:14:42 -0000 Subject: popen and password entry Message-ID: <200604141214.51754.erchamion.beren@gmail.com> hello, i want to use rsync for remote file transfer via popen, but couldnt pass the Password yet. here`s what i did cmd = 'rsync -av config root at 10.1.1.1:/tmp/.' f = os.popen(cmd,'w') f.write('1234') #not worked f.write('1234\n') #not worked every time i see "Password:" line, then i tried popen2 st_out, st_in = popen2.popen2(cmd) st_in.write('1234') #not worked st_in.write('1234\n') #not worked again i got bored to see "Password:" line every time and did st_out.close() to not to see stdout messages from rsync, but even this did not work. also i tried popen3() function same way. what should i do? Thanks. From aahz at pythoncraft.com Fri Jun 2 13:07:10 2006 From: aahz at pythoncraft.com (Aahz) Date: 2 Jun 2006 10:07:10 -0700 Subject: An oddity in list comparison and element assignment References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1149194434.528648.148860@u72g2000cwu.googlegroups.com> <1hg9onn.p25evr18a09f9N%aleax@mac.com> Message-ID: In article <1hg9onn.p25evr18a09f9N%aleax at mac.com>, Alex Martelli wrote: > >Just to share some tidbits (about which, as an Italian now living >between San Francisco and San Jose, I'm sort of proud of...!-)...: > >Bank of America is a private bank, founded in San Francisco more than >100 years ago by an Italian-American guy (Amadeo Giannini, born in San >Jose, CA, but to Italian-born parents) as "Bank of Italy", then renamed >in 1930 in part because the Italian State bank "Banca d'Italia" >objected. It rose to prominence right after the SF earthquake of 100 >years ago, by opening and staffing a temporary branch to ensure >depositors could access their money when they most needed it, while most >other banks were staying closed. Except, of course, that BofA doesn't exist anymore. Oh, the *name* does, but what's now called BofA is simply the current name of the bank that acquired BofA. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I saw `cout' being shifted "Hello world" times to the left and stopped right there." --Steve Gonedes From timx at nospam.dev.null Mon Jun 5 04:14:06 2006 From: timx at nospam.dev.null (Tim X) Date: Mon, 05 Jun 2006 18:14:06 +1000 Subject: HOST - dreamhost.com / Liberality (Hosting, Basic Requirement) References: <4482CDDA.9060905@lazaridis.com> Message-ID: <878xockoj5.fsf@tiger.rapttech.com.au> Joachim Durchholz writes: > Ilias Lazaridis schrieb: >> crossposted to 5 groups, which are affected by this case. >> followup not applicable. > > Actually, in this case, yes. > >> It _seems_ that Mr. Xah Les's account was terminated by dreamhost.com >> because of >> a) the inability of several people to detect the interconnections >> within writings which lead to perfectly valid cross-posts within the >> usenet. > > Actually, his posts are mostly off-topic. > >> b) the non-liberal and essentially non-professional way of how >> dreamhost.com deals with abuse complaints. > > Unless you give some concrete facts, this is simply slander. > URLs don't count. > >> To dreamhost.com: >> You should install an autoresponder to your abuse email, which >> reminds >> people that it is >> * nearly inpossible to rate the content posted to usenet >> * neally inpossible to detect validity of cross-posts >> especially within complex analytical/philosophical writings >> * other important facts > > Why are you wasting our mental bandwidth with that? > Besides, it's utter nonsense. There's an infinity of invalid reasons, > so you can't rule them out with an autoresponder. > >> People can then decide if they still wish to send the abuse complain >> (e.g. can follow a link within the autoresponder). > > Nope. Finding out the provider is enough of a barrier. Additional > barriers are not really necessary. > Xah Lee has been irritating people for months. > > I do share your concerns. Complaint handling often is unprofessional. > However, in Xah Lee's case, he's indeed been irritating too many > people for a too long time that *some* sanction is in fact > appropriate. > I routinely kill his threads, but I'm reading a specific newsgroup for > a purpose, and Xah Lee requires me to kill his. He's essentially doing > semantic spam - analytical and philosophical writings may be well and > fine, but they aren't appropriate on the newsgroups that I frequent > (or only in very specific ways that Xah Lee doesn't address). > >> To anyone: >> Any form of censorship and "suppression of freedom of expression" >> should be kept out of from open-source projects and from usenet. >> It is the within the responsibility of every entity (including >> commercial companies) to act against it. >> http://dev.lazaridis.com/base/wiki/LiberalProjectDefinition > > There are many important goals. Free speech is indeed very high on the > list. On the other hand, I'm pretty sure that Xah Lee will find > another provider. I think the other point here is that everyone *assumes* Xah's account was cancelled simply because of a campaign to report him for spamming multiple newsgroups. I suspect there were other factors involved. for all anyone knows, the provider might have been getting complaints from people about Xah's account, website, e-mail and newsgorup posting for ages and just decided it was more trouble than it was worth to keep him as a customer. Personally, I didn't report Xah to his provider, but I do believe he was a troll (which he himself admits) and which is confirmed by the fact he never hangs around to defend or debate his posts which seem more often than not deliberately designed to start a flamewar. Bottom line is everyone seems to have just accepted Xah's claims and now we have lots of outraged netters screaming about free speech. Given Xah's desire to provoke emotion etc, its even possible Xah created this whole thing just for entertainment! On usernet, I think the secret is "believe nothing, question everything" and remember, on the net, nobody knows your a dog! -- tcross (at) rapttech dot com dot au From xkenneth at gmail.com Thu Jun 22 15:54:37 2006 From: xkenneth at gmail.com (xkenneth) Date: 22 Jun 2006 12:54:37 -0700 Subject: Quick Question Message-ID: <1151006076.949700.130110@u72g2000cwu.googlegroups.com> I want to be able to cycle through an array and print something in hexadecimal. Such as this thisArray = ["AF","0F","5F"] for x in range(len(thisArray)): print "\x" + thisArray[x] However python chokes on the escaped identifier, how can I get around this? Thanks! Regards, Ken From bborcic at gmail.com Mon Jun 19 09:34:06 2006 From: bborcic at gmail.com (Boris Borcic) Date: Mon, 19 Jun 2006 15:34:06 +0200 Subject: [Python-Dev] The baby and the bathwater (Re: Scoping, augmented assignment, 'fast locals' - conclusion) In-Reply-To: References: <449329F0.2000703@gmail.com> Message-ID: <4496A7CE.9050002@gmail.com> Hello, just a couple points On 6/17/06, Josiah Carlson wrote: [errors involving the shadowing of a variable by another] > > Of course everybody makes errors, but it doesn't follow from this, that > > all make the same errors, or should. > > If I implied that everyone has made this particular mistake, I'm sorry. > I was trying to say that I made error X, and that I don't believe that > I'm a unique butterfly to have made error X. Well, don't be so certain you aren't the exceptional butterfly as regards the general issue - if not the error itself, perhaps the onlook. It deemed on me over the week-end that all three of me, you, and Guido indeed, have been acting out our own names in some way. Guido van Rossum's case is most direct : "The guide by red lights". Me, well, the issue of comparing slightly different versions is kind of written in the relationship of my first name and my family name. As for you, your name is exceptional in that it makes your initials shadow those of Jesus-Christ (a "builtin" if any); and if you go to the bottom of it, that collision of identifiers goes slightly further than just the initials. Is the idea that people may get subtly influenced by their own names, new to you ? One's name is to language and thought as one's home is to space... "Bill Gates" has always struck me as an injunction... ... > One consequence of either a fixed or variable set of non-shadowables is > that you would need to use arbitrarily unique names for lexically nested > for loops, and/or specify that such variables are not referencing parent > scopes. > > def foo(...): > for i in ...: > ... > def bar(...): > ... > for i in ...: #unallowed > ... > ... > > You can replace the 'i' with a name of your choosing. Is such > desireable? I would say no for the same reasons why I said no in > regards to being able to explicitly name variables in different levels > within lexically nested scopes: I would argue that one shouldn't be > using closures in the first place, so encouraging its use with a syntax > is right out the door. But that's my opinion, and not really relevant > to the current discussion. I am surprised you would count the obligation of picking distinct names as an encouragement to use lexically nested scopes; compared to the current situation, it is in fact more -restrictive- and should thus count as -discouraging-. And imo picking different names for loop variables in such a case is rather a good thing. But, again, "more good ain't more ease". Nit : retrospectively I believe I let you push me into equating "closures" with "lexically nested function scopes", but am I right in believing "closures" in fact implies functions defined with nested scopes be exported/returned outside of the parent scope ? ... > I don't believe that Guido is the end-all-be-all of language > design, but I do find that I agree with him more often than not (though > perhaps not vv), and at least in regards to this particular > functionality, I side with the 'status quo' end of things. I dont understand the "(though perhaps not vv)". Is the "vv" intended to stand for "you" (eg, myself) ? I've always liked Guido's Python a lot, and part of it has to do with the ante-Bill-Gates "magic of programming". For a looong while, my consistent experience with the "Where do you want to go today ?" MS slogan - as illustrated by MS products - has been that whenever you tried to find imaginative programming solutions (as opposed to "obeying the designer's obvious expectation despite his claim he lets you free") you would collide with glass walls... or end up at a "billing gate" (=some commercial extension product). I've had slightly better experience in later years. Python always had a completely different feel, more like the restitution of the old magic to new generations. (btw, Prolog is the language that most gave me that feeling of "allowing spectacular escapes from the designer's obvious expectations", so it is not a matter of constraints - prolog is quite constraining. I think it has to do with consistency and humbleness of a design that is not trying to out-think its users). As concerns the case in point, I think it was unfortunate that you would not let come into the open that the (risk of) inadvertent capture of builtins by un-nested function scopes was critical to the shape of the "feature". Indeed, speaking of "status quo ante" : augmented assignments arrived with Python 2.0, while nested scopes where first introduced with 2.1. > > Have a good weekend, Thank you. I had a good weekend. I hope you too. And together with my thanks for your efforts, please recieve my apologies for temper... > - Josiah > > [1] http://www.csmonitor.com/2006/0515/p13s01-stct.html ...as this seems to imply you would. Boris -- "On na?t tous les m?tres du m?me monde" From fredrik at pythonware.com Thu Jun 15 15:23:23 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 15 Jun 2006 21:23:23 +0200 Subject: billionlaughs, on me :-(( - on winXP help! In-Reply-To: References: <1150397596.520219.125780@c74g2000cwc.googlegroups.com> Message-ID: Fredrik Lundh wrote: > takes requires that'll teach me to post to comp.lang.python while watching football... From fc14301589 at icqmail.com Sun Jun 11 11:08:20 2006 From: fc14301589 at icqmail.com (TheSaint) Date: Sun, 11 Jun 2006 23:08:20 +0800 Subject: Very newbie programming References: <448ae8ce_1@news.tm.net.my> Message-ID: <448c31d9_1@news.tm.net.my> Maric Michaud wrote: > Le Samedi 10 Juin 2006 17:44, TheSaint a ?crit?: > devices = [ e for e in devices if e.split('/')[-1] in partitions ] This is _not_ the expected result :) is missing a not as : devices = [ e for e in devices if e.split('/')[-1] *not* in partitions ] >> if len(c) != 1: >> sys.exit(0) # if none or more than one match exit >> >> cmnd = str(c)[2:-2] >> err = os.system('umount ' + cmnd) > > why ? > > os.system('umount "%s"' % devices[0]) > for line in icon_file : > if 'URL=/media' in line : > icon = icon.name > dvc = line[11:-1] > break The question is correct, I should go a step further. But as it will unmount multiple (ghost) partitions it should also remove the icons from the desktop as well. So I'm bit confused how to remove *each* icon, unless do it into the "for" loop. I'd like to get the search as fast as possible and solve the appropriate icon with the right device, after all :) Suppose to have the pendrive and the Compact Flash, which both are mounted in /media, what will be removed syncronized with its mount? I didn't get this problem so deep as long as I just considered to use one device at time. F From david.nospam.hopwood at blueyonder.co.uk Tue Jun 27 14:48:01 2006 From: david.nospam.hopwood at blueyonder.co.uk (David Hopwood) Date: Tue, 27 Jun 2006 18:48:01 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: <1151430821.728345.31600@p79g2000cwp.googlegroups.com> References: <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <1151384511.223582.305760@m73g2000cwd.googlegroups.com> <1151420883.426116.288300@b68g2000cwa.googlegroups.com> <1151430821.728345.31600@p79g2000cwp.googlegroups.com> Message-ID: Marshall wrote: > David Hopwood wrote: >>Marshall wrote: >>>David Hopwood wrote: >>>>Marshall wrote: >>>> >>>>>The real question is, are there some programs that we >>>>>can't write *at all* in a statically typed language, because >>>>>they'll *never* be typable? >>>> >>>>In a statically typed language that has a "dynamic" type, all >>>>dynamically typed programs are straightforwardly expressible. >>> >>>So, how does this "dynamic" type work? >> >> >> >>>It can't simply be the "any" type, because that type has no/few >>>functions defined on it. >> >>It isn't. From the abstract of the above paper: >> >> [...] even in statically typed languages, there is often the need to >> deal with data whose type cannot be determined at compile time. To handle >> such situations safely, we propose to add a type Dynamic whose values are >> pairs of a value v and a type tag T where v has the type denoted by T. >> Instances of Dynamic are built with an explicit tagging construct and >> inspected with a type safe typecase construct. > > Well, all this says is that the type "dynamic" is a way to explicitly > indicate the inclusion of rtti. But that doesn't address my objection; > if a typesafe typecase construct is required, it's not like using > a dynamic language. They don't require typecase to inspect values > before one can, say, invoke a function. I was answering the question posed above: "are there some programs that we can't write *at all* in a statically typed language...?" >>"Gradual typing" as described in >> is >>another alternative. The difference between gradual typing and a >>"dynamic" type is one of convenience rather than expressiveness -- >>gradual typing does not require explicit tagging and typecase constructs. > > Perhaps this is the one I should read; it sounds closer to what I'm > talking about. Right; convenience is obviously important, as well as expressiveness. -- David Hopwood From torbenm at app-1.diku.dk Fri Jun 16 07:38:26 2006 From: torbenm at app-1.diku.dk (=?iso-8859-1?q?Torben_=C6gidius_Mogensen?=) Date: 16 Jun 2006 13:38:26 +0200 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <4ffdntF1iei4hU1@individual.net> Message-ID: <7zwtbh8h59.fsf@app-1.diku.dk> Pascal Costanza writes: > Torben ?gidius Mogensen wrote: > > So while it may take longer to get a program that gets > > past the compiler, it takes less time to get a program that works. > > That's incorrect. See http://haskell.org/papers/NSWC/jfp.ps - > especially Figure 3. There are many other differences between these languages than static vs. dynamic types, and some of these differences are likely to be more significant. What you need to test is langauges with similar features and syntax, except one is statically typed and the other dynamically typed. And since these languages would be quite similar, you can use the same test persons: First let one half solve a problem in the statically typed language and the other half the same problem in the dynamically typed language, then swap for the next problem. If you let a dozen persons each solve half a dozen problems, half in the statically typed language and half in the dynamically typed language (using different splits for each problem), you might get a useful figure. Torben From ptaku2_wywal_to_ at tlen.pl Tue Jun 27 12:07:22 2006 From: ptaku2_wywal_to_ at tlen.pl (w.p.) Date: Tue, 27 Jun 2006 18:07:22 +0200 Subject: [W2k, wxPython 2.6.1.0] - MDISashDemo bug? In-Reply-To: References: Message-ID: w.p. wrote: > When i run MDISashDemo and maximize main frame, minimize and maximize > again - LayoutMDIFrame in OnSize dont work more... > Why? > > I need this feature for main MDI frame with toolbar and statusbar with > panels&sizers&bitmapbuttons :) > > Windows 2000, wxPython 2.6.1.0 > > w.p. > When i add this code: self.Bind(wx.EVT_ACTIVATE, self.OnActivate) and def OnActivate(self, event): if event.GetActive(): wx.LayoutAlgorithm().LayoutMDIFrame(self) all is ok. Small improvement in demo :) w.p. From remove_me_mmamsch at googlemail.com Sat Jun 24 13:12:25 2006 From: remove_me_mmamsch at googlemail.com (mmamsch) Date: Sat, 24 Jun 2006 19:12:25 +0200 Subject: subprocess.Popen on Windows References: <1151094433.181414.164410@g10g2000cwb.googlegroups.com> Message-ID: <449d7168$0$4498$9b4e6d93@newsread2.arcor-online.net> On 23.06.2006 23:12:02, "3c273" wrote: >"madpython" wrote in message >news:1151094433.181414.164410 at g10g2000cwb.googlegroups.com... >> playing with subprocess.Popen on Windows I stumbled into the following >> problem: >> Python 2.4.3 (#69, Mar 29 2006, 17:35:34) >> >> IDLE 1.1.3 >> >> >>> import subprocess >> >>> p1=subprocess.Popen("c:\\asd.bat") #works OK >> >>> p2=subprocess.Popen("c:\\asd.bat",stdout=subprocess.PIPE) >> >> Traceback (most recent call last): >> File "", line 1, in -toplevel- >> p2=subprocess.Popen("c:\\asd.bat",stdout=subprocess.PIPE) >> File "C:\Python24\lib\subprocess.py", line 533, in __init__ >> (p2cread, p2cwrite, >> File "C:\Python24\lib\subprocess.py", line 593, in _get_handles >> p2cread = self._make_inheritable(p2cread) >> File "C:\Python24\lib\subprocess.py", line 634, in _make_inheritable >> DUPLICATE_SAME_ACCESS) >> TypeError: an integer is required >> >>> >> What do I do wrongly? >> >I get the same thing. This only happens when using IDLE. From a command >prompt, everthing works as expected. Hopefully somebody else will know why. >Louis > > I think IDLE replaces the sys.stdin and sys.stdout by a class to redirect IO. So when using IDLE stdin and stdout are not integer handles anymore. Greetings, Mathias From russandheather at gmail.com Mon Jun 19 17:35:05 2006 From: russandheather at gmail.com (Russell Warren) Date: 19 Jun 2006 14:35:05 -0700 Subject: Recommended way to fix core python distribution issues in your own apps? Message-ID: <1150752905.405809.231160@p79g2000cwp.googlegroups.com> I've got a case where I need to tweak the implementation of a default python library due to what I consider to be an issue in the library. What is the best way to do this and make an attempt to remain compatible with future releases? My specific problem is with the clock used in the threading.Event and threading.Timer. It currently uses time.time, which is affected by changes in system time. eg: if you change the system clock somehow at some time (say, with an NTP broadcast) you may get a surprise in the timing of your code execution. What I do right now is basically this: import sys import time import threading if sys.platform == 'win32': threading._time = time.clock in which case I'm simply forcing the internal clock used in the Event/Timer code to use a time-independent performance timer rather than the system time. I figured this is a much better way to do it than snagging a private copy of threading.py and making a direct change to it, but am curious if anyone has a better way of doing this type of thing? For example, I have no way of guaranteeing that this hack will work come a change to 2.5 or later. Thanks, Russ From samschul at pacbell.net Fri Jun 16 12:20:25 2006 From: samschul at pacbell.net (sam) Date: 16 Jun 2006 09:20:25 -0700 Subject: Which compiler will Python 2.5 / Windows (Intel) be built with? In-Reply-To: References: <1150367139.495114.148550@g10g2000cwb.googlegroups.com> <44917535$1@nntp0.pdx.net> <1150391891.130185.4640@f6g2000cwb.googlegroups.com> <4491b9e1$1@nntp0.pdx.net> <1150406005.948538.188950@h76g2000cwa.googlegroups.com> Message-ID: <1150474825.456758.15480@h76g2000cwa.googlegroups.com> I have been using the latest VC.net to compile my SCSIPython extension dll for Python 2.3, 2.4, and 2.5 without any problems. I just have to make shure that I link with the correct Python.lib Sam Schulenburg From fredrik at pythonware.com Fri Jun 30 12:18:45 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 30 Jun 2006 18:18:45 +0200 Subject: Way for see if dict has a key In-Reply-To: <44a5409c$0$8389$626a54ce@news.free.fr> References: <6V6pg.21624$_J1.271925@twister2.libero.it><44a5041f$0$29637$636a55ce@news.free.fr><4F7pg.21676$_J1.272665@twister2.libero.it> <1151666867.604260.116320@h44g2000cwa.googlegroups.com> <44a51f34$0$6794$626a54ce@news.free.fr> <44a5409c$0$8389$626a54ce@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > Seems that if "key in dict" do a simple linear search that would be rather silly. hint: http://pyref.infogami.com/__contains__ From rune.strand at gmail.com Wed Jun 14 03:25:57 2006 From: rune.strand at gmail.com (Rune Strand) Date: 14 Jun 2006 00:25:57 -0700 Subject: Looping through a file a block of text at a time not by line In-Reply-To: References: Message-ID: <1150269957.652173.118640@i40g2000cwc.googlegroups.com> Rosario Morgan wrote: > Hello > > Help is great appreciated in advance. > > I need to loop through a file 6000 bytes at a time. I was going to > use the following but do not know how to advance through the file 6000 > bytes at a time. > > file = open('hotels.xml') > block = file.read(6000) > newblock = re.sub(re.compile(r''),'',block) > print newblock > > I cannot use readlines because the file is 138MB all on one line. > > Suggestions? > > -Rosario Probably a more terse way to do this, but this seems to work import os offset = 0 grab_size = 6000 file_size = os.stat('hotels.xml')[6] f = open('hotels.xml', 'r') while offset < file_size: f.seek(offset) data_block = f.read(grab_size) offset += grab_size print data_block f.close() From struggleyb at gmail.com Mon Jun 12 09:56:08 2006 From: struggleyb at gmail.com (Bo Yang) Date: Mon, 12 Jun 2006 21:56:08 +0800 Subject: An error ? In-Reply-To: References: <448D06AB.3070104@gmail.com> <200606121018.44943.maric@aristote.info> Message-ID: <448D7278.4080409@gmail.com> It works , thank you everyone ! I think there is much more I need to learn before I can grasp a full understand of the C/S modle ! Thanks again ! From siona at chiark.greenend.org.uk Mon Jun 12 11:24:24 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 12 Jun 2006 16:24:24 +0100 (BST) Subject: Searching and manipulating lists of tuples References: <1150117632.693617.45310@c74g2000cwc.googlegroups.com> Message-ID: Steve Holden wrote: >def algorith(d, s): > if s in d: > d[s] += 1 > else: > d[s] = 1 def algorith(d, s): d[s] = d.get(s, 0) + 1 And the OP should note that converting between dict d and list of pairs L is simply a matter of L = d.items() and d = dict(L) (assuming some other part of the program wants that list representation). -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From anton.vredegoor at gmail.com Tue Jun 20 10:03:11 2006 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Tue, 20 Jun 2006 16:03:11 +0200 Subject: [OT] code is data In-Reply-To: <4fq5fkF1k346bU1@uni-berlin.de> References: <44965f53$0$12743$636a55ce@news.free.fr> <4496b29f$0$27412$626a54ce@news.free.fr> <4496e9c9$0$14868$626a54ce@news.free.fr> <4fokj4F1ihat3U1@uni-berlin.de> <4497c20e$0$29656$636a55ce@news.free.fr> <4fpuh5F1i9bl1U1@uni-berlin.de> <4497d72d$0$30964$636a55ce@news.free.fr> <4fq5fkF1k346bU1@uni-berlin.de> Message-ID: Diez B. Roggisch wrote: <...> >> The whole point of a code transformation mechanism like the one Anton is >> talking about is to be dynamic. Else one just needs a preprocessor... > > No, it is not the whole point. The point is > > "" > The idea is that we now have a fast parser (ElementTree) with a > reasonable 'API' and a data type (XML or JSON) that can be used as an > intermediate form to store parsing trees. Especially statically typed > little languages seem to be very swallow-able. Maybe I will be able to > reimplement GFABasic (my first love computer language, although not my > first relationship) someday, just for fun. > """ > > No on-the-fly code generation here. He essentially wants lisp-style-macros > with better parsing. Still a programming language. Not a data-monger. The 'problem' is that a lot of incredibly smart people are reading and replying here who are seeing a lot more into my post than I was prepared for :-) Anyway, the last few weeks I have been busy transforming MsWord documents into XML using Open Office, and next parsing this XML and transforming it into a special subset of HTML using ElementTree's XMLWriter class. Then the output of the XMLWriter was put into a Zope/Plone page but I added special markup for footnotes, making them plone objects that could be separately edited, and I added image tags for images that were retrieved from a separate server using an XSLT script. To accomplish that a special zope parser was written to recognize my nonstandard footnote and image tags, and to create the necessary objects, and to insert them into the page. After that I came across some turbogears code (which is stacking code at different levels like it were those things you put under your beer glass) and still later I saw some JSON equivalents of XML. JSON looks a lot like Python dicts which makes it seem likely that javascript will be able to interface with Python more efficiently. Remember that ElementTree comes from the same place that brought us PIL which is a package that can transform images into different types. So if we can transform documents, images and XML, why not sourcecode? Especially if it's not a conversion into a 'lossy' file format, (I consider dynamically typed code versus statically typed code the analog thing to JPEG versus bitmaps) it would be easy to convert all datatypes into the datatypes of another language, thereby making it possible to exchange code between languages. Algorithms just being things that convert sets of data-objects into other sets of data-objects. Now if one would equate standardized code exchange between languages and within a language with macros then I guess there is nothing left for me to do but wait till a certain google bot comes knocking at my ip-address port 80 and transfers me to the google equivalent of Guantanamo. But the whole point of distinguishing macros from official language structures *is* standardization, as some other clever poster already pointed out, so it would be extremely unfair to equate trans-language standardized code exchange with the guerrilla type macro activities that are plaguing the Lisp community. Then there are some people who keep insisting they don't understand what I'm talking about until I simplify things enough to get them on-board, but then simply dismiss my ideas with 'you can already do that easily with this standard python construct'. This strategy was also eloquently refuted by some other poster, so I don't need to repeat it :-) I've gotten a lot of things to think about, so thanks all for your thoughts, but since this is getting way above my head I'll just wimp out and leave the rest of the thread to the experts! Regards, Anton From steve at holdenweb.com Fri Jun 9 11:19:19 2006 From: steve at holdenweb.com (Steve Holden) Date: Fri, 09 Jun 2006 16:19:19 +0100 Subject: [noob question] References and copying In-Reply-To: References: Message-ID: zefciu wrote: > Hello! > > Where can I find a good explanation when does an interpreter copy the > value, and when does it create the reference. I thought I understand > it, but I have just typed in following commands: > > >>>>a=[[1,2],[3,4]] >>>>b=a[1] >>>>b=[5,6] >>>>a > > [[1, 2], [3, 4]] > >>>>b > > [5, 6] > > And I don't understand it. I thought, that b will be a reference to a, > so changing b should change a as well. What do I do wrong. And a > second question - can I create a reference to element of a list of > floating points and use this reference to change that element? > > Greets to all PyFans > zefciu Nope, b is a reference to the same object referenced by a[1], but only until you rebind it. Think of assignment (binding) as storing a pointer to an object in a name. So a = [[2,3],[3,4]] stores a pointer to a list in "a". The list itself holds two pointers to (otherwise anonymous) lists. Then b = a[1] make b point to the same object as a[1] does. At this point you could, for example, execute b[0] = 42 Then when you printed the value of "a" you would see [[1, 2], [42, 4]] and you would see [42, 4] as the value of b. But you don't do that, you next do b = [5, 6] This stores a reference to an entirely different new list in "b", with the results you observe. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From rpdooling at gmail.com Thu Jun 1 14:03:04 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 1 Jun 2006 11:03:04 -0700 Subject: os.walk trouble References: <1149173920.903876.68370@c74g2000cwc.googlegroups.com> Message-ID: <1149184984.891834.294470@y43g2000cwc.googlegroups.com> >> root, dirs, files = os.walk(dirname) If you want to do it this way, you need to stop it after the first one: root, dirs, files = os.walk(dirname).next() print root print dirs print files see this thread http://tinyurl.com/rmyo4 From shejo284 at gmail.com Mon Jun 12 03:44:51 2006 From: shejo284 at gmail.com (Sheldon) Date: 12 Jun 2006 00:44:51 -0700 Subject: printing all variables Message-ID: <1150098291.647296.86340@f6g2000cwb.googlegroups.com> Good day, I would like to know if there is a way to print all the variables set in a python program with having to write "print variable" on all? sincerely, Sheldon From john at castleamber.com Wed Jun 7 14:53:39 2006 From: john at castleamber.com (John Bokma) Date: 7 Jun 2006 18:53:39 GMT Subject: CENSORSHIP - Django Project (Schema Evolution Support) References: <4486B9FB.9030804@lazaridis.com> <4ent10F1f9d3gU1@uni-berlin.de> Message-ID: Ilias Lazaridis wrote: > Diez B. Roggisch wrote: >> http://en.wikipedia.org/wiki/Ilias_Lazaridis > > What has this "wikipedia" entry to do with the topic here? > > What is the credibility and value of the provided "wikipedia" entry? And what's yours? And which source do you think I will trust more? -- John MexIT: http://johnbokma.com/mexit/ personal page: http://johnbokma.com/ Experienced programmer available: http://castleamber.com/ Happy Customers: http://castleamber.com/testimonials.html From michele.simionato at gmail.com Thu Jun 8 05:48:26 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 8 Jun 2006 02:48:26 -0700 Subject: tracking dependencies Message-ID: <1149760106.420216.167790@g10g2000cwb.googlegroups.com> I have a big framework (not written by me) with lots of internal dependencies and I am looking for a tool to see the dependency tree. I.e. given a module x, it should show me all the modules imported by x, and the modules imported by them recursively. Standard library modules should be ignored and there should be an option to turns off the visualization of certain modules, for instance the ones in given subpackages. I guess somebody has already written it, maybe even with a nice visual backend. Any hint? Michele Simionato From jake.emerson at onerain.com Mon Jun 26 23:49:15 2006 From: jake.emerson at onerain.com (Jake Emerson) Date: 26 Jun 2006 20:49:15 -0700 Subject: nested dictionary assignment goes too far References: <1151366182.359999.312270@m73g2000cwd.googlegroups.com> <1151369354.492540.84470@y41g2000cwy.googlegroups.com> Message-ID: <1151380155.383611.148640@b68g2000cwa.googlegroups.com> Thanks a lot Serge and Ben. Your posts were right on. I hope the weather is good wherever you are. Jake From sdcook55 at sbcglobal.net Sun Jun 4 10:17:02 2006 From: sdcook55 at sbcglobal.net (Stan Cook) Date: Sun, 04 Jun 2006 14:17:02 GMT Subject: create a text file In-Reply-To: References: <2xIeg.88125$H71.14049@newssvr13.news.prodigy.com> Message-ID: Fredrik Lundh wrote: > Stan Cook wrote: > >> I'm writing a script to list all of my music files' id3 tags to a >> comma delimited file. The only part I'm missing seems like it should >> be the simplest. I haven't used Python for the last couple of years. >> My question is this: >> >> When I use os.open(,"w"), I get an error >> message, TypeError: an integer is required. Has something >> changed? Did I miss something??? > > the function is called "open", not "os.open". > > there's an open function in the os module, but that's doing something > slightly different (see the library reference documentation for details > if you're curious). > > > Thanks, I found it. From uval at rz.uni-karlsruhe.de Fri Jun 2 19:35:09 2006 From: uval at rz.uni-karlsruhe.de (=?ISO-8859-1?Q?Sch=FCle_Daniel?=) Date: Sat, 03 Jun 2006 01:35:09 +0200 Subject: beginner code problem In-Reply-To: <2006060218415316807-victimorcrime@yahoocom> References: <2006060218415316807-victimorcrime@yahoocom> Message-ID: Hello > Here's the code I wrote: > > import random > > flip = random.randrange(2) > heads = 0 > tails = 0 > count = 0 > > while count < 100: > > if flip == 0: flip never changes again it's not reassigned in the while loop > heads += 1 > > else: > tails += 1 > > > count += 1 > > > > print "The coin landed on heads", heads, 'times ' \ > "and tails", tails, 'times' > in case you know how many times to iterate it's better to use for loop (in python and eq C also) from random import randrange as flip result = [0,0] for i in range(100): result[flip(2)] += 1 or from random import randrange as flip result = {"head":0, "tail":0} for i in range(100): result[["head","tail"]flip(2)] += 1 or >>> class Coin: ... def flip(self): ... import random ... return ("head", "tail")[random.randrange(2)] c = Coin() result = {"head":0,"tail":0} for i in range(100): result[c.flip()] += 1 or many many more the important thing is .. to know what is the most suitable data representation for you is it throw-away-code or is this going to be read by other people .. etc hth, Daniel From fredrik at pythonware.com Tue Jun 6 07:27:24 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 06 Jun 2006 13:27:24 +0200 Subject: How to add few pictures into one In-Reply-To: <1149591704.231602.158740@c74g2000cwc.googlegroups.com> References: <1149511692.796038.155930@c74g2000cwc.googlegroups.com> <1149517433.880564.128350@h76g2000cwa.googlegroups.com> <1149529269.228019.120480@u72g2000cwu.googlegroups.com> <1149573892.526072.6770@i39g2000cwa.googlegroups.com> <1149580572.739202.110940@y43g2000cwc.googlegroups.com> <1149587802.895959.37210@f6g2000cwb.googlegroups.com> <1149591704.231602.158740@c74g2000cwc.googlegroups.com> Message-ID: Lad wrote: > I really would like to have ALL pictures in one file. > So, what would be the easiest/best way how to do that? do you want to look at the images as a slideshow or as a collage? From sreeram at tachyontech.net Sat Jun 10 17:27:53 2006 From: sreeram at tachyontech.net (K.S.Sreeram) Date: Sun, 11 Jun 2006 02:57:53 +0530 Subject: NCrypt 0.6.4 - wrapper for OpenSSL Message-ID: <448B3959.3070503@tachyontech.net> NCrypt 0.6.4 (http://tachyon.in/ncrypt/) NCrypt is a wrapper for OpenSSL built using Pyrex. Although this is the first public release, NCrypt has been under development for the last one year, and is being used in production software. The following OpenSSL features have been wrapped: - hash algorithms (md5, sha1, sha256, etc.) - symmetric ciphers (aes256, aes128, 3des, blowfish etc.) - public key crypto with RSA - diffie hellman key exchange - X.509 certificates - SSL/TLS network protocol Documentation is available as usage examples at http://tachyon.in/ncrypt/usage.html. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 260 bytes Desc: OpenPGP digital signature URL: From david.nospam.hopwood at blueyonder.co.uk Thu Jun 22 18:27:09 2006 From: david.nospam.hopwood at blueyonder.co.uk (David Hopwood) Date: Thu, 22 Jun 2006 22:27:09 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: <87y7vp85sc.fsf@thalassa.informatimago.com> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150902275.129780.50260@p79g2000cwp.googlegroups.com> <1150918629.818145.143220@y41g2000cwy.googlegroups.com> <4fv081F1jh4ifU1@individual.net> <1150967543.947096.72840@g10g2000cwb.googlegroups.com> <4fv84rF1kp06kU1@individual.net> <4fvfuiF1kncqtU1@individual.net> <87ejxh9xoq.fsf@thalassa.informatimago.com> <87ac859m1p.fsf@thalassa.informatimago.com> <87y7vp85sc.fsf@thalassa.informatimago.com> Message-ID: <1PEmg.472643$xt.199547@fe3.news.blueyonder.co.uk> Pascal Bourguignon wrote: > But it's always possible at run-time that new functions and new > function calls be generated such as: > > (let ((x "two")) > (eval `(defmethod g ((self ,(type-of x))) t)) > (eval `(defmethod h ((x ,(type-of x)) (y string)) > (,(intern (format nil "DO-SOMETHING-WITH-A-~A" (type-of x))) x) > (do-something-with-a-string y))) > (funcall (compile nil `(let ((x ,x)) (lambda () (f x "Hi!")))))) > > Will you execute the whole type-inference on the whole program "black > box" everytime you define a new function? Will you recompile all the > "black box" functions to take into account the new type the arguments > can be now? Yes, why not? > This wouldn't be too efficient. It's rare, so it doesn't need to be efficient. 'eval' is inherently inefficient, anyway. -- David Hopwood From alanalan at newsgroup.nospam Wed Jun 7 16:05:10 2006 From: alanalan at newsgroup.nospam (A.M) Date: Wed, 7 Jun 2006 16:05:10 -0400 Subject: os.system and command output References: <8rFhg.1071$Wy.73797@news20.bellglobal.com> Message-ID: > Try: > > s = os.popen("DIR").read() > Thanks Steve. Is there anyway I can get the exit code (what os.system returns) from os.popen? From ldo at geek-central.gen.new_zealand Sat Jun 3 19:19:37 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 04 Jun 2006 11:19:37 +1200 Subject: So what would Python be? Message-ID: Just wondering... From SSchukat at dspace.de Tue Jun 6 05:11:50 2006 From: SSchukat at dspace.de (Stefan Schukat) Date: Tue, 6 Jun 2006 10:11:50 +0100 Subject: embedding Python in COM server loaded with win32com Message-ID: <1B3F2E002D9AD04BBC1A27B370F29EB9022EA2@exchange2003.dspace.de> Hi, when you are running in Python the PyInitialize() is not called and therefore you don't have a valid threadstate since the call in win32com uses the standard idiom Py_BEGIN_ALLOW_THREADS() CallComServer Py_END_ALLOW_THREADS() You could use PyNewInterpreter to get a valid state, but this won't work in Python greater version 2.2, since with the new GILState API does not allow more than one interpreter per thread. You could work around the problem if you would use a localserver instead of an inproc server. With that you would always have a clean process for your server. Stefan > -----Original Message----- > From: python-list-bounces+sschukat=dspace.de at python.org > [mailto:python-list-bounces+sschukat=dspace.de at python.org] On > Behalf Of Fozzie > Sent: Monday, June 05, 2006 3:57 PM > To: python-list at python.org > Subject: embedding Python in COM server loaded with win32com > > Hi, > > I have a problem which is quite circular, and hopefully > either someone has encountered something similar or has a > reason why this will not work. > > We have a COM library providing mathematics to various > systems, most functions are hard-coded but we want to embed a > scripting language to allow arbitrary functions to be used in > the numeric engines within the library, and am using Python for this. > > This seems to work fine called from standalone apps, and from > VB, however, Python scripts, which access the scripts via > win32com.client fail in the embedding code in C++ whenever I > attempt to call PyImport_AddModule. > > As a concrete example, consider the following minimal > interface, (created using an ATL project in VC7), which has > a single property, the user supplied script, and a single > function 'findRoot', which in this case is nothing more than > an indicator that the embedding worked, > > ------------------------------------------------------------- > STDMETHODIMP CMinEmbed::get_script(BSTR* pVal) { > USES_CONVERSION; > *pVal = SysAllocString(A2OLE(__script.c_str())); > return S_OK; > } > STDMETHODIMP CMinEmbed::put_script(BSTR newVal) { > USES_CONVERSION; > __script = std::string( OLE2A( newVal)); > return S_OK; > } > STDMETHODIMP CMinEmbed::findRoot(DOUBLE* root) { > std::string progress; > PyObject * main, * globals, * res, * func; > > try { > > progress = "calling PyInitialize"; > if(!Py_IsInitialized()) Py_Initialize(); > > progress = "get __main__ module"; > main = PyImport_AddModule("__main__"); > > progress = "get __main__module dictionary"; > globals = PyModule_GetDict(main); > > progress = "Run the script."; > res = PyRun_String(__script.c_str(), > Py_file_input, globals, globals); > > progress = "Get the function from main dictionary."; > func = PyDict_GetItemString(globals, "func"); > > progress = "test function, and return indicator"; > if(NULL != func && PyCallable_Check(func)) { > *root = 1.0; > } else { > *root = -1.0; > } > > progress = "clean up"; > Py_XDECREF(res); > Py_Finalize(); > return S_OK; > > } catch(...) { > // SetFailString just sets the > ISupportErrorInfo interface > SetFailString(IID_IMinEmbed, progress.c_str()); > return E_FAIL; > } > } > ------------------------------------------------------------- > > > When I build my server with the above method and run it at > the Python interpretor I get, > > >>> from win32com.client import Dispatch s = > >>> Dispatch('minServer.MinEmbed') s.script = 'def func(x) : > return x*x' > >>> s.findRoot() > Traceback (most recent call last): > File "", line 1, in ? > File "", line 2, in findRoot > File > "i:\1111\Python24\lib\site-packages\win32com\client\dynamic.py", > line 251, in _ApplyTypes_ > result = self._oleobj_.InvokeTypes(*(dispid, LCID, > wFlags, retType, > argTypes) + args) > pywintypes.com_error: (-2147352567, 'Exception occurred.', > (0, None, 'Failure to get main module', None, 0, -2147467259), None) > > However, works fine from VB and standalone apps. > > Is this approach even doable? > > > Thanks in advance > > > Dave Foster > > -- > http://mail.python.org/mailman/listinfo/python-list > From mbutscher at gmx.de Thu Jun 29 14:32:06 2006 From: mbutscher at gmx.de (Michael Butscher) Date: Thu, 29 Jun 2006 20:32:06 +0200 Subject: Interprocess communication on multi-user machine Message-ID: <44a41cae$0$29145$9b4e6d93@newsread4.arcor-online.net> Hi, this is not really Python-specific but I need it for Python. I'm wanting a method for interprocess communication which is OS- independent (sockets would be the normal way to go), but which works if multiple users use the machine at the same time so that one user has no access to the communication of programs of another user. Normally any user could connect to an open socket on a machine regardless which user established the socket (the user's program, to be precise). This should be prevented. I could solve this with an additional login when connecting to socket but this would be uncomfortable for the user. Any hints? TIA Michael -- Homepage: http://www.mbutscher.de/ From Thaqalainnaqvi at gmail.com Tue Jun 13 09:31:18 2006 From: Thaqalainnaqvi at gmail.com (Thaqalainnaqvi at gmail.com) Date: 13 Jun 2006 06:31:18 -0700 Subject: What's wrong in this HTML Source file of a Bank In-Reply-To: <1150204559.415713.288600@h76g2000cwa.googlegroups.com> References: <1150196896.819711.154640@c74g2000cwc.googlegroups.com> <1150204559.415713.288600@h76g2000cwa.googlegroups.com> Message-ID: <1150205478.055121.60300@u72g2000cwu.googlegroups.com> They don't know whats happeing despite sending them several e-mails. From david.nospam.hopwood at blueyonder.co.uk Thu Jun 22 18:17:37 2006 From: david.nospam.hopwood at blueyonder.co.uk (David Hopwood) Date: Thu, 22 Jun 2006 22:17:37 GMT Subject: What is Expressiveness in a Computer Language In-Reply-To: <87ejxh9xoq.fsf@thalassa.informatimago.com> References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150902275.129780.50260@p79g2000cwp.googlegroups.com> <1150918629.818145.143220@y41g2000cwy.googlegroups.com> <4fv081F1jh4ifU1@individual.net> <1150967543.947096.72840@g10g2000cwb.googlegroups.com> <4fv84rF1kp06kU1@individual.net> <4fvfuiF1kncqtU1@individual.net> <87ejxh9xoq.fsf@thalassa.informatimago.com> Message-ID: <5GEmg.208020$8W1.13213@fe1.news.blueyonder.co.uk> Pascal Bourguignon wrote: > Pascal Costanza writes: >>Andreas Rossberg wrote: >>>Pascal Costanza wrote: >>> >>>>Consider a simple expression like 'a + b': In a dynamically typed >>>>language, all I need to have in mind is that the program will >>>>attempt to add two numbers. In a statically typed language, I >>>>additionally need to know that there must a guarantee that a and b >>>>will always hold numbers. >>> >>>I'm confused. Are you telling that you just write a+b in your >>>programs without trying to ensure that a and b are in fact numbers?? >> >>Basically, yes. >> >>Note that this is a simplistic example. Consider, instead, sending a >>message to an object, or calling a generic function, without ensuring >>that there will be applicable methods for all possible cases. When I >>get a "message not understood" exception, I can then decide whether >>that kind of object shouldn't be a receiver in the first place, or >>else whether I should define an appropriate method. I don't want to be >>forced to decide this upfront, because either I don't want to be >>bothered, or maybe I simply can't because I don't understand the >>domain well enough yet, or maybe I want to keep a hook to be able to >>update the program appropriately while it is running. > > Moreover, a good proportion of the program and a good number of > algorithms don't even need to know the type of the objects they > manipulate. > > For example, sort doesn't need to know what type the objects it sorts > are. It only needs to be given a function that is able to compare the > objects. But this is true also in a statically typed language with parametric polymorphism. [...] > Why should adding a few functions or methods, and providing input > values of a new type be rejected from a statically checked point of > view by a compiled program that would be mostly bit-for-bit the same > with or without this new type? It usually wouldn't be -- adding methods in a typical statically typed OO language is unlikely to cause type errors (unless there is a naming conflict, in some cases). Nor would adding new types or new functions. (*Using* new methods without declaring them would cause an error, yes.) -- David Hopwood From cginboston at hotmail.com Wed Jun 7 15:38:18 2006 From: cginboston at hotmail.com (Chance Ginger) Date: Wed, 07 Jun 2006 19:38:18 GMT Subject: Python to C converter References: <1149506038.843016.298470@c74g2000cwc.googlegroups.com> <1149513389.922653.272900@u72g2000cwu.googlegroups.com> <1149517179.095435.266060@j55g2000cwa.googlegroups.com> Message-ID: Isn't Pyrex for writing extensions to Python? As for PyPy, I didn't scroll down far enough to see the compiler info. It does say it is Python written in Python at the top. Shedskin is nothing but a compiler. On Wed, 07 Jun 2006 19:13:27 +0200, Carl Friedrich Bolz wrote: > Chance Ginger wrote: >> If you are looking for a "real" python to C, well in this case >> C++ look for the shedskin compiler. It will take a rather >> nice subset of Python and generate C++ code from it. > > > In which sense is shedskin a more "real" python to C/C++ compiler than > some of the other mentioned projects? As most of the others (PyPy, > Pyrex), Shedskin works only for a small number of Python programs that > don't mix types too wildly. > > BTW: While the RPython (the subset of the Python language that PyPy can > compile) might not be extremely advanced, using it gives you a number of > very interesting features: like having the resulting program been > enhanced to not use the C stack (for deeply recursive code), using > different garbage collection strategies... > > Cheers, > > Carl Friedrich Bolz From bignose+hates-spam at benfinney.id.au Thu Jun 1 18:30:54 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 02 Jun 2006 08:30:54 +1000 Subject: losing handles of open files References: <000c01c68558$a48a9680$0201a8c0@mcuf7> Message-ID: <877j40zext.fsf@benfinney.id.au> Please don't post non-text message bodies to discussion forums. Message bodies should be plain text. "Anthra Norell" writes: > If a piece of code exits with an exception before it closes an open > file, that file seems to remain locked, which is real pain in the > butt You will want to examine the 'finally' clause, which is executed after the 'try' suite regardless of exceptions. You may also be interested in the 'with' statement, coming in Python 2.5, which will be a more natural way of expressing this idiom. -- \ "If nature has made any one thing less susceptible than all | `\ others of exclusive property, it is the action of the thinking | _o__) power called an idea" -- Thomas Jefferson | Ben Finney From python.list at tim.thechases.com Wed Jun 21 08:38:57 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 21 Jun 2006 07:38:57 -0500 Subject: Search substring in a string and get index of all occurances In-Reply-To: <4499034A.9040306@gmail.com> References: <4499034A.9040306@gmail.com> Message-ID: <44993DE1.7030302@tim.thechases.com> > I would like to search for a substring in a string and get the index of > all occurances. > > mystring = 'John has a really nice powerbook.' > substr = ' ' # space > > I would like to get this list: > [4, 8, 10, 17, 22] > > How can I do that without using "for i in mystring" which might be > expensive for large strings? >>> mystring = 'John has a really nice powerbook.' >>> substr = ' ' >>> indicies = [i for i in xrange(len(mystring)) if mystring.startswith(substr, i)] >>> indicies [4, 8, 10, 17, 22] is my preferred way of doing this. Theoretically, it doesn't involve copying any bits of the string, as startswith(substring, offset) *should* be smart enough to do the check internally without copying pieces of mystring for comparison, just to return whether a submatch starts there. Whether it *does* do that is another matter for the higher python powers. It also uses xrange which shouldn't create a temporary array of indicies, but rather use an iteratable sequence generator. It should work for finding all 3 instances of "aba' in "abababa" as well, another common query of a similar form here on the list. -tkc From Serge.Orlov at gmail.com Wed Jun 14 20:08:51 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 14 Jun 2006 17:08:51 -0700 Subject: split with "*" in string and ljust() puzzles References: Message-ID: <1150330131.466322.135350@i40g2000cwc.googlegroups.com> Sambo wrote: > I have just (finally) realized that it is splitting and removing > on single space but that seams useless, and split items > 1 and 2 are empty strings not spaces?? What is useless for you is worth $1,000,000 for somebody else ;) If you have comma separated list '1,,2'.split(',') naturally returns ['1', '', '2']. I think you can get what you want with a simple regexp. From william at 25thandClement.com Fri Jun 9 00:33:21 2006 From: william at 25thandClement.com (William Ahern) Date: Thu, 08 Jun 2006 21:33:21 -0700 Subject: The Nature of the =?iso-8859-13?q?=B4Unix_Philosophy=A1?= References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1149080931.582431.95560@j55g2000cwa.googlegroups.com> <1149730552.161534.121350@i40g2000cwc.googlegroups.com> <4487d188$1@news.broadpark.no> <44882412$0$20779$ec3e2dad@news.usenetmonster.com> <448828bb.84747014@news.xs4all.nl> Message-ID: On Thu, 08 Jun 2006 13:41:13 +0000, Richard Bos wrote: > Frank Silvermann wrote: > >> Nils O. Sel??sdal wrote: >> > Xah Lee wrote: >> >> The Nature of the ???Unix Philosophy??? >> >> > Perhaps you should take a peek at the ideas in Plan 9 from Bell Labs, >> > which is a continuation of this philosophy, unlike the "modern" unix >> > clones. >> Is there an actual Plan 9? I'm only aware of the one from Outer Space. > > . > > But directing the OP there would be futile, as is discussing such > off-topic matter on comp.lang.c. > > Richard Not totally off-topic. The Plan 9 "C" compiler supports some noteworthy additions and changes to the language. Certainly, in contrast, elucidative of standard C. Plus, you gotta love anonymous structures and unions ;) GCC supports them, and so does TinyCC I think. From fredrik at pythonware.com Wed Jun 28 07:31:50 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 28 Jun 2006 13:31:50 +0200 Subject: Immutability References: <4Qj*cEjkr@news.chiark.greenend.org.uk> Message-ID: Sion Arrowsmith wrote: > What I've not seen documented anywhere is the: > @property > def fset(self, value): > ... > idiom. It's not obvious from the documentation of the property > function that it can be used as a decorator like this. probably because it cannot be used in that way: the "property" function takes the *getter* as its first argument, so you can only use this for read- only properties... From sekhon.hari at googlemail.com Mon Jun 26 05:21:52 2006 From: sekhon.hari at googlemail.com (Hari Sekhon) Date: Mon, 26 Jun 2006 10:21:52 +0100 Subject: style question In-Reply-To: <1151313222.382208.98390@b68g2000cwa.googlegroups.com> References: <1151313222.382208.98390@b68g2000cwa.googlegroups.com> Message-ID: <449FA730.3030101@gmail.com> MTD wrote: > Hari Sekhon wrote: > >> Is it better to do: >> >> message = """This is line1. >> This is line2 >> This is line3\n""" >> >> or >> >> message = "This is line1.\n >> message = message + "This is line2\n" >> message = message + "This is line3\n" >> > > Is there any reason you can't do it in one line? > > message = "This is line1.\nThis is line2.\nThis is line3.\n" > > this would also be ugly though, a huge lone line for the paragraph I want to output, which would wrap around and break the visual indentation. otherwise I could do it in one line. but if I was going to do that and it was going to be so long, I'd just use """...""" -------------- next part -------------- An HTML attachment was scrubbed... URL: From DustanGroups at gmail.com Tue Jun 6 09:45:41 2006 From: DustanGroups at gmail.com (Dustan) Date: 6 Jun 2006 06:45:41 -0700 Subject: Again, Downloading and Displaying an Image from the Internet in Tkinter In-Reply-To: <1149563528.127044.32210@y43g2000cwc.googlegroups.com> References: <1149555597.559051.162590@i39g2000cwa.googlegroups.com> <1149556130.667899.199470@j55g2000cwa.googlegroups.com> <1149563528.127044.32210@y43g2000cwc.googlegroups.com> Message-ID: <1149601541.489425.248880@y43g2000cwc.googlegroups.com> Justin Ezequiel wrote: > cannot help you with Tkinter but... > > save=open("image.jpg","wb") > save.write(web_download.read()) > save.close() > > perhaps this would let you open the file in Paint Ok, that worked (was it plain w or the writelines/readlines that messed it up?). But Tkinter still can't find the image. I'm getting an error message: TclError: image "C:\Documents and [pathname snipped]" doesn't exist If it makes a difference, I'm on a Windows XP machine, and don't have to go cross-platform. From cfc at shell01.TheWorld.com Wed Jun 21 18:04:29 2006 From: cfc at shell01.TheWorld.com (Chris F Clark) Date: 21 Jun 2006 18:04:29 -0400 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150746989.489702.26290@i40g2000cwc.googlegroups.com> <1150749670.053433.242210@p79g2000cwp.googlegroups.com> <1150754918.338770.89870@i40g2000cwc.googlegroups.com> Message-ID: Chris F Clark schrieb: > In that sense, a static type system is eliminating tags, because the > information is pre-computed and not explicitly stored as a part of the > computation. Now, you may not view the tag as being there, but in my > mind if there exists a way of perfoming the computation that requires > tags, the tag was there and that tag has been eliminated. Joachim Durchholz replied: > On a semantic level, the tag is always there - it's the type (and > definitely part of an axiomatic definition of the language). > Tag elimination is "just" an optimization. I agree the tag is always there in the abstract. However, for the work I do the optimization of the tag at runtime is important, and we specifically change things into types when we know the system can do that optimization, because then we are getting the system to do the work we would have to do and validating that the job is done correctly. So, I care that the tag is eliminated in practice (and remains in theory--I have to have both). In the end, I'm trying to fit things which are "too big" and "too slow" into much less space and time, using types to help me reliably make my program smaller and faster is just one trick. It's a really great and non-obvious one though, and one I'm glad I learned. Any algebra I can learn that helps me solve my problems better is appreciated. However, I also know that my way of thinking about it is fringe. Most people don't think that the purpose of types is to help one write reliably tighter code. Still, knowing about dynmic typing (tagging) and static typing, helped me understand this trick. Thus, conflating the two meanings may at some level be confusing. However, for me, they aided understanding something that I needed to learn. -Chris From org1234 at gmail.com Wed Jun 7 15:50:55 2006 From: org1234 at gmail.com (aqmaiya) Date: 7 Jun 2006 12:50:55 -0700 Subject: Convert Date to Short formate Message-ID: <1149709855.899702.89100@c74g2000cwc.googlegroups.com> Hello, there is string value 'Dec 06, 2000' I want to convert that string date to SHORT FORMAT like '2000-12-06-. Please help me how do I do that? I'm new in Jython. Thanks, aqmaiya From kent at kentsjohnson.com Thu Jun 15 16:12:19 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Thu, 15 Jun 2006 16:12:19 -0400 Subject: nested functions In-Reply-To: References: <1150319279.865335.323530@u72g2000cwu.googlegroups.com> <1150344748.652441.316680@g10g2000cwb.googlegroups.com> Message-ID: <4491bde2$1_3@newspeer2.tds.net> Fredrik Lundh wrote: > George Sakkis wrote: > >> It shouldn't come as a surprise if it turns out to be slower, since the >> nested function is redefined every time the outer is called. > > except that it isn't, really: all that happens is that a new function object is created from > prebuilt parts, and assigned to a local variable. it's not slower than, say, a method call. Interesting. So func_code for a nested function is created when the module is compiled, and stuck in a new function object when the definition is executed. Like George, I always assumed that the body of the nested function was compiled when the outer function was executed, but that doesn't really make any sense - the *code* for the inner function is static, just the environment changes (globals(), closure). dis.dis reveals all: In [10]: def g(): ....: def h(): ....: print 'foo' ....: return h ....: In [11]: dis.dis(g) 2 0 LOAD_CONST 1 (", line 2>) 3 MAKE_FUNCTION 0 6 STORE_FAST 0 (h) 4 9 LOAD_FAST 0 (h) 12 RETURN_VALUE Thanks Fredrik! Kent From nmm1 at cus.cam.ac.uk Tue Jun 20 15:46:43 2006 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 20 Jun 2006 19:46:43 GMT Subject: Iteration over recursion? References: <1150808045.539887.291180@i40g2000cwc.googlegroups.com> <1150816827.826028.114740@h76g2000cwa.googlegroups.com> <4498211b$0$8390$626a54ce@news.free.fr> <1150828012.837354.160110@u72g2000cwu.googlegroups.com> <449846e0$0$4793$636a55ce@news.free.fr> Message-ID: In article <449846e0$0$4793$636a55ce at news.free.fr>, Bruno Desthuilliers writes: |> Sudden Disruption a ?crit : |> |> Because I do like recursion, and would personnally prefer tail-recursion |> optimisation over nice tracebacks. But I'm not in position to decide |> anything here. [ See below before you jump to conclusions :-) ] If you have ever had to unpick a really nasty problem where tail recursion removal has destroyed all evidence of how the program got there AND the program was written so that it plain did not work without it (memory exhaustion), you will have cursed the concept to hell and back again. Been there - done that :-( |> > Recursion was just an attempt to "unify" design approach by abstracting |> > itteration and creating a new context. It allowed the programmer to |> > isolate himself from the reality that he was actually iterating. Talk |> > about mind fuck. As someone who was in this area when the Algol versus Fortran wars were being fought, that is almost entirely incorrect. Recursion plus tail removal AS A SUBSTITUTE FOR ITERATION is what you are describing, but that came a decade after recursion became widespread in programming languages. |> Recursion is the most convenient way to express some common algorithms. |> Too bad for you if it does some nasty things to your mind. Agreed. Recursion should be used when it is the right technology to clarify the code, and not as a gimmicky, obfuscatory and often dogmatic substitute for iteration! There are algorithms that become almost incomprehensible without recursion, and I have implemented a recursion layer in both assembler AND Fortran just to enable me to write them without going bonkers. Regards, Nick Maclaren. From steve at holdenweb.com Wed Jun 7 09:09:36 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 07 Jun 2006 14:09:36 +0100 Subject: Python language problem In-Reply-To: <1149679099.355060.252250@f6g2000cwb.googlegroups.com> References: <1149678146.681370.5130@c74g2000cwc.googlegroups.com> <4486b41b$1_3@news.bluewin.ch> <1149679099.355060.252250@f6g2000cwb.googlegroups.com> Message-ID: <4486D010.1010808@holdenweb.com> ripley wrote: > Boris Borcic wrote: > >>ripleyfu at gmail.com wrote: >> >>>>>>class A: >>> >>>... pass >>>... >>> >>>>>>a = A() >>>>>>b = a >>>>>>del b >>>>>>a >>> >>><__main__.A instance at 0x00B91BC0> >>>I want to delete 'a' through 'b', why It does't? >>>How can I do that? >> >>del a,b > > > But 'b' is also deleted, i want use 'b' to delete 'a', 'b' is exists. > You can't do what you want to do. Python names are independent references to objects. The "del" statement deletes a name from a namespace (or an item from a structure), and cannot be used to delete all references to a given object. In general there's no way to delete a referenced object - we normally rely on the implementation (in CPython reference counting plus garbage collection, in other implementations just plain garbage collection) to perform the deletion when no live references to an object remain. Perhaps you'd like to explain *why* you find a need to do this (in other words, what's your use case)? Weak references are one possibility that might help you, but without knowing your real requirements it's difficult to be more helpful. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From aum at spam.me.please Mon Jun 19 18:45:28 2006 From: aum at spam.me.please (aum) Date: Tue, 20 Jun 2006 10:45:28 +1200 Subject: pyfcp References: Message-ID: On Mon, 19 Jun 2006 17:51:06 +0200, Marc 'BlackJack' Rintsch wrote: > In , aum wrote: > >> On Mon, 19 Jun 2006 14:45:19 +0800, Thomas Moore wrote: >> >>>> http://www.python.org/pyfcp >>>> >>> >>> It gets me to Error 404. >> >> Apologies - that URL should have been: >> >> http://www.python.org.nz/pyfcp > > I get: Unknown host www.python.org.nz > > Ciao, > Marc 'BlackJack' Rintsch Dammit, what was I thinking?! http://www.freenet.org.nz/pyfcp -- Cheers aum From aleax at mac.com Thu Jun 29 23:59:15 2006 From: aleax at mac.com (Alex Martelli) Date: Thu, 29 Jun 2006 20:59:15 -0700 Subject: decimal by default References: <1151547269.842597.319600@y41g2000cwy.googlegroups.com> <1hhnr9n.74ctg51k4vtc0N%aleax@mac.com> <1151630511.634906.3940@p79g2000cwp.googlegroups.com> Message-ID: <1hhpois.lhe30e15pued8N%aleax@mac.com> Daniel <4daniel at gmail.com> wrote: > Alex Martelli wrote: > > What about: > > > > c = compile(thestring, thestring, '') > > > > cc = new.code( ...all args from c's attributes, except the 5th > > one, constants, which should instead be: > > decimalize(c.co_consts)...) > > Wow, what an elegant solution! I had no hope that it would be this Heh, funny, I was originally parsing your response as ironic, because _I_ don't think of this as elegant -- too boilerplatey (as the expansion I showed right after dispays!)... took me a sec to see you really mean it!-) > simple. I always wondered what compile() was useful for and now I know > at least one thing. I'll try it out tomorrow. Thanks a lot Alex! You're welcome! And, compile is also useful for many other things, such as any situation where you may need to run eval multiple times on the same string of source code (typically on multiple distinct dicts/namespaces): compile the source once, then in the loop eval the code object (bytecode) rather than the source -- that saves time. Also, you may do introspection on the code object -- for example, I show in the Nutshell's 2nd ed how this lets you perform a "safe eval" -- a way to let the user specify any Python "literal" without risking a malicious user running arbitrary code (essentially, you refuse to eval the code object if its co_names isn't empty -- or, you might let said co_names possibly contain just a few names you deem "safe", such as, say, 'sin', 'cos', 'tan', which you can get into your namespace from the math module). Such introspection on names may also allow some further optimization, particularly in the repeated-execution case, if there are "well-known names" that you're able to compute "just in time" (nowadays you can also use a special mapping to "only compute at need" the values for the names that are actually needed). Beyond which, we get into the realm of byecode hacks...!-) Alex From aljosa.mohorovic at gmail.com Thu Jun 1 10:52:20 2006 From: aljosa.mohorovic at gmail.com (aljosa) Date: 1 Jun 2006 07:52:20 -0700 Subject: image lib & Qt4 Message-ID: <1149173540.470829.34940@c74g2000cwc.googlegroups.com> i'm looking for image lib which supports common image types (maybe freeimagepy?) and is relatively easy to display image loaded through that lib in PyQt4. any ideas? Aljosa From mhellwig at xs4all.nl Wed Jun 7 09:51:48 2006 From: mhellwig at xs4all.nl (Martin P. Hellwig) Date: Wed, 07 Jun 2006 15:51:48 +0200 Subject: secure xmlrpc server? In-Reply-To: References: <4486c6ee$0$31647$e4fe514c@news.xs4all.nl> <4486d1e9$0$31646$e4fe514c@news.xs4all.nl> Message-ID: <4486d9f7$0$31650$e4fe514c@news.xs4all.nl> Laszlo Nagy wrote: > http://trevp.net/tlslite/ - no exe installers. > http://sourceforge.net/projects/tlslite/ - no file packages to download > > :-( Download the zip and unpack it: http://trevp.net/tlslite/tlslite-0.3.8.zip Then there is an installers directory >> SimpleXMLRPCServer uses SimpleHTTPServer for its transfer stuff, so >> you might want to look more in that direction. >> > Yes, In fact I read the whole source code of SimpleXMLRPCServer and > other examples like > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81549 > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/165375 > > but I cannot combine the two. I see that the request handler is a > customised HTTP request handler: > > class SimpleXMLRPCRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): > > but I have no idea how to use it with https. Do you know a small example > (like the ones above)? That would help a lot. > > Laszlo > Something like: import SocketServer import SimpleXMLRPCServer import tlslite.api # Overriding with ThreadingMixIn and TLSSocketServerMixIN # to create a secure async server. class txrServer(SocketServer.ThreadingMixIn, tlslite.api.TLSSocketServerMixIn, SimpleXMLRPCServer.SimpleXMLRPCServer): pass But the above is untested (been a while ago, since I experimented with it, for my case it was more functional to use VPN's instead of SSL/TLS). For the rest you can follow the same principals as for the SimpleHTTPServer: http://trevp.net/cryptoID/docs/public/tlslite.integration.TLSSocketServerMixIn.TLSSocketServerMixIn-class.html -- mph From bnblazer at gmail.com Wed Jun 7 13:07:52 2006 From: bnblazer at gmail.com (Brian) Date: 7 Jun 2006 10:07:52 -0700 Subject: creating and naming objects In-Reply-To: References: <1149696358.065614.76150@h76g2000cwa.googlegroups.com> Message-ID: <1149700072.369465.230280@c74g2000cwc.googlegroups.com> Thank you all for your response. I think that I am getting it. Based on those responses, would I be correct in thinking that this would be the way to initialize my Student object and return the values? class Student: def __init__(self, name, id): self.name = name self.id = id def getName(self): return self.name def getId(self): return self.id Additionally, correct me if I am wrong but I can recycle: foo = Student() And doing so will just create a new instance of Student (with whatever attributes it is given) and the original foo is gone? Thanks for your help and patience. After reading my original post and then this one, I could see that it may look suspiciously like a home work assignment. Trust me it's not. The student example just seemed like a good fit to discuss this. Thanks again, Brian From tactics40 at gmail.com Wed Jun 21 11:23:34 2006 From: tactics40 at gmail.com (tactics40 at gmail.com) Date: 21 Jun 2006 08:23:34 -0700 Subject: returning index of minimum in a list of lists In-Reply-To: <1150901648.832039.165590@b68g2000cwa.googlegroups.com> References: <1150901648.832039.165590@b68g2000cwa.googlegroups.com> Message-ID: <1150903414.145552.8140@g10g2000cwb.googlegroups.com> JJLaRocque at gmail.com wrote: > Hi all, > Is there a simple python function to return the list index of the > minimum entry in a list of lists? > ie, for [[3,3,3,3], [3,3,3,1], [3,3,3,3]] to return 2,4. > Or, same question but just for a list of numbers, not a list of lists. > Thanks, > Josh In your example, you returned 2, 4. Did you mean 1, 3? mylist[1][3] is the way you would access the "1" in your list of lists. I don't think this task would have a built in function, but you could write one in less than 4 lines of code easily. From bnblazer at gmail.com Tue Jun 6 11:23:30 2006 From: bnblazer at gmail.com (Brian) Date: 6 Jun 2006 08:23:30 -0700 Subject: calling functions style question Message-ID: <1149607410.719487.213110@h76g2000cwa.googlegroups.com> I just have a basic style question here. Suppose you have the program: def foo1(): do something def foo2() do something else Assume that you want to call these functions at execution. Is it more proper to call them directly like: foo1() foo2() or in an if __name__ == "__main__": ? Both will execute when the script is called directly, I was just wondering if there is a preference, and what the pros and cons to each method were. Thanks, Brian From claird at lairds.us Sun Jun 25 22:57:08 2006 From: claird at lairds.us (Cameron Laird) Date: Mon, 26 Jun 2006 02:57:08 +0000 Subject: Absolute noob to Linux programming needs language choice help References: <1150854682.904891.274480@c74g2000cwc.googlegroups.com> Message-ID: <41v3n3-4f1.ln1@lairds.us> In article , Tim Roberts wrote: >claird at lairds.us (Cameron Laird) wrote: >> >>Tcl's maturity advantage is tiny--*maybe* two years. Both began at >>the end of the '80s. There've been close to two decades since to >>obscure any initial leads. > >The difference is more significant than that. Tcl started in 1987, but >Python's history doesn't begin until the early 1990s, unless you're >counting ABC as well. . . . We agree it was ambiguous. It was only in 1988 that John Ousterhout started *using* Tcl, and '89 when he first gave source to early adopters . Both Tcl and Python have covered a LOT of territory since then. From find at my.address.elsewhere Wed Jun 21 11:56:22 2006 From: find at my.address.elsewhere (Matthias Blume) Date: Wed, 21 Jun 2006 10:56:22 -0500 Subject: What is Expressiveness in a Computer Language References: <1149829487.457604.17510@i40g2000cwc.googlegroups.com> <1149863687.298352.45980@h76g2000cwa.googlegroups.com> <7zpshbsvjy.fsf@app-1.diku.dk> <4fb97sF1if8l6U1@individual.net> <7zu06lqxhu.fsf@app-1.diku.dk> <1150454445.151167.283520@r2g2000cwb.googlegroups.com> <7zslm58ggp.fsf@app-1.diku.dk> <1150706890.543243.284430@h76g2000cwa.googlegroups.com> <7zy7vt1mz2.fsf@app-3.diku.dk> <1150731889.008745.12180@i40g2000cwc.googlegroups.com> <1150794745.148997.245840@b68g2000cwa.googlegroups.com> <4498356b$0$659$bed64819@news.gradwell.net> <0%Wlg.3521$MF6.947@tornado.socal.rr.com> <44992e6c$0$664$bed64819@news.gradwell.net> Message-ID: Darren New writes: > [ ... ] As far as I know, LOTOS is the only > language that *actually* uses abstract data types - you have to use > the equivalent of #include to bring in the integers, for > example. Everything else uses informal rules to say how types work. There are *tons* of languages that "actually" facilitate abstract data types, and some of these languages are actually used by real people. From alexreinhart at satx.rr.com Tue Jun 13 22:05:45 2006 From: alexreinhart at satx.rr.com (Alex Reinhart) Date: Wed, 14 Jun 2006 02:05:45 GMT Subject: [OT] Re: Python open proxy honeypot In-Reply-To: <1150240932.039735.200750@f14g2000cwb.googlegroups.com> References: <1150236597.152868.250740@y43g2000cwc.googlegroups.com> <1150240932.039735.200750@f14g2000cwb.googlegroups.com> Message-ID: Serge Orlov wrote: > Alex Reinhart wrote: >> Serge Orlov wrote: >>> IMHO it's pretty useless, spammers are starting to use botnets, and the >>> more you make inconvenient to them use open proxies, the more of them >>> will move to closed botnets. >> As long as I inconvenience them, or at least catch one or two, I'll be >> satisfied. > > What makes you think that spammers won't discover you're blackholing > their spam as soon as you start to make some impact on their business? > They will just skip your proxypots and move to real open proxies. There are so many spammers and (hopefully) more than one proxypot, so a stream of less-than-coordinated spammers would probably be caught. The more coordinated, careful ones would probably avoid them quickly enough, but I'm sure there are plenty of stupid spammers. > I think you'll make bigger impact if you implement proxy checking > software in Python, so it can run on windows > too. That would be a good goal as well. From junkytownMAKNI at gmail.com Sun Jun 4 14:34:12 2006 From: junkytownMAKNI at gmail.com (SuperHik) Date: Sun, 04 Jun 2006 20:34:12 +0200 Subject: re beginner Message-ID: hi all, I'm trying to understand regex for the first time, and it would be very helpful to get an example. I have an old(er) script with the following task - takes a string I copy-pasted and wich always has the same format: >>> print stuff Yellow hat 2 Blue shirt 1 White socks 4 Green pants 1 Blue bag 4 Nice perfume 3 Wrist watch 7 Mobile phone 4 Wireless cord! 2 Building tools 3 One for the money 7 Two for the show 4 >>> stuff 'Yellow hat\t2\tBlue shirt\t1\nWhite socks\t4\tGreen pants\t1\nBlue bag\t4\tNice perfume\t3\nWrist watch\t7\tMobile phone\t4\nWireless cord!\t2\tBuilding tools\t3\nOne for the money\t7\tTwo for the show\t4' I want to put items from stuff into a dict like this: >>> print mydict {'Wireless cord!': 2, 'Green pants': 1, 'Blue shirt': 1, 'White socks': 4, 'Mobile phone': 4, 'Two for the show': 4, 'One for the money': 7, 'Blue bag': 4, 'Wrist watch': 7, 'Nice perfume': 3, 'Yellow hat': 2, 'Building tools': 3} Here's how I did it: >>> def putindict(items): ... items = items.replace('\n', '\t') ... items = items.split('\t') ... d = {} ... for x in xrange( len(items) ): ... if not items[x].isdigit(): d[items[x]] = int(items[x+1]) ... return d >>> >>> mydict = putindict(stuff) I was wondering is there a better way to do it using re module? perheps even avoiding this for loop? thanks! From joh12005 at yahoo.fr Thu Jun 8 17:22:36 2006 From: joh12005 at yahoo.fr (joh12005 at yahoo.fr) Date: 8 Jun 2006 14:22:36 -0700 Subject: what is often before a pattern ? Message-ID: <1149801756.593936.95110@y43g2000cwc.googlegroups.com> Hello, i'm looking for a way to detect sequence objects which are often before a pattern. say for example some list like: a = "a0 a1 a2 a3 a4 myPatternMatchHere".split() b = "a5 a2 a4 myPatternMatchHere".split() c = "a6 a7 a2 a3 a8 a4 myPatternMatchHere".split() d = "a9 a10 a2 myPatternMatchHere".split() a2 a3 a4 is the most interesting because it appears 2 times upon 4, and overlap a2 a4, and we have some clues that a2 is also important as it appears 4/4. maybe have you some suggestions or idioms where i should look after best. From sysfault at zetafunc.net Fri Jun 9 14:10:59 2006 From: sysfault at zetafunc.net (Anthony Greene) Date: Fri, 09 Jun 2006 14:10:59 -0400 Subject: Pychecker Message-ID: Howdy, I had the impression that pychecker caught and reported such dynamic syntactical errors. #!/usr/bin/env python def add(i): i += 10 status = 3 if 1 == 1: statuss = 15 add(status) ======================= exalted sysfault$ pychecker foo.py Processing foo... Warnings... None ======================= Hence the mispelling of status (statuss), which was done purposely to test if pychecker will acknowledge and report the error. Do i need to enable some type of pychecker option in order for it to pick up the error? I know that it is syntactically correct in python, however it's likely that 'status' is meant. Am i wishing that pychecker will replace a statically typed language mechanism? -- A wise man knows he knows nothing. From gandalf at designaproduct.biz Wed Jun 7 07:18:55 2006 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Wed, 07 Jun 2006 13:18:55 +0200 Subject: Python language problem In-Reply-To: <1149678146.681370.5130@c74g2000cwc.googlegroups.com> References: <1149678146.681370.5130@c74g2000cwc.googlegroups.com> Message-ID: <4486B61F.5030900@designaproduct.biz> ripleyfu at gmail.com i'rta: >>>> class A: >>>> > ... pass > ... > >>>> a = A() >>>> b = a >>>> del b >>>> a >>>> > <__main__.A instance at 0x00B91BC0> > I want to delete 'a' through 'b', why It does't? > How can I do that? > > You must undestand that 'a' and 'b' are names. You can only delete names, not objects. Objects are freed by the garbage collector, automatically. Probably you used to write programs in C or Pascal or other languages with pointers. In Python, there are no pointers, just references and you cannot free an object. You can only delete the references to it. The good question is: why would you like to free an object manually? The garbage collector will do it for you automatically, when the object has no more references. (Well, cyclic references are also garbage collected but not immediately.) If you need to handle resources, you can still use the try-finally statement. Like in: f = file('example.txt','r') try: s = f.read() finally: f.close() # The resource is freed. But the object that was used to access the resource, may not be freed here.... Regards, Laszlo From bob at passcal.nmt.edu Mon Jun 26 19:36:23 2006 From: bob at passcal.nmt.edu (Bob Greschke) Date: Mon, 26 Jun 2006 17:36:23 -0600 Subject: Extracting 3-byte integers Message-ID: I have some binary data read from a file that is arranged like <3-byte int> <3-byte int> <3-byte int> etc. The "ints" are big-endian and there are 169 of them. Is there any clever way to convert these to regular Python ints other than (struct) unpack'ing them one at a time and doing the math? Thanks! Bob From jmbc at nospam.fr Thu Jun 15 09:17:36 2006 From: jmbc at nospam.fr (jean-michel bain-cornu) Date: Thu, 15 Jun 2006 15:17:36 +0200 Subject: Newbie wxpython staticbitmap help please In-Reply-To: <1150376832.271801.19920@f6g2000cwb.googlegroups.com> References: <1150325882.038508.122780@g10g2000cwb.googlegroups.com> <4490f8b6$0$7766$7a628cd7@news.club-internet.fr> <1150376832.271801.19920@f6g2000cwb.googlegroups.com> Message-ID: <44915e36$0$7762$7a628cd7@news.club-internet.fr> > Thanks for any help with any of this I have no time at the moment. I'm going to try to give you an answer tomorrow morning (june 16) (if nobody did of course). See you jm From steven.klass at gmail.com Fri Jun 9 18:22:20 2006 From: steven.klass at gmail.com (rh0dium) Date: 9 Jun 2006 15:22:20 -0700 Subject: Weekend project - Directory simplifier - Shortest paths.. Message-ID: <1149891740.160372.9140@f6g2000cwb.googlegroups.com> Hi all, OK I have two lists of directories.. Master lista=["pad/foo/sch/filea","pad/foo/sch/fileb","pad/foo/sch/filec","pad/foo/lay/filea","pad/foo/lay/fileb","pad/foo/lay/filec","pad/bar/sch/filea","pad/bar/sch/fileb","pad/bar/sch/filec",,"pad/bar/lay/filea","pad/bar/lay/fileb","pad/bar/lay/filec","pad/zen/filea","pad/zen/fileb","pad/a", "pad/b"] Changed listb=["pad/foo/sch/filea","pad/foo/sch/fileb","pad/foo/sch/filec","pad/foo/lay/filea","pad/foo/lay/fileb","pad/foo/lay/filec","pad/bar/sch/filea","pad/bar/sch/fileb","pad/bar/sch/filec",,"pad/bar/lay/filea","pad/bar/lay/filec","pad/zen/fileb", "pad/b"] Now what I want to get out of this is the top most directory which could be used for a copy.. In other words I would like the results of this to be this final=["/pad/foo", "pad/bar/sch", "pad/bar/lay/filea", "pad/bar/lay/filec", "pad/zen/fileb", "pad/b"] So what I need it to do it to look backwards in the Master list and find all similiarites in Changed.. I don't even know how to approach this - can someone give me a hand with this. Thanks much!! From davecook at nowhere.net Mon Jun 26 03:12:02 2006 From: davecook at nowhere.net (Dave Cook) Date: Mon, 26 Jun 2006 07:12:02 GMT Subject: Python database access References: <1151295558.067744.91470@b68g2000cwa.googlegroups.com> Message-ID: <6NLng.22298$8q.10734@dukeread08> On 2006-06-26, Serge Orlov wrote: > On 25 Jun 2006 21:19:18 -0700, arvind wrote: >> I am going to work on Python 2.4.3 and MSSQL database server on >> Windows platform. > The module you're looking for is the first result if you search > "python mysql" on google or if you search "mysql" on python package > index I think he meant Microsoft SQL Server. In which case, google searches on "python mssql" and "python odbc" should be helpful. Dave Cook From uval at rz.uni-karlsruhe.de Fri Jun 30 07:30:45 2006 From: uval at rz.uni-karlsruhe.de (=?windows-1252?Q?Sch=FCle_Daniel?=) Date: Fri, 30 Jun 2006 13:30:45 +0200 Subject: delete first line in a file In-Reply-To: <44a50825$0$3888$91cee783@newsreader01.highway.telekom.at> References: <44a4f854$0$12942$91cee783@newsreader02.highway.telekom.at><44a50151$0$12935$91cee783@newsreader02.highway.telekom.at> <44a50825$0$3888$91cee783@newsreader01.highway.telekom.at> Message-ID: Juergen Huber schrieb: > Fredrik Lundh wrote: >> Juergen Huber wrote: >> >>> ok...i thought as much, that i have to copy this file! >>> >>> how will i do that?! >>> how will i fix this file => delete the first line?! >>> >>> with which commands could i do that?! >> start here: >> >> http://docs.python.org/tut/node9.html#SECTION009200000000000000000 >> >> > > that documentation i have already read, but it wouldn`t help me for my > problem! > i know, how i can read the first line an print them on the screen! > but...how can i say python, delete the first line?! > thats my problem! > in the entry of my posting i wrote, that i am a newbie and so please > understand me, that i ask so questions?! :-) > > thanks for your help! simple! f = file("old.file") ignore = f.readline() file("new.file", "w+").write(f.read()) hth, Daniel From steve at holdenweb.com Fri Jun 9 06:06:12 2006 From: steve at holdenweb.com (Steve Holden) Date: Fri, 09 Jun 2006 11:06:12 +0100 Subject: Allowing zero-dimensional subscripts In-Reply-To: <1149844947.822478.128580@g10g2000cwb.googlegroups.com> References: <1149801040.936452.26270@i40g2000cwc.googlegroups.com> <1149807149.516004.48590@f6g2000cwb.googlegroups.com> <1149832139.948242.64160@f6g2000cwb.googlegroups.com> <1149844947.822478.128580@g10g2000cwb.googlegroups.com> Message-ID: Carl Banks wrote: > Steve Holden wrote: > >>Hey, I have an idea, why don't we look at the language reference manual >>instead of imagining how we think it might work! > > > I don't know. Sounds risky. > > > >>In section 3.2 we find: >> >> >>""" >>Tuples >>The items of a tuple are arbitrary Python objects. Tuples of two or more >>items are formed by comma-separated lists of expressions. A tuple of one >>item (a `singleton') can be formed by affixing a comma to an expression >>(an expression by itself does not create a tuple, since parentheses must >>be usable for grouping of expressions). An empty tuple can be formed by >>an empty pair of parentheses. >>""" >> >>So it seems that your speculation is false. Section 2.6 specifically >>defines "[" and "]" as delimiters. Section 5.3.2 defines a subscription >>(a term I've not really grown to love, but what the heck) as >> >>subscription ::= primary "[" expression_list "]" >> >>and section 5.12, which defines expression_list, explicitly says >> >>"""An expression list containing at least one comma yields a tuple.""". >> >>So it would appear that while your change might be very convenient to >>allow you to refer to scalar values as zero-dimensional arrays, it >>doesn't really fit into Python's conceptual framework. Sorry. > > > Yes, that would appear to be so. You would have a point... if the > documentation were correct. Only it's not. > > According to the reference manual, the rule for an expression_list is: > > expression_list ::= expression ( "," expression )* [","] > > But take the following legal Python subscripted array: > > a[1:2,...,3:4] > But the element inside the brackets there isn't an expression-list, it's a slicing (see section 5.3.2). > Is "1:2" an expression? How about "..."? When I enter 1:2 at the 1:2 is a short slice. ... is an ellipsis. Neither of these elements are allowed in non-subscripting contexts. > Python prompt, I get a syntax error. The fact is, the documentation > here is either wrong or simplified or both. (I don't think it's a big > deal, actually: the real grammar has lots of complexity to handle > tricky cases that would needlessly complicate the reference manual for > a human reader.) So let's look at an excerpt the actual Python grammar > (from 2.4.3). You'll be happy to know subscription isn't used. :) > > trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME > subscriptlist: subscript (',' subscript)* [','] > sliceop: ':' [test] > subscript: '.' '.' '.' | test | [test] ':' [test] [sliceop] > testlist: test (',' test)* [','] > The simplification of the grammar is explicitly documented: """ Rather than further complicating the syntax, this is disambiguated by defining that in this case the interpretation as a subscription takes priority over the interpretation as a slicing (this is the case if the slice list contains no proper slice nor ellipses). Similarly, when the slice list has exactly one short slice and no trailing comma, the interpretation as a simple slicing takes priority over that as an extended slicing. """ > Clearly, the grammar rule used for list subscript is different from the > one used for list of expressions (for some reason, what an ordinary > person would call an expression is called a "test" in the grammar, > whereas "expr" is a non-short-circuiting expression). > > So there's a regular way to create non-empty tuples, and a subscript > way. > > And there's a regular way to create an empty tuple... but not a > subscript way. > > So I'd say this change fits the conceptual framework of the tuple quite > well; in fact, it makes subscript tuples more parallel to their regular > counterparts. > Although this debate is beginning to make me sound like one, I am really not a language lawyer. However, I should point out that what you are describing as a "tuple" should more correctly be described as a "slice-list" once you include slices or an ellipsis as elements. Slicings are described, as I am fairly sure you know, in section 5.3.3. > >>One further point: if you really do conceptualize scalars as >>zero-dimensional arrays, where is the value conceptually stored? > > > Think of it this way: an array with n-dimensions of length 3 would have > 3**n total entries. How many entries would a 0-dimensional array have? > 3**0 == 1. > > Numeric has had zero-dimensional arrays for a long time, and has had no > problem storing them. Think of the rule for accessing an element of an > array: it's a base pointer + sum (indices*stride) for all indices. Now > generalize it down to zero: there are no indices, so the scalar is > stored at the base pointer. > I can see that, and it doesn't seem unreasonable. Fortunately your persistence has goaded me into determining the point that *did* seem unreasonable to me: you were falsely trying to equate slicings and tuples. Having said all of which, there probably *is* a case for proposing that an empty slicing become syntactically acceptable, so why not write the PEP and go for it? But be quick: feature freeze for 2.5b1 looms ... regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From lrahuel.notgood at voila.fr Mon Jun 26 05:38:43 2006 From: lrahuel.notgood at voila.fr (Laurent Rahuel) Date: Mon, 26 Jun 2006 11:38:43 +0200 Subject: style question References: Message-ID: <449fab15$0$870$ba4acef3@news.orange.fr> Hari Sekhon wrote: > Is it better to do: > > message = """This is line1. > This is line2 > This is line3\n""" > > or > > message = "This is line1.\n > message = message + "This is line2\n" > message = message + "This is line3\n" > > > Since the first method does not follow python's clean and easy looking > indentation structure but the second just looks crude and ugly anyway. > > If I indent the first version so the text is lined up to match code > indentation then this comes out in the input and isn't aligned there. Hi, msgs = ['This is line1.','This is line2.','This is line3.'] message = '\n'.join(msgs) Regards, Laurent. From lopez.carlos at adelphia.net Mon Jun 5 23:55:05 2006 From: lopez.carlos at adelphia.net (Carlos Lopez) Date: Mon, 5 Jun 2006 23:55:05 -0400 Subject: OT: unix newbie questions Message-ID: <20060606035507.XHEA21801.mta9.adelphia.net@AT119L38513> Please help i am losing my mind ... UNIX Newbee 23. How do you add a line to the end of an existing file "myfile" with date stamp. (1) Ans : /home/clopez ed test.txt $a The last line of text. . w q 24. Display recent 10 java files, (with *.java extension) , in descending order by time, latest to oldest time. (1) Ans : 25. How do you set only read permissions to user, group and others in octal mode for a file "myfile.txt" ? (2) Ans: 26. You observed that some of your group members are fiddling with your file "myfile" and you wanted to remove the read permission to your group. How do you do? (1) Ans: 28. Here is another long listing of a file. (1) -rw-r----- 1 Y435678 odms 20 Sep 02 17:03 file.txt. What are the owner permissions? read, execute read, write write, execute all since s/he is the owner Ans: 29. The file "users_data" has the following contents : (1) Tom Smith 7.00 15 105.00 Rob Sheryl 8.00 20 160.00 Ken Bradman 7.00 13 91.00 Peter Smith 6.00 15 90.00 Dennis Smith 8.00 13 104.00 Tom Dave 9.00 12 108.00 How do you sort the above file and redirect the output to another file called "sortedusers" Ans : 20. What is the command to list files in a directory : (2) A. Having only three alphabets: Ans: B. Starting with a digit and ending with a digit Ans: Carlos Lopez Computer Tech phone: (440)396-7474 email: lopez.carlos at adelphia.net -------------- next part -------------- An HTML attachment was scrubbed... URL: From nmm1 at cus.cam.ac.uk Thu Jun 15 10:32:17 2006 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 15 Jun 2006 14:32:17 GMT Subject: Numerics, NaNs, IEEE 754 and C99 References: <1150379424.085598.4130@u72g2000cwu.googlegroups.com> Message-ID: In article <1150379424.085598.4130 at u72g2000cwu.googlegroups.com>, "rainbow.cougar at gmail.com" writes: |> |> As one of the few people on this group who will admit to programming |> before 1980, let alone doing numerical programming then (I presume |> writing code to process gigabytes of seismic data via Fast Fourier |> equations meet your criteria), the only semantics that existed then |> were for the program to *CRASH* hard when a singularity or undefined |> state occurred. When using the various flavors of FORTRAN and vector |> processors the undefined states could take a few microseconds to |> manifest, but crash and burn they would, with some difficulty to |> analyze the burning wreckage. Yes, it does, but I had used some dozens of systems, Fortrans and other languages by then. I did not make myself entirely clear, which partly accounts for your response, but I am afraid that you are mistaken. What I was referring to was that the consensus was that it was a program error to calculate a value at a singularity or otherwise when the result was mathematically undefined. Yes, the languages specified that to be undefined behaviour (and usually still do), but it was clear that a good implementation was ALOLOWED to trap and diagnose the failures. Many did and some still do - Python is pretty good, but not in this area. Examples of numerically near-bulletproof compilers included Egtran, XFAT (if I recall after 35+ years), WATFIV, Delft Algol, SPITBOL, FLACC and many others (and some in the 1980s, too). MOST of the better Fortran run-time systems (even IBM's Mod II library) used to detect and flag invalid arguments to library routines. ==>> Why should Python regard that, provably achievable, level of robustness as positevely undesirable? |> C is not a mathematically based language as FORTRAN is, so it is funny |> to criticize it for being what it never was, however IEEE754 and NaN's |> and the other standardizations put into place make back analyzing what |> is wrong with your program and/or data far easier then what we had |> before. As someone who has done it more-or-less continually since the 1960s, I am afraid that is not so. Yes, NaNs COULD do that, if the (fixable) flaws in IEEE 754 were sorted out, but Java and C99 have picked up on the flaws and used them as justification for ignoring 90% of the principles of IEEE 754. ==>> But the flaws in those are not the point here. I am asking whether people would positively OBJECT (as the did in C99) to errors being detected, possibly as an overridable option. Regards, Nick Maclaren. From fredrik at pythonware.com Tue Jun 6 02:46:32 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 06 Jun 2006 08:46:32 +0200 Subject: Python.h In-Reply-To: <1149575387.027832.115870@i39g2000cwa.googlegroups.com> References: <1149575387.027832.115870@i39g2000cwa.googlegroups.com> Message-ID: praveenkumar.117 at gmail.com wrote: > I am running python to c converter application. It throws an > error saying python.h file not found. > Can somebody plz suggest how to resolve this problem. you need the python build files. if you're using Linux, look for something named python-dev or python-devel in your favourite package repository. From alet at librelogiciel.com Fri Jun 2 17:23:53 2006 From: alet at librelogiciel.com (Jerome Alet) Date: Fri, 02 Jun 2006 23:23:53 +0200 Subject: [ANN] pkipplib v0.04 is out Message-ID: Hi there, I'm pleased to announce pkipplib v0.04 This GPLed Python library allows you to create, manage or parse IPP (Internet Printing Protocol) requests. In addition, it exposes a CUPS() class which allows one to interact with a CUPS print server (or an IPP printer). Written in pure Python, there's no need to link with the CUPS' libraries, and it doesn't even require any CUPS related software to work. The mid to long term goal is to support all of the CUPS' IPP API. Summary of changes : - Support for HTTP Basic authentication when connecting to a CUPS server was added. - General reliability was improved. To learn more about it, see examples of use, or download it : http://www.pykota.com/software/pkipplib/ Thank you for reading. Jerome Alet From mdudley at king-cart.com Sun Jun 4 19:36:49 2006 From: mdudley at king-cart.com (Marshall Dudley) Date: Sun, 04 Jun 2006 19:36:49 -0400 Subject: Installation Problem References: <44830900.155C7297@king-cart.com> <44831694.A022913A@king-cart.com> Message-ID: <44836E91.7F640B4@king-cart.com> Warren Block wrote: > Marshall Dudley wrote: > > Sorry, this is a FreeBSD system 4.8-RELEASE > > > > I found another set of documents that say to use the following to > > install:: > > > > python setup.py install > > > > but after running it, I still have the same problem. > > [top-posting trimmed, please don't do that] > > Doesn't the port work for 4.8? It does work on FreeBSD 4.11, but there > may have been changes to the ports system since 4.8. (You should > consider updating to 4.11.) > > There are several patch files in the FreeBSD port, including > one to setup.py. > > The easiest way is to cvsup your ports tree and then > > cd /usr/ports/lang/python > make > make install > make clean > > -- > Warren Block * Rapid City, South Dakota * USA Now I have a python that runs, but the application I want to run it on "denyhosts" gives me the following error: Python >= 2.3 required. You are using: 2.2.2 (#1, Jun 4 2006, 16:29:13) [GCC 2.95.4 20020320 [FreeBSD]] ###################################################################### Visit http://www.python.org and download a more recent version of Python. You should install this version in addition to your current version (rather than upgrading your current version) because your system might depend on the current version. After installing the newer version, for instance version 2.4, simply invoke DenyHosts explicitly with the new version of python, eg: $ python2.4 ./denyhosts.py ###################################################################### Is it not possible to install the latest version of python on my FreeBSD system? Upgrading the FreeBSD is not an option since this is a production system and everything else is working fine. Marshall From fredrik at pythonware.com Mon Jun 12 01:45:36 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 12 Jun 2006 07:45:36 +0200 Subject: Screen Scraping for Modern Applications? In-Reply-To: <1150088989.408815.290690@c74g2000cwc.googlegroups.com> References: <1150077617.598735.85540@h76g2000cwa.googlegroups.com> <1150088989.408815.290690@c74g2000cwc.googlegroups.com> Message-ID: ljr2600 at gmail.com wrote: > Scrape means simply scraping pixel colors from locations on the screen. > I'll worry about assembling it into meaningful information. import ImageGrab im = ImageGrab.grab() v = im.getpixel((x, y)) requires: http://www.pythonware.com/products/pil/ From jstroud at ucla.edu Sun Jun 11 17:26:34 2006 From: jstroud at ucla.edu (James Stroud) Date: Sun, 11 Jun 2006 14:26:34 -0700 Subject: learning python idioms In-Reply-To: <1149998884.261678.299860@u72g2000cwu.googlegroups.com> References: <1149998884.261678.299860@u72g2000cwu.googlegroups.com> Message-ID: conkerll at gmail.com wrote: > After several years developing in Java, I've begun to switch to Python > for several of my new projects as I have found the language quite > interesting. I've read several tutorials and implemented a few sample > programs and I've found that Python enables one to program in a variety > of different styles (I'm not sure if this was the original intention or > not). Thus, I find myself occaisionally slipping into the "Java" > mindset when writing Python code and I wonder if this is not optimal. > Python is not Java and there must be more "correct" ways of doing this > in Python that simply writing Java code with different syntax. Is > there a good reference on the internet about Python-specific idioms and > just good Python style in general. Which language constructs are > efficient and which aren't? > > Thanks in advance, > Ben > As an experiment, I googled 'python idioms' and got a few good hits right at the top. I probably should have done this a long time ago. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From gene.tani at gmail.com Sat Jun 17 11:21:22 2006 From: gene.tani at gmail.com (gene tani) Date: 17 Jun 2006 08:21:22 -0700 Subject: any subway experiences In-Reply-To: <1150533811.911621.112430@y41g2000cwy.googlegroups.com> References: <1150533811.911621.112430@y41g2000cwy.googlegroups.com> Message-ID: <1150557682.055098.227840@i40g2000cwc.googlegroups.com> a wrote: > thanks for reading Yah, the mass transit systems are, um, challenging but workable in many US cities. Canada's much better BUT the Subway framework that's not developed anymore had a dev mailing list: http://groups.google.com/group/subway-devel Google for "subway web framework". And, yeah, read http://catb.org/~esr/faqs/smart-questions.html From grante at visi.com Thu Jun 1 16:04:33 2006 From: grante at visi.com (Grant Edwards) Date: Thu, 01 Jun 2006 20:04:33 -0000 Subject: integer to binary... References: <1149189570.376091.319890@j55g2000cwa.googlegroups.com> <127ugf9jgu7av18@corp.supernews.com> <1149190940.548582.27200@h76g2000cwa.googlegroups.com> <1149191782.973045.215080@g10g2000cwb.googlegroups.com> Message-ID: <127ui2hq44ki846@corp.supernews.com> On 2006-06-01, nicolasg at gmail.com wrote: >>>> does anyone know a module or something to convert numbers like integer >>>> to binary format ? >>> >>> They _are_ in binary format. >>> >>>> for example I want to convert number 7 to 0111 so I can make >>>> some bitwise operations... >>> >>> Just do it: >>> >>> >>> 7 & 3 >>> 3 >>> >>> 7 | 8 >>> 15 >> > this is exactly what I need -> http://www.daniweb.com/code/snippet285.html That's nice, but I don't register at web sites like that. >> I know I can do that but I need to operate in every bit >> separeted. I still don't get what you want a binary string for. I can see wanting a sequence (e.g. array) of boolean values, but how are you going to do bitwise operations on a binary string? -- Grant Edwards grante Yow! .. I think I'd at better go back to my DESK visi.com and toy with a few common MISAPPREHENSIONS... From deets at nospam.web.de Mon Jun 12 05:37:03 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 12 Jun 2006 11:37:03 +0200 Subject: Using PHP in Python References: <1150104925.811155.3550@y43g2000cwc.googlegroups.com> Message-ID: <4f4qvbF1hjj7tU1@uni-berlin.de> Tgone wrote: > Hello, > > I've come across sites that discuss embedding Python in PHP, but is it > possible to access PHP functions in Python? I'm not aware of a generic wrapper thingy. Which doesn't mean there is none. But which functions are you interested in? I can't believe there is much that PHP can do that python _can't_ do, so maybe we can point you in the right direction. Diez From onurb at xiludom.gro Tue Jun 20 07:15:58 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 20 Jun 2006 13:15:58 +0200 Subject: Specifing arguments type for a function In-Reply-To: References: <4fq09iF1k0h0eU1@uni-berlin.de> Message-ID: <4497d8ef$0$29790$626a54ce@news.free.fr> Rony Steelandt wrote: >> Paolo Pantaleo wrote: >> >>> I have a function >>> >>> def f(the_arg): >>> ... >>> >>> and I want to state that the_arg must be only of a certain type >>> (actually a list). Is there a way to do that? >> >> >> Yes and no. You can ensure that the passed object is a list, by >> calling e.g. >> >> def f(arg): >> if not isinstance(arg, list): >> raise "Not a list!" >> >> >> Alternatively, you can just use it as an iterable - and the exception >> will >> come from arg not being iterable. >> >> But what you can't do is make python complain about this: >> >> def f(arg): >> for e in arg: >> print e >> >> >> f(100) >> >> before actually calling f. It will always fail at runtime. >> >> Diez > > > What about > def f(arg): > if type(arg)=='list': FWIW, type() returns a type object, not a string. So your test will always fail. A right way to write this is: if type(arg) is type([]): ... > #do something Usually a very bad idea. It defeats the whole point of duck-typing. In most cases, you don't care about the concrete class - all you want is an object that implements an (implied) interface. NB : I say 'usually' because there are a very few cases where testing the concrete class can make sens - but there again, better to use isinstance() than type(). -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From onurb at xiludom.gro Thu Jun 1 07:49:18 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 01 Jun 2006 13:49:18 +0200 Subject: How do you practice Python? In-Reply-To: <1149152214.215907.31800@i39g2000cwa.googlegroups.com> References: <1149150517.034409.292530@g10g2000cwb.googlegroups.com> <447eaae0$0$20867$636a55ce@news.free.fr> <1149152214.215907.31800@i39g2000cwa.googlegroups.com> Message-ID: <447ed4b1$0$20866$626a54ce@news.free.fr> Ray wrote: > bruno at modulix wrote: > >>>In our field, we don't always get to program in the language we'd like >>>to program. So... how do you practice Python in this case? Say you're >>>doing J2EE right now. >> >>Hopefully not ! > > > I am :-( > Can we do something to help you out of this bad situation ? (sorry...) >>>How do you practice Python to keep your skills >>>sharp? >> >>How *would* I do ? Well, perhaps I'd use Jython ? > > > Um, I mean, what if you have to use something other than > Python/Jython/IronPython? :) Ruby or Smalltalk, then ? No ? J2EE ? Argh ! (me run away) > How do you keep your Python skill sharp? Just by thinking about how I would solve the problem at hand in Python - and then cry :( -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From eval.apply at gmail.com Tue Jun 27 12:22:30 2006 From: eval.apply at gmail.com (Joe Marshall) Date: 27 Jun 2006 09:22:30 -0700 Subject: What is Expressiveness in a Computer Language In-Reply-To: <1151384511.223582.305760@m73g2000cwd.googlegroups.com> References: <1150765102.867144.12590@h76g2000cwa.googlegroups.com> <7MFmg.27168$VE1.8188@newssvr14.news.prodigy.com> <1151384511.223582.305760@m73g2000cwd.googlegroups.com> Message-ID: <1151425350.679754.278820@i40g2000cwc.googlegroups.com> Marshall wrote: > > Yes, an important question (IMHO the *more* important question > than the terminology) is what *programs* do we give up if we > wish to use static typing? I have never been able to pin this > one down at all. It would depend on the type system, naturally. It isn't clear to me which programs we would have to give up, either. I don't have much experience in sophisticated typed languages. It is rather easy to find programs that baffle an unsophisticated typed language (C, C++, Java, etc.). Looking back in comp.lang.lisp, I see these examples: (defun noisy-apply (f arglist) (format t "I am now about to apply ~s to ~s" f arglist) (apply f arglist)) (defun blackhole (argument) (declare (ignore argument)) #'blackhole) But wait a sec. It seems that these were examples I invented in response to the same question from you! > > The real question is, are there some programs that we > can't write *at all* in a statically typed language, because > they'll *never* be typable? Certainly! As soon as you can reflect on the type system you can construct programs that type-check iff they fail to type-check. > > Perhaps, there is no such beast. Or, perhaps I just can't formulate > > it. Or, perhaps we have static type checkers which can do > > computations of unbounded complexity. However, I thought that one of > > the characteristics of type systems was that they did not allow > > unbounded complexity and weren't Turing Complete. > > The C++ type system is Turing complete, although in practical terms > it limits how much processing power it will spend on types at > compile time. I think templates only have to expand to seven levels, so you are severely limited here. > > If you allow Turing Complete type systems, then I would say no--every > > bug can be reforumlated as a type error. If you require your type > > system to be less powerful, then some bugs must escape it. > > I don't think so. Even with a Turing complete type system, a program's > runtime behavior is still something different from its static behavior. > (This is the other side of the "types are not tags" issue--not only > is it the case that there are things static types can do that tags > can't, it is also the case that there are things tags can do that > static types can't.) I agree. The point of static checking is to *not* run the program. If the type system gets too complicated, it may be a de-facto interpreter. From serge.orlov at gmail.com Fri Jun 23 21:54:17 2006 From: serge.orlov at gmail.com (Serge Orlov) Date: Fri, 23 Jun 2006 18:54:17 -0700 Subject: PEP 314 - requirements for Python itself In-Reply-To: <8421BEBC-2446-4129-9607-DF8EE8CDEA3A@mnot.net> References: <8421BEBC-2446-4129-9607-DF8EE8CDEA3A@mnot.net> Message-ID: On 6/23/06, Mark Nottingham wrote: > I was thinking more about things where people can search for packages > that need different versions of python, etc.; not so much for > automation. OK, now I see why you need it. I'm sure using virtual package name "python" to declare python dependence is logical and non-controversial, so you can write to python-dev asking for PEP 314 addendum, I just wanted say that nobody is checking it right now and *right now* run-time checking is the way to go. From steven.bethard at gmail.com Mon Jun 19 12:56:34 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 19 Jun 2006 10:56:34 -0600 Subject: Formatted string to object In-Reply-To: <1150731552.799052.47320@r2g2000cwb.googlegroups.com> References: <1150731552.799052.47320@r2g2000cwb.googlegroups.com> Message-ID: <_YKdnZe-I7zdSgvZnZ2dnUVZ_oednZ2d@comcast.com> janama wrote: > can such a thing be done somehow? > > aaa = self.aaa > bbb = %s.%s % ('parent', 'bbb') > > Can you use strings or %s strings like in the above or > > aaa = 'string' > aaa.%s() % 'upper' Use the getattr() function:: >>> class parent(object): ... class bbb(object): ... pass ... >>> module_ns = __import__(__name__) >>> getattr(getattr(module_ns, 'parent'), 'bbb') >>> import string >>> getattr(getattr(module_ns, 'string'), 'upper') I've imported the module itself here so you can use getattr, but you could also use globals() instead of the inner getattr() call:: >>> getattr(globals()['parent'], 'bbb') >>> getattr(globals()['string'], 'upper') HTH, STeVe From fredrik at pythonware.com Wed Jun 28 11:45:11 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 28 Jun 2006 17:45:11 +0200 Subject: String Question References: <1151508909.273667.270910@x69g2000cwx.googlegroups.com> Message-ID: diffuser78 at gmail.com wrote: > mac_string = '001485e55503' (This is the mac address of a computer.) > > I am using wake on LAN python script to start computer remote.It uses > format like this .... > > s.sendto('\xff'*6 + '\x00\x014\x85\xe5\x55\x03'*16, ('192.168.1.255', > 80)) > > where '\x00\x14\x85\xe5\x55\x03' is the MAC address to be used. s.sendto('\xff'*6 + binascii.unhexlify(mac_string) *16, ('192.168.1.255', 80)) From webraviteja at gmail.com Mon Jun 19 17:39:50 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 19 Jun 2006 14:39:50 -0700 Subject: code is data In-Reply-To: <1150734374.361606.159150@h76g2000cwa.googlegroups.com> References: <1150574111.415068.255900@p79g2000cwp.googlegroups.com> <1150734374.361606.159150@h76g2000cwa.googlegroups.com> Message-ID: <1150753190.645151.25350@r2g2000cwb.googlegroups.com> Kay Schluehr wrote: > Ravi Teja wrote: > > > People have however written various language interpreters (Scheme, > > Forth and yes, even Basic) in Python, just for kicks. Still does not > > make it a DSL language anymore than it makes C a DSL language. > > > > At present, the closest thing to writing a DSL in Python is Logix > > http://livelogix.net/logix/ > > Too bad though, the project is defunct and there has never been enough > > interest in it. > > You might be interested in EasyExtend: > > http://www.fiber-space.de/EasyExtend/doc/EE.html Your framework does look very interesting and might just be what I am looking for. Will give it a try. Thanks. From grahamd at dscpl.com.au Fri Jun 30 00:43:28 2006 From: grahamd at dscpl.com.au (grahamd at dscpl.com.au) Date: 29 Jun 2006 21:43:28 -0700 Subject: Event notification system - where to start ? References: <1151589497.327662.115100@p79g2000cwp.googlegroups.com> Message-ID: <1151642608.455760.73830@x69g2000cwx.googlegroups.com> geskerrett at hotmail.com wrote: > We have been asked to develop and application for a client that is a > 'notification" system. We would like to use python, but are struggling > to find the right starting point. Any suggestions, tips or sample code > would be appreciated. > > Application outline; > > Machine A is running a "listener" application that is connected to a > another device via the serial post and waits for events. We have not > problem working with the serial port, or the waiting for the event to > happen. > > When A received a specific event, it needs to send a message to machine > B that and event has occurred and that type of event. > > Machine B will take the event notification, processes some additional > information (ie. database lookups) and then notify a series of clients > that have "registered" with machine B to receive events. > > I think this is sometimes called "published/subscriber" ??? This is exactly the sort of thing that OSE is purpose built for. See recipe from Python Cookbook online at: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81614 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81615 OSE can be obtained from: http://ose.sourceforge.net The documentation for the Python wrappers for OSE can be found at: http://ose.sourceforge.net/browse.php?group=python-manual&entry=manual.htm Graham From gandalf at designaproduct.biz Thu Jun 8 11:56:36 2006 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Thu, 08 Jun 2006 17:56:36 +0200 Subject: simplexmlrpcserver and allow_none In-Reply-To: References: Message-ID: <448848B4.3020109@designaproduct.biz> Thomas Bellman ?rta: > Laszlo Nagy wrote: > > >> I ran in the same problem again. Many others have the same problem. Just >> Google for this: "SimpleXMLRPCServer allow_none site:python.org". >> Looks like the 'allow_none' patch was commited to trunk on 2005 Dec ( >> http://mail.python.org/pipermail/python-checkins/2005-December/048289.html ) >> > > >> I just upgraded to Python 2.4.3 (it was released on March 29, 2006) and >> SimpleXMLRPCServer.py still has the old code. >> I can work around this by coping the whole file into a new file and >> patch it, but I hate to do that. >> I wonder why it has not been commited to the standard library yet. Does >> anyone know if it will be in the next bugfix release? >> > > Fredrik has already answered your specific question, but while > waiting for 2.5, another way to work around it is to do: > > import xmlrpclib > # WARNING: Dirty hack below. > # Replace the dumps() function in xmlrpclib with one that by default > # handles None, so SimpleXMLRPCServer can return None. > class _xmldumps(object): > def __init__(self, dumps): > self.__dumps = (dumps,) > def __call__(self, *args, **kwargs): > kwargs.setdefault('allow_none', 1) > return self.__dumps[0](*args, **kwargs) > xmlrpclib.dumps = _xmldumps(xmlrpclib.dumps) > > import SimpleXMLRPCServer > Thank you. :-) I already copied out SimpleXMLRPCServer.py from the 2.5 trunk and it seems to be working, but this is much sorter. Laszlo From scruffy.mogwai at gmail.com Thu Jun 8 23:42:00 2006 From: scruffy.mogwai at gmail.com (scruffy.mogwai at gmail.com) Date: 8 Jun 2006 20:42:00 -0700 Subject: what does %u mean? In-Reply-To: <1149823453.947116.200500@y43g2000cwc.googlegroups.com> References: <1149823453.947116.200500@y43g2000cwc.googlegroups.com> Message-ID: <1149824520.553473.189380@u72g2000cwu.googlegroups.com> I'm not sure, but I think it has something to do with unicode. print "%i" % 1 // Prints the integer 1 as a string. print "%u" % (-5) // Prints -5 as a unicode string??? yaru22 wrote: > Hi. I just started learning python. > > In the exercise in my book, it asks me to try print "%u" % (-5) > > I'm wondering what this %u mean? > > Thank you. > > Regards, > > Brian. From kay.schluehr at gmx.net Tue Jun 6 11:35:19 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 6 Jun 2006 08:35:19 -0700 Subject: calling functions style question In-Reply-To: <1149607410.719487.213110@h76g2000cwa.googlegroups.com> References: <1149607410.719487.213110@h76g2000cwa.googlegroups.com> Message-ID: <1149608119.839740.41380@j55g2000cwa.googlegroups.com> Brian wrote: > I just have a basic style question here. Suppose you have the program: > > def foo1(): > do something > > def foo2() > do something else > > Assume that you want to call these functions at execution. Is it more > proper to call them directly like: > > foo1() > foo2() > > or in an if __name__ == "__main__": ? > > Both will execute when the script is called directly, I was just > wondering if there is a preference, and what the pros and cons to each > method were. > > Thanks, > Brian If you want those functions to be called each time your module gets imported you have to apply calls out of the "if __name__ ..." statement. If your module is, for certain reasons, always the __main__ module and never gets imported there is no obvious preference because behaviour will be the same. From rogue_pedro at yahoo.com Sun Jun 25 12:35:25 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 25 Jun 2006 09:35:25 -0700 Subject: HTTP server References: <1151134073.393065.187500@c74g2000cwc.googlegroups.com> <1151162732.819264.190560@i40g2000cwc.googlegroups.com> <1151241369.138325.173690@r2g2000cwb.googlegroups.com> Message-ID: <1151253325.924054.95100@c74g2000cwc.googlegroups.com> placid wrote: > Simon Forman wrote: > > ... > > For what you're asking about you'd probably want to use the > > CGIHTTPRequestHandler from the CGIHTTPServer module instead. Check out > > http://docs.python.org/lib/module-CGIHTTPServer.html > > This is what i was after, thanks for the tip. > You're welcome, my pleasure. : ) ... > > Im having trouble running the following cgi script on windows > > > > #!c:/Python/python.exe -u > > text = """Content-type: text/html > > CGI 101 >

\n
\n") length = f.tell() f.seek(0) self.send_response(200) self.send_header("Content-type", "text/html") self.send_header("Content-Length", str(length)) self.end_headers() return f