Re: Tamil/Indian Languages Support in Tkinter
On Tue, 12 Jun 2007 19:32:38 +0200, reverse_gear <[EMAIL PROTECTED]> wrote: > hi, > Does Tkinter has support for tamil/Indian Languages?? > I tried this code > it is able to print both tamil and german text on console.. but on > Tkinter Label it is printing only the german code > Plz help > from Tkinter import * > import codecs > > german_ae = unicode('\xc3\xa4','utf-8') > tamil_text = unicode('\xe0\xae\xb9\xe0\xae\xbf \xe0\xae\xae\xe0\xaf > \x81\xe0\xae\x95\xe0\xaf\x81\xe0\xae\xa9\xe0\xaf\x8d\xe0\xae\x9f > \xe0\xaf\x8d','utf-8') > root = Tk() > print tamil_text > print german_ae > label = Label(root, text = german_ae) > label2= Label(root, text = tamil_text) > label.pack() > label2.pack() > mainloop() If you have a recent version of tcl/tk, it should work as long as you have the proper fonts installed.BTW, I tried it and the tamil text didn't show at all on my Linux box: no text on the console (just squares) and nothing in the Tkinter label. But I certainly don't have any font able to display these characters. This is apparently not your problem since if it works on the console, you should have a usable font. So my guess would be that some font installed on your system claims to be able to display these characters, but actually isn't. Since you didn't specify a font to use in your labels and the default font probably can't display tamil, tk looks for a font that can. When it finds one, it stops and uses it. So if a font claims to have these characters, but actually can't display them, you end up with a blank text. Did you try to specify the font to use in the labels? A good candidate would obviously be the font used by the console. And you didn't specify on which platform you were, or your Python and tcl/tk version. This may help... HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" -- http://mail.python.org/mailman/listinfo/python-list
Re: Bytes/File Size Format Function
samuraisam <[EMAIL PROTECTED]> wrote: > >Quick file size formatting for all those seekers out there... > >import math > >def filesizeformat(bytes, precision=2): >"""Returns a humanized string for a given amount of bytes""" >bytes = int(bytes) >if bytes is 0: >return '0bytes' >log = math.floor(math.log(bytes, 1024)) >return "%.*f%s" % ( >precision, >bytes / math.pow(1024, log), >['bytes', 'kb', 'mb', 'gb', 'tb','pb', 'eb', 'zb', 'yb'] >[int(log)] >) I have a couple of picky comments. The abbreviation for "bytes" should be "B"; small "b" is bits by convention. All of the prefixes above "k" should be capitalized: kB, MB and GB, not mb and gb. The truly anal retentive would probably argue that you should be using kiB, MiB, and GiB, since you are basing your scale on 1024 instead of 1000. -- Tim Roberts, [EMAIL PROTECTED] Providenza & Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
How to create a tuple quickly with list comprehension?
Hi all, I can use list comprehension to create list quickly. So I expected that I can created tuple quickly with the same syntax. But I found that the same syntax will get a generator, not a tuple. Here is my example: In [147]: a = (i for i in range(10)) In [148]: b = [i for i in range(10)] In [149]: type(a) Out[149]: In [150]: type(b) Out[150]: Is there a way to create a tuple like (1, 2, 3, 4, 5, 6, 7, 8, 9) quickly? I already I can use tuple() on a list which is created by list comprehension to get a desired tuple. Regards, Xiao Jianfeng -- http://mail.python.org/mailman/listinfo/python-list
Re: Bytes/File Size Format Function
On Jun 12, 8:47 pm, samuraisam <[EMAIL PROTECTED]> wrote: > Quick file size formatting for all those seekers out there... > > import math > > def filesizeformat(bytes, precision=2): > """Returns a humanized string for a given amount of bytes""" > bytes = int(bytes) > if bytes is 0: > return '0bytes' > log = math.floor(math.log(bytes, 1024)) > return "%.*f%s" % ( > precision, > bytes / math.pow(1024, log), > ['bytes', 'kb', 'mb', 'gb', 'tb','pb', 'eb', 'zb', 'yb'] > [int(log)] > ) Wait a sec...what if you send it a large amount of bytes? Say... bigger than 2147483647. You'll get an OverflowError. I thought you had my solution... ~Sean -- http://mail.python.org/mailman/listinfo/python-list
Re: Bytes/File Size Format Function
On Jun 13, 12:48 am, [EMAIL PROTECTED] wrote: > On Jun 12, 8:47 pm, samuraisam <[EMAIL PROTECTED]> wrote: > > > > > Quick file size formatting for all those seekers out there... > > > import math > > > def filesizeformat(bytes, precision=2): > > """Returns a humanized string for a given amount of bytes""" > > bytes = int(bytes) > > if bytes is 0: > > return '0bytes' > > log = math.floor(math.log(bytes, 1024)) > > return "%.*f%s" % ( > > precision, > > bytes / math.pow(1024, log), > > ['bytes', 'kb', 'mb', 'gb', 'tb','pb', 'eb', 'zb', 'yb'] > > [int(log)] > > ) > > Wait a sec...what if you send it a large amount of bytes? Say... > bigger than 2147483647. You'll get an OverflowError. I thought you > had my solution... > > ~Sean -- http://mail.python.org/mailman/listinfo/python-list
Re: Bytes/File Size Format Function
On Jun 13, 12:48 am, [EMAIL PROTECTED] wrote: > On Jun 12, 8:47 pm, samuraisam <[EMAIL PROTECTED]> wrote: > > > > > Quick file size formatting for all those seekers out there... > > > import math > > > def filesizeformat(bytes, precision=2): > > """Returns a humanized string for a given amount of bytes""" > > bytes = int(bytes) > > if bytes is 0: > > return '0bytes' > > log = math.floor(math.log(bytes, 1024)) > > return "%.*f%s" % ( > > precision, > > bytes / math.pow(1024, log), > > ['bytes', 'kb', 'mb', 'gb', 'tb','pb', 'eb', 'zb', 'yb'] > > [int(log)] > > ) > > Wait a sec...what if you send it a large amount of bytes? Say... > bigger than 2147483647. You'll get an OverflowError. I thought you > had my solution... > > ~Sean I take it back. -- http://mail.python.org/mailman/listinfo/python-list
Re: a question about unicode in python
2007/6/12, WolfgangZ <[EMAIL PROTECTED]>: > hzqij schrieb: > > i have a python source code test.py > > > > # -*- coding: UTF-8 -*- > > > > # s is a unicode string, include chinese > > s = u'张三' > > > > then i run > > > > $ python test.py > > UnicodeDecodeError: 'utf8' codec can't decode bytes in position 0-1: > > invalid data > > > > by in python interactive, it is right > > > s = u'张三' > > > > why? > > > > > > just an idea: is your text editor really supporting utf-8? In the mail > it is only displayed as '??' which looks for me as the mail editor did > not send the mail as utf. Try to attach a correct text file. That must be your mail client, not his text editor or mail client. I do see two Chinese characters in the message. -- Andre Engels, [EMAIL PROTECTED] ICQ: 6260644 -- Skype: a_engels -- http://mail.python.org/mailman/listinfo/python-list
Re: Multiline lamba implementation in python.
"Gabriel Genellina" <[EMAIL PROTECTED]> wrote: > But you already have "multiline" lambdas right now in that sense, no > need to add anything. I think you were talking about lambdas *with* > statements inside. > > bin = lambda x:((x&8 and '*' or '_') + > (x&4 and '*' or '_') + > (x&2 and '*' or '_') + > (x&1 and '*' or '_')) Or in more recent versions of Python: bin = lambda x:(('*' if x&8 else '_') + ('*' if x&4 else '_') + ('*' if x&2 else '_') + ('*' if x&1 else '_')) but seriously, any example of lambda which simply assigns the function to a variable is flawed. I can sort of understand the people who object to a named function taking the logic 'out of line', but any expression which actually requires a multi-statement function to be embedded in the middle of it is already in danger of causing my brain to implode. -- http://mail.python.org/mailman/listinfo/python-list
Re: userinteraction for a webspider
James Stroud schrieb: > > There are sweatshops in developing countries that provide this service. > > James But since this is for fun/convenience for me only Id rather not make anyone break asweat... Great advice, helpful too -- http://mail.python.org/mailman/listinfo/python-list
Re: How to save python codes in files?
Evan Klitzke wrote: > On 6/12/07, why? <[EMAIL PROTECTED]> wrote: > > Im working with Python 2.2 on my red hat linux system. Is there any > > way to write python codes in separate files and save them so that i > > can view/edit them in the future? Actually I've just started with > > python and would be grateful for a response. Thanx! > > Of course -- just put the code into a text file (using your favorite > text editor) and then run the script using the python command, e.g. by > executing on a command line: > python my_program.py > > Since you're on a Linux system you can also use this as the first line > of your file and then chmod +x the file to make it into an executable > script: > > #!/usr/bin/env python > > -- Im still unable to follow... :( See, if i have to save the following code in a file, how should i proceed? >>> def sum(x,y): return x+y ... >>> -- http://mail.python.org/mailman/listinfo/python-list
Re: How to create a tuple quickly with list comprehension?
On 13 Cze, 09:45, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote: > Hi all, > > I can use list comprehension to create list quickly. So I expected that I > can created tuple quickly with the same syntax. But I found that the > same syntax will get a generator, not a tuple. Here is my example: > > In [147]: a = (i for i in range(10)) > > In [148]: b = [i for i in range(10)] > > In [149]: type(a) > Out[149]: > > In [150]: type(b) > Out[150]: > > Is there a way to create a tuple like (1, 2, 3, 4, 5, 6, 7, 8, 9) > quickly? I already I can use tuple() on a list which is created by list > comprehension to get a desired tuple. > > Regards, > > Xiao Jianfeng You should do it like this: >>> a = tuple([i for i in range(10)]) >>> type(a) >>> print a[0] 0 >>> print a[9] 9 >>> print a (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) Cheers, Marek -- http://mail.python.org/mailman/listinfo/python-list
Re: How to save python codes in files?
On 6/13/07, why? <[EMAIL PROTECTED]> wrote: > > Evan Klitzke wrote: > > On 6/12/07, why? <[EMAIL PROTECTED]> wrote: > > > Im working with Python 2.2 on my red hat linux system. Is there any > > > way to write python codes in separate files and save them so that i > > > can view/edit them in the future? Actually I've just started with > > > python and would be grateful for a response. Thanx! > > > > Of course -- just put the code into a text file (using your favorite > > text editor) and then run the script using the python command, e.g. by > > executing on a command line: > > python my_program.py > > > > Since you're on a Linux system you can also use this as the first line > > of your file and then chmod +x the file to make it into an executable > > script: > > > > #!/usr/bin/env python > > > > -- > Im still unable to follow... :( > See, if i have to save the following code in a file, how should i > proceed? > >>> def sum(x,y): return x+y > ... > >>> If you want to write a program, you need to have some code that actually does something (rather than just containing definitions of functions). Here's a trivial example of a file using your sum function: #!/usr/bin/env python def sum(x, y): return x+y print 'Enter two numbers:' x = int(raw_input()) y = int(raw_input()) print 'The sum is equal to %s + %s = %s' % (x, y, sum(x,y)) -- Evan Klitzke <[EMAIL PROTECTED]> -- http://mail.python.org/mailman/listinfo/python-list
Re: How to create a tuple quickly with list comprehension?
markacy wrote: > On 13 Cze, 09:45, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote: >> Hi all, >> >> I can use list comprehension to create list quickly. So I expected that I >> can created tuple quickly with the same syntax. But I found that the >> same syntax will get a generator, not a tuple. Here is my example: >> >> In [147]: a = (i for i in range(10)) >> >> In [148]: b = [i for i in range(10)] >> >> In [149]: type(a) >> Out[149]: >> >> In [150]: type(b) >> Out[150]: >> >> Is there a way to create a tuple like (1, 2, 3, 4, 5, 6, 7, 8, 9) >> quickly? I already I can use tuple() on a list which is created by list >> comprehension to get a desired tuple. >> >> Regards, >> >> Xiao Jianfeng > > You should do it like this: > a = tuple([i for i in range(10)]) type(a) > print a[0] > 0 print a[9] > 9 print a > (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) No need to create the intermediate list, a generator expression works just fine: a = tuple(i for i in range(10)) Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: questions about solving equations in scipy
Hi Robert, Thanks a lot for your kindness. Robert Kern wrote: > [EMAIL PROTECTED] wrote: >> Hi all, >> >> I have two questions about scipy. > > You're likely to get a better response from the scipy mailing list. Here, you'll > primarily get me, and I have to rush out right now. > > http://www.scipy.org/Mailing_Lists In fact, I have tried to subscribe to the list, but got no response. I will try again. > >> 1) When I was trying to solve a single variable equations using scipy, I >> found two methods: scipy.optimize.fsolve, which is designated to find the >> roots of a polynomial, > > No, it finds the roots of a non-linear system of N functions in N variables. The > documentation makes no mention of polynomials. > >> and scipy.optimize.newton, which is used for Scalar >> function root finding according to the help(). > > There's also brentq, brenth, ridder, and bisect for this problem. > >> I have tried both, and it seemed that both worked well, and fsolve ran >> faster. >> >> My questions is, which is the right choose ? > > Whichever one works faster and more robustly for your problem. fsolve is > implemented in FORTRAN, which sometimes helps. I do recommend looking at the > brentq and brenth if you can provide bounds rather than just an initial guess. "brentq" or "brenth" are used to find a zero of the function f between the argument a and b. It demanded that f(a) and f(b) can not have the same signs. I think it is very convenient to provide valid a and b before I've got the solution of the function. > >> 2) I have to solve a linear equation, with the constraint that all >> variables should be positive. Currently I can solve this problem by >> manually adjusting the solution in each iteration after get the solution >> bu using scipy.linalg.solve(). >> >> Is there a smart way ? > > I don't think that's a well-defined problem. Either the (unique) solution is I found a web page about optimization solver in openoffice( http://wiki.services.openoffice.org/wiki/Optimization_Solver#Non-Linear_Programming). Openoffice has an option of "Allow only positive values", so I think that's a well-defined problem. Sorry for my ignorance if I was wrong. > within the constraint or it's not. Are you sure you don't want to find the > minimum-error solution that obeys the constrain, instead? Yes, I do want to find the minimum-error solution that obeys the constrain. Please tell me more ! Regards, Xiaojf -- http://mail.python.org/mailman/listinfo/python-list
Re: How to save python codes in files?
On 13 Cze, 10:06, why? <[EMAIL PROTECTED]> wrote: > Evan Klitzke wrote: > > On 6/12/07, why? <[EMAIL PROTECTED]> wrote: > > > Im working with Python 2.2 on my red hat linux system. Is there any > > > way to write python codes in separate files and save them so that i > > > can view/edit them in the future? Actually I've just started with > > > python and would be grateful for a response. Thanx! > > > Of course -- just put the code into a text file (using your favorite > > text editor) and then run the script using the python command, e.g. by > > executing on a command line: > > python my_program.py > > > Since you're on a Linux system you can also use this as the first line > > of your file and then chmod +x the file to make it into an executable > > script: > > > #!/usr/bin/env python > > > -- > > Im still unable to follow... :( > See, if i have to save the following code in a file, how should i > proceed? > > >>> def sum(x,y): return x+y > ... :D You should try some basic manual on linux :D Copy and paste the code (do not include >>> and ...) to the editor, save. Then run as advised above. Good luck. Cheers, Marek -- http://mail.python.org/mailman/listinfo/python-list
Re: a question about unicode in python
On 6/13/07, Andre Engels <[EMAIL PROTECTED]> wrote: > 2007/6/12, WolfgangZ <[EMAIL PROTECTED]>: > > hzqij schrieb: > > > i have a python source code test.py > > > > > > # -*- coding: UTF-8 -*- > > > > > > # s is a unicode string, include chinese > > > s = u'张三' > > > > > > then i run > > > > > > $ python test.py > > > UnicodeDecodeError: 'utf8' codec can't decode bytes in position 0-1: > > > invalid data > > > > > > by in python interactive, it is right > > > > > s = u'张三' > > > > > > why? > > > > > > > > > > just an idea: is your text editor really supporting utf-8? In the mail > > it is only displayed as '??' which looks for me as the mail editor did > > not send the mail as utf. Try to attach a correct text file. > > That must be your mail client, not his text editor or mail client. I > do see two Chinese characters in the message. Nonetheless, the email is not UTF-8 encoded (it's encoded in gb2312, which is much more commonly used in China than UTF-8). It's likely that the source code file is encoded using GB characters as well. -- Evan Klitzke <[EMAIL PROTECTED]> -- http://mail.python.org/mailman/listinfo/python-list
Re: cgi.FieldStorage() not working on Windows
On Jun 13, 12:58 pm, arorap <[EMAIL PROTECTED]> wrote: > Thanks for your reply. > > The reason I want to run it as CGI (even though mod_php is available > on my local computer Why do you keep mentioning mod_php, surely you mean mod_python. > is that the target machine to which I will > finally be uploading my scripts runs CGI. > > cgihandler should work just like CGI. I wouldn't rely on it being exactly the same. The way it works uses a number of kludges. Also, the mod_python.cgihandler code in mod_python doesn't really get much attention from mod_python developers anymore and not sure if it was even specifically retested when mod_python 3.3 was released. > Any clue why the > cgi.FieldStorage()might not be working ? Have no idea why it doesn't work as works as written on MacOS X even when mod_python.cgihandler is used. You'll have to get someone else who has Windows to try it. You might be better off going to the mod_python mailing list to get help, or just use plain old CGI instead since using mod_python isn't really going to gain you much anyway. Graham > On Jun 12, 7:59 pm, Graham Dumpleton <[EMAIL PROTECTED]> > wrote: > > > On Jun 13, 1:17 am,arorap<[EMAIL PROTECTED]> wrote: > > > > I've mod_php installed with Apache 2.2. In one of my folders, I'm > > > using the cgihandler as the PythonHandler as my target host runs > > > python only as CGI. Here cgi.FieldStorage() doesn't seem to work. I > > > can see the form data in sys.stdin but cgi.FieldStorage() returns an > > > empty dictionary. Here's the code for the test script I am posting to > > > - > > > > -- > > > #!/usr/bin/python > > > > import os > > > import cgi > > > import sys > > > > print "Content Type: text/plain\n\n" > > > print "Hello CGI World !\n" > > > > for key in os.environ: > > > print key + "= " + os.environ[key] > > > > print cgi.FieldStorage() > > > > print sys.stdin.read() > > > -- > > > > And here's the output I see .. > > > > -- > > > Hello CGI World ! > > > > HTTP_REFERER=http://learnpython/form.htm > > > SERVER_SOFTWARE= Apache/2.2.4 (Win32)mod_python/3.3.1 Python/2.5.1 > > > SCRIPT_NAME= /mptest.py > > > SERVER_SIGNATURE= > > > REQUEST_METHOD= POST > > > SERVER_PROTOCOL= HTTP/1.1 > > > QUERY_STRING= abc=ayz > > > PATH= C:\Program Files\Internet Explorer;;C:\WINDOWS\system32;C: > > > \WINDOWS;C:\WINDOWS\System32\Wbem;q:\bin;m:\cm\clearcase\bin;M:\PERL\NT > > > \EXEC\BIN;m:\cm\clearcase\bin\nt;M:\Perl\NT\EXEC\BIN;m:\perl\nt\exec > > > \bin;m:\cm\clearcase\utils;q:\bin;m:\opus;m:\tvcs;C:\highc331\bin;C: > > > \Program Files\Rational\ClearCase\bin;C:\Program Files\Rational\common > > > CONTENT_LENGTH= 86 > > > HTTP_USER_AGENT= Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; > > > SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727) > > > HTTP_CONNECTION= Keep-Alive > > > SERVER_NAME= learnpython > > > REMOTE_ADDR= 127.0.0.1 > > > PATHEXT= .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH > > > SERVER_PORT= 80 > > > SERVER_ADDR= 127.0.0.1 > > > DOCUMENT_ROOT= D:/Projects/LearnPython/www > > > COMSPEC= C:\WINDOWS\system32\cmd.exe > > > SCRIPT_FILENAME= D:/Projects/LearnPython/www/mptest.py > > > SERVER_ADMIN= [EMAIL PROTECTED] > > > HTTP_HOST= learnpython > > > SystemRoot= C:\WINDOWS > > > HTTP_CACHE_CONTROL= no-cache > > > REQUEST_URI= /mptest.py?abc=ayz > > > HTTP_ACCEPT= */* > > > WINDIR= C:\WINDOWS > > > GATEWAY_INTERFACE= Python-CGI/1.1 > > > REMOTE_PORT= 1081 > > > HTTP_ACCEPT_LANGUAGE= en-us > > > CONTENT_TYPE= application/x-www-form-urlencoded > > > HTTP_ACCEPT_ENCODING= gzip, deflate > > > > FieldStorage(None, None, []) > > > > firstName=puneet&address=hawaii > > > -- > > > > I am posting to this script using a form with two text fields named > > > firstName and address. > > > > any clue where am I going wrong ? > > > You don't need mod_python/cgihandler to run CGI scripts. Rather than > > bring mod_python into the picture and confuse things, set up Apache to > > run your script as a traditional CGI script instead. > > > BTW, the fact that mod_python is loaded means that CGI scripts aren't > > the only way of using Python available to you as you seem to think. > > So, suggest you do some research as to what the differences are > > between CGI and mod_python. -- http://mail.python.org/mailman/listinfo/python-list
Re: MS Word parser
[EMAIL PROTECTED] wrote: > Hi all, > I'm currently using antiword to extract content from MS Word files. > Is there another way to do this without relying on any command prompt > application? Well you haven't given your environment, but is there anything to stop you from controlling Word itself via COM? I'm no Word expert, but looking around, this seems to work: import win32com.client word = win32com.client.Dispatch ("Word.Application") doc = word.Documents.Open ("c:/temp/temp.doc") text = doc.Range ().Text open ("c:/temp/temp.txt", "w").write (text.encode ("UTF-8")) TJG -- http://mail.python.org/mailman/listinfo/python-list
Dive into Python 5.5
Hi, class UserDict: def __init__(self, dict=None): self.data = {} if dict is not None: self.update(dict) I just don't understant this code, as it is not also mention in the book. the update is a method of a dict right? in my understanding the last statement should be self.data.update(dict). someone please explain to me what happen where? Thanks james -- http://mail.python.org/mailman/listinfo/python-list
How to format a string from an array?
a = range(256) I want to output the formated string to be: 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f f0 f1 f2 f3 f4 f5 6 f7 f8 f9 fa fb fc fd fe ff How to do it? -- http://mail.python.org/mailman/listinfo/python-list
Re: Postpone creation of attributes until needed
On Jun 13, 1:24 am, Steven D'Aprano <[EMAIL PROTECTED]> wrote: > On Tue, 12 Jun 2007 08:53:11 -0700, Frank Millman wrote: > > Ah, if I had ever read that there were two instances involved, I hadn't > noticed. Sorry! > No problem - I really appreciate your input. I snipped the rest of your post, as I have figured out a way to make my problem go away, without changing my code radically. It was a 'sequence of events' problem. 1. create table a 2. create table b, create pseudo column on table a, link to column on table b 3. create table c, create pseudo column on table b, link to column on table c This works most times, but if, in step 2, I want to link the pseudo column in table a to the pseudo column in table b, it fails, as the pseudo column in table b does not get created until step 3. Now, if I try to link to a column that does not exist, I set a flag and carry on. When I go to the next step, after creating the pseudo column, I check if the flag exists, and if so I go back and create the link that it tried to create in the first place. It is not very pretty, but it has the big advantage that, by the time all the tables are opened, all the links are correctly set up, and I never have the problem of trying to access non-existent attributes. I will try to explain what benefit all this gives me. Assume a Customers table and an Invoices table. Customers has a primary key which is a generated 'next number', and an alternate key which is the Customer Code. Users will never see the primary key, only the alternate key. Invoices has a foreign key CustomerId, which references the primary key of Customers. However, when capturing an invoice, the user wants to enter the code, not the primary key. It is not difficult to program for this, but it is tedious to do it on every data-entry form. Therefore, in my framework, I set up a pseudo column on Invoices called CustomerCode, which the application programmer can use as if it is a real column. Behind the scenes, I automatically use that to check that it is a valid code, and populate the real column with the primary key. This has been working for some time, and really simplifies the 'business logic' side of things by abstracting a common idiom which would otherwise have to be coded explicitly every time. Now I have added a complication. I have decided to implement the idea of using a single table to store details of all parties with whom we have a relationship, such as Customers, Suppliers, Agents, etc, instead of separate tables each with their own Code, Name, and Address details. Therefore I now have the following- a Parties table with a 'next number' primary key and a PartyCode alternate key, a Customers table with a 'next number' primary key and a PartyId foreign key reference to the Parties table, and an Invoices table with a CustomerId foreign key reference to the Customers table. Now when capturing an invoice, the user enters a Code, then the program must check that the code exists on Parties, retrieve the primary key, then check that it exists on Customers, retrieve that primary key, then store the result on Invoices, with appropriate error messages if any step fails. I have successfully abstracted all of that, so all that complication is removed from the application. Hope that makes sense. Thanks very much for all your attempts to help me, Steven. You have succeeded in getting me to think properly about my problem and come up with a much cleaner solution. I really appreciate it. Frank -- http://mail.python.org/mailman/listinfo/python-list
Re: updating db with csv
On 13 Jun, 06:35, Tim Roberts <[EMAIL PROTECTED]> wrote: > Captain Paralytic <[EMAIL PROTECTED]> wrote: > >On 11 Jun, 07:37, Tim Roberts <[EMAIL PROTECTED]> wrote: > >| Not in standard SQL. MySQL supports a REPLACE extension that does > >| an UPDATE if the key already exists, and an INSERT if it does not. > >| There is also an extension clause to the INSERT statement called > >| "ON DUPLICATE KEY UPDATE xxx" that might do what you want. > > >No Tim, that is not correct. the REPLACE extension does not do an > >update, it does a replace. It delets the old record and inserts a new > >one. The INSERT...ON DUPLICATE KEY UPDATE... does an update. So a > >REPLACE will remove all existing field values not referenced in the > >statement, whilst an INSERT...ON DUPLICATE KEY UPDATE... will preserve > >them. Also REPLACE will make a TIMESTAMP column which has a DEFAULT > >CURRENT_TIMESTAMP setting work like one which has ON UPDATE > >CURRENT_TIMESTAMP DEFAULT CURRENT_TIMESTAMP setting. > > Thanks for the correction; that's an important difference. I'm a Postgres > guy; if I had noticed this was cross-posted to c.d.mysql as well as > comp.lang.python, I probably would have kept quiet. > -- > Tim Roberts, [EMAIL PROTECTED] > Providenza & Boekelheide, Inc. But then you wouldn't have learned about this important difference. I too learn a lot when I give what I think is a correct answer and then have someone else explain what really happens. The wonder of usenet. -- http://mail.python.org/mailman/listinfo/python-list
Re: In C extension .pyd, sizeof INT64 = 4?
On 6 13 , 11 55 , "Martin v. Löwis" <[EMAIL PROTECTED]> wrote: > > I used INT64 and initialize its value from PyArg_ParseTuple. > > The code is PyArg_ParseTuple(args, "l", &nValue). > > It should be PyArg_ParseTuple(args, "L", &nValue). > > That's still incorrect. For the L format flag, use PY_LONG_LONG, > not your own INT64 type. More generally: always use the type > documented in > > http://docs.python.org/api/arg-parsing.html > > Regards, > Martin PY_LONG_LONG is decleared as __int64 on windows. There is no difference. Regards, Allen Chen -- http://mail.python.org/mailman/listinfo/python-list
Re: Where can I suggest an enchantment for Python Zip lib?
> On my 3 year old 3Ghz Pentium III it takes about 8 seconds to zip 20Mb file. > So what is the problem? Not updating the process for 8-10 seconds > should be just fine for most applications. > > -Larry The problem, that: - I want to process 100-200 MB zip files. - I want to abort in process - I want to know the actual position - I want to slow the operation sometimes! Why I want to slow? The big archiving is slow operation. When it is slow, I want to working with other apps while it is processing. So I want to slow the zipping with time.sleep, then the background thread is not use the full CPU... I can work with other apps. dd -- http://mail.python.org/mailman/listinfo/python-list
Re: Bytes/File Size Format Function
samuraisam <[EMAIL PROTECTED]> writes: > Quick file size formatting for all those seekers out there... > > import math > > def filesizeformat(bytes, precision=2): > """Returns a humanized string for a given amount of bytes""" > bytes = int(bytes) > if bytes is 0: > return '0bytes' > log = math.floor(math.log(bytes, 1024)) > return "%.*f%s" % ( > precision, > bytes / math.pow(1024, log), > ['bytes', 'kb', 'mb', 'gb', 'tb','pb', 'eb', 'zb', 'yb'] > [int(log)] > ) The output doesn't match the calculation. The symbol for "bit" is 'b'. The symbol for "byte" is 'B'. 'kb' is 'kilobit', i.e. 1000 bits. 'mb' is a "metre-bit", a combination of two units. And so on. The SI units have definitions that are only muddied by misusing them this way. Especially since we now have units that actually do mean what we want them to. The units that match the calculation you're using are 'KiB', 'MiB', 'GiB' and so on. http://en.wikipedia.org/wiki/Binary_prefix> Dividing by 1024 doesn't give 'kb', it gives 'KiB'. Likewise for the rest of the units. So the list of units should be:: ['bytes', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'] -- \ Contentsofsignaturemaysettleduringshipping. | `\ | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: List sequential initialization
In article <[EMAIL PROTECTED]>, HMS Surprise <[EMAIL PROTECTED]> wrote: > I thought if I could do this: > >>> a = b = '' a and b refer to the same object (the empty string) > >>> a = 'a' You are assigning a new value to a - it now refers to the string 'a', while b refers to the same thing it always has (the empty string) > >>> a > 'a' > >>> b > '' > > then this would behave similarly: > >>> la = lb = [] la and lb refer to the same object, an empty list > >>> la.append('a') You are appending 'a' to the list that la refers to. > >>> la > ['a'] > >>> lb > ['a'] Since lb referred to the same list as la, when you modified the list via la.append, those changes can also be seen via lb. If instead of la.append('a'), you had done: la = ['a'] Then it would have behaved similarly to the first example, and lb would still refer to an empty list. > > I thought wrong! But don't know why. For immutable objects (such as integers, strings, and tuples), the distinction between pointing to the same object or identical copies isn't important since you cannot modify the objects. However, when you use mutable objects (such as lists) and modify them, then it is important to understand when you are dealing with the same object and when you are copying the object. Assignment makes a name refer to an object. Multiple names can refer to the same object (which is what a=b=c does). If you want to make a copy of the object, you need to do so explicitly: >>> a = [1, 2, 3] >>> b = list(a) >>> a.append(4) >>> a [1, 2, 3, 4] >>> b [1, 2, 3] Dave -- http://mail.python.org/mailman/listinfo/python-list
Is there any way to catch expections when call python method in C++
I use try catch, but cannot catch the execeptions of execution python method. PYCALL_API void PyCall(const char * pszModule, const char * pszFunc, void * pArg) { if (pszModule == NULL || pszFunc == NULL) { return; } Py_Initialize(); PyObject * pModule = NULL; PyObject * pFunc = NULL; try { pModule = PyImport_ImportModule(pszModule); pFunc = PyObject_GetAttrString(pModule, pszFunc); PyEval_CallObject(pFunc, (PyObject*)pArg); } catch (...) { fprintf(stderr, "Error: call python method failed"); } Py_Finalize(); } Can I catch it from C++? Thank you. Regards, Allen Chen -- http://mail.python.org/mailman/listinfo/python-list
Re: Dive into Python 5.5
james_027 <[EMAIL PROTECTED]> writes: > class UserDict: > def __init__(self, dict=None): > self.data = {} > if dict is not None: self.update(dict) The code confusingly shadows the builtin 'dict' type with a poorly-chosen parameter name. See if this makes things less confusing:: class UserDict: def __init__(self, from=None): self.data = {} if from is not None: self.update(from) > I just don't understant this code, as it is not also mention in the > book. the update is a method of a dict right? in my understanding > the last statement should be self.data.update(dict). As you point out, the 'update' method isn't defined, and the class inherits from no base classes, so this class as written will fail in the __init__ method when the 'self.update' attribute cannot be found. What should be happening is that the class should inherit from the Python dict type: class UserDict(dict): # ... That way, the 'update' method will be inherited from the 'dict.update' method, and likewise for all the other behaviour expected from a dict type. -- \"Madness is rare in individuals, but in groups, parties, | `\ nations and ages it is the rule." -- Friedrich Nietzsche | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Dive into Python 5.5
> class UserDict: > def __init__(self, dict=None): > self.data = {} > if dict is not None: self.update(dict) > > I just don't understant this code, as it is not also mention in the > book. the update is a method of a dict right? in my understanding the > last statement should be self.data.update(dict). > > someone please explain to me what happen where? You are right, this code will not work, and your suggestion is a reasonable one. HTH, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: How to create a tuple quickly with list comprehension?
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes: > I can use list comprehension to create list quickly. So I expected > that I can created tuple quickly with the same syntax. Nope. The list comprehension syntax creates lists. > But I found that the same syntax will get a generator, not a > tuple. Here is my example: > > In [147]: a = (i for i in range(10)) This contains no commas, so I don't know why you think it has anything to do with a tuple. Bear in mind that parentheses have nothing to do with the syntax for creating a tuple; the parentheses merely determine parsing order, and can enclose any expression. > Is there a way to create a tuple like (1, 2, 3, 4, 5, 6, 7, 8, 9) > quickly? tuple(range(1, 10)) -- \"Know what I hate most? Rhetorical questions." -- Henry N. Camp | `\ | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: cStringIO change in 2.4 vs 2.5. Regression?
Terry Reedy wrote: > "Markus Schöpflin" <[EMAIL PROTECTED]> wrote in message > news:[EMAIL PROTECTED] > | Hello, > | > | I just stumbled accross a difference between cStringIO in Python 2.4 > | and 2.5. You can no longer feed arrays to cStringIO. > [snip] > | Has this change been done on purpose or is it a regression? > > I doubt that an intentional change would have been made for cStringIO and > not StringIO. Two ways to investigate: scan the detailed listing of 2.5 > changes for mention of array and cStringIO modules; check the source code > checkin messages for both for the relevant time period. This might also > suggest who to send an inquiry to who might not be reading here. First of all, thank you very much for you answer and sorry for the late reply, I was AFK for some days. I scanned the NEWS file and the only change which caught my attention is - Patches #1298449 and #1298499: Add some missing checks for error returns in cStringIO.c. but the corresponding check-in doesn't look suspicious. Next I had a look at the source code of the trunk: cStringIO.c:newIobject() calls abstract.c:PyObject_AsCharBuffer(), which, AFAICT, is the only possible source for the exception reported. The exception is raised when the given object doesn't have conversions to an I/O buffer, but when looking at arraymodule.c there is array_as_buffer which provides the needed conversions. The code looks pretty much the same on the 2.5 branch, so I don't have an explanation for the observed behaviour. > If you do not get a satifactory resolution here, file a bug report on SF. > But remember that all bug fixers are volunteers just like you, so any > investigation you do and report on to make response easier will likely make > it quicker also. I think I'll file a bug at SF... maybe someone else will spot something. Thanks, Markus -- http://mail.python.org/mailman/listinfo/python-list
Re: Dive into Python 5.5
On Jun 13, 2:40 am, james_027 <[EMAIL PROTECTED]> wrote: > Hi, > > class UserDict: > def __init__(self, dict=None): > self.data = {} > if dict is not None: self.update(dict) > > I just don't understant this code, as it is not also mention in the > book. the update is a method of a dict right? in my understanding the > last statement should be self.data.update(dict). > > someone please explain to me what happen where? > > Thanks > james This is what "Dive" says: --- To explore this further, let's look at the UserDict class in the UserDict module...In particular, it's stored in the lib directory in your Python installation. --- So you can actually locate the file UserDict.py on your computer and look at the code. If you don't want to do that, then the following is an explanation of what's going on with that code. Suppose you have a class like this: class Dog(object): def __init__(self): self.update() When __init__ executes, the only line in __init__ says go look in self for the method update() and execute it. That means the Dog class probably has at least one additional method: class Dog(object): def __init__(self): self.update() def update(self): print "hello" So if you wrote: d = Dog() the output would be: hello Ok, now suppose you add a line to __init__: class Dog(object): def __init__(self): self.data = {} self.update() def update(self): print "hello" Does the new line in __init__ affect the line self.update() in any way? Is there necessarily any connection between self.data and update()? No. However, if you look at the actual code for UserDict, you can see that inside the method update(), items are added to self.data, so there is a connection. Then the question is: why didn't the person who wrote the class just do the following in __init__: self.data.update(dict) Well, as it turns out, adding items to self.data is not that straight forward. self.data is a dict type and dict types have an update() method that requires another dict as an argument. But the 'dict' parameter variable in __init__ could be sent a dict type or it could be sent another instance of UserDict. So, the code to add items to self.data got complicated enough that the writer of the class decided to move the code into its own method. Note that just because the parameter variable is named 'dict' does not mean the argument sent to the function is a dict type. For instance, you could write this: dict = "hello world" As you can see, the variable named 'dict' does not refer to a dict type. Using a python type as a variable name is a horrible and confusing thing to do, so don't do it in your code. In addition, the writer of the class wanted to provide an update() method for the UserDict class, which could be called at any time, so instead of having to write the same code in two places: once in __init__ to initialize an instance with a given dict and a second time inside the update() method, the programmer wrote the code once in its own method and then called the method from __init__. -- http://mail.python.org/mailman/listinfo/python-list
Re: cStringIO change in 2.4 vs 2.5. Regression?
Markus Schöpflin wrote: [...] > I think I'll file a bug at SF... maybe someone else will spot something. Should have checked the bugtracker first... it was reported the day after my original post: http://sourceforge.net/tracker/index.php?func=detail&aid=1730114&group_id=5470&atid=105470 And it's a 2.5.1 regression, it does work in 2.5. Markus -- http://mail.python.org/mailman/listinfo/python-list
Focus to be removed
Hi Dear I'm very pleased to have your help about to solve a technical issue related to HTML Editlet Editor. In this I' m facing the problem that I'm getting unable to find the particular coding which lets this HTML Editor to be focused after loading on the page. Actually I'm using this HTML Editor in my web page and when the page is loaded, the focus always gone to html editor though I set up the focus to another form element, which is a text box, on the onload event of the body. I want you kindly help me and tell me the particular line or code in the HTML Editor coding which enforces this application to be focused forcefully. Kindly send me replies or mails at [EMAIL PROTECTED] or [EMAIL PROTECTED] I do most welcome of all responses come back from your side and will be always very thankful for your act of kindness. Best Regards Munish Jain -- http://mail.python.org/mailman/listinfo/python-list
Re: In C extension .pyd, sizeof INT64 = 4?
On 12 jun 2007, at 12.03, Allen wrote: > My C extension works wrong, and debug it, found that sizeof (INT64) = > 4, not 8. > I compile on Windows XP platform. > Please tell me how to fix it to support INT64? > Thanks. > > -- > http://mail.python.org/mailman/listinfo/python-list On compilers that can gnerate both 32 and 64 bit executables, the size of some data types vary according to compiler options. You are probably using a typedef long INT64; In order for INT64 to always be 64 bits/8bytes you should declare: typedef long long INT64; - This sig is dedicated to the advancement of Nuclear Power Tommy Nordgren [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: SimplePrograms challenge
--- Steven Bethard <[EMAIL PROTECTED]> wrote: > Stefan Behnel wrote: > > Steven Bethard wrote: > >> If you want to parse invalid HTML, I strongly > encourage you to look into > >> BeautifulSoup. Here's the updated code: > >> > >> import ElementSoup # > http://effbot.org/zone/element-soup.htm > >> import cStringIO > >> > >> tree = > ElementSoup.parse(cStringIO.StringIO(page2)) > >> for a_node in tree.getiterator('a'): > >> url = a_node.get('href') > >> if url is not None: > >> print url > >> > [snip] > > > > Here's an lxml version: > > > > from lxml import etree as et # > http://codespeak.net/lxml > > html = et.HTML(page2) > > for href in html.xpath("//a/@href[string()]"): > > print href > > > > Doesn't count as a 15-liner, though, even if you > add the above HTML code to it. > > Definitely better than the HTMLParser code. =) > Personally, I still > prefer the xpath-less version, but that's only > because I can never > remember what all the line noise characters in xpath > mean. ;-) > I think there might be other people who will balk at the xpath syntax, simply due to their unfamiliarity with it. And, on the other hand, if you really like the xpath syntax, then the program really becomes more of an endorsement for xpath's clean syntax than for Python's. To the extent that Python enables you to implement an xpath solution cleanly, that's great, but then you have the problem that lxml is not batteries included. I do hope we can find something to put on the page, but I'm the wrong person to decide on it, since I don't really do any rigorous HTML screen scraping in my current coding. (I still think it's a common use case, even though I don't do it myself.) I suggested earlier that maybe we post multiple solutions. That makes me a little nervous, to the extent that it shows that the Python community has a hard time coming to consensus on tools sometimes. This is not a completely unfair knock on Python, although I think the reason multiple solutions tend to emerge for this type of thing is precisely due to the simplicity and power of the language itself. So I don't know. What about trying to agree on an XML parsing example instead? Thoughts? Pinpoint customers who are looking for what you sell. http://searchmarketing.yahoo.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Convert String to Int and Arithmetic
Kay Schluehr: > >>> int(cpuSpeed.split(":")[1].strip()) Probably this suffices: int(cpuSpeed.split(":")[1]) Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: How to create a tuple quickly with list comprehension?
In <[EMAIL PROTECTED]>, Diez B. Roggisch wrote: > No need to create the intermediate list, a generator expression works just > fine: > > a = tuple(i for i in range(10)) But `range()` creates the intermediate list anyway. ;-) a = tuple(xrange(10)) Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: How to create a tuple quickly with list comprehension?
[EMAIL PROTECTED] a écrit : > Hi all, > > I can use list comprehension to create list quickly. So I expected that I > can created tuple quickly with the same syntax. But I found that the > same syntax will get a generator, not a tuple. Here is my example: > > In [147]: a = (i for i in range(10)) > > In [148]: b = [i for i in range(10)] > > > In [149]: type(a) > Out[149]: > > In [150]: type(b) > Out[150]: > > Is there a way to create a tuple like (1, 2, 3, 4, 5, 6, 7, 8, 9) > quickly? t = tuple(range(1, 10)) If the use of 'range' in your above snippet was just for the exemple, see Diez's answer. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to format a string from an array?
On Jun 13, 11:11 am, Allen <[EMAIL PROTECTED]> wrote: > a = range(256) > I want to output the formated string to be: > 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f > 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f > > f0 f1 f2 f3 f4 f5 6 f7 f8 f9 fa fb fc fd fe ff > > How to do it? You can start with hex_list = [ ("0"+hex(i)[2:])[-2:] for i in a ] This statement generates a list [ "00", "01", ... "ff"]. Now you only have to print this list. Greetings, Uwe -- http://mail.python.org/mailman/listinfo/python-list
Re: Why can't easy_install Django
On 13 Jun, 03:21, kernel1983 <[EMAIL PROTECTED]> wrote: > I look it up in PyPI [...] > Django is a big project. Why no one maintain this? Did the guy lost > his password? Who knows? But then, if you're running a GNU/Linux distribution like Debian, it's quite possible to use a system package, anyway: http://packages.debian.org/python-django http://packages.ubuntu.com/python-django Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: How to create a tuple quickly with list comprehension?
On Jun 13, 5:37 am, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote: > In <[EMAIL PROTECTED]>, Diez B. Roggisch wrote: > > > No need to create the intermediate list, a generator expression works just > > fine: > > > a = tuple(i for i in range(10)) > > But `range()` creates the intermediate list anyway. ;-) I imagine that's special case. -- http://mail.python.org/mailman/listinfo/python-list
Re: SimplePrograms challenge
Steve Howell wrote: > I suggested earlier that maybe we post multiple > solutions. That makes me a little nervous, to the > extent that it shows that the Python community has a > hard time coming to consensus on tools sometimes. We agree that BeautifulSoup is the best for parsing HTML. :) > This is not a completely unfair knock on Python, > although I think the reason multiple solutions tend to > emerge for this type of thing is precisely due to the > simplicity and power of the language itself. > > So I don't know. What about trying to agree on an XML > parsing example instead? > > Thoughts? I vote for example with ElementTree (without xpath) with a mention of using ElementSoup for invalid HTML. -- Regards, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there any way to catch expections when call python method in C++
One way is to create an intermediate python function, which returns a special value when an exception is caught. def ExceptionCatcher(FunctionToCall): def F(): try: FunctionToCall() except: return -1 return 0 return F Then instead of calling your function, you would call ExceptionCatcher(YourFunction). You can then check the return value in your C++ code. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python's "only one way to do it" philosophy isn't good?
On 2007-06-12, Anders J. Munch <[EMAIL PROTECTED]> wrote: > Paul Rubin wrote: >> Steven D'Aprano <[EMAIL PROTECTED]> writes: Not tail calls, in general, no. >>> Sorry, how does that work? You're suggesting that there is an >>> algorithm which the compiler could follow to optimize away >>> tail-recursion, but human beings can't follow the same >>> algorithm? >>> >>> Now I'm confused. >> >> The usual compiler method is to translate the code into >> continuation-passing style and thereby gain tail-recursion >> optimization automagically. > > There's no need to go into CPS just to optimise tail-recursion. > After all, compilers were optimising tail-calls decades before > Appel's work on SML/NJ. > > Converting tail-recursion to iteration is trivial, and > perfectly reasonable for a human to do by hand. For simple recursive tail calls, yeah, it can be. Translating a tail-recursive Factorial function into a while loop is easy. But tail-call optimization technically works for any tail-call, including mutual recursion, and non-recursive tail-calls. You can't reasonably hand-optimize away the stack frame for all tail-calls. def foo(x) bar(x) The only way to hand-optimize the call to bar is to inline it yourself. -- Neil Cerutti Will the highways on the Internet become more few? --George W. Bush -- http://mail.python.org/mailman/listinfo/python-list
Re: Python's "only one way to do it" philosophy isn't good?
On 2007-06-13, Steve Howell <[EMAIL PROTECTED]> wrote: > You would just change the language definition to say that once > you enter f(), any call to f() from within f() behaves as if > the recursively called f() still points to the originally bound > version of f. To want any other behavior would be absurd, > anyhow. There's a reason it's generally refered to as "tail-call" optimization and not "tail-recursive" optimization. The former is more general, and, I believe, easier to implement than the latter. -- Neil Cerutti The peace-making meeting scheduled for today has been cancelled due to a conflict. --Church Bulletin Blooper -- http://mail.python.org/mailman/listinfo/python-list
ANN: xlrd 0.6.1 final is now available
The final release of version 0.6.1 of xlrd is now available from http://www.lexicon.net/sjmachin/xlrd.htm and from the Cheeseshop (http://cheeseshop.python.org/pypi/xlrd). What is xlrd? It's a small (download approx 0.1 Mb) pure-Python library for extracting information from Microsoft Excel (tm) files, anywhere Python 2.1 or later will run -- no need for Excel itself, nor COM, nor even Windows. Further info: follow the links on the home page. This major release incorporates the functionality of 0.6.0 which was not released independently for various reasons including the need to push ahead with the 0.6.1 functionality. New in 0.6.0: facility to access named cell ranges and named constants (Excel UI: Insert/Name/Define). New in 0.6.1: extracts formatting information for cells (font, "number format", background, border, alignment and protection) and rows/ columns (height/width etc). To save memory and time for those who don't need it, this information is extracted only if formatting_info=1 is supplied to the open_workbook() function. The cell records BLANK and MULBLANKS which contain no data, only formatting information, will continue to be ignored in the default (no formatting info) case. There have been several changes made to handle anomalous files (written by 3rd party software) which Excel will open without complaint, but failed with xlrd, usually because an assertion fails or xlrd deliberately raises an exception. Refer to HISTORY.html for details. These have been changed to accept the anomaly either silently or with a NOTE message or a WARNING message, as appropriate. Many thanks are due to Simplistix Ltd (http://www.simplistix.co.uk) for funding the new functionality in 0.6.1. Since 0.6.1a4 was released in February, only one bug-fix and some tidying up have been done -- see HISTORY.html for details. Feedback: general discussion on the python-excel newsgroup (sign up at http://groups.google.com/group/python-excel?lnk=li&hl=en) or e-mail to sjmachin at lexicon dot net, preferably with [xlrd] as part of the message subject. Cheers, John -- http://mail.python.org/mailman/listinfo/python-list
Re: How to format a string from an array?
On Jun 13, 11:11 am, Allen <[EMAIL PROTECTED]> wrote: > a = range(256) > I want to output the formated string to be: > 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f > 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f > > f0 f1 f2 f3 f4 f5 6 f7 f8 f9 fa fb fc fd fe ff > > How to do it? a = range(256) for i in xrange(0, 256, 16): print ' '.join('%02x' % n for n in a[i:i+16]) 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 31 32 33 34 35 36 37 38 39 3a 3b 3c 3d 3e 3f 40 41 42 43 44 45 46 47 48 49 4a 4b 4c 4d 4e 4f 50 51 52 53 54 55 56 57 58 59 5a 5b 5c 5d 5e 5f 60 61 62 63 64 65 66 67 68 69 6a 6b 6c 6d 6e 6f 70 71 72 73 74 75 76 77 78 79 7a 7b 7c 7d 7e 7f 80 81 82 83 84 85 86 87 88 89 8a 8b 8c 8d 8e 8f 90 91 92 93 94 95 96 97 98 99 9a 9b 9c 9d 9e 9f a0 a1 a2 a3 a4 a5 a6 a7 a8 a9 aa ab ac ad ae af b0 b1 b2 b3 b4 b5 b6 b7 b8 b9 ba bb bc bd be bf c0 c1 c2 c3 c4 c5 c6 c7 c8 c9 ca cb cc cd ce cf d0 d1 d2 d3 d4 d5 d6 d7 d8 d9 da db dc dd de df e0 e1 e2 e3 e4 e5 e6 e7 e8 e9 ea eb ec ed ee ef f0 f1 f2 f3 f4 f5 f6 f7 f8 f9 fa fb fc fd fe ff -- http://mail.python.org/mailman/listinfo/python-list
shape recognition
hi there, does anybody know about shape / gesture recognition librarys for python? like cali: http://immi.inesc-id.pt/cali/ thx joerg -- http://mail.python.org/mailman/listinfo/python-list
Convert binary string to something meaningful??
I have this string that is being returned from a query on a DBISAM database. The field must be some sort of blob, and when I connect to the database thru ODBC in MS Access, the field type comes thru as OLE Object, and Access cannot read the field (it usually crashes Access). I can sorta pick out the data that I need (7.0, 28, 5TH PRINCIPAL MRD, 10.0 - and these occur in roughly the same place in every record returned from the db), but I am wondering if there is a way to convert this. I looked at the struct module, but I really dont know the format of the data for sure. For starters, could someone tell me what '\x00' more than likely is? Any hints on modules to look at or esp code snippets would be greatly appreciated. Thanks. \x9c \x01\x00\x007.0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00 28.0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00 10.0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00WN \x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x10\xa3@ [EMAIL PROTECTED] NW SE \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00CONGRESS QTR\x00\x00\x00\x005\x00\x005TH PRINCIPAL MRD \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0 0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0 0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0 0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00 -- http://mail.python.org/mailman/listinfo/python-list
Re: cgi.FieldStorage() not working on Windows
OOps .. yes I mean mod_python. I've been using PHP way too long :P .. hence the typo On Jun 13, 4:01 am, Graham Dumpleton <[EMAIL PROTECTED]> wrote: > On Jun 13, 12:58 pm,arorap<[EMAIL PROTECTED]> wrote: > > > Thanks for your reply. > > > The reason I want to run it as CGI (even though mod_php is available > > on my local computer > > Why do you keep mentioning mod_php, surely you mean mod_python. > > > is that the target machine to which I will > > finally be uploading my scripts runs CGI. > > > cgihandler should work just like CGI. > > I wouldn't rely on it being exactly the same. The way it works uses a > number of kludges. Also, the mod_python.cgihandler code in mod_python > doesn't really get much attention from mod_python developers anymore > and not sure if it was even specifically retested when mod_python 3.3 > was released. > > > Any clue why the > > cgi.FieldStorage()might not be working ? > > Have no idea why it doesn't work as works as written on MacOS X even > when mod_python.cgihandler is used. > > You'll have to get someone else who has Windows to try it. You might > be better off going to the mod_python mailing list to get help, or > just use plain old CGI instead since using mod_python isn't really > going to gain you much anyway. > > Graham > > > > > On Jun 12, 7:59 pm, Graham Dumpleton <[EMAIL PROTECTED]> > > wrote: > > > > On Jun 13, 1:17 am,arorap<[EMAIL PROTECTED]> wrote: > > > > > I've mod_php installed with Apache 2.2. In one of my folders, I'm > > > > using the cgihandler as the PythonHandler as my target host runs > > > > python only as CGI. Here cgi.FieldStorage() doesn't seem to work. I > > > > can see the form data in sys.stdin but cgi.FieldStorage() returns an > > > > empty dictionary. Here's the code for the test script I am posting to > > > > - > > > > > -- > > > > #!/usr/bin/python > > > > > import os > > > > import cgi > > > > import sys > > > > > print "Content Type: text/plain\n\n" > > > > print "Hello CGI World !\n" > > > > > for key in os.environ: > > > > print key + "= " + os.environ[key] > > > > > print cgi.FieldStorage() > > > > > print sys.stdin.read() > > > > -- > > > > > And here's the output I see .. > > > > > -- > > > > Hello CGI World ! > > > > > HTTP_REFERER=http://learnpython/form.htm > > > > SERVER_SOFTWARE= Apache/2.2.4 (Win32)mod_python/3.3.1 Python/2.5.1 > > > > SCRIPT_NAME= /mptest.py > > > > SERVER_SIGNATURE= > > > > REQUEST_METHOD= POST > > > > SERVER_PROTOCOL= HTTP/1.1 > > > > QUERY_STRING= abc=ayz > > > > PATH= C:\Program Files\Internet Explorer;;C:\WINDOWS\system32;C: > > > > \WINDOWS;C:\WINDOWS\System32\Wbem;q:\bin;m:\cm\clearcase\bin;M:\PERL\NT > > > > \EXEC\BIN;m:\cm\clearcase\bin\nt;M:\Perl\NT\EXEC\BIN;m:\perl\nt\exec > > > > \bin;m:\cm\clearcase\utils;q:\bin;m:\opus;m:\tvcs;C:\highc331\bin;C: > > > > \Program Files\Rational\ClearCase\bin;C:\Program Files\Rational\common > > > > CONTENT_LENGTH= 86 > > > > HTTP_USER_AGENT= Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; > > > > SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727) > > > > HTTP_CONNECTION= Keep-Alive > > > > SERVER_NAME= learnpython > > > > REMOTE_ADDR= 127.0.0.1 > > > > PATHEXT= .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH > > > > SERVER_PORT= 80 > > > > SERVER_ADDR= 127.0.0.1 > > > > DOCUMENT_ROOT= D:/Projects/LearnPython/www > > > > COMSPEC= C:\WINDOWS\system32\cmd.exe > > > > SCRIPT_FILENAME= D:/Projects/LearnPython/www/mptest.py > > > > SERVER_ADMIN= [EMAIL PROTECTED] > > > > HTTP_HOST= learnpython > > > > SystemRoot= C:\WINDOWS > > > > HTTP_CACHE_CONTROL= no-cache > > > > REQUEST_URI= /mptest.py?abc=ayz > > > > HTTP_ACCEPT= */* > > > > WINDIR= C:\WINDOWS > > > > GATEWAY_INTERFACE= Python-CGI/1.1 > > > > REMOTE_PORT= 1081 > > > > HTTP_ACCEPT_LANGUAGE= en-us > > > > CONTENT_TYPE= application/x-www-form-urlencoded > > > > HTTP_ACCEPT_ENCODING= gzip, deflate > > > > > FieldStorage(None, None, []) > > > > > firstName=puneet&address=hawaii > > > > -- > > > > > I am posting to this script using a form with two text fields named > > > > firstName and address. > > > > > any clue where am I going wrong ? > > > > You don't need mod_python/cgihandler to run CGI scripts. Rather than > > > bring mod_python into the picture and confuse things, set up Apache to > > > run your script as a traditional CGI script instead. > > > > BTW, the fact that mod_python is loaded means that CGI scripts aren't > > > the only way of using Python available to you as you seem to think. > > > So, suggest you do some research as to what the differences are > > > between CGI and mod_python.- Hide quoted text - > > - Show quoted text - -- http://mail.python.org/mailman/listinfo/python-list
Re: Convert binary string to something meaningful??
On 2007-06-13, supercooper <[EMAIL PROTECTED]> wrote: > I have this string that is being returned from a query on a DBISAM > database. The field must be some sort of blob, and when I connect to > the database thru ODBC in MS Access, the field type comes thru as OLE > Object, and Access cannot read the field (it usually crashes Access). > I can sorta pick out the data that I need (7.0, 28, 5TH PRINCIPAL MRD, > 10.0 - and these occur in roughly the same place in every record > returned from the db), but I am wondering if there is a way to convert > this. I looked at the struct module, but I really dont know the format > of the data for sure. For starters, could someone tell me what '\x00' > more than likely is? It's a byte where all 8 bits are zeros. Your data probably has fixed field widths, and unused bytes are just zero-filled. -- Grant Edwards grante Yow! How's the wife? at Is she at home enjoying visi.comcapitalism? -- http://mail.python.org/mailman/listinfo/python-list
passing arguments to tcpserver classes
Is there an easy way to pass arguments to a handler class that is used by the standard TCPServer? normally --> srvr =SocketServer.TCPServer(('',port_num), TCPHandlerClass) I'd like to be able to: srvr =SocketServer.TCPServer(('',port_num), TCPHandlerClass, (arg1,arg2)) And have arg1, arg2 available via TCPHandlerClass.__init__ or some other way. Where TCPHandlerClass: class TCPHandlerClass(SocketServer.StreamRequestHandler): def handle(self): #handle stream events here# Thanks for any advice. -- http://mail.python.org/mailman/listinfo/python-list
Re: httplib / connection
> The > httplib.HTTP class that you were using is very old and deprecated for > several years now. > > -- > Gabriel Genellina :-( oh , tks! i took it from www.ug.it.usyd.edu.au/~comp5315/lec-09.html which class must i use? tks in advance -- http://mail.python.org/mailman/listinfo/python-list
Re: Postpone creation of attributes until needed
On Wed, 13 Jun 2007 02:15:11 -0700, Frank Millman wrote: > Thanks very much for all your attempts to help me, Steven. You have > succeeded in getting me to think properly about my problem and come up > with a much cleaner solution. I really appreciate it. Glad to be of help. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there any way to catch expections when call python method in C++
Allen wrote: > I use try catch, but cannot catch the execeptions of execution python > method. > > PYCALL_API void PyCall(const char * pszModule, const char * pszFunc, > void * pArg) > { > if (pszModule == NULL || pszFunc == NULL) > { > return; > } > > Py_Initialize(); > > PyObject * pModule = NULL; > PyObject * pFunc = NULL; > > try { > > pModule = PyImport_ImportModule(pszModule); > pFunc = PyObject_GetAttrString(pModule, pszFunc); > > PyEval_CallObject(pFunc, (PyObject*)pArg); > } catch (...) { >fprintf(stderr, "Error: call python method failed"); > } > > Py_Finalize(); > } > > Can I catch it from C++? No. CPython is written in C, not C++, and C has no concept of exceptions. Exceptions in Python is usually indicated by return value in the interpreter, and has no mapping to the C++ exception model. You should never let C++ exceptions propagate into the python functions either. PyImport_ImportModule will return NULL if an exception occured, and so will also PyObject_GetAttrString and PyEval_CallObject do. -- rbh -- http://mail.python.org/mailman/listinfo/python-list
Optimizing constants in loops
The peephole optimizer now takes things like if 0: do_stuff() and optimizes them away, and optimizes away the conditional in "if 1:". What if I had a function like this? def func(debug=False): for index in xrange(100): if debug: print index do_stuff(index) Could the "if debug" be optimized away on function invocation if debug is immutable and never reassigned in the function? When performance really matters in some inner loop, I usually move the conditional outside like this: def func(debug=False): if debug: for index in xrange(100): print index do_stuff(index) else: for index in xrange(100): do_stuff(index) It would be nice if this sort of thing could be done automatically, either by the interpreter or a function decorator. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Python Job Opportunity
My company : EWT, LLC EWT is a proprietary securities trading company and is a member firm of major stock and futures exchanges. Founded in 2002, EWT was formed to capitalize on the shift of the securities industry towards electronic platforms in the United States and abroad. Location: Beverly Hills, CA - USA Position: We are seeking developers to work on proprietary trading strategies that will run on our high-performance, electronic trading platform. Responsibilities include improving the scalability, performance and efficiency of existing strategies. This position involves strong collaboration with traders to research and prototype new strategies. · Candidates should have an interest in trading and financial markets · Candidates should enjoy working in a fast-paced, dynamic environment · Analytic ability and raw talent are required · Strong mathematical aptitude; background in math, physics, or statistics is a plus · Proficiency with Python is required · Experience in distributed and/or highly concurrent systems is a plus As a highly successful firm in the finance industry, we are able to offer extremely competitive compensation, well above market value. We are always looking for people with extraordinary skills, experience, creativity and drive to join our rapidly expanding company. If this describes you, then please apply. Please email resumes to [EMAIL PROTECTED] or, preferably, apply through our website at www.ewtcareers.com (follow the Careers tab). -- http://mail.python.org/mailman/listinfo/python-list
Re: SimplePrograms challenge
Rob Wolfe wrote: > Steve Howell wrote: > >> I suggested earlier that maybe we post multiple >> solutions. That makes me a little nervous, to the >> extent that it shows that the Python community has a >> hard time coming to consensus on tools sometimes. > > We agree that BeautifulSoup is the best for parsing HTML. :) > >> This is not a completely unfair knock on Python, >> although I think the reason multiple solutions tend to >> emerge for this type of thing is precisely due to the >> simplicity and power of the language itself. >> >> So I don't know. What about trying to agree on an XML >> parsing example instead? >> >> Thoughts? > > I vote for example with ElementTree (without xpath) > with a mention of using ElementSoup for invalid HTML. Sounds good to me. Maybe something like:: import xml.etree.ElementTree as etree dinner_recipe = ''' 24slicesbaguette 2+tbspolive_oil 1cuptomatoes 1-2tbspgarlic 1/2cupParmesan 1jarpesto ''' pantry = set(['olive oil', 'pesto']) tree = etree.fromstring(dinner_recipe) for item_elem in tree.getiterator('item'): if item_elem.text not in pantry: print item_elem.text Though I wouldn't know where to put the ElementSoup link in this one... STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: Optimizing constants in loops
Michael Hoffman schrieb: > The peephole optimizer now takes things like > > if 0: > do_stuff() > > and optimizes them away, and optimizes away the conditional in "if 1:". > > What if I had a function like this? > > def func(debug=False): > for index in xrange(100): > if debug: > print index > do_stuff(index) > > Could the "if debug" be optimized away on function invocation if debug > is immutable and never reassigned in the function? When performance > really matters in some inner loop, I usually move the conditional > outside like this: > > def func(debug=False): > if debug: > for index in xrange(100): > print index > do_stuff(index) > else: > for index in xrange(100): > do_stuff(index) > > It would be nice if this sort of thing could be done automatically, > either by the interpreter or a function decorator. Just use the builtin __debug__ variable for that purpose. __debug__ is 'True' if Python is run normally, and 'False' if run with the '-O' or '-OO' command line flag. The optimizer works in the way you describe above (which it will not if you use a custom variable). Thomas -- http://mail.python.org/mailman/listinfo/python-list
problem on waiting exit thread and write on file
I have a list of parameters. I need to run in thread a command, one thread for one parameter. So i made a for loop, creating 5 threads and waiting their stop with: for parameter in parameters Thread{ write on BW2 } Main { open file BW2 for write . (creating list of thread with a counter) Stopped=False while (Stopped == False): if not thread5.isAlive(): if not thread4.isAlive(): if not thread3.isAlive(): if not thread2.isAlive(): if not thread1.isAlive(): Stopped=True if (Stopped == False): time.sleep(0.3) .. close file BW2 } Somethimes i get however the error that i can't write on a file already closed There is a way more easy to wait that all children exit and to run a queue of threads? I tried also this: a=0 while (a == 0): try: os.waitpid(-2, 0) except OSError, exc: # all CHILD finished a=1 but the same problem persist. The only way to don't have error is to had a time.sleep(4) before closing the file from the main program. -- http://mail.python.org/mailman/listinfo/python-list
Re: MS Word parser
On Jun 13, 1:28 am, Tim Golden <[EMAIL PROTECTED]> wrote: > [EMAIL PROTECTED] wrote: > > Hi all, > > I'm currently using antiword to extract content from MS Word files. > > Is there another way to do this without relying on any command prompt > > application? > > Well you haven't given your environment, but is there > anything to stop you from controlling Word itself via > COM? I'm no Word expert, but looking around, this > seems to work: > > > import win32com.client > word = win32com.client.Dispatch ("Word.Application") > doc = word.Documents.Open ("c:/temp/temp.doc") > text = doc.Range ().Text > > open ("c:/temp/temp.txt", "w").write (text.encode ("UTF-8")) > > > TJG Tim, I'm on Linux (RedHat) so using Word is not an option for me. Any other suggestions? -- http://mail.python.org/mailman/listinfo/python-list
Re: Bytes/File Size Format Function
Haha, you guys. Use it however you want. But trust me, if you put MiB and GiB instead of the more-common mb and gb [MB and GB] in your applications, your users will probably have a harder time understanding what you mean. -- http://mail.python.org/mailman/listinfo/python-list
Cretins.
Please do not do business with those cretins who without authorization attaching the following text to my postings: == Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News== http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups = East and West-Coast Server Farms - Total Privacy via Encryption = == Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News== http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups = East and West-Coast Server Farms - Total Privacy via Encryption = -- http://mail.python.org/mailman/listinfo/python-list
Re: Python's "only one way to do it" philosophy isn't good?
Neil Cerutti wrote: > On 2007-06-12, Anders J. Munch <[EMAIL PROTECTED]> wrote: >> Converting tail-recursion to iteration is trivial, and >> perfectly reasonable for a human to do by hand. > > For simple recursive tail calls, yeah, it can be. Translating a > tail-recursive Factorial function into a while loop is easy. But > tail-call optimization technically works for any tail-call, > including mutual recursion, and non-recursive tail-calls. You > can't reasonably hand-optimize away the stack frame for all > tail-calls. I may have misunderstood, I thought we were talking about tail recursion only. The general tail-call optimisation, where all leaf calls become jumps and the called function usurps the current stack frame, is a different ballgame entirely. There's no pure-Python transformation for that, but that still doesn't mean you need CPS. General tail-call optimisation is of course completely out-of-bounds for Python, because it ruins tracebacks. Unlike tail recursion, which could use recursion counters. - Anders -- http://mail.python.org/mailman/listinfo/python-list
Re: Python's "only one way to do it" philosophy isn't good?
Alexander Schmolck wrote: > "Anders J. Munch" <[EMAIL PROTECTED]> writes: > >> Like Steven said, tail-call optimisation is not necessary as you can always >> hand-optimise it yourself. > > Care to demonstrate on some code written in CPS (a compiler or parser, say)? I meant tail recursion, not tail-call, sorry, that was just my fingers trying to save typing. - Anders -- http://mail.python.org/mailman/listinfo/python-list
Re: Windows build of PostgreSQL library for 2.5
On 30 May, 16:20, Ben Sizer <[EMAIL PROTECTED]> wrote: > On 30 May, 15:42, Frank Millman <[EMAIL PROTECTED]> wrote: > > > On May 30, 4:15 pm,BenSizer<[EMAIL PROTECTED]> wrote: > > > > I've been looking for a Windows version of a library to interface to > > > PostgreSQL, but can only find ones compiled under Python version 2.4. > > > Is there a 2.5 build out there? > > > Is this what you are looking for? > > >http://stickpeople.com/projects/python/win-psycopg/ > > It may well be, thanks. On second thoughts, is there one anywhere without an extra multi- megabyte dependency? This seems to rely on the eGenix 'mx' library. -- Ben Sizer -- http://mail.python.org/mailman/listinfo/python-list
Re: Bytes/File Size Format Function
Ben Finney wrote: > The symbol for "bit" is 'b'. The symbol for "byte" is 'B'. 'kb' is > 'kilobit', i.e. 1000 bits. 'mb' is a "metre-bit", a combination of two > units. And so on. The SI units have definitions that are only muddied > by misusing them this way. I have to disagree: 'mb' should stand for "milli-bit" :) which could be considered as the probability of a bit ... this might be useful for quantum computing. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Help!!!
Hi, you could try this: def parse(self, ifile): id="" seq="" for line in open(ifile, 'r'): if '>'==line[0]: if id!="" and len(seq)>0: yield id,seq seq = "" id=line[1:].strip("\n") elif id!="": for word in line.split(): seq += word if id!="" and len(seq)>0: yield id,seq for id, seq in parse("some.fa"): print "%s \n %s" %(id, seq) Its adapted from the fasta parser in PyGr. >From what I understand biopython isnt very active and I think theres a re-factor of it going on at the moment in the form of corebio. Hope this helps; Thanks Nathan -- http://mail.python.org/mailman/listinfo/python-list
Re: Optimizing constants in loops
Thomas Heller wrote: > Just use the builtin __debug__ variable for that purpose. > __debug__ is 'True' if Python is run normally, and 'False' > if run with the '-O' or '-OO' command line flag. > The optimizer works in the way you describe above (which > it will not if you use a custom variable). Thanks, I didn't know that __debug__ was optimized like this. But that was really just a specific example of the general case. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: Windows build of PostgreSQL library for 2.5
On Jun 13, 12:57 pm, Ben Sizer <[EMAIL PROTECTED]> wrote: > On 30 May, 16:20, Ben Sizer <[EMAIL PROTECTED]> wrote: > > > On 30 May, 15:42, Frank Millman <[EMAIL PROTECTED]> wrote: > > > > On May 30, 4:15 pm,BenSizer<[EMAIL PROTECTED]> wrote: > > > > > I've been looking for a Windows version of a library to interface to > > > > PostgreSQL, but can only find ones compiled under Python version 2.4. > > > > Is there a 2.5 build out there? > > > > Is this what you are looking for? > > > >http://stickpeople.com/projects/python/win-psycopg/ > > > It may well be, thanks. > > On second thoughts, is there one anywhere without an extra multi- > megabyte dependency? This seems to rely on the eGenix 'mx' library. > > -- > Ben Sizer IIRC version 2 (psycopg2) doesn't depend on mx: http://www.stickpeople.com/projects/python/win-psycopg/psycopg2-2.0.5.1.win32-py2.5-pg8.2.0-release.exe George -- http://mail.python.org/mailman/listinfo/python-list
Re: Focus to be removed
En Wed, 13 Jun 2007 07:13:18 -0300, <[EMAIL PROTECTED]> escribió: > I'm very pleased to have your help about to solve a technical issue > related to HTML Editlet Editor. In this I' m facing the problem that You should ask the author - I don't think this product has anything to do with Python. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: problem on waiting exit thread and write on file
In <[EMAIL PROTECTED]>, Flyzone wrote: > I need to run in thread a command, one thread for one parameter. > So i made a for loop, creating 5 threads and waiting their stop with: > Main { >open file BW2 for write >. (creating list of thread with a counter) >Stopped=False >while (Stopped == False): > if not thread5.isAlive(): > if not thread4.isAlive(): > if not thread3.isAlive(): > if not thread2.isAlive(): > if not thread1.isAlive(): > Stopped=True > if (Stopped == False): > time.sleep(0.3) If you create a list with threads where do the names `thread1` to `thread5` come from? This snippet expects the threads in a list or another iterable: for thread in threads: thread.join() Much shorter, isn't it!? :-) Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Help!!!
Elfine Peterson Tjio wrote: > I'm trying to make a program that reads Fasta file and print it out. I used > the SeqIO module and the results is: > > 'ATGGTCATSingleAlphabet()' > > For this purpose, should I use SeqIO or Fasta? > > for example: > > from Bio import SeqIO > > or > > from Bio import Fasta > > I want it to print every letter. Can anyone point me to the right direction. > The newest biopython tutorial or book recommendation will be appreciated, > too. Dear Elfine: The correct place for such a question is the BioPython discussion list at [EMAIL PROTECTED] You can subscribe to it here: http://lists.open-bio.org/mailman/listinfo/biopython/ The newest BioPython tutorial (last updated 16 March 2007) can be found at http://biopython.org/DIST/docs/tutorial/Tutorial.pdf SeqIO and Fasta should both work fine. You could also try >>> help(SeqIO) >>> help(Fasta) after your import for some further information. Cheers, Christof -- http://mail.python.org/mailman/listinfo/python-list
Re: logging module and threading
On Jun 13, 1:28 am, "James T. Dennis" <[EMAIL PROTECTED]> wrote: > This sounds like a job for the Queue class/module to me. > Could you create a Queue such that all your worker threads > are producers to it and you have one dedicated thread as a > consumer that relays log entries from the Queue into your loggers? Or, use a SocketHandler to serialize the events over a socket, and de- mux them on the receiving end. The docs have an example: http://docs.python.org/lib/network-logging.html Regards, Vinay Sajip -- http://mail.python.org/mailman/listinfo/python-list
Re: Python's "only one way to do it" philosophy isn't good?
On 2007-06-13, Anders J. Munch <[EMAIL PROTECTED]> wrote: > General tail-call optimisation is of course completely > out-of-bounds for Python, because it ruins tracebacks. Unlike > tail recursion, which could use recursion counters. Is it really ruined? To use a similar example: def foo(x): bar(x+1) def bar(x): if x > 10: raise ValueError else: foo(x+2) Today, when I call foo(4), I get something like: C:\WINNT\system32\cmd.exe /c python temp.py Traceback (most recent call last): File "temp.py", line 529, in foo(4) File "temp.py", line 521, in foo bar(x+1) File "temp.py", line 527, in bar foo(x+2) File "temp.py", line 521, in foo bar(x+1) File "temp.py", line 527, in bar foo(x+2) File "temp.py", line 521, in foo bar(x+1) File "temp.py", line 525, in bar raise ValueError ValueError shell returned 1 With tail-call optimization you'd get something like: C:\WINNT\system32\cmd.exe /c python temp.py Traceback (most recent call last): File "temp.py", line 529, in foo(4) File "temp.py", line 525, in bar raise ValueError ValueError shell returned 1 What makes the latter harder to work with? -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list
Re: Python's "only one way to do it" philosophy isn't good?
On Wed, 2007-06-13 at 18:22 +, Neil Cerutti wrote: > On 2007-06-13, Anders J. Munch <[EMAIL PROTECTED]> wrote: > > General tail-call optimisation is of course completely > > out-of-bounds for Python, because it ruins tracebacks. Unlike > > tail recursion, which could use recursion counters. > > Is it really ruined? To use a similar example: > > def foo(x): > bar(x+1) > > def bar(x): > if x > 10: > raise ValueError > else: > foo(x+2) > > Today, when I call foo(4), I get something like: > > C:\WINNT\system32\cmd.exe /c python temp.py > Traceback (most recent call last): > File "temp.py", line 529, in > foo(4) > File "temp.py", line 521, in foo > bar(x+1) > File "temp.py", line 527, in bar > foo(x+2) > File "temp.py", line 521, in foo > bar(x+1) > File "temp.py", line 527, in bar > foo(x+2) > File "temp.py", line 521, in foo > bar(x+1) > File "temp.py", line 525, in bar > raise ValueError > ValueError > shell returned 1 > > With tail-call optimization you'd get something like: > > C:\WINNT\system32\cmd.exe /c python temp.py > Traceback (most recent call last): > File "temp.py", line 529, in > foo(4) > File "temp.py", line 525, in bar > raise ValueError > ValueError > shell returned 1 > > What makes the latter harder to work with? The fact that you don't see how many call levels down your algorithm got before throwing an exception. This may be an important clue in debugging a recursive algorithm. -- Carsten Haese http://informixdb.sourceforge.net -- http://mail.python.org/mailman/listinfo/python-list
Re: Python's "only one way to do it" philosophy isn't good?
On 2007-06-13, Neil Cerutti <[EMAIL PROTECTED]> wrote: > On 2007-06-13, Anders J. Munch <[EMAIL PROTECTED]> wrote: >> General tail-call optimisation is of course completely >> out-of-bounds for Python, because it ruins tracebacks. Unlike >> tail recursion, which could use recursion counters. > > Is it really ruined? To use a similar example: I found some interesting notes by Alex Martelli pertaining to tail-call optimisation, and my assumption that tail-call optimization is easier to implement than tail-recursive optimization may have been naive. ;) http://groups.google.com/group/comp.lang.python/msg/1a7103c1bd70?hl=en&; Moreover, there are (or were) technical reasons that you can't do tail-call optimization in Python, which can't even recognize tail-calls at compile time. According to Tim Peters: http://groups.google.com/group/comp.lang.python/msg/ea1de1e35aefb828?hl=en&; -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list
Goto
How does one effect a goto in python? I only want to use it for debug. I dasn't slap an "if" clause around the portion to dummy out, the indentation police will nab me. Thanx, jh -- http://mail.python.org/mailman/listinfo/python-list
Build EXE on Mac OsX 10.4
Has anyone sucesfully built a *.exe file on a mac operating system before from a *.py file? I have been trying to do this with pyinstaller, but I keep getting errors and I don't know how to install UPX properly. I tried putting the linux UPX folder in my python 2.4 directory, but that didn't work. I am just generally confused right now. Ha. If anybody can lend me some insight I would really appreciate it. Thank you for taking the time to read this post. -b -- http://mail.python.org/mailman/listinfo/python-list
Re: Goto
> How does one effect a goto in python? I only want to use it for debug. > I dasn't slap an "if" clause around the portion to dummy out, the > indentation police will nab me. http://entrian.com/goto/ -- http://mail.python.org/mailman/listinfo/python-list
Re: SimplePrograms challenge
Steven Bethard <[EMAIL PROTECTED]> writes: >> I vote for example with ElementTree (without xpath) >> with a mention of using ElementSoup for invalid HTML. > > Sounds good to me. Maybe something like:: > > import xml.etree.ElementTree as etree > dinner_recipe = ''' > > 24slicesbaguette > 2+tbspolive_oil ^ Is that a typo here? > 1cuptomatoes > 1-2tbspgarlic > 1/2cupParmesan > 1jarpesto > ''' > pantry = set(['olive oil', 'pesto']) > tree = etree.fromstring(dinner_recipe) > for item_elem in tree.getiterator('item'): > if item_elem.text not in pantry: > print item_elem.text That's nice example. :) > Though I wouldn't know where to put the ElementSoup link in this one... I had a regular HTML in mind, something like: # HTML page dinner_recipe = ''' Recipe amtunititem 24slicesbaguette 2+tbspolive_oil 1cuptomatoes 1-2tbspgarlic 1/2cupParmesan 1jarpesto ''' # program import xml.etree.ElementTree as etree tree = etree.fromstring(dinner_recipe) #import ElementSoup as etree # for invalid HTML #from cStringIO import StringIO # use this #tree = etree.parse(StringIO(dinner_recipe)) # wrapper for BeautifulSoup pantry = set(['olive oil', 'pesto']) for ingredient in tree.getiterator('tr'): amt, unit, item = ingredient.getchildren() if item.tag == "td" and item.text not in pantry: print "%s: %s %s" % (item.text, amt.text, unit.text) But if that's too complicated I will not insist on this. :) Your example is good enough. -- Regards, Rob -- http://mail.python.org/mailman/listinfo/python-list
mapping subintervals
hi, I have the following problem which is turning out to be non-trivial. I realize that this is not exactly a python problem but more of an algorithm problem -- but I post it here because I want to implement this in python. I want to write a code that given an interval (integer tuple: start,stop) will find which other interval it matches to. Here is an example, suppose I have the following NON-OVERLAPPING intervals 10 - 21 ==> 'a1' 34 - 51 ==> 'a2' 77 - 101 ==> 'a3' etc So, suppose I'm give an interval such as (42,50), I should go through the list and map it to "a2" etc if the region is a subset of an exiting interval. If the query interval does not exist in the table or maps to two or more intervals (eg, (45, 80)) the program return a None. One naive way to solve this problem is to create an array such as follows: [None, None, None, , None, a1, a1, a1, ..., a1, None, None ..., None, a2, ... etc] at indicies 123 9 10 11 12 21 22 23 33 34, ... now with this in place I can easily solve the problem. However, this is not a feasable solution because the initial list has intervals whose range can go to billions! So I need a smarter idea. So what I can do is sort the initial list and then go through each element from the start and test if the a > X[i][0] and b < X[i][1] where (a,b) is my query start and stop and X is a n x 2 array with the known intervals. I don't like this solution because it can be really really slow as for each query I'm doing a linear search and on average I'll be searching almost half the list before I find the right interval. Is there a smarter way to do this? I've my problem is not clear please let me know and I'll try to explain the unclear parts again. Many thanks Lee -- http://mail.python.org/mailman/listinfo/python-list
Re: In C extension .pyd, sizeof INT64 = 4?
On 12 jun, 17:06, "Martin v. Lo"wis" <[EMAIL PROTECTED]> wrote: > > What *is*INT64? It's not a builtin type of standard C, it isn't > defined by Microsoft C, and it isn't predefined by Python. > > So it must be something that you have defined, and apparently > incorrectly. How did you define it? It is defined in basetsd.h, included by winnt.h; the OP should not redefine it, and that also explains why I could compile my test program without any problem. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: SimplePrograms challenge
Rob Wolfe wrote: > Steven Bethard <[EMAIL PROTECTED]> writes: > >>> I vote for example with ElementTree (without xpath) >>> with a mention of using ElementSoup for invalid HTML. >> Sounds good to me. Maybe something like:: >> >> import xml.etree.ElementTree as etree >> dinner_recipe = ''' >> >> 24slicesbaguette >> 2+tbspolive_oil > ^ > Is that a typo here? Just trying to make Thunderbird line-wrap correctly. ;-) It's better with a space instead of an underscore. >> 1cuptomatoes >> 1-2tbspgarlic >> 1/2cupParmesan >> 1jarpesto >> ''' >> pantry = set(['olive oil', 'pesto']) >> tree = etree.fromstring(dinner_recipe) >> for item_elem in tree.getiterator('item'): >> if item_elem.text not in pantry: >> print item_elem.text > > That's nice example. :) > >> Though I wouldn't know where to put the ElementSoup link in this one... > > I had a regular HTML in mind, something like: > > > # HTML page > dinner_recipe = ''' > Recipe > > amtunititem > 24slicesbaguette > 2+tbspolive_oil > 1cuptomatoes > 1-2tbspgarlic > 1/2cupParmesan > 1jarpesto > > ''' > > # program > import xml.etree.ElementTree as etree > tree = etree.fromstring(dinner_recipe) > > #import ElementSoup as etree # for invalid HTML > #from cStringIO import StringIO # use this > #tree = etree.parse(StringIO(dinner_recipe)) # wrapper for BeautifulSoup > > pantry = set(['olive oil', 'pesto']) > > for ingredient in tree.getiterator('tr'): > amt, unit, item = ingredient.getchildren() > if item.tag == "td" and item.text not in pantry: > print "%s: %s %s" % (item.text, amt.text, unit.text) > > > But if that's too complicated I will not insist on this. :) > Your example is good enough. Sure, that looks fine to me. =) Steve -- http://mail.python.org/mailman/listinfo/python-list
Re: Goto
On Wed, 2007-06-13 at 12:20 -0700, HMS Surprise wrote: > How does one effect a goto in python? One doesn't. > I only want to use it for debug. > I dasn't slap an "if" clause around the portion to dummy out, the > indentation police will nab me. If you want to disable a code block without indenting it into an "if False:" block, use triple quotes, either ''' or """, to turn it into a long string. HTH, -- Carsten Haese http://informixdb.sourceforge.net -- http://mail.python.org/mailman/listinfo/python-list
wx Listbox event
Hi, I need to charge a list when starts the program. I've tried a few events like: self.llistatids = wx.ListBox(self, -1, choices=['a'], style=wx.LB_SINGLE|wx.LB_ALWAYS_SB) self.llistatids.SetBackgroundColour(wx.Colour(255, 255, 220)) self.llistatids.Bind(wx.EVT_LISTBOX, self.carrega_llistatids) But I cannot do it, any idea? -- http://mail.python.org/mailman/listinfo/python-list
Re: Build EXE on Mac OsX 10.4
Tempo wrote: > Has anyone sucesfully built a *.exe file on a mac operating system > before from a *.py file? I have been trying to do this with > pyinstaller, but I keep getting errors and I don't know how to install > UPX properly. I tried putting the linux UPX folder in my python 2.4 > directory, but that didn't work. I am just generally confused right > now. Ha. If anybody can lend me some insight I would really appreciate > it. Thank you for taking the time to read this post. You need to build Mac Apps on Mac, Windows EXE's on Windows, and Linux ELF's on Linux. You can't build a windows.exe from Mac, just as you can't build a mac.app from Windows. -- pkm ~ http://paulmcnett.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Python's "only one way to do it" philosophy isn't good?
"Steve Howell" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] | | You would just change the language definition to say | that once you enter f(), any call to f() from within | f() behaves as if the recursively called f() still | points to the originally bound version of f. I am pretty sure such a context-dependent rule cannot be written as a context-free grammar rule. In any case, the function object does not exist when code is being compiled to a code object. So this requires implementation-dependent post-patching of the code object. R. Hetchinger(sp?) posted a Cookbook recipe for doing this for CPython. Anyone wanting the speedup (with CPython) can use it. tjr -- http://mail.python.org/mailman/listinfo/python-list
Re: Goto
Thanks folks! jh -- http://mail.python.org/mailman/listinfo/python-list
Re: Build EXE on Mac OsX 10.4
Okay. Great. Thanks for clarifying that for me. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to create a tuple quickly with list comprehension?
<[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] | I can use list comprehension to create list quickly. So I expected that I | can created tuple quickly with the same syntax. But I found that the | same syntax will get a generator, not a tuple. Here is my example: | | In [147]: a = (i for i in range(10)) | | In [148]: b = [i for i in range(10)] | | In [149]: type(a) | Out[149]: | | In [150]: type(b) | Out[150]: | | Is there a way to create a tuple like (1, 2, 3, 4, 5, 6, 7, 8, 9) | quickly? I already I can use tuple() on a list which is created by list | comprehension to get a desired tuple. But why do you 'desire' a tuple (rather than a list)? There are only a few situations where it makes a difference. One is dictionary keys, but a sequnce of several, rather that a few, is not typical of keys. tjr -- http://mail.python.org/mailman/listinfo/python-list
Re: mapping subintervals
On Jun 13, 2:32 pm, Lee Sander <[EMAIL PROTECTED]> wrote: > hi, > I have the following problem which is turning out to be non-trivial. I > realize that this is not > exactly a python problem but more of an algorithm problem -- but I > post it here because > I want to implement this in python. > > I want to write a code that given an interval (integer tuple: > start,stop) will find which other > interval it matches to. Here is an example, > suppose I have the following NON-OVERLAPPING intervals > > 10 - 21 ==> 'a1' > 34 - 51 ==> 'a2' > 77 - 101 ==> 'a3' > etc > > So, suppose I'm give an interval such as (42,50), I should go through > the list and map it to "a2" etc > if the region is a subset of an exiting interval. If the query > interval does not exist in the table or > maps to two or more intervals (eg, (45, 80)) the program return a > None. ...snip... > Many thanks > Lee OK - I'm going to assume your intervals are inclusive (i.e. 34-51 contains both 34 and 51). If your intervals are all really all non-overlapping, one thing you can try is to put all the endpoints in a single list, and sort it. Then, you can use the bisect module to search for intervals, which will give you a logarithmic time algorithm. Here, I'm going to assume you just need the index of the containing interval. If you really need a name (i.e. 'a1' or 'a2'), you can use a list of names, and index into that. I hope those assumptions are valid! if so, the following should work: from bisect import bisect # assume initial intervals are sorted intervals=[(10,21),(34,51), (77,101)] # get a sorted list of endpoints endpts=sorted([a for a,b in intervals]+[b for a,b in intervals]) def test_interval(ivl,endpts): # Find where the left endpoint of ivl would lie in the list # i.e. the index of the first element greater than ivl[0] l_idx=bisect(endpts,ivl[0]) # If l_idx is even, then it lies between two intervals, and thus # is not contained in any interval. Otherwise it returns the index if l_idx % 2 == 0: return None # if l_idx is out of bounds (i.e. ==len(endpts)), then ivl is # not contained in any interval (too large) if l_idx==len(endpts): return None # Now, all we need to do is check that the right endpoint of ivl is # less than or equal to the corresponding endpoint in the list. # Happily, that endpoint is at index l_idx if ivl[1]<=endpts[l_idx]: # So return the index of the interval: return (l_idx-1)/2 else: return None Then, from a shell: >>> print tst.test_interval((0,13),endpts) None >>> print tst.test_interval((15,21),endpts) 0 >>> print tst.test_interval((35,40),endpts) 1 >>> print tst.test_interval((40,80),endpts) None >>> print tst.test_interval((109,200),endpts) None -- http://mail.python.org/mailman/listinfo/python-list
Re: SimplePrograms challenge
# writing/reading CSV files, tuple-unpacking, cmp() built-in import csv writer = csv.writer(open('stocks.csv', 'wb')) writer.writerows([ ('GOOG', 'Google, Inc.', 505.24, 0.47, 0.09), ('YHOO', 'Yahoo! Inc.', 27.38, 0.33, 1.22), ('CNET', 'CNET Networks, Inc.', 8.62, -0.13, -1.49) ]) stocks = csv.reader(open('stocks.csv', 'rb')) for ticker, name, price, change, pct in stocks: print '%s is %s (%s%%)' % ( name, {-1: 'down', 0: 'unchanged', 1: 'up'}[cmp(float(change), 0.0)], pct ) -- http://mail.python.org/mailman/listinfo/python-list
Re: Windows XP timezone language issue
On Jun 13, 7:31 am, Paul Sijben <[EMAIL PROTECTED]> wrote: > I ran into an internationalization issue. I need a consistent idea about > the timezone my application is running on. However when I run the following: > >>> import time > >>> time.tzname > > I get back ('West-Europa (standaardtijd)', 'West-Europa (zomertijd)') > which is in dutch (the language of the host machine) and verbose. > I wanted to get ('CEST','CET') or something international so I can work > with itin the same way on all platforms. > > That is the right way to find out the timezone in a consistent way > across platforms (windows/linux/mac) and languages? > Well, time.timezone will return the timezone as an integer. -- http://mail.python.org/mailman/listinfo/python-list
one-time initialization of class members
Hi, I have a situation where I have some class members that should only be done once. Essentially my problem looks like this: class Base(object): dataset = None def __init__(self, param): if type(self).dataset is None: # code to load dataset based on param, expensive class ChildClass1(Base): def __init__(self): Base.__init__(self, data_params) class AnotherChildClass(Base): def __init__(self): Base.__init__(self, other_data_params) This seems to work, initialization is only done at the first creation of either class. I was just wondering if this is the 'pythonic' way to do this as my solution does feel a bit hackish. -- http://mail.python.org/mailman/listinfo/python-list
Re: Build EXE on Mac OsX 10.4
Paul McNett wrote: > Tempo wrote: >> Has anyone sucesfully built a *.exe file on a mac operating system >> before from a *.py file? I have been trying to do this with >> pyinstaller, but I keep getting errors and I don't know how to install >> UPX properly. I tried putting the linux UPX folder in my python 2.4 >> directory, but that didn't work. I am just generally confused right >> now. Ha. If anybody can lend me some insight I would really appreciate >> it. Thank you for taking the time to read this post. > > You need to build Mac Apps on Mac, Windows EXE's on Windows, and Linux > ELF's on Linux. You can't build a windows.exe from Mac, just as you > can't build a mac.app from Windows. > Also, use py2app--that's the standard on the Mac. I don't believe pyinstaller works on OS X. -- Kevin Walzer Code by Kevin http://www.codebykevin.com -- http://mail.python.org/mailman/listinfo/python-list
Re: mapping subintervals
Matteo skrev: > OK - I'm going to assume your intervals are inclusive (i.e. 34-51 > contains both 34 and 51). > > If your intervals are all really all non-overlapping, one thing you > can try is to put all the endpoints in a single list, and sort it. > Then, you can use the bisect module to search for intervals, which > will give you a logarithmic time algorithm. > > Here, I'm going to assume you just need the index of the containing > interval. If you really need a name (i.e. 'a1' or 'a2'), you can use a > list of names, and index into that. > > I hope those assumptions are valid! if so, the following should work: I have taken the liberty of simplifying your code, using the fact that tuples are sorted lexicographically. Note that this requires all intervals to be tuples and not lists (since list(a) < tuple(b) is always True). from bisect import bisect def test_interval(ivl,intervals): # Find where ivl would lie in the list # i.e. the index of the first interval sorting as larger than ivl idx=bisect(intervals,ivl) # Left endpoints equal is a special case - a matching interval will be # to the right of the insertion point if idx < len(intervals) and intervals[idx][0] == ivl[0]: if intervals[idx][1] >= ivl[1]: return idx else: return None # Otherwise, we need to check to the left of the insertion point if idx > 0 and intervals[idx-1][1] >= ivl[1]: return idx-1 else: return None >>> intervals =[(10, 21), (34, 51), (77, 101)] >>> print test_interval((34,35),intervals) 1 >>> print test_interval((34,53),intervals) None >>> print test_interval((77,53),intervals) 2 >>> print test_interval((77,83),intervals) 2 >>> print test_interval((77,102),intervals) None >>> print test_interval((77,101),intervals) 2 u"Nis J\xf8rgensen" -- http://mail.python.org/mailman/listinfo/python-list
Re: one-time initialization of class members
James Turk wrote: > Hi, > > I have a situation where I have some class members that should only be > done once. Essentially my problem looks like this: > > class Base(object): > dataset = None > > def __init__(self, param): > if type(self).dataset is None: > # code to load dataset based on param, expensive > > class ChildClass1(Base): > def __init__(self): > Base.__init__(self, data_params) > > class AnotherChildClass(Base): > def __init__(self): > Base.__init__(self, other_data_params) > > > This seems to work, initialization is only done at the first creation > of either class. I was just wondering if this is the 'pythonic' way > to do this as my solution does feel a bit hackish. What should happen with code like:: ChildClass1('foo') ChildClass1('bar') The 'param' is different, but 'dataset' should only get set the first time? STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: Bytes/File Size Format Function
Avell Diroll <[EMAIL PROTECTED]> writes: > I have to disagree: 'mb' should stand for "milli-bit" :) Yes, you're right. My "metre-bit" was wrong. -- \ "Whenever you read a good book, it's like the author is right | `\ there, in the room talking to you, which is why I don't like to | _o__)read good books." -- Jack Handey | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list