Re: using super() to call two parent classes __init__() method
7stud wrote: When I run the following code and call super() in the Base class's __init__ () method, only one Parent's __init__() method is called. class Parent1(object): def __init__(self): print Parent1 init called. self.x = 10 class Parent2(object): def __init__(self): print Parent2 init called. self.y = 15 class Base(Parent1, Parent2): def __init__(self): super(Base, self).__init__() self.z = 20 b = Base() --output:-- Parent1 init called. If you want super() to work for you then all your classes have to use it. There is only one call to an __init__() method in your definitions - Parent1 and Parent2 should also be calling their super().__init__(). regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --- Asciimercial -- Get on the web: Blog, lens and tag the Internet Many services currently offer free registration --- Thank You for Reading - -- http://mail.python.org/mailman/listinfo/python-list
Re: to property or function in class object
On Fri, 17 Aug 2007 02:29:47 +, james_027 wrote: i am very new to python, not knowing much about good design. I have an object here for example a Customer object, where I need to retrieve a info which has a number of lines of code to get it. my question is weather what approach should I use? to use the property which is from the python new class style as I understand or simple use function that will return the the info I needed. I'd say it's a matter of taste here. Where `get_*` and `set_*` methods should not be used is getting and setting simple attributes. Here properties are very handy if such a simple attribute changes to something calculated later on, because it is possible to change the class without the need to change the code that uses such objects. In the other case, more complex code to get or set some information in the first place, it is a matter of taste IMHO. Ask yourself if the user would expect `balance` to be an attribute of that class. If it seems to be natural to have such an attribute. And usually attribute access does not trigger really heavy computation. Constructing the answer from some different attributes or doing a conversion before returning something is okay, but a calculation that lasts an hour or so would surprise many. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
clarification
hi everybody, i have a file with data separated by tab mydata: fhl1fkh2 dfp1chk1 mal3alp14 mal3moe1 mal3spi1 mal3bub1 mal3bub3 mal3mph1 mal3mad3 hob1nak1 hob1wsp1 hob1rad3 cdr2cdc13 cdr2cdc2 shows these two are separated by tab represented as columns i have to check the common data between these two coloumn1 an coloumn2 my code: data = [] data1 = [] result = [] fh = open('sheet1','r') for line in fh.readlines(): splitted = line.strip().split('\t') data.append(splitted[0]) data1.append(splitted[1]) for k in data: if k in data1: result.append(k) print result fh.close() can you tell me problem with my script and what should is do for this regards shafreen -- http://mail.python.org/mailman/listinfo/python-list
Re: How to say $a=$b-{A} ||={} in Python?
beginner a écrit : Hi All. I'd like to do the following in more succint code: if k in b: a=b[k] else: a={} b[k]=a a['A']=1 In perl it is just one line: $a=$b-{A} ||={}. Thanks, Geoffrey One solution I often use in such cases: try: a = b[k] except KeyError: #or except IndexError: if b is a list/tuple and not a dict a = {} b[k] = a a['A'] = 1 Indeed, exceptions are handled faster than if/else loops. As it was mentionned earlier, One neat solution in Perl may not be the perfect one in Python. Cheers, Sébastien -- http://mail.python.org/mailman/listinfo/python-list
Re: (sort of) deterministic timing in Python
Paul Rubin http://p..id wrote: [EMAIL PROTECTED] (John Fisher) writes: mark start time start event event finishes count time until next interval start second event⦠rather than this: start event event finishes sleep for interval start second event ... So how do I accomplish this in Python with a minimum of labour? Normally I'd use something like: from time import time t0 = time() start event ... event finishes t1 = time() elapsed = t1 - t0 sleep(interval - elapsed) start second event ... Am I missing something? Not much - only beware of cases when elapsed is greater than interval - not sure what time.sleep(negative_number) does. - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Re: python socket usage
Oğuz Yarımtepe wrote: As i read pickle module is Python-spesific. I need to talk with a Java application and get the infortion that it will send. What i do right now is listening a socket and reding the string that is sent by the java application. So the java application is sending a string and i am reading and parsing it and getting the related infortion i need. A more professional way may be the reading the object itself. Is it possible to get the array for ex. object that is sent from the Java application with sockets? No. Sockets send and receive byte. Any transfer of higher-level object values requires the sender to encode the values into bytes, and the receiver to parse the bytes to construct an object; even then the result is a value copy, not the object itself. For many kinds of objects, there are libraries available to do the encoding and parsing. If you need reference semantics, there are object request brokers. Say more about your problem, and there's a good chance you'll get more useful answers. -- --Bryan -- http://mail.python.org/mailman/listinfo/python-list
Re: to property or function in class object
james_027 wrote: hi, i am very new to python, not knowing much about good design. I have an object here for example a Customer object, where I need to retrieve a info which has a number of lines of code to get it. my question is weather what approach should I use? to use the property which is from the python new class style as I understand or simple use function that will return the the info I needed. class Customer(object): current_balance = property(fget=_get_current_balance) This will need to go down below the definition of _get_current_balance() if you want to avoid an error in compilation. def _get_current_balance(self): # coding here or def get_current_balance(self): # coding here While both approach would get the job done, I don't know much about the performance, benefits, design philosophy between the two approach. Any lecture will be very appreciated. It's pretty much a matter of choice when the method to retrieve the value doesn't take any arguments. If it *does* take arguments then you can't use a property. regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --- Asciimercial -- Get on the web: Blog, lens and tag the Internet Many services currently offer free registration --- Thank You for Reading - -- http://mail.python.org/mailman/listinfo/python-list
Air conditioners for cars!
Have a problem with car air conditioner, go here http://car-air-conditioning.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
Guitars, tabs, amps and more
Reviews of latest models of best guitars, fender, gibson, yamaha, and many more, with pictures and prices. http://pro-guitars.blogspot.com/ And if you want to win a free guitar go here http://freeguitars.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: clarification
On Friday 17 August 2007, Beema shafreen wrote: hi everybody, i have a file with data separated by tab mydata: fhl1fkh2 dfp1chk1 mal3alp14 mal3moe1 mal3spi1 mal3bub1 mal3bub3 mal3mph1 mal3mad3 hob1nak1 hob1wsp1 hob1rad3 cdr2cdc13 cdr2cdc2 shows these two are separated by tab represented as columns i have to check the common data between these two coloumn1 an coloumn2 my code: data = [] data1 = [] result = [] fh = open('sheet1','r') for line in fh.readlines(): splitted = line.strip().split('\t') data.append(splitted[0]) data1.append(splitted[1]) for k in data: if k in data1: result.append(k) print result fh.close() can you tell me problem with my script and what should is do for this No, I have not tested it. You tell us the problem, and we might understand the situation better than you. -- Regards, Thomas Jollans GPG key: 0xF421434B may be found on various keyservers, eg pgp.mit.edu Hacker key http://hackerkey.com/: v4sw6+8Yhw4/5ln3pr5Ock2ma2u7Lw2Nl7Di2e2t3/4TMb6HOPTen5/6g5OPa1XsMr9p-7/-6 -- http://mail.python.org/mailman/listinfo/python-list
Tuned cars!!!
If you like tuned cars, come here, you will fond many interesting stuff http://tuning-styling.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: clarification
Thomas Jollans a écrit : On Friday 17 August 2007, Beema shafreen wrote: hi everybody, i have a file with data separated by tab mydata: fhl1fkh2 zip shows these two are separated by tab represented as columns i have to check the common data between these two coloumn1 an coloumn2 my code: data = [] data1 = [] result = [] fh = open('sheet1','r') for line in fh.readlines(): splitted = line.strip().split('\t') data.append(splitted[0]) data1.append(splitted[1]) for k in data: if k in data1: result.append(k) print result fh.close() Use set data type for data and data1 (you fill them with an algo like th one you wrote - just use add() in place of appen()) then use set intersection to get common data. See doc for set data type: http://docs.python.org/lib/types-set.html Would look like (not tested): data = set() data1 = set() fh = open('sheet1','r') for line in fh.readlines(): splitted = line.strip().split('\t') data.add(splitted[0]) data1.add(splitted[1]) result = data.intersection(data1) -- http://mail.python.org/mailman/listinfo/python-list
Re: clarification
Laurent Pointal a écrit : [cleaning] fh = open('sheet1') for line in fh: -- http://mail.python.org/mailman/listinfo/python-list
Re: advice about `correct' use of decorator
Are you developing a website or a GUI program? It will be used in a web development. It is an important point? Yes, I think. Unless you use AJAX. :-) Most web sites work this way: user clicks - request to server - process on server - response I would rather enclose the whole handler in try/except and raise a custom PermissionDenied exception when the user has inscuficient permissions. There are problems with a decorator used for authorization. The context needs to be determined. E.g. which user is accessing the method? (It can be hard to tell if the method is part of a thread object that lies in a thread pool and is shared between simultaneous clients...) Also it might be that the method's purpose is to change objects of the same class, and the user has permission to modify one object but not the other. In this case, authorization must be done inside the function call... How do you express this with a decorator? These are just ideas. You should analyze your problem and make your decision. If you only want to restrict access to functions, then probably using decorators is perfect. Best, Laszlo -- http://mail.python.org/mailman/listinfo/python-list
passing variables and values to texboxdisplays
hi! Can any one tell me why is it that i can't see my second frame and why is the value of freq not Appended in the First frame ...thanks I know it is wx python but it has to do with passing variables.thanks import wx def create(parent): return Frame1(parent) [wxID_FRAME1, wxID_FRAME1FREQ, wxID_FRAME1FREQDISP, wxID_FRAME1STATICTEXT1, ] = [wx.NewId() for _init_ctrls in range(4)] class Frame1(wx.Frame): def _init_ctrls(self, prnt): # generated method, don't edit wx.Frame.__init__(self, id=wxID_FRAME1, name='', parent=prnt, pos=wx.Point(380, 179), size=wx.Size(241, 133), style=wx.DEFAULT_FRAME_STYLE, title='Frame1') self.SetClientSize(wx.Size(233, 99)) self.staticText1 = wx.StaticText(id=wxID_FRAME1STATICTEXT1, label='frequency disp', name='staticText1', parent=self, pos=wx.Point(24, 32), size=wx.Size(71, 13), style=0) self.freqdisp = wx.TextCtrl(id=wxID_FRAME1FREQDISP, name='freqdisp', parent=self, pos=wx.Point(104, 24), size=wx.Size(100, 21), style=0, value='') self.freq = wx.Button(id=wxID_FRAME1FREQ, label='get freq', name='freq', parent=self, pos=wx.Point(24, 56), size=wx.Size(184, 23), style=0) self.freq.Bind(wx.EVT_BUTTON, self.OnButton1Button, id=wxID_FRAME1FREQ) def __init__(self, parent): self._init_ctrls(parent) def OnButton1Button(self, event): def create(parent): return Frame2(parent) [wxID_FRAME2, wxID_FRAME2FREQ, wxID_FRAME2FREQDISP, wxID_FRAME2STATICTEXT1,] = [wx.NewId() for _init_ctrls in range(4)] class Frame2: def __init__(self): # wx.Frame.__init__(self, id=wxID_FRAME2, name='', parent=prt, pos=wx.Point(400, 179), size=wx.Size(300, 133), style=wx.DEFAULT_FRAME_STYLE, title='Frame2') self.SetClientSize(wx.Size(233, 99)) self.staticText1 = wx.StaticText(id=wxID_FRAME2STATICTEXT1, label='frequency goes here first', name='staticText2', parent=self, pos=wx.Point(24, 32), size=wx.Size(71, 13), style=0) self.freqdisp2 = wx.TextCtrl(id=wxID_FRAME2FREQDISP, name='freqdisp2', parent=self, pos=wx.Point(104, 24), size=wx.Size(100, 21), style=0, value=' ') self.freq = wx.Button(id=wxID_FRAME2FREQ, label='get freq', name='freq', parent=self, pos=wx.Point(24, 56), size=wx.Size(184, 23), style=0) self.freq.Bind(wx.EVT_BUTTON, self.OnButton2Button, id=wxID_FRAME2FREQ) def __init__(self, parent): self._init_ctrls(parent) def OnButton2Button(self, event): freqdisp.Append('this is it 24HZ!') if __name__ == '__main__': app = wx.PySimpleApp() frame = create(None) frame.Show() app.MainLoop() -- http://mail.python.org/mailman/listinfo/python-list
Re: advice about `correct' use of decorator
On 8/16/07, Gerardo Herzig [EMAIL PROTECTED] wrote: @is_logued_in def change_pass(): bla bla And so on for all the other functions who needs that the user is still loged in. where obviosly the is_logued_in() function will determine if the dude is still loged in, and THEN execute change_pass(). If the dude is not loged in, change_pass() is NOT executed at all. Instead, it will be redirected to the `login' screen. I think this is redundant use of a decorator. You can achieve the exact same effect by writing: def is_logued_in(): if not user.is_logged_in(): raise NotLoggedInError It costs you one more line, but reduces complexity. And if you are worried about that extra line you can put it in a function. -- mvh Björn -- http://mail.python.org/mailman/listinfo/python-list
Naming dictionaries recursively
I'd like to do something like this; iterate through a file which consists of data stored in dictionary format, one dict on each line, and read each line into a new dict using one of the values in the dict as its name... for example: stuff = open('data.txt') for eachLine in stuff: name{} name = eachLine and then do something clever to extract the value of the key (name) from the line and use it as the dictionary's name. A line from data.txt would look like this: {'name' : Bob, 'species' : Humboldt, 'colour' : red, 'habits' : predatory}. Aim is to call one of them by name, and merge the values in that dictionary into a string pulled from another source. -- http://mail.python.org/mailman/listinfo/python-list
Re: Naming dictionaries recursively
On Aug 17, 7:38 am, TYR [EMAIL PROTECTED] wrote: I'd like to do something like this; iterate through a file which consists of data stored in dictionary format, one dict on each line, and read each line into a new dict using one of the values in the dict as its name... for example: stuff = open('data.txt') for eachLine in stuff: name{} name = eachLine and then do something clever to extract the value of the key (name) from the line and use it as the dictionary's name. A line from data.txt would look like this: {'name' : Bob, 'species' : Humboldt, 'colour' : red, 'habits' : predatory}. Aim is to call one of them by name, and merge the values in that dictionary into a string pulled from another source. I'm not sure I follow exactly what you want to do, but you can always use eval for each line in that file. But, if the line you provided for testing is one that actually comes from the file, you'll have to patch it before you eval the line. I think this regexp will work. Be careful though, it assumes that all values are whole words, that is they don't have spaces in them. # This is far from ideal, but you get what you pay for :). re.sub(r':\s*(\w+)(,|})', r': '\1'\2, line) Anyway, after you've cleaned up your input line this ought to work: d = eval(line) Also, if you're building the input file from within a python program, maybe you should consider the pickle module. That ought to give you a good start... jw -- http://mail.python.org/mailman/listinfo/python-list
Re: Naming dictionaries recursively
On Fri, 17 Aug 2007 12:38:16 +, TYR wrote: I'd like to do something like this; iterate through a file which consists of data stored in dictionary format, one dict on each line, and read each line into a new dict using one of the values in the dict as its name... Store the dictionaries in a dictionary with that value as key. A line from data.txt would look like this: {'name' : Bob, 'species' : Humboldt, 'colour' : red, 'habits' : predatory}. Aim is to call one of them by name, and merge the values in that dictionary into a string pulled from another source. So the tougher problem seems to be parsing those lines. That is not a valid Python dictionary unless the names `Bob`, `Humboldt`, `red`, and `predatory` are not already defined. So you can't just ``eval`` it. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Downloading multiple csv files from a website
I'd like to download data from the website http://www.russell.com/Indexes/performance/daily_values_US.asp. On this web page, there are links to a number of .csv files, and I'd like to download all of them automatically each day. The file names are not visible on the page, but if I click on a link, a csv file opens in Excel. I've searched this group and looked into urllib, but have not found functions or code snippets that will allow me to download and rename each file. Would someone kindly point me to appropriate libraries/functions and/or code snippets that will get me started? Thanks in advance Thomas Philips -- http://mail.python.org/mailman/listinfo/python-list
Re: clarification
Laurent Pointal wrote: Thomas Jollans a écrit : On Friday 17 August 2007, Beema shafreen wrote: hi everybody, i have a file with data separated by tab mydata: fhl1fkh2 zip shows these two are separated by tab represented as columns i have to check the common data between these two coloumn1 an coloumn2 my code: data = [] data1 = [] result = [] fh = open('sheet1','r') for line in fh.readlines(): splitted = line.strip().split('\t') data.append(splitted[0]) data1.append(splitted[1]) for k in data: if k in data1: result.append(k) print result fh.close() Use set data type for data and data1 (you fill them with an algo like th one you wrote - just use add() in place of appen()) then use set intersection to get common data. See doc for set data type: http://docs.python.org/lib/types-set.html Would look like (not tested): data = set() data1 = set() fh = open('sheet1','r') for line in fh.readlines(): splitted = line.strip().split('\t') data.add(splitted[0]) data1.add(splitted[1]) result = data.intersection(data1) lefts = set() rights = set() with open('sheet1', 'r') as fh: for line in fh: trimmed = line.strip() if trimmed: # Skip blanks (file end often looks like that) left, right = line.strip().split('\t') lefts.add(left) rights.add(right) result = lefts rights -Scott -- http://mail.python.org/mailman/listinfo/python-list
Question on SPE and pwintypes.dll
I'm running SPE 8.3.c under XP, on a new PC. The files for SPE and Python were copied to the new machine, but the OS wasn't migrated, so the registry didn't know about either. I reinstalled Python 2.5.1, and Python seems fine. I made a shortcut to SPE.pyw. Clicking on the shortcut gives an error pop-up, application failed to start cannot find pwintypes.dll. When I click OK, SPE seems to start normally. Any idea what's up? Googling for pwintypes.dll didn't give me any hits. Gerry -- http://mail.python.org/mailman/listinfo/python-list
Need to generate some functions.
Given a list of names ll = (n1, n2, n3, n4) I want to create a pair of functions based off of each name. An example of what I want to happen would look like this: def mkn1dict(address): return {'Address': address, 'Control': SOME_CONST} def mkn1Classobj(address): return Classobj( mkn1classobj(address) ) I know how to do this in a preprocessor, but I'd like to do it directly in python. Can this be done? TIA -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net -- http://mail.python.org/mailman/listinfo/python-list
Re: How to say $a=$b-{A} ||={} in Python?
On Aug 17, 2:35 am, Sébastien Buchoux [EMAIL PROTECTED] wrote: beginner a écrit : Hi All. I'd like to do the following in more succint code: if k in b: a=b[k] else: a={} b[k]=a a['A']=1 In perl it is just one line: $a=$b-{A} ||={}. Thanks, Geoffrey One solution I often use in such cases: try: a = b[k] except KeyError: #or except IndexError: if b is a list/tuple and not a dict a = {} b[k] = a a['A'] = 1 Indeed, exceptions are handled faster than if/else loops. As it was mentionned earlier, One neat solution in Perl may not be the perfect one in Python. Cheers, Sébastien- Hide quoted text - - Show quoted text - Wow. This solution is interesting. I'll try this. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to say $a=$b-{A} ||={} in Python?
On Aug 16, 11:02 pm, Carsten Haese [EMAIL PROTECTED] wrote: On Fri, 17 Aug 2007 03:15:10 -, beginner wrote On Aug 16, 9:32 pm, Carsten Haese [EMAIL PROTECTED] wrote: What is the best solution in Perl need not be the best solution in Python. In Python you should just use a tuple as your dict key, i.e. a[k1,k2] = v, unless you have some other constraints you're not telling us. HTH, -- Carsten Haesehttp://informixdb.sourceforge.net I use tuples this way all the time. It is indeed very neat. But it is not a replacement for double hash-table. If I want to retrieve information just by K1, it is not efficient to index on (K1, K2). If you have to look up all values associates with k1 and any k2, you're right, that's not efficient. That would fall under other constraints you're not telling us. I'm not a mind reader. -Carsten Yeah, I should have mentioned that I actually want to group the data by K1 and then by K2. -- http://mail.python.org/mailman/listinfo/python-list
best GUI library for vector drawing program
Hello, What would be the best cross-platform GUI library to use for a vector based CAD program ( something like Visio on Windows ) WxWidgets, Tk, PyQt, Java Swing, Java SWT, I need the capibility to draw and edit in a window that looks like a page of paper so WYSIWYG is very important, and I need to save the drawings in vector based file formats like PS, EPS, SVG, as well as image formats like jpg, png, and gif. Also, the images need to be high resolution so that they can be pasted into various other programs in Windows OS, and Linux OS, and the Mac OS. Thanks in advance, Dan -- http://mail.python.org/mailman/listinfo/python-list
Re: best GUI library for vector drawing program
chewie54 wrote: What would be the best cross-platform GUI library to use for a vector based CAD program ( something like Visio on Windows ) WxWidgets, Tk, PyQt, Java Swing, Java SWT, I need the capibility to draw and edit in a window that looks like a page of paper so WYSIWYG is very important, and I need to save the drawings in vector based file formats like PS, EPS, SVG, as well as image formats like jpg, png, and gif. Also, the images need to be high resolution so that they can be pasted into various other programs in Windows OS, and Linux OS, and the Mac OS. You might actually consider asking in the 'comp.graphics' hierarchy instead of the language newsgroups. V -- Please remove capital 'A's when replying by e-mail I do not respond to top-posted replies, please don't ask -- http://mail.python.org/mailman/listinfo/python-list
Re: Downloading multiple csv files from a website
On Aug 17, 8:08 am, [EMAIL PROTECTED] wrote: I'd like to download data from the websitehttp://www.russell.com/Indexes/performance/daily_values_US.asp. On this web page, there are links to a number of .csv files, and I'd like to download all of them automatically each day. The file names are not visible on the page, but if I click on a link, a csv file opens in Excel. I've searched this group and looked into urllib, but have not found functions or code snippets that will allow me to download and rename each file. Would someone kindly point me to appropriate libraries/functions and/or code snippets that will get me started? Thanks in advance Thomas Philips This link shows how to extract a list of URLs: http://www.java2s.com/Code/Python/Network/ExtractlistofURLsinawebpage.htm and this one shows how to download: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/83208 Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: how to pass a custom object to re.search?
[EMAIL PROTECTED] wrote: Is it possible to make what I want (to pass a custom object to re.search)? Try to implement __str__() for your object and provide a string representation for it. re.search(str(custom_object)) -- Lawrence, oluyede.org - neropercaso.it It is difficult to get a man to understand something when his salary depends on not understanding it - Upton Sinclair -- http://mail.python.org/mailman/listinfo/python-list
how to pass a custom object to re.search?
Hi, sorry if this is a faq. I've searched and got no result. I'm willing to pass a custom object to re.search method, but I'm getting the error: TypeError: expected string or buffer I don't want to make my object to inherit from basestring (nor I know how to do it...). Then I was left with 'buffer'. I tried to make my object inherit from types.BufferType and got the error: TypeError: Error when calling the metaclass bases type 'buffer' is not an acceptable base type If I call the function buffer passing an instance of my object I get: TypeError: buffer object expected Is it possible to make what I want (to pass a custom object to re.search)? regards, Bruno -- http://mail.python.org/mailman/listinfo/python-list
Re: best GUI library for vector drawing program
On Aug 17, 9:45 am, Victor Bazarov [EMAIL PROTECTED] wrote: chewie54 wrote: What would be the best cross-platform GUI library to use for a vector based CAD program ( something like Visio on Windows ) WxWidgets, Tk, PyQt, Java Swing, Java SWT, I need the capibility to draw and edit in a window that looks like a page of paper so WYSIWYG is very important, and I need to save the drawings in vector based file formats like PS, EPS, SVG, as well as image formats like jpg, png, and gif. Also, the images need to be high resolution so that they can be pasted into various other programs in Windows OS, and Linux OS, and the Mac OS. You might actually consider asking in the 'comp.graphics' hierarchy instead of the language newsgroups. V -- Please remove capital 'A's when replying by e-mail I do not respond to top-posted replies, please don't ask That group doesn't seem to be active anymore. -- http://mail.python.org/mailman/listinfo/python-list
Re: (sort of) deterministic timing in Python
On 8/17/07, Hendrik van Rooyen [EMAIL PROTECTED] wrote: Paul Rubin http://p..id wrote: [EMAIL PROTECTED] (John Fisher) writes: mark start time start event event finishes count time until next interval start second event… rather than this: start event event finishes sleep for interval start second event ... So how do I accomplish this in Python with a minimum of labour? Normally I'd use something like: from time import time t0 = time() start event ... event finishes t1 = time() elapsed = t1 - t0 sleep(interval - elapsed) start second event ... Am I missing something? Not much - only beware of cases when elapsed is greater than interval - not sure what time.sleep(negative_number) does. On Windows 2k3, Python 2.5 it sleeps forever (or almost forever? Maybe a signed/unsigned thing) so yeah, be careful of it. -- http://mail.python.org/mailman/listinfo/python-list
unexpected optparse set_default/set_defaults behavior
Some rather unexpected behavior in the set_default/set_defaults methods for OptionParser that I noticed recently: import optparse parser = optparse.OptionParser() parser.add_option(-r, --restart, dest=restart, action=store_true) Option at 0x-483b3414: -r/--restart parser.defaults {'restart': None} parser.set_default(retart, False) parser.defaults {'retart': False, 'restart': None} Why does set_default not raise an exception when passed a key that it doesn't recognize? Bad typysts bewaer. The only reason I can think not to raise an exception is so that defaults can be defined before the options are added. Is there some use case that I'm not thinking of here? I realize that changing this could break some existing scripts, but I'm still tempted to file this as a bug. Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: best GUI library for vector drawing program
On Aug 17, 8:27 am, chewie54 [EMAIL PROTECTED] wrote: Hello, What would be the best cross-platform GUI library to use for a vector based CAD program ( something like Visio on Windows ) WxWidgets, Tk, PyQt, Java Swing, Java SWT, I need the capibility to draw and edit in a window that looks like a page of paper so WYSIWYG is very important, and I need to save the drawings in vector based file formats like PS, EPS, SVG, as well as image formats like jpg, png, and gif. Also, the images need to be high resolution so that they can be pasted into various other programs in Windows OS, and Linux OS, and the Mac OS. Thanks in advance, Dan I think wxPython in conjunction with PIL and/or matplotlib could work. I'm pretty sure the people on the wxPython user's list have done vector graphics using those other libraries. Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: Question on SPE and pwintypes.dll
On Aug 17, 8:38 am, Gerry [EMAIL PROTECTED] wrote: I'm running SPE 8.3.c under XP, on a new PC. The files for SPE and Python were copied to the new machine, but the OS wasn't migrated, so the registry didn't know about either. I reinstalled Python 2.5.1, and Python seems fine. I made a shortcut to SPE.pyw. Clicking on the shortcut gives an error pop-up, application failed to start cannot find pwintypes.dll. When I click OK, SPE seems to start normally. Any idea what's up? Googling for pwintypes.dll didn't give me any hits. Gerry Probably just need to do a search in the registry of the old PC for SPE or that dll file and then make the appropriate changes on your new PC. Or just reinstall SPE. Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: how to pass a custom object to re.search?
Try to implement __str__() for your object and provide a string representation for it. re.search(str(custom_object)) I've done that (and added __unicode__ too). I only didn't want to, I want to do: re.search(custom_object) so, code that worked before as: re.search(parentobj.custom_object) don't have to be changed for: re.search(str(parentobj.custom_object)) and I'm also curious to know if it is possible to do that... :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Need to generate some functions.
you can use the dictionary returned by the built in function vars, along the lines of vars()[foo] = lambda x: 3*x foo(2) 6 but polluting your name space with data counts as bad style and will probably bite you at some point -- you probably are better of putting closures in a dictionary: def mkdict(address): def something(): return {'Address': address, 'Control': SOME_CONST} return something mk = {} mk[n1] = mkdict(n1) mk[n1]() {'Control': 'SOME_CONST', 'Address': 'n1'} Steven W. Orr wrote: Given a list of names ll = (n1, n2, n3, n4) I want to create a pair of functions based off of each name. An example of what I want to happen would look like this: def mkn1dict(address): return {'Address': address, 'Control': SOME_CONST} def mkn1Classobj(address): return Classobj( mkn1classobj(address) ) I know how to do this in a preprocessor, but I'd like to do it directly in python. Can this be done? TIA -- http://mail.python.org/mailman/listinfo/python-list
Re: how to pass a custom object to re.search?
[EMAIL PROTECTED] wrote: and I'm also curious to know if it is possible to do that... :-) Only if re.search() doesn't check for the type of the argument, which it seems it does. -- Lawrence, oluyede.org - neropercaso.it It is difficult to get a man to understand something when his salary depends on not understanding it - Upton Sinclair -- http://mail.python.org/mailman/listinfo/python-list
Re: passing variables and values to texboxdisplays
On Aug 17, 6:57 am, yadin [EMAIL PROTECTED] wrote: hi! Can any one tell me why is it that i can't see my second frame and why is the value of freq not Appended in the First frame ...thanks I know it is wx python but it has to do with passing variables.thanks import wx def create(parent): return Frame1(parent) [wxID_FRAME1, wxID_FRAME1FREQ, wxID_FRAME1FREQDISP, wxID_FRAME1STATICTEXT1, ] = [wx.NewId() for _init_ctrls in range(4)] class Frame1(wx.Frame): def _init_ctrls(self, prnt): # generated method, don't edit wx.Frame.__init__(self, id=wxID_FRAME1, name='', parent=prnt, pos=wx.Point(380, 179), size=wx.Size(241, 133), style=wx.DEFAULT_FRAME_STYLE, title='Frame1') self.SetClientSize(wx.Size(233, 99)) self.staticText1 = wx.StaticText(id=wxID_FRAME1STATICTEXT1, label='frequency disp', name='staticText1', parent=self, pos=wx.Point(24, 32), size=wx.Size(71, 13), style=0) self.freqdisp = wx.TextCtrl(id=wxID_FRAME1FREQDISP, name='freqdisp', parent=self, pos=wx.Point(104, 24), size=wx.Size(100, 21), style=0, value='') self.freq = wx.Button(id=wxID_FRAME1FREQ, label='get freq', name='freq', parent=self, pos=wx.Point(24, 56), size=wx.Size(184, 23), style=0) self.freq.Bind(wx.EVT_BUTTON, self.OnButton1Button, id=wxID_FRAME1FREQ) def __init__(self, parent): self._init_ctrls(parent) def OnButton1Button(self, event): def create(parent): return Frame2(parent) [wxID_FRAME2, wxID_FRAME2FREQ, wxID_FRAME2FREQDISP, wxID_FRAME2STATICTEXT1,] = [wx.NewId() for _init_ctrls in range(4)] class Frame2: def __init__(self): # wx.Frame.__init__(self, id=wxID_FRAME2, name='', parent=prt, pos=wx.Point(400, 179), size=wx.Size(300, 133), style=wx.DEFAULT_FRAME_STYLE, title='Frame2') self.SetClientSize(wx.Size(233, 99)) self.staticText1 = wx.StaticText(id=wxID_FRAME2STATICTEXT1, label='frequency goes here first', name='staticText2', parent=self, pos=wx.Point(24, 32), size=wx.Size(71, 13), style=0) self.freqdisp2 = wx.TextCtrl(id=wxID_FRAME2FREQDISP, name='freqdisp2', parent=self, pos=wx.Point(104, 24), size=wx.Size(100, 21), style=0, value=' ') self.freq = wx.Button(id=wxID_FRAME2FREQ, label='get freq', name='freq', parent=self, pos=wx.Point(24, 56), size=wx.Size(184, 23), style=0) self.freq.Bind(wx.EVT_BUTTON, self.OnButton2Button, id=wxID_FRAME2FREQ) def __init__(self, parent): self._init_ctrls(parent) def OnButton2Button(self, event): freqdisp.Append('this is it 24HZ!') if __name__ == '__main__': app = wx.PySimpleApp() frame = create(None) frame.Show() app.MainLoop() Your 2nd frame isn't subclassing wx.Frame and there's nothing calling the Show() method even if it had been. Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: Downloading multiple csv files from a website
Our systems administrator suggested that I try wget, a GNU utility that is designed to pick up data. It might prove to be the easiest way to get the data I want, and I am going to try that first. Thanks again. Thomas Philips -- http://mail.python.org/mailman/listinfo/python-list
help to make program better
hi! Can any one tell me why is it that i can't see my second frame and why is the value of freq not Appended in the First frame ...thanks I know it is wx python but it has to do with passing variables.thanks import wx def create(parent): return Frame1(parent) [wxID_FRAME1, wxID_FRAME1FREQ, wxID_FRAME1FREQDISP, wxID_FRAME1STATICTEXT1, ] = [wx.NewId() for _init_ctrls in range(4)] class Frame1(wx.Frame): def _init_ctrls(self, prnt): # generated method, don't edit wx.Frame.__init__(self, id=wxID_FRAME1, name='', parent=prnt, pos=wx.Point(380, 179), size=wx.Size(241, 133), style=wx.DEFAULT_FRAME_STYLE, title='Frame1') self.SetClientSize(wx.Size(233, 99)) self.staticText1 = wx.StaticText(id=wxID_FRAME1STATICTEXT1, label='frequency disp', name='staticText1', parent=self, pos=wx.Point(24, 32), size=wx.Size(71, 13), style=0) self.freqdisp = wx.TextCtrl(id=wxID_FRAME1FREQDISP, name='freqdisp', parent=self, pos=wx.Point(104, 24), size=wx.Size(100, 21), style=0, value='') self.freq = wx.Button(id=wxID_FRAME1FREQ, label='get freq', name='freq', parent=self, pos=wx.Point(24, 56), size=wx.Size(184, 23), style=0) self.freq.Bind(wx.EVT_BUTTON, self.OnButton1Button, id=wxID_FRAME1FREQ) def __init__(self, parent): self._init_ctrls(parent) def OnButton1Button(self, event): def create(parent): return Frame2(parent) [wxID_FRAME2, wxID_FRAME2FREQ, wxID_FRAME2FREQDISP, wxID_FRAME2STATICTEXT1,] = [wx.NewId() for _init_ctrls in range(4)] class Frame2: def __init__(self): # wx.Frame.__init__(self, id=wxID_FRAME2, name='', parent=prt, pos=wx.Point(400, 179), size=wx.Size(300, 133), style=wx.DEFAULT_FRAME_STYLE, title='Frame2') self.SetClientSize(wx.Size(233, 99)) self.staticText1 = wx.StaticText(id=wxID_FRAME2STATICTEXT1, label='frequency goes here first', name='staticText2', parent=self, pos=wx.Point(24, 32), size=wx.Size(71, 13), style=0) self.freqdisp2 = wx.TextCtrl(id=wxID_FRAME2FREQDISP, name='freqdisp2', parent=self, pos=wx.Point(104, 24), size=wx.Size(100, 21), style=0, value=' ') self.freq = wx.Button(id=wxID_FRAME2FREQ, label='get freq', name='freq', parent=self, pos=wx.Point(24, 56), size=wx.Size(184, 23), style=0) self.freq.Bind(wx.EVT_BUTTON, self.OnButton2Button, id=wxID_FRAME2FREQ) def __init__(self, parent): self._init_ctrls(parent) def OnButton2Button(self, event): freqdisp.Append('this is it 24HZ!') if __name__ == '__main__': app = wx.PySimpleApp() frame = create(None) frame.Show() app.MainLoop() -- http://mail.python.org/mailman/listinfo/python-list
Re: Naming dictionaries recursively
On Aug 17, 7:38 am, TYR [EMAIL PROTECTED] wrote: I'd like to do something like this; iterate through a file which consists of data stored in dictionary format, one dict on each line, and read each line into a new dict using one of the values in the dict as its name... for example: stuff = open('data.txt') for eachLine in stuff: name{} name = eachLine and then do something clever to extract the value of the key (name) from the line and use it as the dictionary's name. A line from data.txt would look like this: {'name' : Bob, 'species' : Humboldt, 'colour' : red, 'habits' : predatory}. Aim is to call one of them by name, and merge the values in that dictionary into a string pulled from another source. Pyparsing includes an example that is very similar to this. Here is that example adapted to your specific data: from pyparsing import * line = {'name' : Bob, 'species' : Humboldt, 'colour' : red, 'habits' : predatory} LBRACE,RBRACE,COLON,COMMA = map(Suppress,{}:,) key = sglQuotedString.setParseAction(removeQuotes) value = OneOrMore(Word(alphanums))\ .setParseAction(keepOriginalText) entry = Group(key + COLON + empty + value) lineExpr = LBRACE + Dict(delimitedList(entry)) + RBRACE parsedData = lineExpr.parseString(line) # some examples of accessing the parsed data print Keys:, parsedData.keys() print parsedData.name print parsedData.colour print Name: %(name)s \nSpecies: %(species)s \n \ Colour: %(colour)s \nHabits: %(habits)s % parsedData Prints: Keys: ['colour', 'habits', 'name', 'species'] Bob red Name: Bob Species: Humboldt Colour: red Habits: predatory -- Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: how to pass a custom object to re.search?
[EMAIL PROTECTED] wrote: I've done that (and added __unicode__ too). I only didn't want to, I want to do: re.search(custom_object) so, code that worked before as: re.search(parentobj.custom_object) don't have to be changed for: re.search(str(parentobj.custom_object)) and I'm also curious to know if it is possible to do that... :-) Not without monkeypatching the re module: import re _original_compile = re._compile def _wrapped_compile(*key): try: custom_compile = key[0].__compile__ except AttributeError: return _original_compile(*key) else: return custom_compile(*key[1:]) re._compile = _wrapped_compile class Aaa(object): def __compile__(self, *args): return re.compile([Aa]+) print re.findall(Aaa(), a yadda so wht) Peter -- http://mail.python.org/mailman/listinfo/python-list
Getting the result of a process after exec*()
Hi, I am trying to write a Python script that takes a ZIP file from a web form (using CGI) and uses either of the UN*X unzip, gunzip, tar, bunzip2 utilities to expand it. I can use Python to save the script to disk; but processing it is another matter. If for example I have received a *.tar.gz file, I need to first pass it through gunzip; then through the tar utility. I also want to process the resulting directory. The problem for me is this: once an external process is called via exec*() the script has effectively fulfilled its task. Is there any way one can process a file with an external process and continue further processing in Python; /once the external processing is completed/? Many thanks, Andrew -- http://mail.python.org/mailman/listinfo/python-list
Re: Naming dictionaries recursively
So the tougher problem seems to be parsing those lines. That is not a valid Python dictionary unless the names `Bob`, `Humboldt`, `red`, and `predatory` are not already defined. So you can't just ``eval`` it. In what way? {'key': val}, right? Anyway, I can always change the format they go into the file in. -- http://mail.python.org/mailman/listinfo/python-list
Re: Hijack! Different book:
On Aug 16, 3:50 pm, Steve Holden [EMAIL PROTECTED] wrote: Dennis Lee Bieber wrote: On Thu, 16 Aug 2007 04:21:07 -0700, Paul Boddie [EMAIL PROTECTED] declaimed the following in comp.lang.python: Is this the book that came out before TurboGears even reached 1.0, probably having diminished relevance now that there are 1.1 and 2.0 Not sure -- I'd ordered it in January, but Amazon didn't ship it until a week ago; don't know if it was this, or the other book in the shipment that held it up. JANUARY!?? So much for Amazon's customer service. Or is it only February where you live? regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --- Asciimercial -- Get on the web: Blog, lens and tag the Internet Many services currently offer free registration --- Thank You for Reading - Yeah...The Python Power! book was supposed to be released months ago, so I ordered it 4-6 months ago, but it only shipped a week ago when it actually released. Admittedly, this has nothing to do with the TurboGears book. Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: Question on SPE and pwintypes.dll
On Aug 17, 10:14 am, [EMAIL PROTECTED] wrote: On Aug 17, 8:38 am, Gerry [EMAIL PROTECTED] wrote: I'm running SPE 8.3.c under XP, on a new PC. The files for SPE and Python were copied to the new machine, but the OS wasn't migrated, so the registry didn't know about either. I reinstalled Python 2.5.1, and Python seems fine. I made a shortcut to SPE.pyw. Clicking on the shortcut gives an error pop-up, application failed to start cannot find pwintypes.dll. When I click OK, SPE seems to start normally. Any idea what's up? Googling for pwintypes.dll didn't give me any hits. Gerry Probably just need to do a search in the registry of the old PC for SPE or that dll file and then make the appropriate changes on your new PC. Or just reinstall SPE. Mike Thanks -- I'll give that a try. Gerry -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting the result of a process after exec*()
On 8/17/07, AndrewTK [EMAIL PROTECTED] wrote: The problem for me is this: once an external process is called via exec*() the script has effectively fulfilled its task. Is there any way one can process a file with an external process and continue further processing in Python; /once the external processing is completed/? Assuming you're looking at the docs for the os module, instead of the exec*() functions, check out the spawn*() functions, or, to use a subshell, system(). Better yet, take a look at the subprocess module: http://docs.python.org/lib/module-subprocess.html -Miles -- http://mail.python.org/mailman/listinfo/python-list
Re: advice about `correct' use of decorator
Laszlo Nagy wrote: Are you developing a website or a GUI program? It will be used in a web development. It is an important point? Yes, I think. Unless you use AJAX. :-) Most web sites work this way: user clicks - request to server - process on server - response I would rather enclose the whole handler in try/except and raise a custom PermissionDenied exception when the user has inscuficient permissions. There are problems with a decorator used for authorization. The context needs to be determined. E.g. which user is accessing the method? (It can be hard to tell if the method is part of a thread object that lies in a thread pool and is shared between simultaneous clients...) Also it might be that the method's purpose is to change objects of the same class, and the user has permission to modify one object but not the other. In this case, authorization must be done inside the function call... How do you express this with a decorator? These are just ideas. You should analyze your problem and make your decision. If you only want to restrict access to functions, then probably using decorators is perfect. Best, Laszlo I post the change_pass() function as an example, there is a buch of other functions (the whole site actually) that will require a logged user. May the change_pass() function have additional control, shure, but it will be not part of the `global' requirement. Thank you very much for your time, Laszlo Gerardo -- http://mail.python.org/mailman/listinfo/python-list
Re: best GUI library for vector drawing program
I used wxWidgets for a work like that. I found it quite easy to use and I found simple to create a Gui with wxdev which is quite rad. bye Pier Paolo -- http://mail.python.org/mailman/listinfo/python-list
Re: advice about `correct' use of decorator
BJörn Lindqvist wrote: On 8/16/07, Gerardo Herzig [EMAIL PROTECTED] wrote: @is_logued_in def change_pass(): bla bla And so on for all the other functions who needs that the user is still loged in. where obviosly the is_logued_in() function will determine if the dude is still loged in, and THEN execute change_pass(). If the dude is not loged in, change_pass() is NOT executed at all. Instead, it will be redirected to the `login' screen. I think this is redundant use of a decorator. You can achieve the exact same effect by writing: def is_logued_in(): if not user.is_logged_in(): raise NotLoggedInError It costs you one more line, but reduces complexity. And if you are worried about that extra line you can put it in a function. As far as i know (by the way, AFAK is the shortcut?, and BTW means `by the way'? ), decorators are not indispensable. I mean, all that you can do with python, you can doit without decorators. And from my point of view, this hides the complexity for the other developers of my group, since all they have to do is add the @is_logged_in line at the top of the cgi script, and not to worrie about exceptions, not even how the decorator is implemented (i may log the error in some file). All they have to know is that any abnormal situation will redirect to the `login' screen. Thank you for your comments! Gerardo -- http://mail.python.org/mailman/listinfo/python-list
help to make program better
hi! Can any one tell me why is it that i can't see my second frame and why is the value of freq not Appended in the First frame ...thanks I know it is wx python but it has to do with passing variables.thanks import wx def create(parent): return Frame1(parent) [wxID_FRAME1, wxID_FRAME1FREQ, wxID_FRAME1FREQDISP, wxID_FRAME1STATICTEXT1, ] = [wx.NewId() for _init_ctrls in range(4)] class Frame1(wx.Frame): def _init_ctrls(self, prnt): # generated method, don't edit wx.Frame.__init__(self, id=wxID_FRAME1, name='', parent=prnt, pos=wx.Point(380, 179), size=wx.Size(241, 133), style=wx.DEFAULT_FRAME_STYLE, title='Frame1') self.SetClientSize(wx.Size(233, 99)) self.staticText1 = wx.StaticText(id=wxID_FRAME1STATICTEXT1, label='frequency disp', name='staticText1', parent=self, pos=wx.Point(24, 32), size=wx.Size(71, 13), style=0) self.freqdisp = wx.TextCtrl(id=wxID_FRAME1FREQDISP, name='freqdisp', parent=self, pos=wx.Point(104, 24), size=wx.Size(100, 21), style=0, value='') self.freq = wx.Button(id=wxID_FRAME1FREQ, label='get freq', name='freq', parent=self, pos=wx.Point(24, 56), size=wx.Size(184, 23), style=0) self.freq.Bind(wx.EVT_BUTTON, self.OnButton1Button, id=wxID_FRAME1FREQ) def __init__(self, parent): self._init_ctrls(parent) def OnButton1Button(self, event): def create(parent): return Frame2(parent) [wxID_FRAME2, wxID_FRAME2FREQ, wxID_FRAME2FREQDISP, wxID_FRAME2STATICTEXT1,] = [wx.NewId() for _init_ctrls in range(4)] class Frame2: def __init__(self): # wx.Frame.__init__(self, id=wxID_FRAME2, name='', parent=prt, pos=wx.Point(400, 179), size=wx.Size(300, 133), style=wx.DEFAULT_FRAME_STYLE, title='Frame2') self.SetClientSize(wx.Size(233, 99)) self.staticText1 = wx.StaticText(id=wxID_FRAME2STATICTEXT1, label='frequency goes here first', name='staticText2', parent=self, pos=wx.Point(24, 32), size=wx.Size(71, 13), style=0) self.freqdisp2 = wx.TextCtrl(id=wxID_FRAME2FREQDISP, name='freqdisp2', parent=self, pos=wx.Point(104, 24), size=wx.Size(100, 21), style=0, value=' ') self.freq = wx.Button(id=wxID_FRAME2FREQ, label='get freq', name='freq', parent=self, pos=wx.Point(24, 56), size=wx.Size(184, 23), style=0) self.freq.Bind(wx.EVT_BUTTON, self.OnButton2Button, id=wxID_FRAME2FREQ) def __init__(self, parent): self._init_ctrls(parent) def OnButton2Button(self, event): freqdisp.Append('this is it 24HZ!') Show() if __name__ == '__main__': app = wx.PySimpleApp() frame = create(None) frame.Show() app.MainLoop() -- http://mail.python.org/mailman/listinfo/python-list
Re: help to make program better
On Aug 17, 9:27 am, yadin [EMAIL PROTECTED] wrote: hi! Can any one tell me why is it that i can't see my second frame and why is the value of freq not Appended in the First frame ...thanks I know it is wx python but it has to do with passing variables.thanks import wx def create(parent): return Frame1(parent) [wxID_FRAME1, wxID_FRAME1FREQ, wxID_FRAME1FREQDISP, wxID_FRAME1STATICTEXT1, ] = [wx.NewId() for _init_ctrls in range(4)] class Frame1(wx.Frame): def _init_ctrls(self, prnt): # generated method, don't edit wx.Frame.__init__(self, id=wxID_FRAME1, name='', parent=prnt, pos=wx.Point(380, 179), size=wx.Size(241, 133), style=wx.DEFAULT_FRAME_STYLE, title='Frame1') self.SetClientSize(wx.Size(233, 99)) self.staticText1 = wx.StaticText(id=wxID_FRAME1STATICTEXT1, label='frequency disp', name='staticText1', parent=self, pos=wx.Point(24, 32), size=wx.Size(71, 13), style=0) self.freqdisp = wx.TextCtrl(id=wxID_FRAME1FREQDISP, name='freqdisp', parent=self, pos=wx.Point(104, 24), size=wx.Size(100, 21), style=0, value='') self.freq = wx.Button(id=wxID_FRAME1FREQ, label='get freq', name='freq', parent=self, pos=wx.Point(24, 56), size=wx.Size(184, 23), style=0) self.freq.Bind(wx.EVT_BUTTON, self.OnButton1Button, id=wxID_FRAME1FREQ) def __init__(self, parent): self._init_ctrls(parent) def OnButton1Button(self, event): def create(parent): return Frame2(parent) [wxID_FRAME2, wxID_FRAME2FREQ, wxID_FRAME2FREQDISP, wxID_FRAME2STATICTEXT1,] = [wx.NewId() for _init_ctrls in range(4)] class Frame2: ~~~should be class Frame2(wx.Frame): def __init__(self): # wx.Frame.__init__(self, id=wxID_FRAME2, name='', parent=prt, pos=wx.Point(400, 179), size=wx.Size(300, 133), style=wx.DEFAULT_FRAME_STYLE, title='Frame2') self.SetClientSize(wx.Size(233, 99)) self.staticText1 = wx.StaticText(id=wxID_FRAME2STATICTEXT1, label='frequency goes here first', name='staticText2', parent=self, pos=wx.Point(24, 32), size=wx.Size(71, 13), style=0) self.freqdisp2 = wx.TextCtrl(id=wxID_FRAME2FREQDISP, name='freqdisp2', parent=self, pos=wx.Point(104, 24), size=wx.Size(100, 21), style=0, value=' ') self.freq = wx.Button(id=wxID_FRAME2FREQ, label='get freq', name='freq', parent=self, pos=wx.Point(24, 56), size=wx.Size(184, 23), style=0) self.freq.Bind(wx.EVT_BUTTON, self.OnButton2Button, id=wxID_FRAME2FREQ) def __init__(self, parent): self._init_ctrls(parent) def OnButton2Button(self, event): freqdisp.Append('this is it 24HZ!') Show() should be create(self).Show() if __name__ == '__main__': app = wx.PySimpleApp() frame = create(None) frame.Show() app.MainLoop() Hi, I found two errors in your program. one is that class Frame2 must be inherited from wx.Frame, the other is Show() must belong a object. -- http://mail.python.org/mailman/listinfo/python-list
help on object programing
class big(self): x = 32 list = [] def inside (self): class small(self): # a new class defined inside the first y = 348 list.append(y) # send the value to first list list.append(x) print list how can i define my variables so that there are valid outside the class??? -- http://mail.python.org/mailman/listinfo/python-list
Re: best GUI library for vector drawing program
On Aug 17, 12:08 pm, Jeremy Sanders jeremy [EMAIL PROTECTED] wrote: chewie54 wrote: What would be the best cross-platform GUI library to use for a vector based CAD program ( something like Visio on Windows ) WxWidgets, Tk, PyQt, Java Swing, Java SWT, I need the capibility to draw and edit in a window that looks like a page of paper so WYSIWYG is very important, and I need to save the drawings in vector based file formats like PS, EPS, SVG, as well as image formats like jpg, png, and gif. Also, the images need to be high resolution so that they can be pasted into various other programs in Windows OS, and Linux OS, and the Mac OS. PyQt/Qt4 is capable of that (SVG export was added in Qt4.3). I have a graph drawing application based around it (Veusz). If you base everything around QPainter, you'll be able to write to any of those output formats (including eps and pdf), and bitmaps. Antialiasing is optional for bitmap formats. Jeremy -- Jeremy Sandershttp://www.jeremysanders.net/ Jeremy, I looked at your application, Veusz (it looks very nice), and I see you have binary distrubitions for each os. Is is difficult to build these binaries for each system. Could you tell me how that is done? Thanks, Dan -- http://mail.python.org/mailman/listinfo/python-list
Re: Can python threads take advantage of use dual core ?
nikhilketkar schrieb: What are the implications of the Global Interpreter Lock in Python ? Does this mean that Python threads cannot exploit a dual core processor and the only advantage of using threads is in that computation and IO-bound operations can continue in parallel ? Essentially, yes. That is unless the computation is done in C-code which released the GIL beforehand. But a certain tradeoff is to expected nontheless. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: best GUI library for vector drawing program
chewie54 wrote: What would be the best cross-platform GUI library to use for a vector based CAD program ( something like Visio on Windows ) WxWidgets, Tk, PyQt, Java Swing, Java SWT, I need the capibility to draw and edit in a window that looks like a page of paper so WYSIWYG is very important, and I need to save the drawings in vector based file formats like PS, EPS, SVG, as well as image formats like jpg, png, and gif. Also, the images need to be high resolution so that they can be pasted into various other programs in Windows OS, and Linux OS, and the Mac OS. PyQt/Qt4 is capable of that (SVG export was added in Qt4.3). I have a graph drawing application based around it (Veusz). If you base everything around QPainter, you'll be able to write to any of those output formats (including eps and pdf), and bitmaps. Antialiasing is optional for bitmap formats. Jeremy -- Jeremy Sanders http://www.jeremysanders.net/ -- http://mail.python.org/mailman/listinfo/python-list
Re: best GUI library for vector drawing program
On Aug 17, 9:27 am, chewie54 [EMAIL PROTECTED] wrote: Hello, What would be the best cross-platform GUI library to use for a vector based CAD program ( something like Visio on Windows ) WxWidgets, Tk, PyQt, Java Swing, Java SWT, I need the capibility to draw and edit in a window that looks like a page of paper so WYSIWYG is very important, and I need to save the drawings in vector based file formats like PS, EPS, SVG, as well as image formats like jpg, png, and gif. Also, the images need to be high resolution so that they can be pasted into various other programs in Windows OS, and Linux OS, and the Mac OS. Thanks in advance, Dan Also, I forgot to mention that it must have scripting capabilities so and I would like to embed a Tcl or Python interpreter. -- http://mail.python.org/mailman/listinfo/python-list
Can python threads take advantage of use dual core ?
What are the implications of the Global Interpreter Lock in Python ? Does this mean that Python threads cannot exploit a dual core processor and the only advantage of using threads is in that computation and IO-bound operations can continue in parallel ? Thanks, Nikhil -- http://mail.python.org/mailman/listinfo/python-list
Re: Can python threads take advantage of use dual core ?
Diez B. Roggisch wrote: nikhilketkar schrieb: What are the implications of the Global Interpreter Lock in Python ? Does this mean that Python threads cannot exploit a dual core processor and the only advantage of using threads is in that computation and IO-bound operations can continue in parallel ? Essentially, yes. That is unless the computation is done in C-code which released the GIL beforehand. Which virtually all computation-intensive extensions do. Also, note the processing package, which allows you to use a separate process more or less like a thread, thus avoiding GIL issues completely. Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: Memory leak when creating lots of object
Godzilla [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] | What should I do next? Can I force garbage collection manually? If so, | how do I do that? Read doc for gc module. I think import gc gc.collect() -- http://mail.python.org/mailman/listinfo/python-list
Re: to property or function in class object
james_027 wrote: i am very new to python, not knowing much about good design. I have an object here for example a Customer object, where I need to retrieve a info which has a number of lines of code to get it. my question is weather what approach should I use? to use the property which is from the python new class style as I understand or simple use function that will return the the info I needed. [snip] While both approach would get the job done, I don't know much about the performance, benefits, design philosophy between the two approach. I tend to view property as only something you use for the purposes of backwards compatibility. So if you started with something as a simple attribute and you later realize that it needs to do some computation, you can use properties to keep the same API. However, if I know right off the bat that I need to do some computation to return a result, then I'll always prefer a method. People expect a method call to take some computation. People don't always expect that from a simple attribute access. So I think it's more predictable for your users if you use a method when there's any real work being done. STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: help on object programing
On Aug 17, 11:07 am, yadin [EMAIL PROTECTED] wrote: class big(self): x = 32 list = [] def inside (self): class small(self): # a new class defined inside the first y = 348 list.append(y) # send the value to first list list.append(x) print list how can i define my variables so that there are valid outside the class??? Well, first you have to create an instance of the class big: bigInstance = big(); then to get to bigInstance's list you do bigInstance.list and you can get to the list: print bigInstance.list; but the list will be empty. check out the dive into python book to understand it object oriented programming a little more. http://www.diveintopython.org/ -- http://mail.python.org/mailman/listinfo/python-list
Making a copy (not reference) of a file handle, or starting stdin over at line 0
I wrote a script which will convert a tab-delimited file to a fixed-width file, or a fixed-width file into a tab-delimited. It reads a config file which defines the field lengths, and uses it to convert either way. Here's an example of the config file: 1:6,7:1,8:9,17:15,32:10 This converts a fixed-width file to a tab-delimited where the first field is the first six characters of the file, the second is the seventh, etc. Conversely, it converts a tab-delimited file to a file where the first six characters are the first tab field, right-padded with spaces, and so on. What I want to do is look at the file and decide whether to run the function to convert the file to tab or FW. Here is what works (mostly): x = inputFile.readline().split(\t) inputFile.seek(0) if len(x) 1: toFW(inputFile) else: toTab(inputFile) The problem is that my file accepts the input file via stdin (pipe) or as an argument to the script. If I send the filename as an argument, everything works perfectly. If I pipe the input file into the script, it is unable to seek() it. I tried making a copy of inputFile and doing a readline() from it, but being a reference, it makes no difference. How can I check a line (or two) from my input file (or stdin stream) and still be able to process all the records with my function? Thanks, Shawn -- http://mail.python.org/mailman/listinfo/python-list
Python and Tkinter Programming--Expensive!
Why is the book in Subject (author is Grayson) so expensive? $100 on Amazon and $195 on ABE. Aren't there alternatives? -- Wayne Watson (Nevada City, CA) Web Page: speckledwithStars.net -- http://mail.python.org/mailman/listinfo/python-list
Re: unexpected optparse set_default/set_defaults behavior
[EMAIL PROTECTED] wrote: Some rather unexpected behavior in the set_default/set_defaults methods for OptionParser that I noticed recently: import optparse parser = optparse.OptionParser() parser.add_option(-r, --restart, dest=restart, action=store_true) Option at 0x-483b3414: -r/--restart parser.defaults {'restart': None} parser.set_default(retart, False) parser.defaults {'retart': False, 'restart': None} Why does set_default not raise an exception when passed a key that it doesn't recognize? Bad typysts bewaer. The only reason I can think not to raise an exception is so that defaults can be defined before the options are added. Is there some use case that I'm not thinking of here? I'm not really sure what other use case there is with optparse, but argparse has the same behavior because sometimes it's useful to store values that can't be changed by anything on the command line. This is particularly useful when you're dealing with sub-commands:: import argparse parser = argparse.ArgumentParser() subparsers = parser.add_subparsers() # set up the foo parser, adding a static func default foo_parser = subparsers.add_parser('foo') foo_parser.set_defaults(func=lambda: 'do something for foo') foo_parser.add_argument('--foo') # set up the bar parser, adding a staic func default bar_parser = subparsers.add_parser('bar') bar_parser.set_defaults(func=lambda: 'do something for bar') bar_parser.add_argument('bar') # parse the arguments and call whichever func was selected args = parser.parse_args(['bar', '13']) args.func() 'do something for bar' I know optparse doesn't support sub-commands, but I can imagine that if you were trying to hack optparse to do something similar you might find it useful to be able to specify defaults that weren't ever set by anything at the command line. STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: best GUI library for vector drawing program
On Aug 17, 12:07 pm, chewie54 [EMAIL PROTECTED] wrote: On Aug 17, 9:27 am, chewie54 [EMAIL PROTECTED] wrote: Hello, What would be the best cross-platform GUI library to use for a vector based CAD program ( something like Visio on Windows ) WxWidgets, Tk, PyQt, Java Swing, Java SWT, I need the capibility to draw and edit in a window that looks like a page of paper so WYSIWYG is very important, and I need to save the drawings in vector based file formats like PS, EPS, SVG, as well as image formats like jpg, png, and gif. Also, the images need to be high resolution so that they can be pasted into various other programs in Windows OS, and Linux OS, and the Mac OS. Thanks in advance, Dan Also, I forgot to mention that it must have scripting capabilities so and I would like to embed a Tcl or Python interpreter. I should have also mentioned that is for a commercial application. That doesn't rule Qt or PyQt out, but this is a startup company with very little income so my first choice would be to use some GUI library that is free to use for commercial apps. Thanks again, Dan -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with directory recursion!
Here's part of the output that's incorrect: models\W_BoomerEdge BYOS_C.entity.xml BYOS_C_Collision.entity.xml Notice that the file BYOS_C.entity.xml is showing up as a file in the directory W_BoomerEdge. This file does not exist in this folder, but yet in a different folder. The output is consistent with the 'print' statements you will see in the function I posted earlier. On 8/17/07, Robert Dailey [EMAIL PROTECTED] wrote: Hi, I've created a function that is used to recurse a directory tree in Windows XP using os.walk(). For the most part it works, however in some instances the data is incorrect and I'm getting invalid sub-directory paths. Here's the function: def __doSearch( root_dir, sub_path, restype, ext ): print sub_path # Searches the specified directory and generates a # list of files to preload. complete_path = osp.normpath( osp.join( root_dir, sub_path ) ) for root, dirs, files in os.walk( complete_path ): # Record the list of file hash ID's for file in files: split = __resType( file ) if split[1] == restype: #print sub_path print \t, file __appendResource( ext, sub_path, split[0] ) # Remove .svn subdirectories; we don't walk these. if .svn in dirs: dirs.remove( .svn ) # Recurse child directories for dir in dirs: __doSearch( root_dir, osp.join( sub_path, dir ), restype, ext ) Does anyone see anything immediately suspicious about the code? I'm assuming that in Python, every time a function is called recursively it gets its own copy of local variables. For some reason the sub_path variable isn't consistent depending on where I use it. For example, if you notice the print call at the very start of the function, it will output something like models/ships. However, after passing it into __appendResource(), it appears to be just models. -- http://mail.python.org/mailman/listinfo/python-list
Problem with directory recursion!
Hi, I've created a function that is used to recurse a directory tree in Windows XP using os.walk(). For the most part it works, however in some instances the data is incorrect and I'm getting invalid sub-directory paths. Here's the function: def __doSearch( root_dir, sub_path, restype, ext ): print sub_path # Searches the specified directory and generates a # list of files to preload. complete_path = osp.normpath( osp.join( root_dir, sub_path ) ) for root, dirs, files in os.walk( complete_path ): # Record the list of file hash ID's for file in files: split = __resType( file ) if split[1] == restype: #print sub_path print \t, file __appendResource( ext, sub_path, split[0] ) # Remove .svn subdirectories; we don't walk these. if .svn in dirs: dirs.remove( .svn ) # Recurse child directories for dir in dirs: __doSearch( root_dir, osp.join( sub_path, dir ), restype, ext ) Does anyone see anything immediately suspicious about the code? I'm assuming that in Python, every time a function is called recursively it gets its own copy of local variables. For some reason the sub_path variable isn't consistent depending on where I use it. For example, if you notice the print call at the very start of the function, it will output something like models/ships. However, after passing it into __appendResource(), it appears to be just models. -- http://mail.python.org/mailman/listinfo/python-list
Re: best GUI library for vector drawing program
chewie54 wrote on 17.08.2007 15:27: Hello, What would be the best cross-platform GUI library to use for a vector based CAD program ( something like Visio on Windows ) WxWidgets, Tk, PyQt, Java Swing, Java SWT, I need the capibility to draw and edit in a window that looks like a page of paper so WYSIWYG is very important, and I need to save the drawings in vector based file formats like PS, EPS, SVG, as well as image formats like jpg, png, and gif. Also, the images need to be high resolution so that they can be pasted into various other programs in Windows OS, and Linux OS, and the Mac OS. The NetBeans Platform offers a nice module for this. NetBeans itself uses it for UML, BPEL and ERD modelling and other features (such as the visual XSD editor) http://platform.netbeans.org/ http://graph.netbeans.org/ Thomas -- http://mail.python.org/mailman/listinfo/python-list
question
I've parsed a webpage into a text file. In doing so, I've kept all the text I'm interested in, and removed all the text I don't want. My result is a text file that is comma-separated. However, the text file is one, very long, single string. I need to substitute every eighth (8th) comma with a new line (\n). I've tried regular expressions, but don't know how to make this happen on only every eighth comma. I'd post my code, but none of it works. Thanks for the help. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python and Tkinter Programming--Expensive!
On Aug 17, 12:59 pm, W. Watson [EMAIL PROTECTED] wrote: Why is the book in Subject (author is Grayson) so expensive? $100 on Amazon and $195 on ABE. Aren't there alternatives? -- Wayne Watson (Nevada City, CA) Web Page: speckledwithStars.net Probably because it is out of print, and thus, hard-to-find. I got my copy last year and it definitely didn't cost that much then. Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: help on object programing
On 2007-08-17, yadin [EMAIL PROTECTED] wrote: class big(self): x = 32 list = [] def inside (self): class small(self): # a new class defined inside the first y = 348 list.append(y) # send the value to first list list.append(x) print list how can i define my variables so that there are valid outside the class??? Be sure to read and try the code in the sections of the Python tutorial that discuss classes and the objects they create. In my opinion the classes section of the official tutorial is unfortunately the least tutorial part of the tutorial. But it won't steer you wrong. -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list
Re: question
[EMAIL PROTECTED] wrote: I've parsed a webpage into a text file. In doing so, I've kept all the text I'm interested in, and removed all the text I don't want. My result is a text file that is comma-separated. However, the text file is one, very long, single string. I need to substitute every eighth (8th) comma with a new line (\n). I've tried regular expressions, but don't know how to make this happen on only every eighth comma. I'd post my code, but none of it works. Thanks for the help. text = aaa, * 20 from itertools import cycle, groupby print \n.join(,.join(g) for k, g in groupby(text.split(,), ... key=lambda key, c=cycle([True]*8+[False]*8): c.next())) aaa,aaa,aaa,aaa,aaa,aaa,aaa,aaa aaa,aaa,aaa,aaa,aaa,aaa,aaa,aaa aaa,aaa,aaa,aaa, :-) Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Making a copy (not reference) of a file handle, or starting stdin over at line 0
Shawn Milochik wrote: How can I check a line (or two) from my input file (or stdin stream) and still be able to process all the records with my function? One way: from itertools import chain firstline = instream.next() head = [firstline] # loop over entire file for line in chain(head, instream): process(line) You can of course read more than one line as long as you append it to the head list. Here's an alternative: from itertools import tee a, b = tee(instream) for line in a: # determine file format, # break when done # this is crucial for memory efficiency # but may have no effect in implementations # other than CPython del a # loop over entire file for line in b: # process line Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: question
You need to post some kind of code (even non-working) to show that you've actually done some work. Nobody will do your work for you. -- http://mail.python.org/mailman/listinfo/python-list
Re: Naming dictionaries recursively
On Aug 17, 3:43 pm, TYR [EMAIL PROTECTED] wrote: So the tougher problem seems to be parsing those lines. That is not a valid Python dictionary unless the names `Bob`, `Humboldt`, `red`, and `predatory` are not already defined. So you can't just ``eval`` it. In what way? {'key': val}, right? Anyway, I can always change the format they go into the file in. If you control the file format then you could create a valid python list of dictionaries as the intermediate file format. Something like: data = [ {'name' : 'Bob', 'species' : 'Humboldt', 'colour' : 'red', 'habits' : 'predatory'}, { ... }, ... } You can then name the file with a .py ending and import it as a list of dictionaries that you can then process to form a dict of dicts: datadict = dict( (data2name(d), d) for d in modulename.data ) - Paddy. -- http://mail.python.org/mailman/listinfo/python-list
Re: Can python threads take advantage of use dual core ?
nikhilketkar wrote: What are the implications of the Global Interpreter Lock in Python ? Please have a look at the archives. This topic is brought up anew every few weeks. Does this mean that Python threads cannot exploit a dual core processor and the only advantage of using threads is in that computation and IO-bound operations can continue in parallel ? Not generally, no. Regards, Björn -- BOFH excuse #93: Feature not yet implemented -- http://mail.python.org/mailman/listinfo/python-list
Encryption and hashing
Since that I'm working to let encrypt/hash data in the data base of my projects I have been looking for libraries and/or wrappers. So I want give my feedback about it. In the first I found PyCrypto [1] but I see any problems: * I think that isn't been maintained because the last modification of its web was on 30 Sep 2006 * Since that has not been uploaded to SourceForge [2] we cann't know when was released the last version * There algorithms more secure and modern that it hasn't. Then, I found 2 great C libraries that are being maintained and updated with many algorithms. They're MCrypt [3] and MHash [4], and both have released the last version on this year. For who knows any of criptography I comment that you can use algorithms as secure as Rijndael, Twofish, or Serpent with the CFB cipher mode. And for hash you can use RIPEMD, SHA-2 or WHIRLPOOL. And the best is that there are wrappers for Python [5] [6]. For if anybody is interested on playing with them: In the first you need the headers. In Debian/Ubuntu: $ sudo apt-cache install libmcrypt-dev libmhash-dev $ wget http://labix.org/download/python-mcrypt/python-mcrypt-1.1.tar.gz $ wget http://labix.org/download/python-mhash/python-mhash-1.4.tar.gz $ tar xzf python-mcrypt*.tar.gz; tar xzf python-mhash*.tar.gz $ cd python-mhash*; sudo python setup.py install; cd .. $ cd python-mcrypt*; sudo python setup.py install; cd.. [1] http://www.amk.ca/python/code/crypto [2] http://sourceforge.net/projects/pycrypto [3] http://mcrypt.sourceforge.net/ [4] http://mhash.sourceforge.net/ [5] http://labix.org/python-mcrypt [6] http://labix.org/python-mhash -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with directory recursion!
I figured it out. I was doing a recursive function call when I didn't have to. The walk() method already walks into every possible sub-directory for you! On 8/17/07, Robert Dailey [EMAIL PROTECTED] wrote: Here's part of the output that's incorrect: models\W_BoomerEdge BYOS_C.entity.xml BYOS_C_Collision.entity.xml Notice that the file BYOS_C.entity.xml is showing up as a file in the directory W_BoomerEdge. This file does not exist in this folder, but yet in a different folder. The output is consistent with the 'print' statements you will see in the function I posted earlier. On 8/17/07, Robert Dailey [EMAIL PROTECTED] wrote: Hi, I've created a function that is used to recurse a directory tree in Windows XP using os.walk(). For the most part it works, however in some instances the data is incorrect and I'm getting invalid sub-directory paths. Here's the function: def __doSearch( root_dir, sub_path, restype, ext ): print sub_path # Searches the specified directory and generates a # list of files to preload. complete_path = osp.normpath( osp.join( root_dir, sub_path ) ) for root, dirs, files in os.walk( complete_path ): # Record the list of file hash ID's for file in files: split = __resType( file ) if split[1] == restype: #print sub_path print \t, file __appendResource( ext, sub_path, split[0] ) # Remove .svn subdirectories; we don't walk these. if .svn in dirs: dirs.remove( .svn ) # Recurse child directories for dir in dirs: __doSearch( root_dir, osp.join( sub_path, dir ), restype, ext ) Does anyone see anything immediately suspicious about the code? I'm assuming that in Python, every time a function is called recursively it gets its own copy of local variables. For some reason the sub_path variable isn't consistent depending on where I use it. For example, if you notice the print call at the very start of the function, it will output something like models/ships. However, after passing it into __appendResource(), it appears to be just models. -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with directory recursion!
Does anyone see anything immediately suspicious about the code? Yes. os.walk does the recursion for you. Either you should use os.listdir instead of os.walk, or use os.walk ONCE and iterate over the results. I prefer to use the former because usually I do not remember how os.walk works. Read and try the example that is given in the docs: http://docs.python.org/lib/os-file-dir.html Best, Laszlo -- http://mail.python.org/mailman/listinfo/python-list
Re: Encryption and hashing
For who knows any of criptography I comment that you can use algorithms as secure as Rijndael, Twofish, or Serpent with the CFB cipher mode. And for hash you can use RIPEMD, SHA-2 or WHIRLPOOL. As I recall, PyCrypto can also use these, and many others. And it can also do RSA. And the best is that there are wrappers for Python [5] [6]. One advantage of PyCrypto is that it works on many platforms. If standard C extensions are not available, it will fall back to a pure python implementation. Well yes, sometimes it is slow. But it is also much easier to use than pyOpenSSL, for example. (BTW you forgot to mention some other popular ones, like pyOpenSSL, mcrypto2 etc.) Laszlo -- http://mail.python.org/mailman/listinfo/python-list
Re: Downloading multiple csv files from a website
Mike, Thanks for the pointers. I looked through the ASPN cookbook, but found a more reliable (and easier to implement) way to get the files I want. I downloaded GNU Wget from http://users.ugent.be/~bpuype/wget/( the current version is 1.10.2), and then ran it from Python as follows import os rc = os.system('wget --debug --output-document=c:\\downloads\ \russell1000index_cyr.csv --output-file=log.txt http://www.russell.com/common/indexes/csvs/russell1000index_cyr.csv') rc is the return code, and is 0 if the download succeeds. I also tried the subprocess module import subprocess f = subprocess.Popen('wget --debug --output-document=c:\\downloads\ \russell1000index_cyr.csv --output-file=log.txt http://www.russell.com/common/indexes/csvs/russell1000index_cyr.csv') This, too, works just fine. Wget does a lot more error-checking than the recipe in the Python cookbook, does FTP as well as http, and supports OpenSSL - its essentially a one-stop solution. In addition, I can write batch files that do all the downloads without any need for Python to be installed on the machine. Thanks again Thomas Philips -- http://mail.python.org/mailman/listinfo/python-list
Re: best GUI library for vector drawing program
chewie54 wrote: I looked at your application, Veusz (it looks very nice), and I see you have binary distrubitions for each os. Is is difficult to build these binaries for each system. Could you tell me how that is done? I use pyinstaller to make the binaries (see the veusz_pyinst.spec file), and NSIS to make a Windows installer from the Windows binary (see veusz.nsi). The Linux binary, unfortunately, isn't 100% compatible, as I've found trying to run on 64 bit systems. I assume it's some sort of glibc mismatch. Making the linux binaries on an old distribution helps the compatibility (I use centos 3 in a virtual environment). jeremy -- Jeremy Sanders http://www.jeremysanders.net/ -- http://mail.python.org/mailman/listinfo/python-list
Re: why psyco using more memery in liunx?
kyo guan wrote: Hi all: When you import psyco in python2.5, you can see the memery grow up near 40MB in linux. but the same version python and psyco, is only grow up 1MB under windows. I have a hunch it's because of how the OS's are reporting shared memory usage. IE, the 1 MB increase under windows may not be altogether truthful, and neither is the reported 40 MB on linux. Memory usage is tricky to judge on any modern OS, as shared libraries do increase the apparent memory use by an application, but the libraries are shared with other applications and OS components. kyo -- http://mail.python.org/mailman/listinfo/python-list
Re: how to convert a c program to java program
I heard I need to port C program to JPython first and compile it to native JAVA. I don't know anything about JPython. Is there a tool to do the porting? If not, what is the quickest way to learn JPython? I'm assuming that you are refering to Jython. You probably want to start by learning Python, since Jython is essentially just an implementation of Python written in Java. I'm not sure why you need to involve Jython at all though. Syntax wise there are many more similarities between C and Java than there are between C and Python or Python and Java. Anyway, if you want to learn Python try one of these: http://python.org/doc/tut/ or http://www.diveintopython.org/. Matt -- http://mail.python.org/mailman/listinfo/python-list
Re: help on object programing
how can i define my variables so that there are valid outside the class??? Not to be obnoxious, but your sample code has a number of fairly big conceptual issues (like subclassing self and assigning 32 at the big class level and printing 'list' which is a built-in type). Been there myself - it took me a while to understand class vs. instance variables. You are also using fairly advanced techniques such as embedded classes which look above a newbie level. I took the liberty to comment and fix up your code a bit so that it runs: #classes either inherit or not and signify that in parenthesis. inheriting 'self' makes no sense #for a class declaration. but it does make perfect sense to have 'self' as a param to a class method (def) class big: #class-level variable x = 32 #changed to mylist to avoid confusion with list built-in. mylist = [] #this is a normal instance method - 'self' refers to the class instance you just created. def inside (self): #is this really what you wanted? an embedded class - syntaxically correct, but not used often class small: # a new class defined inside the first y = 348 #ok, now I am referring to the mylist variable associated (bound in python-speak) to the big class. #y is defined here so no need to do anything big.mylist.append(y) # send the value to first list #same with big.x big.mylist.append(big.x) #instantiate the class, because you are calling an instance method (i.e. you need to have created an instance to use that method) #call the call mybig = big().inside() #refer to the mylist variable declared at the class, not instance level. #class level means any other calls you make will alter that variable print 'my class level mylist variable:',big.mylist console output: my class level mylist variable: [348, 32] Can you perhaps rephrase your requirements to indicate what you want to achieve? Strictly speaking, it looks like you could do this: class Big: def getlist(self): return [348,32] mylist =Big().getlist() That's probably not what you were asking for, but it does express the results you would get out of your code, especially as you are not passing in any significant parameters to the 'inside' function. OK, perhaps a bit more useful. #no inheritance - could also be class Big(object) where object is the python root class class Big: #initialize the class level to be empty myclasslist = [] def __init__(self): #initialize the instance level variable to be empty self.myinstancelist = [] def appendAndGet(self,x,y): #modify the instance's personal list self.myinstancelist.append(x) self.myinstancelist.append(y) #will now modify shared class-level variable. Big.myclasslist.append(x) Big.myclasslist.append(y) return self.myinstancelist print Big.myclasslist without any instances around:, Big.myclasslist bigA = Big() result = bigA.appendAndGet(348,32) print result #1:, result print Big.myclasslist:, Big.myclasslist bigB = Big() result = bigB.appendAndGet(11,22) print result #2:, result #and the instance also still has its myinstancelist around print same as result #2:, bigB.myinstancelist print Big.myclasslist:, Big.myclasslist console output: D:\user\workspace\vg\tmptestingtestc.py my class level mylist variable: [348, 32] Big.myclasslist without any instances around: [] result #1: [348, 32] Big.myclasslist: [348, 32] result #2: [11, 22] same as result #2: [11, 22] Big.myclasslist: [348, 32, 11, 22] Try perhaps Dive Into Python's class intro: www.diveintopython.org/object_oriented_framework/defining_classes.html Cheers -- http://mail.python.org/mailman/listinfo/python-list
round-trip from egg to code and back to egg
I'd like to use Scriptaculous with TurboGears on Python 2.5. Unfortunately, Scriptaculous is currently in the Cheese Shop only as a Python 2.4 egg. If I had the setup.py that was used to generate the egg, I think it would be really easy to generate a new Python 2.5 egg from the existing 2.4 egg. In fact, it would be gruntwork we could easily offload from the package authors. The trouble is, an egg doesn't include setup.py. Is there any direct way to round-trip a Python package from egg to installed code and into a new egg? I might be able to mine enough information from the files in EGG-INFO to reconstruct setup.py - reverse-engineering - but that seems unnervingly like work. Three possibilities come to mind - 1. I'm missing something simple 2. setuptools could be modified to include the original setup.py with the egg 3. a script could mine EGG-INFO to regenerate setup.py - maybe such a script has already been written? Can somebody who understands eggs better comment? Thanks very much! - Catherine http://catherinedevlin.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Array and floating point
Hello, I'm experiencing a problem where the float being appended to the array is not the same as the result of the appending. from array import * x = array('f') x.append(float(0.1)) x[0] 0.1000149011612 float(0.1) 0.10001 I'm expecting x[0] = 0.10001 Thanks Jonathan Shan -- http://mail.python.org/mailman/listinfo/python-list
Re: wxpython log redirect
On Aug 16, 2:29 pm, [EMAIL PROTECTED] wrote: Hello, Why this wx example don't return \nHELLO WORLD and other text in same window: import wx import logging import sys def nekaj(): print \nHELLO WORLD class WxLog(logging.Handler): def __init__(self, ctrl): logging.Handler.__init__(self) self.ctrl = ctrl def emit(self, record): self.ctrl.AppendText(self.format(record)+\n) class MainFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, title=logging test) sizer = wx.BoxSizer(wx.VERTICAL) log = wx.TextCtrl(self, style=wx.TE_MULTILINE) rootLogger = logging.getLogger('') rootLogger.setLevel(logging.DEBUG) hdlr = WxLog(log) hdlr.setFormatter(logging.Formatter('%(levelname)s | %(name)s | %(message)s [@ %(asctime)s in %(filename)s:%(lineno)d]')) rootLogger.addHandler(hdlr) rootLogger.debug(str(sys.stdout)) nekaj() # goes to the function nekaj if __name__ ==__main__: app = wx.App(0) frame = MainFrame() frame.Show() app.MainLoop() Regards, Vedran Why are you using the logging module? All you need to do is redirect stdout. See below: Give this a try: code class XPinst(wx.App): def __init__(self, redirect=False, filename=None): wx.App.__init__(self, redirect, filename) def OnInit(self): self.frame = wx.Frame(None, -1, title='Redirect Test', size=(620,450), style=wx.STAY_ON_TOP| wx.DEFAULT_FRAME_STYLE) panel = wx.Panel(self.frame, -1) self.log = wx.TextCtrl(panel, -1, size=(500,400), style = wx.TE_MULTILINE|wx.TE_READONLY| wx.HSCROLL) redir=RedirectText(self.log) sys.stdout=redir print 'test' self.frame.Show() return True class RedirectText: def __init__(self,aWxTextCtrl): self.out=aWxTextCtrl def write(self,string): self.out.WriteText(string) /code If you use wx.App, you can also just set the redirect parameter to True as well. Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: Array and floating point
On Aug 17, 2:06 pm, Jonathan Shan [EMAIL PROTECTED] wrote: Hello, I'm experiencing a problem where the float being appended to the array is not the same as the result of the appending. from array import * x = array('f') x.append(float(0.1)) x[0] 0.1000149011612 float(0.1) 0.10001 I'm expecting x[0] = 0.10001 Thanks Jonathan Shan Floating point precision problems on x86 type machines is well documented on the web if you want to know more about it. For your example use Python's decimal class instead of floating point. Gmpy is also available for scientific type apps, http://docs.python.org/lib/module-decimal.html http://pydoc.org/2.4.1/decimal.html http://gmpy.sourceforge.net/ import decimal x = decimal.Decimal( 0.1 ) print x y = decimal.Decimal( 0.10001 ) print y print y/x print y*x -- http://mail.python.org/mailman/listinfo/python-list
Re: Array and floating point
Jonathan Shan wrote: Hello, I'm experiencing a problem where the float being appended to the array is not the same as the result of the appending. from array import * x = array('f') x.append(float(0.1)) x[0] 0.1000149011612 float(0.1) 0.10001 I'm expecting x[0] = 0.10001 array(f) is an array of C floats while Python's float type is a double in C terms. That's why you lose some precision. Try array(d) instead: from array import array x = array(d) x.append(0.1) x[0] 0.10001 Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Array and floating point
Jonathan Shan wrote: Hello, I'm experiencing a problem where the float being appended to the array is not the same as the result of the appending. from array import * x = array('f') x.append(float(0.1)) x[0] 0.1000149011612 float(0.1) 0.10001 I'm expecting x[0] = 0.10001 'f' denotes a single-precision floating point number. Python's float objects are double-precision floating point numbers. Use 'd' instead. -- Robert Kern I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth. -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: sub-classing the types in the builtin module datetime
[EMAIL PROTECTED] wrote: [My question snipped] This problem arises when you change the function signature of __new__. I'm a little unclear as to why but it seems for the classmethods (thosed marked with the METH_CLASS flag in the C source code), you need to arrange to bypass the normal method resolution (I used a metaclass to do this): import datetime class Date(datetime.datetime): pass class FixClassMethods(type): def __init__(cls, classname, bases, classdict): # add strptime if using Python 2.5 flagged_as_meth_class = ('today', 'now', 'fromtimestamp', 'fromordinal', 'now', 'utcnow', 'utcfromtimestamp', 'combine') for meth in flagged_as_meth_class: setattr(cls, meth, getattr(datetime.datetime, meth)) class DateChangesNewSignature(datetime.datetime): @staticmethod def str2ymd(strval): , mm, dd = (int(substr) for substr in (strval[:4], strval[4:6], strval[6:])) return , mm, dd def __new__(cls, strval): , mm, dd = DateChangesNewSignature.str2ymd(strval) return super(DateChangesNewSignature,cls).__new__(cls, , mm, dd) def __init__(self, strval): , mm, dd = DateChangesNewSignature.str2ymd(strval) super(DateChangesNewSignature, self).__init__(, mm, dd) class DLast(DateChangesNewSignature): __metaclass__ = FixClassMethods f = Date(2007,07,07) print f print f.today() f2 = DateChangesNewSignature(20070707) print f2 try: print f2.today() except TypeError, e: print str(e) print Uh? f3 = DLast(20070707) print f3 print f3.today() I get: 2007-07-07 00:00:00 2007-08-16 12:57:41.480679 2007-07-07 00:00:00 __new__() takes exactly 2 arguments (9 given) Uh? 2007-07-07 00:00:00 2007-08-16 12:57:41.483104 -- Hope this helps, Steven Steven, Thanks, you provide an elegant solution to the datetime problem I raised. I like the illustration of metaclass usage you have have given, it's something I have had trouble grasping. You handle the examples I gave. However, on reflection,I feel that ('today', 'now', 'fromtimestamp', 'fromordinal', 'now', 'utcnow', 'utcfromtimestamp', 'combine') are completely inappropriate as methods and that they should have been set up as functions of datetime and not as methods of datetime.datetime. The difficulty I have in adopting your approach is that it would be difficult for the reader to comprehend the code. My feeling is that it should be possible to change a signature using simple Python approaches. I'll puzzle some more. Thanks again. Colin W. -- http://mail.python.org/mailman/listinfo/python-list
Re: Can python threads take advantage of use dual core ?
On Aug 17, 6:00 pm, nikhilketkar [EMAIL PROTECTED] wrote: What are the implications of the Global Interpreter Lock in Python ? This is asked every second week or so. The GIL is similar to the Big Kernel Lock (BKL) use to support SMPs in older versions of the Linux kernel. The GIL prevents the Python interpreter to be active in more than one thread at a time. If you have a single CPU with a single core, the GIL has no consequence what so ever. If you have multiple CPUs and/or multiple cores, the GIL has the consequence that you can forget about SMP scalability using Python threads. SMP scalability require more fine grained object locking, which is what the Java and .NET runtimes do, as well as current versions of the Linux kernel. Note that IronPython and Jython use fine grained locking instead of a GIL. Does this mean that Python threads cannot exploit a dual core processor and the only advantage of using threads is in that computation and IO-bound operations can continue in parallel ? The Python standard library releases the GIL in read/write operations for e.g. files and sockets. This can be combined with threads to allow multiple IO operations to continue in parallel. The GIL has no or very little significance for IO-bound scalability in Python. CPU-bound tasks are a different game. This is where the GIL matter. You must either release the GIL or use multiple processes for exploiting multiple processors in an SMP computer with Python. The GIL can be released explicitely in C extension code. f2py and ctypes can also release the GIL. Note that you would NOT use threads for speeding up CPU-bound operations, even when programming in C or Fortran. Threads are neither the only nor the preferred way to exploit multicore CPUs for CPU-bound tasks. Instead of threads, use either an MPI library or OpenMP compiler pragmas. You can use MPI directly from Python (e.g. mpi4py), or you can use OpenMP pragmas in C or Fortran code which you call using ctypes or f2py. Summary: Use Python threads if you need to run IO operations in parallel. Do not use Python threads if you need to run computations in parallel. Regards, Sturla Molden -- http://mail.python.org/mailman/listinfo/python-list
Re: Can python threads take advantage of use dual core ?
On Aug 17, 6:00 pm, nikhilketkar [EMAIL PROTECTED] wrote: What are the implications of the Global Interpreter Lock in Python ? This is asked every second week or so. The GIL is similar to the Big Kernel Lock (BKL) use to support SMPs in older versions of the Linux kernel. The GIL prevents the Python interpreter to be active in more than one thread at a time. If you have a single CPU with a single core, the GIL has no consequence what so ever. If you have multiple CPUs and/or multiple cores, the GIL has the consequence that you can forget about SMP scalability using Python threads. SMP scalability require more fine grained object locking, which is what the Java and .NET runtimes do, as well as current versions of the Linux kernel. Note that IronPython and Jython use fine grained locking instead of a GIL. Does this mean that Python threads cannot exploit a dual core processor and the only advantage of using threads is in that computation and IO-bound operations can continue in parallel ? The Python standard library releases the GIL in read/write operations for e.g. files and sockets. This can be combined with threads to allow multiple IO operations to continue in parallel. The GIL has no or very little significance for IO-bound scalability in Python. CPU-bound tasks are a different game. This is where the GIL matter. You must either release the GIL or use multiple processes for exploiting multiple processors in an SMP computer with Python. The GIL can be released explicitely in C extension code. f2py and ctypes can also release the GIL. Note that you would NOT use threads for speeding up CPU-bound operations, even when programming in C or Fortran. Threads are neither the only nor the preferred way to exploit multicore CPUs for CPU-bound tasks. Instead of threads, use either an MPI library or OpenMP compiler pragmas. You can use MPI directly from Python (e.g. mpi4py), or you can use OpenMP pragmas in C or Fortran code which you call using ctypes or f2py. Summary: Use Python threads if you need to run IO operations in parallel. Do not use Python threads if you need to run computations in parallel. Regards, Sturla Molden -- http://mail.python.org/mailman/listinfo/python-list
Re: Encryption and hashing
Kless [EMAIL PROTECTED] writes: For who knows any of criptography I comment that you can use algorithms as secure as Rijndael, Twofish, or Serpent with the CFB cipher mode. And for hash you can use RIPEMD, SHA-2 or WHIRLPOOL. PyCrypto does includes the AES version of Rijndael as Crypto.Cipher.AES and the 256-bit version of SHA-2 as Crypto.Hash.SHA256. -Marshall -- http://mail.python.org/mailman/listinfo/python-list
Re: Python and Tkinter Programming--Expensive!
W. Watson wrote: Why is the book in Subject (author is Grayson) so expensive? $100 on Amazon and $195 on ABE. Aren't there alternatives? Read the fine print. Its available as an ebook for about $25.00 at Manning. You can print out just the parts you need--or read it from your iphone. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ -- http://mail.python.org/mailman/listinfo/python-list
Problems with threading in embedded Python
Hi all, I hope this hasn't been brought up before, but if it did i missed it, so bear with me please :) anyway, i'm trying to embed Python into a C program. A sample python syript i want to run is as follows: ---SNIP--- import time import threading go_on = 1 t = 0 def ProcessMessage(): print ... ProcessMessage def Main(): global go_on print ... Main while go_on: ProcessMessage () print ... ... , time.sleep (0.2) def Setup(): global t print ... Setup t = threading.Thread (None, Main) t.start () # t.join (0) # print t.isAlive() def Shutdown(): global go_on, t go_on = 0 t.join () print ... Shutdown ---SNIP--- I call Setup from C, which should create a new thread which should enter the loop in Main. well, it doesn't :) It prints ... Setup and does nothing. when i call Shutdown from C, it prints ... Main , followed by ... Shutdown, and exits... So it seems to me the python interpreter wants to run the seperate thread, but doesn't get time from the scheduler (is that the thing about 100 opcodes?) How can i handle this problem? Do I need to wrap all the Py_Stuff() into its own thread? do i need artificial python code that only serves the purpose of piling up enough opcodes so that the Main() thread gets eventually called? I hope you can help me, if you need more code (f.ex. the C-code ), i will post more :) (basically I modified the run_func.cc file from the docs, added PyEval_InitThreads() and monkeyed around with GIL and Acquire/ReleaseLock, but so far i had no luck :) Cheers, Nico -- http://mail.python.org/mailman/listinfo/python-list
wxPython in C++ app using wxWidgets
I have an application written in C++ that uses wxWidgets for GUI. I use embedded Python for scripting inside of this application. I want to use wxPython to add GUI to my scripts - because my C++ App uses wxWidgets I thought it to be easy. The problem is that wxPython knows nothing about wxApp/wxFrame objects created in my C++ application, and insists (by giving me asserts) that I create another wxApp object for wxPython inside my scripts. Obviously, this is not what I want. I want the scripts to use the same wxApp/wxFrame object that my C++ application already created. More specifically, I want to create dialogs in wxPython that will have my application wxFrame as parent. I'm stuck. Any help appreciated. Thanks, M. -- http://mail.python.org/mailman/listinfo/python-list