Re: dictionary of dictionaries
On Dec 10, 6:58 pm, Peter Otten <[EMAIL PROTECTED]> wrote: > kettle wrote: > > On Dec 9, 5:49 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote: > >> On Sun, 09 Dec 2007 00:35:18 -0800, kettle wrote: > >> > Hi, > >> > I'm wondering what the best practice is for creating an extensible > >> > dictionary-of-dictionaries in python? > > >> > In perl I would just do something like: > > >> > my %hash_of_hashes; > >> > for(my $i=0;$i<10;$i++){ > >> > for(my $j=0;$j<10;$j++){ > >> >${$hash_of_hashes{$i}}{$j} = int(rand(10)); > >> > } > >> > } > > >> > but it seems to be more hassle to replicate this in python. I've > >> > found a couple of references around the web but they seem cumbersome. > >> > I'd like something compact. > > >> Use `collections.defaultdict`: > > >> from collections import defaultdict > >> from random import randint > > >> data = defaultdict(dict) > >> for i in xrange(11): > >> for j in xrange(11): > >> data[i][j] = randint(0, 10) > > >> If the keys `i` and `j` are not "independent" you might use a "flat" > >> dictionary with a tuple of both as keys: > > >> data = dict(((i, j), randint(0, 10)) for i in xrange(11) for j in > >> xrange(11)) > > >> And just for completeness: The given data in the example can be stored in a > >> list of lists of course: > > >> data = [[randint(0, 10) for dummy in xrange(11)] for dummy in xrange(11)] > > >> Ciao, > >> Marc 'BlackJack' Rintsch > > > Thanks for the heads up. Indeed it's just as nice as perl. One more > > question though, this defaultdict seems to only work with python2.5+ > > in the case of python < 2.5 it seems I have to do something like: > > #!/usr/bin/python > > from random import randint > > > dict_dict = {} > > for x in xrange(10): > > for y in xrange(10): > > r = randint(0,10) > > try: > > dict_dict[x][y] = r > > except: > > if x in dict_dict: > > dict_dict[x][y] = r > > else: > > dict_dict[x] = {} > > dict_dict[x][y] = r > > You can clean that up a bit: > > from random import randrange > > dict_dict = {} > for x in xrange(10): > dict_dict[x] = dict((y, randrange(11)) for y in xrange(10)) > > > > > what I really want to / need to be able to do is autoincrement the > > values when I hit another word. Again in perl I'd just do something > > like: > > > my %my_hash; > > while(){ > > chomp; > > @_ = split(/\s+/); > > grep{$my_hash{$_}++} @_; > > } > > > and this generalizes transparently to a hash of hashes or hash of a > > hash of hashes etc. In python < 2.5 this seems to require something > > like: > > > for line in file: > > words = line.split() > > for word in words: > > my_dict[word] = 1 + my_dict.get(word, 0) > > > which I guess I can generalize to a dict of dicts but it seems it will > > require more if/else statements to check whether or not the higher- > > level keys exist. I guess the real answer is that I should just > > migrate to python2.5...! > > Well, there's also dict.setdefault() > > >>> pairs = ["ab", "ab", "ac", "bc"] > >>> outer = {} > >>> for a, b in pairs: > > ... inner = outer.setdefault(a, {}) > ... inner[b] = inner.get(b, 0) + 1 > ...>>> outer > > {'a': {'c': 1, 'b': 2}, 'b': {'c': 1}} > > and it's not hard to write your own defaultdict > > >>> class Dict(dict): > > ... def __getitem__(self, key): > ... return self.get(key, 0) > ...>>> d = Dict() > >>> for c in "abbbcdeafgh": d[c] += 1 > ... > >>> d > > {'a': 2, 'c': 1, 'b': 3, 'e': 1, 'd': 1, 'g': 1, 'f': 1, 'h': 1} > > Peter One last question. I've heard the 'Explicit vs. Implicit' argument but this seems to boil down to a question of general usage case scenarios and what most people 'expect' for default behavior. The above defaultdict implementation defining the __getitem__ method seems like it is more generally useful than the real default. What is the reasoning behind NOT using this as the default implementation for a dict in python? -- http://mail.python.org/mailman/listinfo/python-list
Re: dictionary of dictionaries
On Dec 10, 6:58 pm, Peter Otten <[EMAIL PROTECTED]> wrote: > kettle wrote: > > On Dec 9, 5:49 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote: > >> On Sun, 09 Dec 2007 00:35:18 -0800, kettle wrote: > >> > Hi, > >> > I'm wondering what the best practice is for creating an extensible > >> > dictionary-of-dictionaries in python? > > >> > In perl I would just do something like: > > >> > my %hash_of_hashes; > >> > for(my $i=0;$i<10;$i++){ > >> > for(my $j=0;$j<10;$j++){ > >> >${$hash_of_hashes{$i}}{$j} = int(rand(10)); > >> > } > >> > } > > >> > but it seems to be more hassle to replicate this in python. I've > >> > found a couple of references around the web but they seem cumbersome. > >> > I'd like something compact. > > >> Use `collections.defaultdict`: > > >> from collections import defaultdict > >> from random import randint > > >> data = defaultdict(dict) > >> for i in xrange(11): > >> for j in xrange(11): > >> data[i][j] = randint(0, 10) > > >> If the keys `i` and `j` are not "independent" you might use a "flat" > >> dictionary with a tuple of both as keys: > > >> data = dict(((i, j), randint(0, 10)) for i in xrange(11) for j in > >> xrange(11)) > > >> And just for completeness: The given data in the example can be stored in a > >> list of lists of course: > > >> data = [[randint(0, 10) for dummy in xrange(11)] for dummy in xrange(11)] > > >> Ciao, > >> Marc 'BlackJack' Rintsch > > > Thanks for the heads up. Indeed it's just as nice as perl. One more > > question though, this defaultdict seems to only work with python2.5+ > > in the case of python < 2.5 it seems I have to do something like: > > #!/usr/bin/python > > from random import randint > > > dict_dict = {} > > for x in xrange(10): > > for y in xrange(10): > > r = randint(0,10) > > try: > > dict_dict[x][y] = r > > except: > > if x in dict_dict: > > dict_dict[x][y] = r > > else: > > dict_dict[x] = {} > > dict_dict[x][y] = r > > You can clean that up a bit: > > from random import randrange > > dict_dict = {} > for x in xrange(10): > dict_dict[x] = dict((y, randrange(11)) for y in xrange(10)) > > > > > what I really want to / need to be able to do is autoincrement the > > values when I hit another word. Again in perl I'd just do something > > like: > > > my %my_hash; > > while(){ > > chomp; > > @_ = split(/\s+/); > > grep{$my_hash{$_}++} @_; > > } > > > and this generalizes transparently to a hash of hashes or hash of a > > hash of hashes etc. In python < 2.5 this seems to require something > > like: > > > for line in file: > > words = line.split() > > for word in words: > > my_dict[word] = 1 + my_dict.get(word, 0) > > > which I guess I can generalize to a dict of dicts but it seems it will > > require more if/else statements to check whether or not the higher- > > level keys exist. I guess the real answer is that I should just > > migrate to python2.5...! > > Well, there's also dict.setdefault() > > >>> pairs = ["ab", "ab", "ac", "bc"] > >>> outer = {} > >>> for a, b in pairs: > > ... inner = outer.setdefault(a, {}) > ... inner[b] = inner.get(b, 0) + 1 > ...>>> outer > > {'a': {'c': 1, 'b': 2}, 'b': {'c': 1}} > > and it's not hard to write your own defaultdict > > >>> class Dict(dict): > > ... def __getitem__(self, key): > ... return self.get(key, 0) > ...>>> d = Dict() > >>> for c in "abbbcdeafgh": d[c] += 1 > ... > >>> d > > {'a': 2, 'c': 1, 'b': 3, 'e': 1, 'd': 1, 'g': 1, 'f': 1, 'h': 1} > > Peter Nice, thanks for all the tips! I knew there had to be some handier python ways to do these things. My initial attempts were just what occurred to me first given my still limited knowledge of the language and its idioms. Thanks again! -joe -- http://mail.python.org/mailman/listinfo/python-list
Re: Serializing Python compiled code.
[EMAIL PROTECTED] wrote: > >In a C++ application having a Python interpreter embedded, is it >possible to compile a small Python snippet into object code and >serialize the compiled object code to, for example, a database? I am >exploring the possibility of writing a data driven application, where >small-sized object code can be read from a database and executed. >Keeping aside all other considerations such as security, etc for a >moment, is this feasible? The biggest problem, in my view, is that the compiled object code won't work with any other version of Python, or with versions where the compiler was built with other options, or possibly even on other processors with the same version. The nice thing about a database server is that you can use it from different computers without worrying about versions or processors. Compilation is not that expensive. Why not just store the raw code snippets? -- Tim Roberts, [EMAIL PROTECTED] Providenza & Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is a "real" C-Python possible?
> We obviously need more effort to make Python more efficient for CPU > bound tasks. Particularly JIT compilation like Java, compilation like > Lisp or data specialization like Psyco. Given that the Python core team has been mostly silent about JIT compilation and Armin Rigos work in particular which started 5 years ago ( Psyco will not be promoted towards Python 3.0 and there is no indication that anyone but Armin would maintain Psyco ) I wonder about this sudden insight. But maybe you can tell us more when you work on such stuff for CPython yourself? Given your status in the core Python team this would have a chance of not being just a loosely coupled independent project as almost all the interesting stuff that happens around Python these days. -- http://mail.python.org/mailman/listinfo/python-list
Re: Help needed with python unicode cgi-bin script
Just want to make sure, how exactly are you doing that? > Thanks for the reply, Jack. I tried setting mode to binary but it had no > affect. -- http://mail.python.org/mailman/listinfo/python-list
Web page from hell breaks BeautifulSoup, almost
This web page: http://azultralights.com/ulclass.html parses OK with BeautifulSoup, but "prettify" will hit the recursion limit if you try to display it. I raised the recursion limit to a large number, and it was converted to 5MB of text successfully, in about a minute. The page has real problems. 1901 errors from the W3C validator, and that's after forcing an encoding and a doctype. "body" tags nested 3 deep. "head" element inside two "body" tags. Tags opened with an upper case tag and closed with a lower case tag. All "font" tags unclosed. Hundreds of "li" tags outside a "ol" or "ul". Yet Firefox is quite happy to display it. It looks even better in IE, according to comments on the page. The page consists of a long list of classified ads, all with unclosed tags. So the maximum depth is huge. Worst HTML I've seen in a while. (We use BeautifulSoup to parse hostile web sites in bulk, so we tend to discover more hard cases than most users.) John Nagle SiteTruth -- http://mail.python.org/mailman/listinfo/python-list
Re: Best way to protect my new commercial software.
> > 1. Put all the compiled Python bytecode in a heavily encrypted binary > file. Consider using a hardware hash in the key. > > 2. Program a small binary executable (.exe file) in C or C++ that: > > 2a. Reads the binary file. > > 2b. Decrypts it to conventional Python byte code. > > 2c. Embeds a Python interpreter. > > 2d. Executes the bytecode with the embedded Python interpreter. > > 3. Protect the executable with a licence manager such as Flexlm or > SoftwarePassport. > > I will not make reverse engineering impossible, but it will be > extremely difficult. > > As noted, the only completely safe solution is to provide a web > application instead of distributing your program. > > > > -- > http://mail.python.org/mailman/listinfo/python-list > Guidelines are good. but as you stated, web application instead of desktop apps. Well, the main aim and interest here was to protect it against piracy and web application are easier to be get shared and pirated than desk apps. And there is no foolproof method known to me. Even Flexlm used in Acrobat(Adobe) is cracked in easy manner. The best thing to me looks like none. You can go with anything, and always fear that if the app is needed by many others, it will be cracked. Othewise, the method stated above is good to go. Get app core into python, encrypt-assemble the compiled python code with some key. When launched, get it reversed to python bytecode and there you go,. Now, since your apps loader is built in C, you can apply available methods for C/C++/ Remember, since python is readable easily, you fear so. But no language exists which humans can't read. At worst level, they will have to go for Assembly Level decompiling, but thats possible too -- -=Ravi=- -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie
On Dec 10, 8:03 pm, "Whizzer" <[EMAIL PROTECTED]> wrote: > Is OReilly's Learning Python a good place to start learning to program? > I've been told Python is a good first language. > > Thanks for the advice. If you already have Python installed,just go to the bottom of this article and check the various links and recommended books. Good luck. http://tinyurl.com/w7wgp rd -- http://mail.python.org/mailman/listinfo/python-list
Re: Job Offer: Python Ninja or Pirate!
On Mon, 10 Dec 2007 19:27:43 -0800, George Sakkis wrote: > On Dec 10, 2:11 pm, Stargaming <[EMAIL PROTECTED]> wrote: >> On Mon, 10 Dec 2007 16:10:16 +0200, Nikos Vergas wrote: >> >> [snip] >> >> >> Problem: In the dynamic language of your choice, write a short >> >> program that will: >> >> 1. define a list of the following user ids 42346, 77290, 729 (you >> >> can >> >> hardcode these, but it should >> >> still work with more or less ids) >> >> 2. retrieve an xml document related to each user at this url >> >> "http:// >> >> api.etsy.com/feeds/xml_user_details.php?id=" >> >> 3. retrieve the data contained in the city element from each xml >> >> document >> >> 4. keep a running total of how many users are found in each city 5. >> >> display the total count of users living in each city >> [snip] >> >> > i wanted to make it a one liner, but i had to import modules :( >> >> > import sys, xml, urllib >> >> > dummy = [sys.stdout.write(city + ': ' + str(num) + '\n') for city, >> > num in set([[(a, o.count(a)) for a in p] for o, p in [2*tuple([[city >> > for city in >> > ((xml.dom.minidom.parseString(urllib.urlopen('http://api.etsy.com/ feeds/ >> >> xml_user_details.php?id=' >> >> > + str(id)).read()).getElementsByTagName('city')[0].childNodes + >> > [(lambda t: (setattr(t, 'data', 'no city'), >> > t))(xml.dom.minidom.Text())[1]])[0].data.lower().replace(' ', ' ') >> > for id in [71234, 71234, 71234, 71234, 71234, 71234, >> > 42792])]])]][0])] >> >> I suggest `__import__` in such cases. >> >> Even though I do not qualify for the job, I came up with this () >> code (modified list values for demonstration, mixed together from >> previous post and original task): >> >> print '\n'.join('%s: %d'%(x,len(list(y))) for x,y in __import__ >> ('itertools').groupby(sorted(__import__('xml').dom.minidom.parse >> (__import__('urllib').urlopen('http://api.etsy.com/feeds/ >> xml_user_details.php?id=%d'%i)).getElementsByTagName('city') >> [0].lastChild.data.title() for i in (71234, 729, 42346, 77290, 729, >> 729 >> >> I still find this rather readable, though, and there is no bad side- >> effect magic! :-) >> >> Output should be: >> >> | Chicago: 3 >> | Fort Lauderdale: 1 >> | Jersey City And South Florida: 1 >> | New York: 1 > > Alas, it's not: > > AttributeError: 'module' object has no attribute 'dom' > > Here's a working version, optimized for char length (one line, 241 > chars): > > import urllib as U,elementtree.ElementTree as > E;c=[E.parse(U.urlopen('http://api.etsy.com/feeds/xml_user_details.php? > id=%d'%u)).findtext('//city')for u in > 71234,729,42346,77290,729,729];print'\n'.join('%s: %s'% > (i,c.count(i))for i in set(c)) > > George Heh, yes. I did the same error as the participant before me -- test it in a premodified environment. A fix is easy, __import__ 'xml.dom.minidom' instead of 'xml'. :-) ;-is-cheating'ly yours, -- http://mail.python.org/mailman/listinfo/python-list
Re: Any way to program custom syntax to python prompt? >> I want to edit matrices.
On Mon, 10 Dec 2007 16:54:08 -0800, mosi wrote: > Python matrices are usually defined with numpy scipy array or similar. > e.g. matrix1 = [[1, 2], [3, 4], [5, 6]] > I would like to have easier way of defining matrices, for example: matrix = [1, 2; 3, 4; 5, 6] > matrix = > [ 1, 2; > 3, 4; > 5, 6;] > > Any ideas how could this be done? The ";" sign is reserved, the "[ ]" is > used for lists. You could have some class `Matrix` with a constructor taking a string, as in ``Matrix("[1, 2; 3, 4; 5, 6]")``. A very naive parser could just strip trailing/leading brackets and all spaces, split on ';', split again on ',', done. > Also, how to program custom operations for this new "class?" matrix ??? > > For example: matrix + 2 > [ 3, 4; > 5, 6; > 7, 8;] > > Possibly with operator overloading? Yes, by simply overloading __add__ et al. See http://docs.python.org/ref/ specialnames.html for details (certainly, "Emulating numeric types" should be interesting to you). > I appreciate all your comments, directions, pointers. mosi Cheers, -- http://mail.python.org/mailman/listinfo/python-list
Re: Job Offer: Python Ninja or Pirate!
On Dec 10, 2:11 pm, Stargaming <[EMAIL PROTECTED]> wrote: > On Mon, 10 Dec 2007 16:10:16 +0200, Nikos Vergas wrote: > > [snip] > > >> Problem: In the dynamic language of your choice, write a short program > >> that will: > >> 1. define a list of the following user ids 42346, 77290, 729 (you can > >> hardcode these, but it should > >> still work with more or less ids) > >> 2. retrieve an xml document related to each user at this url "http:// > >> api.etsy.com/feeds/xml_user_details.php?id=" > >> 3. retrieve the data contained in the city element from each xml > >> document > >> 4. keep a running total of how many users are found in each city 5. > >> display the total count of users living in each city > [snip] > > > i wanted to make it a one liner, but i had to import modules :( > > > import sys, xml, urllib > > > dummy = [sys.stdout.write(city + ': ' + str(num) + '\n') for city, num > > in set([[(a, o.count(a)) for a in p] for o, p in [2*tuple([[city for > > city in > > ((xml.dom.minidom.parseString(urllib.urlopen('http://api.etsy.com/feeds/ > > xml_user_details.php?id=' > > > + str(id)).read()).getElementsByTagName('city')[0].childNodes + [(lambda > > t: (setattr(t, 'data', 'no city'), > > t))(xml.dom.minidom.Text())[1]])[0].data.lower().replace(' ', ' ') for > > id in [71234, 71234, 71234, 71234, 71234, 71234, 42792])]])]][0])] > > I suggest `__import__` in such cases. > > Even though I do not qualify for the job, I came up with this () > code (modified list values for demonstration, mixed together from > previous post and original task): > > print '\n'.join('%s: %d'%(x,len(list(y))) for x,y in __import__ > ('itertools').groupby(sorted(__import__('xml').dom.minidom.parse > (__import__('urllib').urlopen('http://api.etsy.com/feeds/ > xml_user_details.php?id=%d'%i)).getElementsByTagName('city') > [0].lastChild.data.title() for i in (71234, 729, 42346, 77290, 729, > 729 > > I still find this rather readable, though, and there is no bad side- > effect magic! :-) > > Output should be: > > | Chicago: 3 > | Fort Lauderdale: 1 > | Jersey City And South Florida: 1 > | New York: 1 Alas, it's not: AttributeError: 'module' object has no attribute 'dom' Here's a working version, optimized for char length (one line, 241 chars): import urllib as U,elementtree.ElementTree as E;c=[E.parse(U.urlopen('http://api.etsy.com/feeds/xml_user_details.php? id=%d'%u)).findtext('//city')for u in 71234,729,42346,77290,729,729];print'\n'.join('%s: %s'% (i,c.count(i))for i in set(c)) George -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie
On Dec 11, 5:03 am, "Whizzer" <[EMAIL PROTECTED]> wrote: > Is OReilly's Learning Python a good place to start learning to program? > I've been told Python is a good first language. > > Thanks for the advice. I learn it from python own tutorials comes with it's installation. It is so important that you do not study bad books. there are lots a of bad books about python that you can't imagine. I rate OReilly's Learning Python 3 stars. -- http://mail.python.org/mailman/listinfo/python-list
need the unsigned value from dl.call()
I'm using dl.call() to call a C function in an external library. It's working great so far except for one function, which returns an unsigned int in the C version. However, in python it returns a signed value to me. How can I get the unsigned value from this? I haven't brushed up on my two's complement in a while, so I was hoping someone could give me a hand. Thanks eliss -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie edit/compile/run cycle question
Bruno Desthuilliers <[EMAIL PROTECTED]> wrote: > Jeremy C B Nicoll a écrit : > > Figuring out how IDLE works is a bit beyond me at this stage. > > Did you try out, or is it just an a priori ? Sort of, no and yes... A few weeks ago I started trying to use Python & IDLE and found a bug (which I reported on idle-dev). In the course of discussing that I found out that the whole IDLE source was present in \idlelib which I hadn't realised, and did look at it. But for a Python newbie (if not a programming newbie) it's too much to understand. -- Jeremy C B Nicoll - my opinions are my own. -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie
On Dec 10, 2007 9:03 PM, Whizzer <[EMAIL PROTECTED]> wrote: > Is OReilly's Learning Python a good place to start learning to program? > I've been told Python is a good first language. I think this is a great place to start, there is a free version right there online. http://diveintopython.org/ -- http://mail.python.org/mailman/listinfo/python-list
newbie
Is OReilly's Learning Python a good place to start learning to program? I've been told Python is a good first language. Thanks for the advice. -- http://mail.python.org/mailman/listinfo/python-list
Re: GUI development with 3D view
If all you need to do is display a bunch of arrows, as you mention, the easiest thing to do might be to use Visual Python. It is extremely easy to use. gsal -- http://mail.python.org/mailman/listinfo/python-list
xpath and current python xml libraries
PyXML seems to be long gone. Is lxml the way to go if i want to have xpath supported? -- http://mail.python.org/mailman/listinfo/python-list
Re: Any way to program custom syntax to python prompt? >> I want to edit matrices.
On 11 Des, 01:54, mosi <[EMAIL PROTECTED]> wrote: > Python matrices are usually defined with numpy scipy array or similar. > e.g.>>> matrix1 = [[1, 2], [3, 4], [5, 6]] That is a list of Python lists, not a NumPy array or matrix. > For example:>>> matrix + 2 > > [ 3, 4; > 5, 6; > 7, 8;] > > Possibly with operator overloading? Go and get NumPy: www.scipy.org Then buy Travis Oliphant's book. -- http://mail.python.org/mailman/listinfo/python-list
Re: Best way to protect my new commercial software.
greg wrote: > Tim Chase wrote: >> -Write Lovecraftian code ("import goto" comes to mind) designed >> to make reverse-engineers go insane trying to figure out what you >> were thinking > > The problem with that is it makes it hard for *you* to > figure out what you were thinking... Psst...other than the Saas answer, they were *all* really bad ideas :) Sorry if my jesting came across as actually serious. -tkc -- http://mail.python.org/mailman/listinfo/python-list
Any way to program custom syntax to python prompt? >> I want to edit matrices.
Python matrices are usually defined with numpy scipy array or similar. e.g. >>> matrix1 = [[1, 2], [3, 4], [5, 6]] I would like to have easier way of defining matrices, for example: >>> matrix = [1, 2; 3, 4; 5, 6] >>> matrix = [ 1, 2; 3, 4; 5, 6;] Any ideas how could this be done? The ";" sign is reserved, the "[ ]" is used for lists. Also, how to program custom operations for this new "class?" matrix ??? For example: >>> matrix + 2 [ 3, 4; 5, 6; 7, 8;] Possibly with operator overloading? I appreciate all your comments, directions, pointers. mosi -- http://mail.python.org/mailman/listinfo/python-list
Re: Best way to protect my new commercial software.
On 10 Des, 08:15, farsheed <[EMAIL PROTECTED]> wrote: > I wrote a software and I want to protect it so can not be cracked > easily. I wrote it in python and compile it using py2exe. what is the > best way in your opinion? I wrote this in another thread, 1. Put all the compiled Python bytecode in a heavily encrypted binary file. Consider using a hardware hash in the key. 2. Program a small binary executable (.exe file) in C or C++ that: 2a. Reads the binary file. 2b. Decrypts it to conventional Python byte code. 2c. Embeds a Python interpreter. 2d. Executes the bytecode with the embedded Python interpreter. 3. Protect the executable with a licence manager such as Flexlm or SoftwarePassport. I will not make reverse engineering impossible, but it will be extremely difficult. As noted, the only completely safe solution is to provide a web application instead of distributing your program. -- http://mail.python.org/mailman/listinfo/python-list
Re: reading cookies from PHP
Jack Holt wrote: > Hello there. > I'm a PHP fan but a Python newbie. I wrote anapplication in Python > that needs to read a cookie setup from a PHP page. Is itpossible to do it? > > If not, what if I create a TXT file - as well as a cookie - thatcontains > the cookie's data? Will python be able to open the file and readthe > data? The TXT file can contain: > > Username = dude > Password = python Cookies are sent browser by the web server, and sent back to the web server by the browser. So, yes, you can set the cookie with the PHP script and read it with the python program. I do it like this: import Cookie myCookies = Cookie.SimpleCookie() if 'HTTP_COOKIE' in os.environ: myCookies.load(os.environ['HTTP_COOKIE']) After that, the cookies will be available via a dictionary style lookup: user_name = myCookies['user_name'] j -- http://mail.python.org/mailman/listinfo/python-list
Re: Best way to protect my new commercial software.
Tim Chase wrote: > -Write Lovecraftian code ("import goto" comes to mind) designed > to make reverse-engineers go insane trying to figure out what you > were thinking The problem with that is it makes it hard for *you* to figure out what you were thinking... -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: Best way to protect my new commercial software.
Carl Banks wrote: > From the OP's post, it seemed likely to me that the OP was asked by a > misguided management to make sure it was "reverse-engineer-proof". In that case, just package it with py2exe and tell him it's done. The misguided management won't know any better. -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: Best way to protect my new commercial software.
farsheed wrote: > It is some kind of in house tool and I want to copy protect it. this > is very complicated tool and not useful for > many people. So there will be very few people with any incentive to steal it, and even less if it's not distributed to the public. -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie edit/compile/run cycle question
> python -c "import py_compile; py_compile.compile(r'FILENAME')" > > ... where FILENAME is the filename of the python script you want to check. > > What this does in practice is (trying to) compile the source, and any > errors or warnings will be reported. better written: python -mpy_compile FILENAME also see compileall Matt -- http://mail.python.org/mailman/listinfo/python-list
Re: GUI development with 3D view
On 10 Des, 13:33, Achim Domma <[EMAIL PROTECTED]> wrote: > I'm looking for quite some time now for a gui library for python, > which allows me to display 3D graphics. Main OS is windows, Mac OS X > and Linux would be nice to have. I want to use python 2.5. My first > try was wx + pyOpenGL but there are no working binaries for python > 2.5. Huh? The latest version of PyOpenGL uses ctypes and has no binaries as it is implemented in pure Python. Personally I use my own ctypes wrapper for the few OpenGL routines I need. There is a lot of unwanted overhead in PyOpenGL. Also consider calling OpenGL from a Pyrex extension. That may save you some overhead if you make a lot of calls to the OpenGL library. A remedy for that may be to use display lists, or combine vertex arrays or vertex buffers with NumPy arrays. Excerpts from my OpenGL wrapper: from ctypes import * import numpy from threading import Lock opengl_lock = Lock() GL = windll.opengl32 GLU = windll.glu32 GL_PROJECTION = 0x1701 GL_MODELVIEW = 0x1700 GL_DEPTH_TEST = 0x0B71 GL_VERTEX_ARRAY = 0x8074 GL_NORMAL_ARRAY = 0x8075 glBegin = GL.glBegin glBegin.argtypes = (c_int,) glBegin.restype = None glEnd = GL.glEnd glEnd.argtypes = () glEnd.restype = None glVertex3f = GL.glVertex3f glVertex3f.argtypes = (c_float, c_float, c_float) glVertex3f.restype = None gltypemap = { GL_BYTE : numpy.ctypeslib.ndpointer(dtype = numpy.int8, flags='aligned,contiguous'), GL_UNSIGNED_BYTE : numpy.ctypeslib.ndpointer(dtype = numpy.uint8, flags='aligned,contiguous'), GL_SHORT : numpy.ctypeslib.ndpointer(dtype = numpy.int16, flags='aligned,contiguous'), GL_UNSIGNED_SHORT : numpy.ctypeslib.ndpointer(dtype = numpy.uint16, flags='aligned,contiguous'), GL_INT : numpy.ctypeslib.ndpointer(dtype = numpy.int32, flags='aligned,contiguous'), GL_UNSIGNED_INT : numpy.ctypeslib.ndpointer(dtype = numpy.uint32, flags='aligned,contiguous'), GL_FLOAT : numpy.ctypeslib.ndpointer(dtype = numpy.float32, flags='aligned,contiguous'), GL_DOUBLE : numpy.ctypeslib.ndpointer(dtype = numpy.float64, flags='aligned,contiguous'), GL_UNSIGNED_BYTE_3_3_2 : numpy.ctypeslib.ndpointer(dtype = numpy.uint8, flags='aligned,contiguous') } def glVertexPointer(size, gltype, stride, array): opengl_lock.acquire() glfun = GL.glVertexPointer glfun.argtypes = (c_int, c_int, c_int, gltypemap[gltype]) glfun.restype = None glfun(size, gltype, stride, array) opengl_lock.release() def glGenBuffersARB(n): opengl_lock.acquire() PFNGLGENBUFFERSARBPROC = WINFUNCTYPE(None, c_uint, gltypemap[GL_UNSIGNED_INT]) wglGetProcAddress = GL.wglGetProcAddress wglGetProcAddress.argtypes = (c_char_p,) wglGetProcAddress.restype = PFNGLGENBUFFERSARBPROC glfun = wglGetProcAddress('glGenBuffersARB') buffers = numpy.zeros(n, dtype=numpy.uint32) glfun(n, buffers) opengl_lock.release() return buffers Interfacing Python with OpenGL is not rocket science. -- http://mail.python.org/mailman/listinfo/python-list
reading cookies from PHP
Hello there. I’m a PHP fan but a Python newbie. I wrote anapplication in Python that needs to read a cookie setup from a PHP page. Is itpossible to do it? If not, what if I create a TXT file - as well as a cookie - thatcontains the cookie’s data? Will python be able to open the file and readthe data? The TXT file can contain: Username = dude Password = python Please help! Thanks, -Dan - Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try it now.-- http://mail.python.org/mailman/listinfo/python-list
Re: Help needed with python unicode cgi-bin script
On Dec 11, 9:55 am, "weheh" <[EMAIL PROTECTED]> wrote: > Hi Martin, thanks for your response. My updates are interleaved with your > response below: > > > What is the encoding of that file? Without a correct answer to that > > question, you will not be able to achieve what you want. > > I don't know for sure the encoding of the file. I'm assuming it has no > intrinsic encoding since I copied the word "año" into vim and then saved it > as the example text file called, "spanish.txt". Every text file encoded, and very few of them are tagged with the name of the encoding in any reliable fashion. > > > Possible answers are "iso-8859-1", "utf-8", "windows-1252", and "cp850" > > (these all support the word "año") > > >> Instead of seeing "año" I see "a?o". > > > I don't see anything here. Where do you see the question mark? Did you > > perhaps run the CGI script in a web server, and pointed your web browser > > to the web page, and saw the question mark in the web browser? > > The cgi-bin scripts prints to stdout, i.e. to my browser, and when I use > print I see a square box where the ñ should be. When I use print repr(...) I > see 'a\xf1o'. I never see the desired 'ñ' character. > > Sending "Content-type: text/html" is not enough. The web browser needs > > > to know what the encoding is. So you should send > > > Content-type: text/html; charset="your-encoding-here" > > Sorry, somehow my cut and paste job into outlook missed the exact line you > had above that specifies encoding tp be set as "utf8", but it's there in my > program. Not to worry. > > > Use "extras/page information" in Firefox to find out what the web > > browser thinks the encoding of the page is. > > Firefox says the page is UTF8. > > > P.S. Please, stop shouting. > > OK, it's just that it hurts when I've been pulling my hair out for days on > end over a single line of code. I don't want to go bald just yet. Forget for the moment what you see in the browser. You need to find out how your file is encoded. Look at your file using print repr(open('c:/test/spanish.txt','rb').read()) If you see 'a\xf1o' then use charset="windows-1252" else if you see 'a\xc3\xb1o' then use charset="utf-8" else Based on your responses to Martin, it appears that your file is actually windows-1252 but you are telling browsers that it is utf-8. Another check: if the file is utf-8, then doing open('c:/test/spanish.txt','rb').read().decode('utf8') should be OK; if it's not valid utf8, it will complain. Yet another check: open the file with Notepad. Do File/SaveAs, and look at the Encoding box -- ANSI or UTF-8? HTH, John -- http://mail.python.org/mailman/listinfo/python-list
Re: Is a "real" C-Python possible?
On 9 Des, 23:34, Christian Heimes <[EMAIL PROTECTED]> wrote: > >http://antoniocangiano.com/2007/11/28/holy-shmoly-ruby-19-smokes-pyth... > > The Ruby developers are allowed to be proud. They were able to optimize > some aspects of the implementation to get one algorithm about 14 times > faster. That's good work. But why was it so slow in the first place? The thing to notice here is that Congiano spent 31.5 seconds computing 36 Fibonacci numbers in Python and 11.9 seconds doing the same in Ruby. Those numbers are ridiculous! The only thing they prove is that Congiano should not be programming computers. Anyone getting such results should take a serious look at their algoritm instead of blaming the language. I don't care if it takes 31.5 seconds to compute 36 Fibonacci numbers in Python 2.5.1 with the dumbest possible algorithm. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is a "real" C-Python possible?
On 10 Des, 23:49, [EMAIL PROTECTED] (Aahz) wrote: > "Premature optimization is the root of all evil in programming." > --C.A.R. Hoare (often misattributed to Knuth, who was himself quoting > Hoare) Oh, I was Hoare? Thanks. Anyway, it doesn't change the argument that optimizing in wrong places is a waste of effort. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is a "real" C-Python possible?
On 10 Des, 23:54, Bruno Desthuilliers <[EMAIL PROTECTED]> wrote: > Or a lack of time and money. Lisp is one of the older programming > languages around, and at a time had BigBucks(tm) invested on it to try > and make it practically usable. Yes. But strangely enough, the two Lisp implementations that really kick ass are both free and not particularly old. CMUCL and SBCL proves that you can make a dynamic language implementation extremely efficient if you try hard enough. There are also implementations of Scheme (e.g. Bigloo) that shows the same. -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie edit/compile/run cycle question
Jeremy C B Nicoll a écrit : > Simon Forman <[EMAIL PROTECTED]> wrote: > > >>On Dec 8, 6:45 pm, Jeremy C B Nicoll <[EMAIL PROTECTED]> wrote: > > >>>Ah, I've been using IDLE so far (but would probably prefer to write >>>Python in my normal text editor). In IDLE Alt-X syntax checks the saved >>>copy of the file being edited (at least it seems to), and I was >>>wondering how to replicate that elsewhere. >> >>I don't know of a command line tool to do that, but I hasten to point >>out that you have the source code of IDLE available so you could just >>figure out what it's doing and encapsulate that in a script. > > > I was afraid someone would suggest that. Figuring out how IDLE works is a > bit beyond me at this stage. Did you try out, or is it just an a priori ? -- http://mail.python.org/mailman/listinfo/python-list
RE: Equivalent of perl's Pod::Usage?
> On Behalf Of Nick Craig-Wood > As for Pod::Usage - write the instructions for your script as > a docstring at the top of your file, then use this little function... > > def usage(error): > """ > Print the usage, an error message, then exit with an error > """ > print >>sys.stderr, globals()['__doc__'] > print >>sys.stderr, error > sys.exit(1) argparse[1] also prints out very pretty usage for you. [1] http://argparse.python-hosting.com/ Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
Re: Are Python deques linked lists?
> > I'm looking for a linked list implementation. Something > > iterable with constant time insertion anywhere in the list. I > > was wondering if deque() is the class to use or if there's > > something else. Is there? > > The deque is implemented as a list of arrays. See 5.12.1 Recipes > for the trick of using rotate to delete an item from within the > deque. The docs don't spell out the efficiency (in terms of O > notation) of the rotate method, though. You'll have check the > source, or perhaps Raymond is reading and could explain. Deques have O(1) append/pop behaviors at either. Mid-sequence insertions, deletions, and rotations are O(n), although the constant factor is low. Raymond -- http://mail.python.org/mailman/listinfo/python-list
Re: Help needed with python unicode cgi-bin script
Hi Martin, thanks for your response. My updates are interleaved with your response below: > What is the encoding of that file? Without a correct answer to that > question, you will not be able to achieve what you want. I don't know for sure the encoding of the file. I'm assuming it has no intrinsic encoding since I copied the word "año" into vim and then saved it as the example text file called, "spanish.txt". > Possible answers are "iso-8859-1", "utf-8", "windows-1252", and "cp850" > (these all support the word "año") > >> Instead of seeing "año" I see "a?o". > > I don't see anything here. Where do you see the question mark? Did you > perhaps run the CGI script in a web server, and pointed your web browser > to the web page, and saw the question mark in the web browser? The cgi-bin scripts prints to stdout, i.e. to my browser, and when I use print I see a square box where the ñ should be. When I use print repr(...) I see 'a\xf1o'. I never see the desired 'ñ' character. Sending "Content-type: text/html" is not enough. The web browser needs > to know what the encoding is. So you should send > > Content-type: text/html; charset="your-encoding-here" Sorry, somehow my cut and paste job into outlook missed the exact line you had above that specifies encoding tp be set as "utf8", but it's there in my program. Not to worry. > Use "extras/page information" in Firefox to find out what the web > browser thinks the encoding of the page is. Firefox says the page is UTF8. > P.S. Please, stop shouting. OK, it's just that it hurts when I've been pulling my hair out for days on end over a single line of code. I don't want to go bald just yet. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is a "real" C-Python possible?
sturlamolden a écrit : > On 9 Des, 23:34, Christian Heimes <[EMAIL PROTECTED]> wrote: > > >>Nevertheless it is just one algorithm that beats Python in an area that >>is well known to be slow. Python's numbers are several factors slower >>than C code because the overhead of the dynamic language throws lots of >>data out of the cache line. If you need fast and highly optimized int >>and floating point operations you can rewrite the algorithm in C and >>create a Python interface for it. > > > Lisp is a dynamically typed language. CMUCL can compete with Fortran > for numerical work. SBCL can compete with the Java server VM. If the > current CPython VM throws data out of the cache line, then it must be > a design flaw in the VM. Or a lack of time and money. Lisp is one of the older programming languages around, and at a time had BigBucks(tm) invested on it to try and make it practically usable. -- http://mail.python.org/mailman/listinfo/python-list
Re: Help needed with python unicode cgi-bin script
Thanks for the reply, Jack. I tried setting mode to binary but it had no affect. "Jack" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > You probably need to set stdout mode to binary. They are not by default on > Windows. > > > "weheh" <[EMAIL PROTECTED]> wrote in message > news:[EMAIL PROTECTED] >> Dear web gods: >> >> After much, much, much struggle with unicode, many an hour reading all >> the examples online, coding them, testing them, ripping them apart and >> putting them back together, I am humbled. Therefore, I humble myself >> before you to seek guidance on a simple python unicode cgi-bin scripting >> problem. >> >> My problem is more complex than this, but how about I boil down one >> sticking point for starters. I have a file with a Spanish word in it, >> "años", which I wish to read with: >> >> >> #!C:/Program Files/Python23/python.exe >> >> STARTHTML= u'''Content-Type: text/html >> >> > "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd";> >> http://www.w3.org/1999/xhtml"; lang="en" xml:lang="en"> >> >> >> >> ''' >> ENDHTML = u''' >> >> >> ''' >> print STARTHTML >> print open('c:/test/spanish.txt','r').read() >> print ENDHTML >> >> >> Instead of seeing "año" I see "a?o". BAD BAD BAD >> Yet, if I open the file with the browser (IE/Mozilla), I see "año." THIS >> IS WHAT I WANT >> >> WHAT GIVES? >> >> Next, I'll get into codecs and stuff, but how about starting with this? >> >> The general question is, does anybody have a complete working example of >> a cgi-bin script that does the above properly that they'd be willing to >> share? I've tried various examples online but haven't been able to get >> any to work. I end up seeing hex code for the non-ascii characters >> u'a\xf1o', and later on 'a\xc3\xb1o', which are also BAD BAD BAD. >> >> Thanks -- your humble supplicant. >> > > -- http://mail.python.org/mailman/listinfo/python-list
Re: J in the Q
Wayne Brehaut a écrit : > On Mon, 10 Dec 2007 21:41:56 +0100, Bruno Desthuilliers > <[EMAIL PROTECTED]> wrote: > > >>Wayne Brehaut a écrit : >>(snip spam) >> >>>Obvious, since God is One, and so He divides 1, and 0, and -1, and all >>>integers both positive and negative (Peace Be Upon Them). >>> >>>wwwayne >> >> >>wwwayne, >> >>My isp did a good job at filtering out that spam. In fact, if it wasn't >>for your answer, I wouldn't even know someone about it. Does that ring a >>bell, or do I have to say it out loud ? PLEASE DONT ANSWER TO SPAMS ! >> >>Nah. > > > I suppose you realize that now any troll lurking nearby knows how to > bypass your ISP's spam filter and p you off? Yadda yadda. > Rule number 2: NEVER REPLY TO A REPLY TO A SPAMMER! > > Please killfilter me so you won't be bothered by my posts. If you > didn't provide so much useful information I'd killfilter you too so I > wouldn't be bothered by your cranky retorts to all my posts. "all" ? Well, I didn't notice, but if it's true there must be some reason. > Did you somehow miss the complete reposting of this guy's previous > message by Deltantor on 05 Dec 2007? Never saw this on my screen. Not even a single spot. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is a "real" C-Python possible?
In article <[EMAIL PROTECTED]>, sturlamolden <[EMAIL PROTECTED]> wrote: > >Donald Knuth, one of the fathers of modern computer science, is famous >for stating that "premature optimization is the root of all evil in >computer science." >From my .sig database: "Premature optimization is the root of all evil in programming." --C.A.R. Hoare (often misattributed to Knuth, who was himself quoting Hoare) -- Aahz ([EMAIL PROTECTED]) <*> http://www.pythoncraft.com/ "Typing is cheap. Thinking is expensive." --Roy Smith -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie edit/compile/run cycle question
Simon Forman <[EMAIL PROTECTED]> wrote: > On Dec 8, 6:45 pm, Jeremy C B Nicoll <[EMAIL PROTECTED]> wrote: > > Ah, I've been using IDLE so far (but would probably prefer to write > > Python in my normal text editor). In IDLE Alt-X syntax checks the saved > > copy of the file being edited (at least it seems to), and I was > > wondering how to replicate that elsewhere. > > I don't know of a command line tool to do that, but I hasten to point > out that you have the source code of IDLE available so you could just > figure out what it's doing and encapsulate that in a script. I was afraid someone would suggest that. Figuring out how IDLE works is a bit beyond me at this stage. I note the idea posted by Jan Claeys involves running a working python program which manages the compile process, which is an approach I'd not have thought of in a hurry. My experience of other languages' compilers has never been like this, eg to compile a Fortran program I would not expect to run a Fortran program that calls the compiler, IYSWIM. -- Jeremy C B Nicoll - my opinions are my own. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is a "real" C-Python possible?
Jack a écrit : > Aahz a écrit >> >>Could you provide some evidence that Python is slower than Java or PHP? > > > I think most Java-Python benchmarks you can find online will indicate > that Java is a 3-10 times faster. A few here: > http://mail.python.org/pipermail/python-list/2002-January/125789.html > http://blog.snaplogic.org/?p=55 This last one points to a funny anthology (year 2k, Python 1.5.2 and Java 1.1) piece of a paper (electronic paper of course) if you read past the "benchmark" part (which BTW doesn't pretend to be that serious - the 'do nothing' test is just hilarious). I really like this part (sorry, I only kept the titles - but you can have a look at the whole text, url is below): """ * Unresolved Release-Critical Bugs in Java* 1. Don't Use Swing. (snip rant about Swing memory leaks, just kept this:) The AWT does this too, but you could probably write an application that ran for longer than 20 minutes using it. 2. Don't allocate memory. (snip) 3. Don't use java.lang.String.intern (snip) 4. Don't expect your app to run (snip) 5. Don't print anything (snip) 6. Don't write large apps (snip) 7. Don't write small apps (snip) """ Heck... This sure looks like a very high price to pay wrt/ "raw speed" gain !-) Oh, yes, the url: http://www.twistedmatrix.com/users/glyph/rant/python-vs-java.html Yeps, that's it : twisted. No surprise the guy "decided to move Twisted Reality to python." It's really worth reading. While I was by that time a total newbie to programming, and will probably never be anything close to the author, it looks like we took a similar decision at the same time, and mostly based on similar observations : *in practice*, Java sucks big time - when Python JustWorks(tm). -- http://mail.python.org/mailman/listinfo/python-list
Re: Is a "real" C-Python possible?
On 9 Des, 23:34, Christian Heimes <[EMAIL PROTECTED]> wrote: > Nevertheless it is just one algorithm that beats Python in an area that > is well known to be slow. Python's numbers are several factors slower > than C code because the overhead of the dynamic language throws lots of > data out of the cache line. If you need fast and highly optimized int > and floating point operations you can rewrite the algorithm in C and > create a Python interface for it. Lisp is a dynamically typed language. CMUCL can compete with Fortran for numerical work. SBCL can compete with the Java server VM. If the current CPython VM throws data out of the cache line, then it must be a design flaw in the VM. -- http://mail.python.org/mailman/listinfo/python-list
ANN: pyparsing 1.4.10 released!
I'm happy to announce that I have just uploaded the latest release (v1.4.10) of pyparsing. I had to quick turnaround this release because a bug I thought I had fixed in 1.4.9 still persisted. I now have unit tests to catch the problematic variations in the operatorPrecedence method. This release has a few new features and a few minor bug-fixes. Here are the notes for both 1.4.9 and 1.4.10: Version 1.4.10 - December 9, 2007 - - Fixed bug introduced in v1.4.8, parse actions were called for intermediate operator levels, not just the deepest matching operation level. Again, big thanks to Torsten Marek for helping isolate this problem! Version 1.4.9 - December 8, 2007 - Added '*' multiplication operator support when creating grammars, accepting either an integer, or a two-integer tuple multiplier, as in: ipAddress = Word(nums) + ('.'+Word(nums))*3 usPhoneNumber = Word(nums) + ('-'+Word(nums))*(1,2) If multiplying by a tuple, the two integer values represent min and max multiples. Suggested by Vincent of eToy.com, great idea, Vincent! - Added pop() method to ParseResults. If pop is called with an integer or with no arguments, it will use list semantics and update the ParseResults' list of tokens. If pop is called with a non-integer (a string, for instance), then it will use dict semantics and update the ParseResults' internal dict. Suggested by Donn Ingle, thanks Donn! - Fixed bug in nestedExpr, original version was overly greedy! Thanks to Michael Ramirez for raising this issue. - Fixed internal bug in ParseResults - when an item was deleted, the key indices were not updated. Thanks to Tim Mitchell for posting a bugfix patch to the SF bug tracking system! - Fixed internal bug in operatorPrecedence - when the results of a right-associative term were sent to a parse action, the wrong tokens were sent. Reported by Torsten Marek, nice job! - Fixed quoted string built-ins to accept '\xHH' hex characters within the string. Download pyparsing 1.4.10 at http://sourceforge.net/projects/pyparsing/. The pyparsing Wiki is at http://pyparsing.wikispaces.com -- Paul Pyparsing is a pure-Python class library for quickly developing recursive-descent parsers. Parser grammars are assembled directly in the calling Python code, using classes such as Literal, Word, OneOrMore, Optional, etc., combined with operators '+', '|', and '^' for And, MatchFirst, and Or. No separate code-generation or external files are required. Pyparsing can be used in many cases in place of regular expressions, with shorter learning curve and greater readability and maintainability. Pyparsing comes with a number of parsing examples, including: - "Hello, World!" (English, Korean, Greek, and Spanish(new)) - chemical formulas - configuration file parser - web page URL extractor - 5-function arithmetic expression parser - subset of CORBA IDL - chess portable game notation - simple SQL parser - Mozilla calendar file parser - EBNF parser/compiler - Python value string parser (lists, dicts, tuples, with nesting) (safe alternative to eval) - HTML tag stripper - S-expression parser - macro substitution preprocessor -- http://mail.python.org/mailman/listinfo/python-list
Re: Is a "real" C-Python possible?
On 9 Des, 22:14, "Jack" <[EMAIL PROTECTED]> wrote: > I understand that the standard Python distribution is considered > the C-Python. Howerver, the current C-Python is really a combination > of C and Python implementation. There are about 2000 Python files > included in the Windows version of Python distribution. I'm not sure > how much of the C-Python is implemented in C but I think the more > modules implemented in C, the better performance and lower memory > footprint it will get. Donald Knuth, one of the fathers of modern computer science, is famous for stating that "premature optimization is the root of all evil in computer science." A typical computer program tends to have bottlenecks that accounts for more than 90% of the elapsed run time. Directing your optimizations anywhere else is futile. Writing a program in C will not improve the speed of your hardware. If the bottleneck is a harddisk or a network connection, using C will not change that. Disk i/o is a typical example of that. It is not the language that determines the speed by which Python or C can read from a disk. It is the disk itself. I had a data vizualization program that was slowed down by the need to move hundreds of megabytes of vertex data to video RAM. It would obviously not help to make the handful of OpenGL calls from C instead of Python. The problem was the amount of data and the speed of the hardware (ram or bus). The fact that I used Python instead of C actually helped to make the problem easier to solve. We have seen several examples that 'dynamic' and 'interpreted' languages can be quite efficient: There is an implementation of Common Lisp - CMUCL - that can compete with Fortran in efficiency for numerical computing. There are also versions of Lisp than can compete with the latest versions of JIT-compiled Java, e.g. SBCL and Allegro. As it happens, SBCL and CMUCL is mostly implemented in Lisp. The issue of speed for a language like Python has a lot to do with the quality of the implementation. What really makes CMUCL shine is the compiler that emits efficient native code on the fly. If it is possible to make a very fast Lisp, it should be possible to make a very fast Python as well. I remember people complaining 10 years ago that 'Lisp is so slow'. A huge effort has been put into making Lisp efficient enough for AI. I hope Python some day will gain a little from that effort as well. We have a Python library that allows us to perform a wide range of numerical tasks at 'native speed': NumPy (http://www.scipy.org). How such array libraries can be used to get excellent speedups is explained here: http://home.online.no/~pjacklam/matlab/doc/mtt/index.html We obviously need more effort to make Python more efficient for CPU bound tasks. Particularly JIT compilation like Java, compilation like Lisp or data specialization like Psyco. But writing larger parts of the standard library in C is not a solution. -- http://mail.python.org/mailman/listinfo/python-list
Source formatting fixer?
Does anyone know of a package that can be used to "fix" bad formatting in Python code? I don't mean actual errors, just instances where someone did things that violate the style guide and render the code harder to read. If nothing exists, I'll start working on some sed scripts or something to add spaces back in but I'm hoping someone out there has already done something like this. Thanks! Bret Wortman -- http://mail.python.org/mailman/listinfo/python-list
Re: Is a "real" C-Python possible?
[EMAIL PROTECTED] a écrit : (snip) > I'd like to provide some evidence that Python is *faster* than Java. Then benchmark the time taken for the interpreter (oops, sorry: "VM") to start !-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Is a "real" C-Python possible?
Jack a écrit : >>>I'm not sure >>>how much of the C-Python is implemented in C but I think the more >>>modules implemented in C, the better performance and lower memory >>>footprint it will get. >> >>Prove it. ;-) > > > I guess this is subjective :) If yes, benchmarks are not an argument. Else, you'll have hard time making your point !-) (hint: doing objective benchmarking is really a difficult art) > - that's what I felt in my experience > with web applications developed in Python and PHP. I wasn't able to > find a direct comparison online. Could it be the case that you are comparing Python CGI scripts with mod_php ? Anyway, since php is also usable (hem... maybe not the appropriate qualificative) outside Apache, it should quite easy to make a more serious test ? Seriously: I never saw any benchmark where php was faster than Python for any kind of stuff - unless of course you're trying to compare Zope running as a CGI script with an hello world PHP script runned by mod_php. -- http://mail.python.org/mailman/listinfo/python-list
Re: J in the Q
On Mon, 10 Dec 2007 21:41:56 +0100, Bruno Desthuilliers <[EMAIL PROTECTED]> wrote: >Wayne Brehaut a écrit : >(snip spam) >> Obvious, since God is One, and so He divides 1, and 0, and -1, and all >> integers both positive and negative (Peace Be Upon Them). >> >> wwwayne > > >wwwayne, > >My isp did a good job at filtering out that spam. In fact, if it wasn't >for your answer, I wouldn't even know someone about it. Does that ring a >bell, or do I have to say it out loud ? PLEASE DONT ANSWER TO SPAMS ! > >Nah. I suppose you realize that now any troll lurking nearby knows how to bypass your ISP's spam filter and p you off? Rule number 2: NEVER REPLY TO A REPLY TO A SPAMMER! Please killfilter me so you won't be bothered by my posts. If you didn't provide so much useful information I'd killfilter you too so I wouldn't be bothered by your cranky retorts to all my posts. Did you somehow miss the complete reposting of this guy's previous message by Deltantor on 05 Dec 2007? Or is just me that youfeel the need to chastise? o/o wwwayne -- http://mail.python.org/mailman/listinfo/python-list
Re: Ruby's Template Engine for Python
[EMAIL PROTECTED] a écrit : > On Dec 8, 3:24 pm, Samuel <[EMAIL PROTECTED]> wrote: > >>On Sat, 08 Dec 2007 13:06:15 -0800, Steve Howell wrote: >> >>>This is what I came up with: >> >>>http://pylonshq.com/pastetags/form_remote_tag >> >>I see that Pylons uses a standard templating systems with all the JS >>renderers hooked into it as standard template function calls. That's >>great, now I just have to find the piece of code that provides those >>callbacks. >> >>Ah, here it is: >> >> >>>http://pylonshq.com/WebHelpers/module-webhelpers.html >> >>And there I go, easily adding the same functionality to any template >>system of my choice. That was easier than I expected. >> >>Thanks for your help ;-)! >> > I think TurboGears does something similar using the Kid template > system. I don't think so. I mean, I don't know what your thinking about, but Pylons webhelpers module is not tight to a specific template engine. OTHO, it - well, at least the 'remote' part - relies on a specific js lib, which is definitiveky not the one I'd choose, and the code it produces is not something I'd put in production - I definitively don't want 'onclick' attributes in my html code (yuck), and I'm one of those crazy guys that insist on having code working without javascript first. Oh, yes : also and FWIW, Kid has been somewhat superseded by Genshi, and Turbogears 2.0 is based on Pylons. -- http://mail.python.org/mailman/listinfo/python-list
Re: JESUS in the QURAN
Wayne Brehaut a écrit : (snip spam) > Obvious, since God is One, and so He divides 1, and 0, and -1, and all > integers both positive and negative (Peace Be Upon Them). > > wwwayne wwwayne, My isp did a good job at filtering out that spam. In fact, if it wasn't for your answer, I wouldn't even know someone about it. Does that ring a bell, or do I have to say it out loud ? PLEASE DONT ANSWER TO SPAMS ! Nah. -- http://mail.python.org/mailman/listinfo/python-list
Re: logging.py: mutiple system users writing to same file getting permission errors.
On Dec 7, 12:46 pm, Vinay Sajip <[EMAIL PROTECTED]> wrote: > On Dec 6, 6:35 pm, evenrik <[EMAIL PROTECTED]> wrote: > > > An a redhat box I have root, apache and other normal users run code > > that uses theloggingmodule to write to the same log file. Since > > umasks are set to 2 or 022 this gets permission errors. > > > I have fixed my issue by patching theloggingcode everywhere there is > > an open for write with: > > try: > > old_umask = os.umask(0) > > # open for write here > > finally: > > os.umask(old_umask) > > > Is there a better way to solve this issue? > > Are there any security problems with this solution other than the log > > file not being protected? > > Multiple processes writing to the same log file may step on each > other's toes: logging contains thread synchronisation code but no > protection against multiple processes accessing the same resource. The > best solution would be to log from all processes to a SocketHandler, > and then have a socket receiver process write the logs to file. This > effectively serialises access to the log file. An example is given in > the logging docs, see > > http://docs.python.org/lib/network-logging.html > > Of course, you can have the receiver process run under a uid of your > choosing which has the appropriate permissions to write to the log > file. > > Regards, > > Vinay Sajip Thank you for the warning about multiple processes. We decided to try creating a DBHandler to write the logs to PostgeSQL. -- http://mail.python.org/mailman/listinfo/python-list
Re: JESUS in the QURAN
On Mon, 10 Dec 2007 11:20:49 -0800 (PST), aassime abdellatif <[EMAIL PROTECTED]> wrote: > 'And they devised, and God >devised, and God devised, and God is the best of divisors. Obvious, since God is One, and so He divides 1, and 0, and -1, and all integers both positive and negative (Peace Be Upon Them). wwwayne -- http://mail.python.org/mailman/listinfo/python-list
Re: Job Offer: Python Ninja or Pirate!
On 10 Dec, 19:11, Stargaming <[EMAIL PROTECTED]> wrote: > On Mon, 10 Dec 2007 16:10:16 +0200, Nikos Vergas wrote: > > [snip] > > >> Problem: In the dynamic language of your choice, write a short program > >> that will: > >> 1. define a list of the following user ids 42346, 77290, 729 (you can > >> hardcode these, but it should > >> still work with more or less ids) > >> 2. retrieve an xml document related to each user at this url "http:// > >> api.etsy.com/feeds/xml_user_details.php?id=" > >> 3. retrieve the data contained in the city element from each xml > >> document > >> 4. keep a running total of how many users are found in each city 5. > >> display the total count of users living in each city > [snip] > > > i wanted to make it a one liner, but i had to import modules :( > > > import sys, xml, urllib > > > dummy = [sys.stdout.write(city + ': ' + str(num) + '\n') for city, num > > in set([[(a, o.count(a)) for a in p] for o, p in [2*tuple([[city for > > city in > > ((xml.dom.minidom.parseString(urllib.urlopen('http://api.etsy.com/feeds/ > > xml_user_details.php?id=' > > > + str(id)).read()).getElementsByTagName('city')[0].childNodes + [(lambda > > t: (setattr(t, 'data', 'no city'), > > t))(xml.dom.minidom.Text())[1]])[0].data.lower().replace(' ', ' ') for > > id in [71234, 71234, 71234, 71234, 71234, 71234, 42792])]])]][0])] > > I suggest `__import__` in such cases. > > Even though I do not qualify for the job, I came up with this () > code (modified list values for demonstration, mixed together from > previous post and original task): > > print '\n'.join('%s: %d'%(x,len(list(y))) for x,y in __import__ > ('itertools').groupby(sorted(__import__('xml').dom.minidom.parse > (__import__('urllib').urlopen('http://api.etsy.com/feeds/ > xml_user_details.php?id=%d'%i)).getElementsByTagName('city') > [0].lastChild.data.title() for i in (71234, 729, 42346, 77290, 729, > 729 > > I still find this rather readable, though, and there is no bad side- > effect magic! :-) > > Output should be: > > | Chicago: 3 > | Fort Lauderdale: 1 > | Jersey City And South Florida: 1 > | New York: 1 > > Cheers, A simpleton's version: #!/usr/local/bin/python import urllib from elementtree import ElementTree as et userids = [71234,729,42346,77290,729,729] url = 'http://api.etsy.com/feeds/xml_user_details.php?id=' if __name__ == "__main__": city = {} for userid in userids: feed = urllib.urlopen(url+str(userid)) tree = et.parse(feed) for elem in tree.getiterator('city'): if not city.has_key(elem.text):city[elem.text] = 1 else: city[elem.text] += 1 for k,v in city.items(): if not k == None:print k,':\t',v Output: Fort Lauderdale : 1 new york : 1 Jersey City and South Florida : 1 Chicago : 3 Cheers -- http://mail.python.org/mailman/listinfo/python-list
Re: Best way to protect my new commercial software.
On 2007-12-10, Chris Mellon <[EMAIL PROTECTED]> wrote: > On Dec 10, 2007 5:56 AM, Carl Banks <[EMAIL PROTECTED]> wrote: >> On Dec 10, 6:26 am, Tim Chase <[EMAIL PROTECTED]> wrote: >> > > So you say there is not any trusted way? >> > >> > You cannot distribute any program with the expectation that it >> > cannot be reverse engineered. >> [snip] >> >> >> >From the OP's post, it seemed likely to me that the OP was asked by a >> misguided management to make sure it was "reverse-engineer-proof". So >> any attempt to convince the OP may be aimed at the wrong person. >> >> Misguided as they are, sometimes you have to placate these people. >> So, are there any ways to make it "harder" to reverse engineer a >> program? > > Just telling them you did is at least as effective as anything else. > Anyone who knows enough to know that you're lying knows why it's > impossible. If you're distributing source code, run it through pyobfuscate and call it done. Otherwise, just use py2exe or something similar to bundle it up. Both are pretty ineffective at preventing reverse engineering. But so's everything else. If none of the options really work, then you might as well pick an ineffective one that's cheap and easy. -- Grant Edwards grante Yow! Am I having fun yet? at visi.com -- http://mail.python.org/mailman/listinfo/python-list
Re: I'm missing something here with range vs. xrange
On Dec 11, 3:55 am, "Chris Mellon" <[EMAIL PROTECTED]> wrote: [snip] > No. What range does is create and return a list of integers. The > iteration is a separate step, and is traditional list iteration. In > longhand, for x in range(y): looks something like this: > > range = [] > #this loop happens in C and is super-fast for small values of y, it > #gets much much slower when y gets out of the range of pre-allocated list > pools > #and the small integer cache > while y >= 0: > range.append(y) > y -= 1 When y is 3, the above appears to produce [3, 2, 1, 0] ... -- http://mail.python.org/mailman/listinfo/python-list
module level subclassing
Hi all, Is there a way to access the classes defined in the __init__.py into the modules files in the directory? for example say i have a module (dir) M with contents __init__.py and a.pyand b.py a.py and b.py would like to subclass/instantiate a class defined in __init__.py how's that possible ? kindly enlighten regards, KM -- http://mail.python.org/mailman/listinfo/python-list
Re: searching a value of a dict (each value is a list)
Seongsu Lee: >I have a dictionary with million keys. Each value in the dictionary has a list >with up to thousand integers.< Let's say each integer can be represented with 32 bits (if there are less numbers then a 3-byte representation may suffice, but this makes things more complex), that is 2^2 bytes. Let's say there are 2^20 keys each one associated to 2^10 values. So to represent the values you need 2^32 bytes. It means 4 GB, so I don't think Python suffices to store them in RAM, because a Python int object requires quite more than 4 bytes (only represented inside an array.array it may need just 4 bytes). So if you can use 128 MB RAM to store such data structure you need to store data on HD too. You probably can use a lower-level language. On disk you can keep the reverse index, represented as an array of records/structs, each of such structures keep two 32-bit numbers (so such array is 8 GB). Such index is sorted according to the first element of the struct. The first number is the value of the original dictionary and the second nuber is its key. Inside the RAM you can keep another sorted array that "summarizes" your whole data. When you need a number you can do a binary search on the array in RAM, such array gives you the position where you can read (with a seek) a little part of the file (512 bytes may suffice), to perform a little binary search (if the block is very little a linear scan suffices) on it too to find the number you need. Note that the summarizing data structure in RAM may be represented with just a Python dict too, so in the end you can use Python to solve this problem. You may need a lower-level language to create the 8 GB file on disk (or create it with Python, but it may take lot of time. You may sort it with the sort unix command). This isn't a complete solution, but I think it may work. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Exponent Question
databyss wrote: > I have a simple program and the output isn't what I expect. Could > somebody please explain why? > > Here's the code: > > #simple program > print "v = 2" > v = 2 > print "v**v = 2**2 =", v**v > print "v**v**v = 2**2**2 =", v**v**v > print "v**v**v**v = 2**2**2**2 =", v**v**v**v > #end program > > Here's the output: > > v = 2 > v**v = 2**2 = 4 > v**v**v = 2**2**2 = 16 > v**v**v**v = 2**2**2**2 = 65536 > > I would expect 2**2**2**2 to be 256 Exponentiation is right-associative. I.e. 2**2**2**2 == 2**(2**(2**2)) The reason is that left-associativity is better written with multiplication. (x**y)**z == x**(y*z) -- 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
JESUS in the QURAN
JESUS in the QURAN The Islamic view of Jesus lies between two extremes. The Jews , who rejected Jesus as a Prophet of God, called him an impostor. The Christians, on the other hand, considered him to be the son of God and worship him as such. Islam considers Jesus to be one of the great prophets of God and respects him as much as Ibrahim (Abraham), Moses, and Mohammed. (Peace Be Upon Them) This is conformity with the Islamic view of the oneness of God, the oneness of Divine guidance, and the complementary role of the subsequent mission of God's messengers. The essence of Islam - willing submission to the will of God - was revealed to Adam, who was passed it on to his children. All following revelations to Noah, Ibrahim, Moses, Jesus, and finally Mohammed (Peace Be Upon Them) were conformity with that message, with some elaboration to define the revelation between man and God, man and man, man and instructions. Thus, any contradictions among revealed religions is viewed by Islam as a man-made element introduced into these religions. The position of Jesus in the three major religions - Judaism, Christianity, and Islam - should not be an exception. Although the Quran does not present a detailed life-story of Jesus, it highlights the important aspects of his birth, his mission, his ascension to heaven, and passes judgements on the Christian beliefs concerning him. The Quranic account of Jesus starts with the conception of his mother, Mary, whose mother, the wife of Imran, vowed to dedicate her child to the service of God in the temple. When Mary became a woman, the Holy Spirit (the Archangel Gabriel) appeared to her as a man bringing her news of a son. We read the following dialogue in the Quran between Mary and the Angel: "When the angel said, "Mary, god gives you a good tidings of a Word from Him whose name is messiah, Jesus, son of Mary, -high honoured shall he be in this world and the next, near stationed to God. He shall speak to men in the cradle, and of age, and righteous he shall be, "lord" said Mary "How shall I have a son, seeing no mortal has touched me? "Even so, he said "God creates what He will". When he decrees a thing He but say to it, "Be", and it is. (Al-Imran 3:45-47) In a chapter (Surah) entitled "Maryam" (Mary), the Quran tells us how Mary gave birth to her son, and how the Jesus accused her when she brought the child home: "Then she brought the child to her folk, carrying him, and they said, "Mary, you have surely committed a monstrous thing. Sister of Aaron, your father was not a wicked man, nor your mother a woman unchaste. Mary pointed to the child; but they said, 'Hoe shall we speak to one who still in the cradle, a little child. And he said, 'Lo, I am God's servant, God has given me the Book and made me a Prophet Blessed He has made me ,wherever/may be; and hi has enjoined me to prayer, and to give the alms so long as I live, and likewise to cherish my mother; He has not made me arrogant and wicked. Peace be upon me, the day I was born, and the day I die, and the day I am raised up a live. "Maryam 19:29-33) in the same chapter, following the above quotation, God assures Mohammed (PBUH) and through him the whole world, that what is told above is the TRUTH about Jesus (PBUH), although Christians might not accept it. Jesus is NOT the son of God: He was obviously enough, the son of Mary. The verses continue: "That is Jesus, son of Mary, in word of truth, concerning which they are doubting. It is not for God to take a son unto Him. Glory be to Him, He nut says to it, 'Be, and it is. (Maryam 19:34-35) After this strong statement about the nature of Jesus, God directed Mohammed (PBUH) to call the Christians to worship the one God: "Surely God is my God, and your God, so surely serve him. This is the straight path". (Maryam 19:36) The rejection of the very idea of God having a son is restated later in the same chapter with even stronger words: "And they say, The All- merciful has taken unto Himself a son. You have indeed advanced something hideous. As if the skies are about to burst, the earth to split asunder and its mountain to fall down in the utter ruin for that they have attributed to the All-merciful a son; and behaves not the All-merciful to take a son. None there in the heavens and earth but comes to the All-merciful as a servant" (Maryam 19:88-93) The Quran recognizes the fact that Jesus had no human father, but this does not make him the son of God, or God himself. By this criterion, Adam would have been more entitled more entitled to be the son of God, because he had neither a father nor a mother, so the Quran draws attention to the miraculous creation of both in the following verses; " truly the likeness of Jesus, in God's sight is as Adam's likeness; He created him of dust, then He said upon him, 'Be' and hi was. (Al- Imran 3:59) The Quran rejects the concept of Trinity God the Father, God the son, God the Holy Spirit - as strongly as it rejects the concept of Jesus
Re: abusing exceptions for continuations
On Dec 10, 2:39 am, gangesmaster <[EMAIL PROTECTED]> wrote: > i've had this strange idea of using the exception's traceback (which > holds the stack frame) to enable functional continuations, meaning, > raise some special exception which will be caught by a reactor/ > scheduler/framework, which could later revive it by restoring the > frame. > > i'm thinking of using the generator's implementation (some minimal > support on the c-side) > > has this been tried before? what were the results? > > thanks, > -tomer Simpy has a mechanism like this, for discrete event simulation modeling of processes and resources. Processes "run" for a while, then yield a delay or a hold on a resource, and are resumed later. -- Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Dumb newbie back in shell
[EMAIL PROTECTED] a écrit : > Not trying to write C, I meant "trying to use Python like it was C" - but I guess it doesn't matter that much !-) > I'm trying to write Decaf, a language I've > designed (see www.MartinRinehart.com for more) but which doesn't > exist. Got to code the first bit in something. Later I can write Decaf > in Decaf. Chose Python as it looked like a faster write (learning > curve included) than C or C++. Indeed. > Python is commonly called a "scripting" language because of its use as > one of the Ps in the LAMP stack. Now that's a definition I never heard before !-) > I'm using it as a general-purpose > programming language with the neat feature of being able to write > scripts in its own console. Seriously, the Python shell is not meant to write serious code. I sometimes use it like a, well, shell (mostly to do quick maintenance on Zope apps - just like you'd fire a command-line SQL client to inspect and fix a problem on your favorite RDBMS), but the main use of it is still to quickly explore APIs, corner cases etc... Now perhaps I'm misunderstanding you, but your questions about module reloading are IMHO a sign your asking to much from the Python REPL. Anyway, welcome on board !-) Regards -- http://mail.python.org/mailman/listinfo/python-list
Re: Job Offer: Python Ninja or Pirate!
On Mon, 10 Dec 2007 16:10:16 +0200, Nikos Vergas wrote: [snip] >> Problem: In the dynamic language of your choice, write a short program >> that will: >> 1. define a list of the following user ids 42346, 77290, 729 (you can >> hardcode these, but it should >> still work with more or less ids) >> 2. retrieve an xml document related to each user at this url "http:// >> api.etsy.com/feeds/xml_user_details.php?id=" >> 3. retrieve the data contained in the city element from each xml >> document >> 4. keep a running total of how many users are found in each city 5. >> display the total count of users living in each city [snip] > > i wanted to make it a one liner, but i had to import modules :( > > import sys, xml, urllib > > dummy = [sys.stdout.write(city + ': ' + str(num) + '\n') for city, num > in set([[(a, o.count(a)) for a in p] for o, p in [2*tuple([[city for > city in > ((xml.dom.minidom.parseString(urllib.urlopen('http://api.etsy.com/feeds/ xml_user_details.php?id=' > + str(id)).read()).getElementsByTagName('city')[0].childNodes + [(lambda > t: (setattr(t, 'data', 'no city'), > t))(xml.dom.minidom.Text())[1]])[0].data.lower().replace(' ', ' ') for > id in [71234, 71234, 71234, 71234, 71234, 71234, 42792])]])]][0])] I suggest `__import__` in such cases. Even though I do not qualify for the job, I came up with this () code (modified list values for demonstration, mixed together from previous post and original task): print '\n'.join('%s: %d'%(x,len(list(y))) for x,y in __import__ ('itertools').groupby(sorted(__import__('xml').dom.minidom.parse (__import__('urllib').urlopen('http://api.etsy.com/feeds/ xml_user_details.php?id=%d'%i)).getElementsByTagName('city') [0].lastChild.data.title() for i in (71234, 729, 42346, 77290, 729, 729 I still find this rather readable, though, and there is no bad side- effect magic! :-) Output should be: | Chicago: 3 | Fort Lauderdale: 1 | Jersey City And South Florida: 1 | New York: 1 Cheers, -- http://mail.python.org/mailman/listinfo/python-list
Re: Converting Excel time-format (hours since 1.1.1901)
On Dec 10, 3:49 am, Dirk Hagemann <[EMAIL PROTECTED]> wrote: > On 9 Dez., 18:38, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote: > > > > > > > On Dec 9, 8:52�am, Dirk Hagemann <[EMAIL PROTECTED]> wrote: > > > > On 7 Dez., 22:36, John Machin <[EMAIL PROTECTED]> wrote: > > > > > On Dec 8, 12:20 am, Dirk Hagemann <[EMAIL PROTECTED]> wrote: > > > > > > Hello, > > > > > > From a zone-file of a Microsoft Active Directory integrated DNS server > > > > > I get the date/time of the dynamic update entries in a format, which > > > > > is as far as I know the hours since january 1st 1901. > > > > > As Tim Golden has guessed, it is the number of hours since > > > > 1601-01-01T00:00:00. Weird but true. See (for > > > > example)http://www.netpro.com/forum/messageview.cfm?catid=15&threadid=457 > > > > > > For Example: the number 3566839 is 27.11.07 7:00. > > > > > Y2K bug! The number 3566839 is a representation of > > > > 2007-11-27T07:00:00. > > > > > > To calculate this in > > > > >ExcelI use this: > > > > > ="01.01.1901"+(A1/24-(REST(A1;24)/24))+ZEIT(REST(A1;24);0;0) �(put > > > > > 3566839 in field A1 and switch the format of the result-field to the > > > > > corresponding date-time format). > > > > > "01.01.1901" => date(1901, 1, 1) > > > > > (A1/24-(REST(A1;24)/24)) => (A1/24-(MOD(A1,24)/24)) > > > > which simplifies to INT(A1/24) > > > > > ZEIT(REST(A1;24);0;0) => TIME(MOD(A1,24),0,0) > > > > > This is a convoluted way of writing DATE(1901, 1, 1) + A1 / 24 > > > > > Your result is "correct" apart from the century. This is the result of > > > > two canceling errors (1) yours in being 3 centuries out of kilter (2) > > > > Microsoft's in perpetuating the Lotus 123 "1900 is a leap year" bug. > > > > > If you must calculate this inExcel, this formula might be better: > > > > > =DATE(2001, 1, �1) + A1 / 24 - 146097 > > > > > (146097 is the number of days in a 400-year cycle, 400 * 365 + 100 - 4 > > > > + 1) > > > > > > You might guess what I need now: I want to calculate this somehow in > > > > > python. > > > > > > Sorry, but I couldn't find anything in the module time or something > > > > > else to get this calculated. > > > > > > Does anyone know how to convert this time in python to something > > > > > usable or how to convert this formula in python? > > > > > One very slight change to what Tim Golden suggested: make the result a > > > > datetime, not a date. > > > > > >>> dnsdatetime2py = lambda x: datetime.datetime(1601,1,1,0,0,0) + > > > > >>> datetime.timedelta(hours=x) > > > > >>> dnsdatetime2py(3566839) # your example > > > > > datetime.datetime(2007, 11, 27, 7, 0)>>> dnsdatetime2py(3554631) # > > > > example in cited web posting > > > > > datetime.datetime(2006, 7, 6, 15, 0) > > > > > HTH, > > > > John > > > > YES - that's it! > > > Thanks a lot to John, Tim and all the others who helped me to handle > > > this time format!!! > > > > I was irritated by the date of 01.01.1901 in the Excel formula, but in > > > the end it was obvious that it has to be hours since 1601. Who knows > > > how Excel calculates in the background... > > > Everyone knows. Excel assumes an integer is > > DAYS SINCE 1900 and all it's calculations > > are based on that assumption. > > > It's YOUR fault if you give Excel an integer > > that represents HOURS SINCE 1601, so don't > > expect meaningful calculations from Excel if > > you give it an incorrect data type. > > > > Enjoy the sunday and have a great week! > > > Dirk > > Sorry, but then I seem not to belong to "everyone". I apologize for the snide tone. But the reality is that you DO belong to everyone as how Excel calculates time in the background is explicitly stated in the Help files. > And it was not me > who created this Excel-formula, I just posted it as a kind of help. > And actually I just asked if somebody knows something about this time- > format and how to convert it. I think I already wrote that I did a > mistake and not Excel. I wasn't trying to assign blame. There's a computer term called GIGO, it stands for Garbage In, Garbage Out. It means that even if your formulae are correct, the result will be no better than the input, bad input produces bad output and the computer has no way to tell this. It is the programmer's responsibility to verify consistency. The magnitude of the number is inconsitent with Excel time formats. That's a clue that you can't use Excel date functions directly on this number. It is also inconsistent with hours from 1901 as it would be off by 4 centuries. That's a clue that either the formula is wrong or your interpretation of it is wrong. Once you have all the wrinkles ironed out, it will then become clear how to convert this number to it's equivalent Excel format so that you CAN use Excel date functions if desired. -- http://mail.python.org/mailman/listinfo/python-list
Re: abusing exceptions for continuations
gangesmaster a écrit : > i've had this strange idea of using the exception's traceback (which > holds the stack frame) to enable functional continuations, meaning, > raise some special exception which will be caught by a reactor/ > scheduler/framework, which could later revive it by restoring the > frame. > > i'm thinking of using the generator's implementation (some minimal > support on the c-side) > > has this been tried before? what were the results? I don't know, but you may want to have a look at Stackless Python. -- http://mail.python.org/mailman/listinfo/python-list
Re: Job Offer: Python Ninja or Pirate!
> import sys, xml, urllib > > dummy = [sys.stdout.write(city + ': ' + str(num) + '\n') for city, num in > set([[(a, o.count(a)) for a in p] for o, p in [2*tuple([[city for city in > ((xml.dom.minidom.parseString(urllib.urlopen(' > http://api.etsy.com/feeds/xml_user_details.php?id=' > + str(id)).read()).getElementsByTagName('city')[0].childNodes + [(lambda > t: (setattr(t, 'data', 'no city'), > t))(xml.dom.minidom.Text())[1]])[0].data.lower().replace(' ', ' ') for id > in [71234, 71234, 71234, 71234, 71234, 71234, 42792])]])]][0])] > Is that python or perl? -- http://mail.python.org/mailman/listinfo/python-list
Re: Distinguishing attributes and methods
Steve Howell a écrit : > --- Jan Claeys <[EMAIL PROTECTED]> wrote: > >>To conclude this discussion: >> >> * in Python, methods are attributes >> * in Ruby, attributes are methods >> > > > So clearly one of the languages has it all wrong. ;) > Nope, quite on the contrary, both got it right !-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Distinguishing attributes and methods
Jan Claeys a écrit : > Op Sun, 09 Dec 2007 12:44:46 -0800, schreef MonkeeSage: > > >>The point is that just because the attributes are "looked up the same >>way" or whatever, doesn't make them the same *kind* of attribute. To say >>that all attributes are the same in python muddies the water. They are >>the same in a generic sense that they are attributes, but not in their >>particular qualities. Like saying "all humans are the same" -- yes, in a >>general sense of being human. But to leave it at that is not very >>helpful. > > > Well, I guess Python is a language for human being... ;-) > > > To conclude this discussion: > > * in Python, methods are attributes > * in Ruby, attributes are methods > And this is probably the most sensible post in this thread !-) -- http://mail.python.org/mailman/listinfo/python-list
Re: GUI development with 3D view
Re! On Vista, OpenGL depend of (releases of) video-cards. Some cards don't support OpenGL => problem! Some cards have native openGL support => good (dream?) Some cards need update (drivers) @-salutations Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Re: SimpleXMLRPCServer interruptable?
On Dec 6, 7:43 pm, "Gabriel Genellina" <[EMAIL PROTECTED]> wrote: > En Thu, 06 Dec 2007 13:11:09 -0300, Bret <[EMAIL PROTECTED]> escribió: > > > > > For completeness, what I ended up doing is this: > > > server = SimpleXMLRPCServer((host, port)) > > server.socket.settimeout(0.1) > > > ServerWrapper became: > > > def ServerWrapper(): > > while True: > > try: > > server.handle_request() > > if self.done.isSet(): > > break > > except timeout: > > pass > > > And that seems to do the trick! Giving the socket a timeout allows me > > to check the Event more frequently and catch the change within a > > reasonable time. > > Remember that the timeout applies to *all* socket operations; what if the > XML request requires more than 0.1s to read? > If handling large requests is more important than the delay at shutdown > time, consider raising that value. > > -- > Gabriel Genellina Good point. Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: Are Python deques linked lists?
On 2007-12-10, Neil Cerutti <[EMAIL PROTECTED]> wrote: > On 2007-12-10, Peter Otten <[EMAIL PROTECTED]> wrote: >> Neil Cerutti wrote: def test(): ll = LinkedList([random.randint(1,1000) for i in range(10)]) for el in ll: if el.value%2==0: ll.delete(el) print [el.value for el in ll] if __name__=='__main__': test() Support for deleting elements other than the current one, and insertBefore/insertAfter methods is left as an exercise. >>> >>> Making an object its own iterator [works] for files, but not >>> for a container. After the deletions, you can never iterate >>> again. >> >> Look at the test code again -- there is a second iteration >> after the deletions (the list comprehension). > > Thanks for the correction. I didn't think that through. > >> However, you will get into trouble if you try to run two >> simultaneous iterations over the same LinkedList, so there is >> room for another exercise ;) > > I just remembered that iter(an_iterator) is itself, so nothing > prevents you from saving a reference to it before iterating: > > iter = iter(a_linked_list) > for it in iter: > if it.value % 2 == 0: > iter.delete() > > It looks a little weird, but perhaps it's still better than a > while loop. Ugh! Assuming you don't shadow built-ins. ;-) -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list
Re: Are Python deques linked lists?
On 2007-12-10, Peter Otten <[EMAIL PROTECTED]> wrote: > Neil Cerutti wrote: >>> def test(): >>> ll = LinkedList([random.randint(1,1000) for i in range(10)]) >>> >>> for el in ll: >>> if el.value%2==0: >>> ll.delete(el) >>> >>> print [el.value for el in ll] >>> >>> >>> if __name__=='__main__': >>> test() >>> >>> Support for deleting elements other than the current one, and >>> insertBefore/insertAfter methods is left as an exercise. >> >> Making an object its own iterator [works] for files, but not >> for a container. After the deletions, you can never iterate >> again. > > Look at the test code again -- there is a second iteration > after the deletions (the list comprehension). Thanks for the correction. I didn't think that through. > However, you will get into trouble if you try to run two > simultaneous iterations over the same LinkedList, so there is > room for another exercise ;) I just remembered that iter(an_iterator) is itself, so nothing prevents you from saving a reference to it before iterating: iter = iter(a_linked_list) for it in iter: if it.value % 2 == 0: iter.delete() It looks a little weird, but perhaps it's still better than a while loop. -- Neil Cerutti The pastor will preach his farewell message, after which the choir will sing, "Break Forth Into Joy." --Church Bulletin Blooper -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Exponent Question
databyss wrote: > I would expect 2**2**2**2 to be 256 I stumbled upon it, too. 2**2**2**2 == 2**(2**(2**2)) == 2**16 == 65536 Christian -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Exponent Question
: > v = 2 > v**v = 2**2 = 4 > v**v**v = 2**2**2 = 16 > v**v**v**v = 2**2**2**2 = 65536 > > I would expect 2**2**2**2 to be 256 "... in an unparenthesized sequence of power and unary operators, the operators are evaluated from right to left ..." - http://docs.python.org/ref/power.html So, 2**2**2**2 = 2**(2**(2**2)) = 65536 -[]z. -- http://mail.python.org/mailman/listinfo/python-list
Re: Are Python deques linked lists?
Peter Otten <[EMAIL PROTECTED]> wrote: > Neil Cerutti wrote: > >> On 2007-12-10, Duncan Booth <[EMAIL PROTECTED]> wrote: > >>> def test(): >>> ll = LinkedList([random.randint(1,1000) for i in range(10)]) >>> >>> for el in ll: >>> if el.value%2==0: >>> ll.delete(el) >>> >>> print [el.value for el in ll] >>> >>> >>> if __name__=='__main__': >>> test() >>> >>> Support for deleting elements other than the current one, and >>> insertBefore/insertAfter methods is left as an exercise. >> >> Making an object its own iterator [works] for files, but not for a >> container. After the deletions, you can never iterate again. It isn't its own iterator. The iterator is a separate generator object. > > Look at the test code again -- there is a second iteration after the > deletions (the list comprehension). > > However, you will get into trouble if you try to run two simultaneous > iterations over the same LinkedList, so there is room for another > exercise ;) > Only if you try to modify the list from both of them. Non-modifying iterations don't interfere. Changing the code to handle modifications from simultaneous iterations is fairly straightforward but probably tedious to cover all possible cases: probably the simplest thing is to catch such cases and throw an exception. But my point wasn't to give a bullet-proof implementation of a linked list, just to demonstrate that there is no bar to having one which lets you use a for loop and delete elements. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Exponent Question
databyss wrote: > I have a simple program and the output isn't what I expect. Could > somebody please explain why? > > Here's the code: > > #simple program > print "v = 2" > v = 2 > print "v**v = 2**2 =", v**v > print "v**v**v = 2**2**2 =", v**v**v > print "v**v**v**v = 2**2**2**2 =", v**v**v**v > #end program > > Here's the output: > > v = 2 > v**v = 2**2 = 4 > v**v**v = 2**2**2 = 16 > v**v**v**v = 2**2**2**2 = 65536 > > I would expect 2**2**2**2 to be 256 Order of operations and proximity: >>> 2**(2**(2**2)) 65536 >>> ((2**2)**2)**2 256 Apparently Python assumes the former and you assume the latter. When in doubt about order of operations, use parens. And even when you *know* the order of operations, be kind to those who will have to read your code later and put in the parens anyways. -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: Dumb newbie back in shell
Peter, question is, why did the first one work? In my real code I've got module-level vars and an error msg trying to use them in a function. In my test example I've got them accessed from within a function w/o error message. I am confused. Martin Peter Otten wrote: > MartinRinehart wrote: > > > However, here's the little tester I wrote: > > > > # t.py - testing > > > > global g > > g = 'global var, here' > > > > def f(): > > print g > > > > f() > > > > It prints 'global var, here,' not an error message. Wassup? > > Try it again with a modified f(): > > def f(): > print g > g = 42 > > In Python variables that are assigned to in a function are > function-local by default. > > Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Exponent Question
On Mon, 2007-12-10 at 10:15 -0800, databyss wrote: > I have a simple program and the output isn't what I expect. Could > somebody please explain why? > [...] > v**v**v**v = 2**2**2**2 = 65536 > > I would expect 2**2**2**2 to be 256 Exponentiation is right-associative. 2**2**2**2 = 2**(2**(2**2)) = 2**(2**4) = 2**16 = 65536. -- Carsten Haese http://informixdb.sourceforge.net -- http://mail.python.org/mailman/listinfo/python-list
Re: Best way to protect my new commercial software.
On Dec 10, 2007 5:56 AM, Carl Banks <[EMAIL PROTECTED]> wrote: > On Dec 10, 6:26 am, Tim Chase <[EMAIL PROTECTED]> wrote: > > > So you say there is not any trusted way? > > > > You cannot distribute any program with the expectation that it > > cannot be reverse engineered. > [snip] > > > >From the OP's post, it seemed likely to me that the OP was asked by a > misguided management to make sure it was "reverse-engineer-proof". So > any attempt to convince the OP may be aimed at the wrong person. > > Misguided as they are, sometimes you have to placate these people. > So, are there any ways to make it "harder" to reverse engineer a > program? > > Just telling them you did is at least as effective as anything else. Anyone who knows enough to know that you're lying knows why it's impossible. -- http://mail.python.org/mailman/listinfo/python-list
Python Exponent Question
I have a simple program and the output isn't what I expect. Could somebody please explain why? Here's the code: #simple program print "v = 2" v = 2 print "v**v = 2**2 =", v**v print "v**v**v = 2**2**2 =", v**v**v print "v**v**v**v = 2**2**2**2 =", v**v**v**v #end program Here's the output: >>> v = 2 v**v = 2**2 = 4 v**v**v = 2**2**2 = 16 v**v**v**v = 2**2**2**2 = 65536 >>> I would expect 2**2**2**2 to be 256 -- http://mail.python.org/mailman/listinfo/python-list
Re: Dumb newbie back in shell
Not trying to write C, I'm trying to write Decaf, a language I've designed (see www.MartinRinehart.com for more) but which doesn't exist. Got to code the first bit in something. Later I can write Decaf in Decaf. Chose Python as it looked like a faster write (learning curve included) than C or C++. Python is commonly called a "scripting" language because of its use as one of the Ps in the LAMP stack. I'm using it as a general-purpose programming language with the neat feature of being able to write scripts in its own console. Bruno Desthuilliers wrote: > [EMAIL PROTECTED] a �crit : > > OK, it's a scripting language. > > For which definition of "scripting language" ?-) > > def g(): > > ...os.remove('tokeneizer.pyc') > > ...reload( tokeneizer ) > > ...tokeneizer.tokenize('sample_decaf.d') > > ... > > > > But that gets me to: > > > > ... line 110, in get_toks > > UnboundLocalError: local variable 'line_ptr' referenced before > > assignment > > > > Here's a bit of the code, with line #s > > > > ... > > 68 global line_ptr > > 69 global char_ptr > > ... > > 75 line_ptr = 0 > > 76 char_ptr = 0 > > ... > > 109 def get_toks( text ): > > 110 while line_ptr < last_line: > > ... > > So when is a global var global? > > Short answer : never !-) > > Long answer: > > First point: "global" really means "module level" - there's no > "application global" namespaces. > > Second point: every name declared as the top-level is global - according > to the above definition. So there's no need to declare them as such. The > only place where you need the global statement is when you want to > rebind a module-level name from within a function. And it's in this > function that you need to declare the name as global. > > FWIW, this is documented. > > Last point: Python is not C, and it definitively doesn't have pointers. > Trying to write C in Python is a waste of time and an experiment in > frustration (just like trying to write language XXX in language YYY for > any distinct values of XXX and YYY). > > HTH -- http://mail.python.org/mailman/listinfo/python-list
Re: Is a "real" C-Python possible?
On Dec 9, 10:07 pm, "Jack" <[EMAIL PROTECTED]> wrote: > >> I think most Java-Python benchmarks you can find online will indicate > >> that Java is a 3-10 times faster. A few here: > >>http://mail.python.org/pipermail/python-list/2002-January/125789.html > >>http://blog.snaplogic.org/?p=55 > > > There are lies, damn lies and benchmarks. :) > > > Pure Python code is not going to beat Java code until the Python core > > gets a JIT compiler. If you want fair results you have to either > > disable the JIT in Java or use Psyco for Python. Otherwise you are > > comparing the quality of one language implementation to the quality of a > > JIT compiler. > > The second articple does have a column for Psyco. It helps in some areas > but still not good enough to stand up against Java. Plus, Psyco is not the > main stream and has stopped development. > > I'm also wondering, if Psyco is the right way to do, any reason it's not > being integrated into standard Python? Instead of recurring to benchmarks, I recommend that you read the following: http://highscalability.com/youtube-architecture There are no comparisons there, just a sample of what python and psyco can achieve. For a language that isn't designed with speed in mind, I think that's quite impressive. -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent of perl's Pod::Usage?
Adam Funk <[EMAIL PROTECTED]> wrote: > Sorry about that! POD is a mark-up language that Perl's Pod::Usage > module can translate into man pages (and other documentation formats). > > So what I'm really after is an easy way to generate something that > looks like a man page. You might want to investigate reST http://docutils.sourceforge.net/rst.html That said, python does a good job of turning doc strings and class descriptions into man pages even without any special markup, if you wrote docstrings everywhere. Try pydoc on any bit of python (without the .py) and you'll see what I mean As for Pod::Usage - write the instructions for your script as a docstring at the top of your file, then use this little function... def usage(error): """ Print the usage, an error message, then exit with an error """ print >>sys.stderr, globals()['__doc__'] print >>sys.stderr, error sys.exit(1) -- Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list
Re: Job Offer: Python Ninja or Pirate!
On Dec 10, 6:10 am, "Nikos Vergas" <[EMAIL PROTECTED]> wrote: > > Challenge: > > A valid response will be either a solution to the problem below, or a > > link to some code of which you > > are particularly proud. > > > Problem: In the dynamic language of your choice, write a short program > > that will: > > 1. define a list of the following user ids 42346, 77290, 729 (you can > > hardcode these, but it should > > still work with more or less ids) > > 2. retrieve an xml document related to each user at this url "http:// > > api.etsy.com/feeds/xml_user_details.php?id=" > > 3. retrieve the data contained in the city element from each xml > > document > > 4. keep a running total of how many users are found in each city > > 5. display the total count of users living in each city > > > You can assume user ids are valid and that the url is available. The > > output should look something > > like: > > > Charlotte: 1 > > New York: 2 > > i wanted to make it a one liner, but i had to import modules :( > > import sys, xml, urllib > > dummy = [sys.stdout.write(city + ': ' + str(num) + '\n') for city, num in > set([[(a, o.count(a)) for a in p] for o, p in [2*tuple([[city for city in > ((xml.dom.minidom.parseString(urllib.urlopen('http://api.etsy.com/feeds/xml_user_details.php?id=' > + str(id)).read()).getElementsByTagName('city')[0].childNodes + [(lambda > t: (setattr(t, 'data', 'no city'), > t))(xml.dom.minidom.Text())[1]])[0].data.lower().replace(' ', ' ') for id > in [71234, 71234, 71234, 71234, 71234, 71234, 42792])]])]][0])] Cute, now can you make it readable? ;-) ~S -- http://mail.python.org/mailman/listinfo/python-list
Re: Dumb newbie back in shell
MartinRinehart wrote: > However, here's the little tester I wrote: > > # t.py - testing > > global g > g = 'global var, here' > > def f(): > print g > > f() > > It prints 'global var, here,' not an error message. Wassup? Try it again with a modified f(): def f(): print g g = 42 In Python variables that are assigned to in a function are function-local by default. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie edit/compile/run cycle question
[EMAIL PROTECTED] a écrit : > Bruno, > > Please explain why the NOP import is a GoodThing. Use small words > please. I'm not as young as I used to be. Each module that need access to another module must explicitely import it. This means that, in a typical program, your main script will import a couple modules, each importing other modules, etc. Chances are that some modules - and not necessarily light-weight ones - may end up being imported dozens or more times. Now the import statement does 2 things : first load the module, then inject it in the current namespace. Obviously, the costly operation is the first one, and obviously it doesn't need to be done more than once for a given process. I'd even say it should *not* be done more than once for a given process, since reloading a module doesn't affect objects using the already existing code. So caching the module on first import is obviously the right thing to do. > I didn't know about reload(), but now that I'm informed on that point > I'm still using > > os.remove('foo.pyc') > reload(foo) Mmm... I stopped using the reload function many years ago - in practice, it's the perfect way to go on wild goose chase for bugs that don't even exist - but IIRC, you shouldn't have to manually remove the .pyc file. > A single command to do that would be nice. That was the purpose of the reload function AFAICT. Now it has proven to be such a disaster in practical use that everyone and her sister found better ways - like the ones that have already been suggested here. -- http://mail.python.org/mailman/listinfo/python-list
Re: Dumb newbie back in shell
Thanks, Marc. However, here's the little tester I wrote: # t.py - testing global g g = 'global var, here' def f(): print g f() It prints 'global var, here,' not an error message. Wassup? Marc 'BlackJack' Rintsch wrote: > On Mon, 10 Dec 2007 08:31:01 -0800, MartinRinehart wrote: > > > But that gets me to: > > > > ... line 110, in get_toks > > UnboundLocalError: local variable 'line_ptr' referenced before > > assignment > > > > Here's a bit of the code, with line #s > > > > ... > > 68 global line_ptr > > 69 global char_ptr > > ... > > 75 line_ptr = 0 > > 76 char_ptr = 0 > > ... > > 109 def get_toks( text ): > > 110 while line_ptr < last_line: > > ... > > So when is a global var global? > > When you declare it ``global`` *in the function*. ``global`` on module > level has no effect. IMHO that should emit at least a warning... > > Ciao, > Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Are Python deques linked lists?
Neil Cerutti wrote: > On 2007-12-10, Duncan Booth <[EMAIL PROTECTED]> wrote: >> def test(): >> ll = LinkedList([random.randint(1,1000) for i in range(10)]) >> >> for el in ll: >> if el.value%2==0: >> ll.delete(el) >> >> print [el.value for el in ll] >> >> >> if __name__=='__main__': >> test() >> >> Support for deleting elements other than the current one, and >> insertBefore/insertAfter methods is left as an exercise. > > Making an object its own iterator [works] for files, but not for a > container. After the deletions, you can never iterate again. Look at the test code again -- there is a second iteration after the deletions (the list comprehension). However, you will get into trouble if you try to run two simultaneous iterations over the same LinkedList, so there is room for another exercise ;) Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Dumb newbie back in shell
[EMAIL PROTECTED] a écrit : > OK, it's a scripting language. For which definition of "scripting language" ?-) def g(): > ...os.remove('tokeneizer.pyc') > ...reload( tokeneizer ) > ...tokeneizer.tokenize('sample_decaf.d') > ... > > But that gets me to: > > ... line 110, in get_toks > UnboundLocalError: local variable 'line_ptr' referenced before > assignment > > Here's a bit of the code, with line #s > > ... > 68 global line_ptr > 69 global char_ptr > ... > 75 line_ptr = 0 > 76 char_ptr = 0 > ... > 109 def get_toks( text ): > 110 while line_ptr < last_line: > ... > So when is a global var global? Short answer : never !-) Long answer: First point: "global" really means "module level" - there's no "application global" namespaces. Second point: every name declared as the top-level is global - according to the above definition. So there's no need to declare them as such. The only place where you need the global statement is when you want to rebind a module-level name from within a function. And it's in this function that you need to declare the name as global. FWIW, this is documented. Last point: Python is not C, and it definitively doesn't have pointers. Trying to write C in Python is a waste of time and an experiment in frustration (just like trying to write language XXX in language YYY for any distinct values of XXX and YYY). HTH -- http://mail.python.org/mailman/listinfo/python-list
Re: Dumb newbie back in shell
On Mon, 10 Dec 2007 08:31:01 -0800, MartinRinehart wrote: > But that gets me to: > > ... line 110, in get_toks > UnboundLocalError: local variable 'line_ptr' referenced before > assignment > > Here's a bit of the code, with line #s > > ... > 68 global line_ptr > 69 global char_ptr > ... > 75 line_ptr = 0 > 76 char_ptr = 0 > ... > 109 def get_toks( text ): > 110 while line_ptr < last_line: > ... > So when is a global var global? When you declare it ``global`` *in the function*. ``global`` on module level has no effect. IMHO that should emit at least a warning… Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: GUI development with 3D view
Diez B. Roggisch wrote: ... > I was under the impression that PyOpenGL is ctypes-based in the new > versions? > It is, but I haven't had the time to do a new release and check it on a Windows box. There are minor fixes in CVS that *should* IIRC make us run better on those Windows machines that have problems with the 3.x alphas so far. Tempus fugit, Mike -- Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: I'm missing something here with range vs. xrange
On Dec 7, 2007 8:58 PM, Joe Goldthwaite <[EMAIL PROTECTED]> wrote: > >You can't imagine why someone might prefer an iterative solution over > >a greedy one? Depending on the conditions, the cost of creating the > >list can be a greater or a lesser part of the total time spent. Actual > >iteration is essentially the same cost for both. Try looking at memory > >usage while you're running these tests. > > I can imagine why someone would want to use in iterative solution. What I > don't understand is why there's so little difference between the two. > Here's what I think is going on; > > To do a range(100) > > 1. Allocate a big chunk of memory > 2. Fill the memory with the range of integers > 3. Setup an index into the memory array > 4. Every time the program asks for the next item, bump >the memory index by one, get the value and return it. > No. What range does is create and return a list of integers. The iteration is a separate step, and is traditional list iteration. In longhand, for x in range(y): looks something like this: range = [] #this loop happens in C and is super-fast for small values of y, it #gets much much slower when y gets out of the range of pre-allocated list pools #and the small integer cache while y >= 0: range.append(y) y -= 1 for x in range: #blah List iteration works more or less as you describe, since it's implemented in C. What you describe is more or less how psyco optimizes the use of range(), though. > To do an xrange(1000) > > 1. Set up a counter > 2. Every time the program asks for the next item, increment > the counter and return it. > This is essentially correct, but remember that it's constructing and returning an int object each time. This is exactly the same thing that the range() constructor does, it just happens lazily. > I guess I thought that between these two methods, the second would be > dramatically faster. An order of magnitude faster. My surprise is that it's > not. That's why I figured I'm missing something because the above steps > don't seem to describe what's going on. Hence, the title, "I'm missing > something". > The creation of the xrange object is massively faster - at least an order of magnitude. However, once you actually iterate over both of them you're normalizing almost all of the overhead that range has. The advantage of xrange is the reduced memory pressure (and the improved performance that often entails). -- http://mail.python.org/mailman/listinfo/python-list
Re: detecting disc serial number without win32
PiErre wrote: > I have to run a python script on a Linux machine. This script was > developed on a windows workstation and it > uses the win32 library to detect the cd (or dvd) serial number (in the > - format). > How can I change the script to do the same task on linux? > I found an old post on the same task [ "(Joliet) volume name and > serial number" on 26 Feb 2003 ] > but without answer... Hey, that was my first post on c.l.py. After that underwhelming response I took to answering posts :-) > Any chance there is now a way of implement such a low-level feature? On Ubuntu there is the python-cddb package http://packages.ubuntu.com/gutsy/python/python-cddb providing DiskID.disk_id(), and retrieving CD titles etc. works fine. However, comparing the disk IDs with the serial numbers in that Access-DB of yore, they differ -- so back to square one. Older not wiser, Peter -- http://mail.python.org/mailman/listinfo/python-list
SOAPpy server shutting down?
I have a soap server I am running on an OS X Server using SOAPpy. To start the server I am running server = SOAPpy.SOAPServer(('IPADDRESS", PORT), namespace=NAMESPACE) server.serve_forever() I am starting the server manually in the background by running from the command line as follows: ./mySOAPServer.py & However, when I log out of my ssh session, the server often stops working. I have not been able to find a consistent amount of time it will stay up, however it always seems to go down after an hour or so. Any ideas on how to prevent this or take care of the problem. So far all I could come up with is running a cron job to check for the process, then start it if it is not running. However, in the production environment I need this to be running 24/7 so I can't really afford any down time. I would need to run my cron job every minute or so to get the most up-time possible and would like to avoid this. Any ideas? Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Dumb newbie back in shell
OK, it's a scripting language. >>> def g(): ...os.remove('tokeneizer.pyc') ...reload( tokeneizer ) ...tokeneizer.tokenize('sample_decaf.d') ... >>> But that gets me to: ... line 110, in get_toks UnboundLocalError: local variable 'line_ptr' referenced before assignment Here's a bit of the code, with line #s ... 68 global line_ptr 69 global char_ptr ... 75 line_ptr = 0 76 char_ptr = 0 ... 109 def get_toks( text ): 110 while line_ptr < last_line: ... So when is a global var global? -- http://mail.python.org/mailman/listinfo/python-list
Re: Is a "real" C-Python possible?
On Dec 9, 1:14 pm, "Jack" <[EMAIL PROTECTED]> wrote: > I wonder if it's possible to have a Python that's completely (or at > least for the most part) implemented in C, just like PHP - I think > this is where PHP gets its performance advantage. Or maybe I'm wrong > because the core modules that matter are already in C and those Python > files are really a think wrapper. Anyhow, if would be ideal if Python > has performance similar to Java, with both being interpreted languages. -1 This would seriously muck-up the evolution of the language. Having a few building blocks written in C provides a basis for writing very fast pure python (for example, sets, heapq, itertools). Beyond those building blocks, it is a step backwards to write in C. Also, if you really need performance, the traditional solutions are to use tools like Psyco or Pyrex. Raymond -- http://mail.python.org/mailman/listinfo/python-list
Re: Are Python deques linked lists?
On Dec 9, 10:54 pm, John Machin <[EMAIL PROTECTED]> wrote: > On Dec 10, 9:43 am, "Just Another Victim of the Ambient Morality" > > <[EMAIL PROTECTED]> wrote: > > I'm looking for a linked list implementation. Something iterable with > > constant time insertion anywhere in the list. > > It's on the shelf between the jar of phlogiston and the perpetual > motion machine. lol! -- Ant. -- http://mail.python.org/mailman/listinfo/python-list
Re: a Python person's experience with Ruby
On Dec 9, 2007 5:11 AM, Arnaud Delobelle <[EMAIL PROTECTED]> wrote: > On Dec 9, 12:15 am, Bruno Desthuilliers > <[EMAIL PROTECTED]> wrote: > > Richard Jones a écrit : > > > > > > > > > Bruno Desthuilliers wrote: > > > > >>class A(object): > > >> @apply > > >> def a(): > > >> def fget(self): > > >> return self._a > > >> def fset(self, val): > > >> self._a = val > > >> return property(**locals()) > > >> def __init__(self): > > >> self.a = "foo" > > > > > That property setup seems overly complicated. As far as I can see, it only > > > avoids defining the setter in the class namespace, > > > > Yes. That's mosly the point. > > > > > yet is more complicated > > > and obfuscated to boot ;) > > > > Well, that's your POV, so what can I say ? It's indeed a bit hackish, > > and requires a couple minutes of attention the first time you see it. > > And you just have to learn it once !-) > > Perhaps 'return property(fget, fset)' would be easier to make sense of > than **locals() > > > Now I'd certainly prefer something like: > > > > class A(object): > > @propget > > def a(self): > > return self._a > > @propset > > def a(self, val): > > self._a = val > > > > But until there's something similar *builtin*, I'll stick to the @apply > > trick. > > At first sight, I like the look of this. Obviously I can't provide a > builtin implementation, but there's an easy way to achieve this. It > uses sys._getframe but there is no need to fiddle with metaclasses: > Something very like this will be in 3k, and I believe is also being backported to 2.6. See python-dev archives for more. -- http://mail.python.org/mailman/listinfo/python-list
Re: Error when executing the library reference echo server example
On Mon, 10 Dec 2007 06:38:57 -0800 (PST), [EMAIL PROTECTED] wrote: > [snip] > >I tried it in Linux and it worked fine so I've been trying different >things as the code seems to be correct. >Finally, I've found that if both server and client are run from IDLE, >the thing crashes with the mentioned error. But if the server is run >within a shell and the client within IDLE (or another shell) it works >perfectly. Therefore I suppose the problem is in IDLE (or in my actual >IDLE version) and not in the code. It's certainly true that it may work better in some environments, and it is definitely true that many programs/libraries don't work as expected when run from IDLE. However, that doesn't mean that the example is correct. Keep in mind that handling error conditions is an important part of writing correct programs. You can't rely on everything always going right all the time. Even if you stick with the socket module, you should make sure to handle exceptions from socket calls and always check the return value of the send method. Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list