Spyce 2.0 beta
The beta of Spyce 2.0 is available at http://spyce.sourceforge.net/docs/get.html. Spyce is a python web application server, combining the features of popular frameworks such as JSP and ASP.NET with Pythonic elegance. Spyce may be deployed as a standalone server (or proxied behind Apache), or under mod_python, FastCGI, or CGI. Documentation and demos are at http://spyce.sourceforge.net/. Highlights of Spyce 2.0 include: Active Handlers - reusable components without the leaky abstractions seen in ASP.NET et al. - http://spyce.sourceforge.net/docs/doc-lang_handlers.html Active Tag compiler - http://spyce.sourceforge.net/docs/doc-tag_new2.html OpenACS-like (Tiles-ish, for you JSP people) parent/child templating system - roughly the same speed as include.spyce, so using one parent template has about 1/2 the overhead as the old standard two-includes-for-header-and-footer. - http://spyce.sourceforge.net/docs/doc-tag_core.html#parent Full changelog at http://svn-hosting.com/svn/spyce/trunk/spyce/CHANGES. -Jonathan -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Re: OOPS concept
Hi all, Well this doesnt explain new style classes. let me be more clear. is there any online tutorial/ recommended book which deals explicitly with object oriented programming in python? regards, KM --- Try this online book, it may help, the url is: http://www.byteofpython.info Hi all, Is there any good step by step online tutorial on OOPS concepts in python ? i have checked some on the python.org.__doc__ page but couldnt make much sense. especially i need help on newstyle classes. regards, KM -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: If you use PayPal you might consider an alternative
Allan [EMAIL PROTECTED] wrote: If you used PayPal and are not satisifed with their service there is a new and better service opening. They will be starting up during the early summer this year. The best of all - signup is FREE. Check out their benefits: www.greenzap.com/benefits That web zite iz juzt too cutezy. I could never truzt it, even if I hadn't learned about it through a newzgroup zpam. -- - Tim Roberts, [EMAIL PROTECTED] Providenza Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: OOPS concept
Google, search. km [EMAIL PROTECTED] ??? news:[EMAIL PROTECTED] ???... Hi all, Well this doesnt explain new style classes. let me be more clear. is there any online tutorial/ recommended book which deals explicitly with object oriented programming in python? regards, KM -- - Try this online book, it may help, the url is: http://www.byteofpython.info Hi all, Is there any good step by step online tutorial on OOPS concepts in python ? i have checked some on the python.org.__doc__ page but couldnt make much sense. especially i need help on newstyle classes. regards, KM -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
[wxPython] own maximize for wxMDIChildFrame - bugs?
I use code below: 1) frame receive too many maximize events on create and on close child window - why? 2) how to catch key events for wxMDIParentFrame ? 3) childWin.SetSize() in OnMaximize send additional maximize event (?) 4) wxMDIChildFrame is initially visible! 5) sorry for english :) 6) wxPython 2.5.4.1 (Windows) import wx #-- class MyParentFrame(wx.MDIParentFrame): def __init__(self): wx.MDIParentFrame.__init__(self, None, -1, MDI Parent, size=(600,400), style=wx.DEFAULT_FRAME_STYLE|wx.FRAME_NO_WINDOW_MENU) self.winCount = 0 self.CreateStatusBar() self.MainTb=self.CreateToolBar(wx.TB_HORIZONTAL|wx.NO_BORDER|wx.TB_FLAT) biblioBut=wx.Button(self.MainTb,1231,label=Biblio) newWndBut=wx.Button(self.MainTb,1213,label=NewWnd) wx.EVT_BUTTON(self,newWndBut.GetId(), self.OnNewWindow) self.MainTb.AddControl(biblioBut) self.MainTb.AddSeparator() self.MainTb.AddControl(newWndBut) self.MainTb.Realize() self.SetToolBar(self.MainTb) self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDownParent) def OnKeyDownParent(self, event): print OnKeyDownParent def OnKeyDownChild(self, event): print OnKeyDownChild def OnClose(self, evt): self.GetActiveChild().Close(True) def OnMaximize(self, event): childWin = event.GetEventObject() win = childWin.GetParent() print maximize +self.GetTitle() childWin.SetSize(wx.Size(win.GetClientSize().GetWidth(),win.GetClientSize().GetHeight()-1)) childWin.SetPosition(wx.Point(0,-1*win.GetClientAreaOrigin().y+1)) event.Skip() def OnNewWindow(self,event): self.winCount = self.winCount + 1 win = wx.MDIChildFrame(self, -1, Child Window: %d % self.winCount) win.Maximize() #win.Show() # !! MainTb=win.CreateToolBar(wx.TB_HORIZONTAL|wx.NO_BORDER|wx.TB_FLAT) SBut=wx.Button(MainTb,1213,label=Func) MainTb.AddControl(SBut) MainTb.Realize() win.SetToolBar(MainTb) win.Bind(wx.EVT_MAXIMIZE, self.OnMaximize) win.Bind(wx.EVT_KEY_DOWN, self.OnKeyDownChild) win.Show(True) #-- if __name__ == '__main__': class MyApp(wx.App): def OnInit(self): wx.InitAllImageHandlers() frame = MyParentFrame() frame.Show(True) self.SetTopWindow(frame) return True app = MyApp(False) app.MainLoop() -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for Example of wxFontEnumerator Use
weston [EMAIL PROTECTED] schrieb im Newsbeitrag news:[EMAIL PROTECTED] | Can anyone give an example of proper usage of wxFontEnumerator? In the wxPython Demo: wxPython Overview Miscellaneous FontEnumerator If you haven't downloaded the demo/docs yet, you should. You can get your version from http://wxpython.org/download.php. Regards, -- Vincent Wehren | | Thanks, | | Weston | -- http://mail.python.org/mailman/listinfo/python-list
Re: Determine ip address
http://checkip.tk/ codecraig ha scritto: hi, how can i use python to figure the ip address of the machine which the python script is running on? I dont mean like 127.0.0.1but i want the external IP address (such as ipconfig on windows displays). any ideas?? THanks -- http://mail.python.org/mailman/listinfo/python-list
Adding new methods to new-style classes dynamically
Good day to all. Some time ago I'd been playing with a framework which uses dynamic class creation havily. Say, I could do: class A: pass # I method name is dynamic meth_name = 'foo' #method code can also be dynamic - any executable object will be good enough func = lambda self: self.__class__.__name__ A.__dict__[meth_name] = func a = A() print a.foo() A # methods could be added/changed at runtime, without re-instantination A.__dict__[meth_name] = lambda self: type(self) print a.foo() type 'instance' #well, try this with the new-style class class A(object): pass # the new-style __dict__ is a dictproxy object A.__dict__[meth_name] = lambda self: type(self) Traceback (most recent call last): File interactive input, line 1, in ? TypeError: object does not support item assignment Of course, I can do A.foo = some_executable_object But that does help when a dynamic method name is needed. Another option is: exec('A.%s = %s'%('foo', 'some_executable_option')) But I don't like eval'ling things :) Is there other way to add/change methods to new-style classes dynamically? -- http://mail.python.org/mailman/listinfo/python-list
Re: properties vs. eval()
Why are you using eval in the first place? This isn't bash. Use setattr and getattr for dynamic attribute access. -- http://mail.python.org/mailman/listinfo/python-list
Re: Adding new methods to new-style classes dynamically
Do you mean setattr? setattr(A, meth_name, lambda self: type(self)) Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: Adding new methods to new-style classes dynamically
Max Derkachev wrote: [snip] #well, try this with the new-style class class A(object): pass # the new-style __dict__ is a dictproxy object A.__dict__[meth_name] = lambda self: type(self) Traceback (most recent call last): File interactive input, line 1, in ? TypeError: object does not support item assignment Of course, I can do A.foo = some_executable_object But that does help when a dynamic method name is needed. Another option is: exec('A.%s = %s'%('foo', 'some_executable_option')) But I don't like eval'ling things :) Is there other way to add/change methods to new-style classes dynamically? Ever considered setattr()? Not only does it appear to do the job but also it avoids those __make__your__eyes__bleed__ double underscores. class A(object): ...pass ... A.__dict__['foo'] = 123 Traceback (most recent call last): File stdin, line 1, in ? TypeError: object does not support item assignment setattr(A, 'foo', 123) A.foo 123 def bar(self): ...print 'bar bar blog ship' ... setattr(A, 'bar', bar) eh = A() eh.bar() bar bar blog ship HTH, John -- http://mail.python.org/mailman/listinfo/python-list
Sockets
I have a problem and I don't quite know how to implement the solution. I'll have a server application that will listen on a tcp port and make many similtaneous connections to remote clients. From time to time, I'll need to write a small amount of data on one of those sockets. A notification to write to one of the sockets will come from another program/process. I think that the best way to send the notification to this server application is via a udp message. Alternatively, I could use tcp, but I don't think I'll need the extra complexity for what I want to do. (Other suggestions welcome.) The server application will multiplex the connections using 'select', so much of the time it will be blocked on 'select'. My problem is how to also listen on a udp port while the process is blocked by 'select'. Should I run a separate thread? And if so can I share the socket connection across the two threads? (Thread 1 will be accepting client connections, thread 2 will we writing data to it.) Or should I simply let 'select' time out after some period? I'm a bit lost as to how to do this, I hope someone can put me on the right track. Any solution that I use should be applicable on Linux and Windows platforms. Thanks Dan -- http://mail.python.org/mailman/listinfo/python-list
Strange behaviour of __cmp__
See the following... class X(list): def __cmp__(self,anX): print comparing from,id(self) return cmp(self.v,anX.v) x1=X() x2=X() x1.v=-1 x2.v=100 x1x2 False x1x2 False I expected x1x2 or x1x2 were False and True respectively. -- http://mail.python.org/mailman/listinfo/python-list
Re: UnicodeDecodeError
Thomas Thomas wrote: filename=unicode(filename); #file = ('file', filename, data) #This won't work will give a UnicodeDecodeError: 'ascii' codec can't decode byte 0xc7 in position 10: ordinal not in range(128) there's no way the tuple creation will generate a UnicodeDecodeError all by itself. are you sure the error occurs on that line? are you running this with a stock interpreter, or are you using some fancy IDE thing? what does filename really contain? (there's no 0xc7 character in the filepath in your example). try adding print repr(filepath) before the os.path.split call, and let us know what it prints. /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Determine ip address
[Format recovered from top-posting.] [EMAIL PROTECTED] writes: codecraig ha scritto: how can i use python to figure the ip address of the machine which the python script is running on? I dont mean like 127.0.0.1but i want the external IP address (such as ipconfig on windows displays). http://checkip.tk/ That won't work if you're on a NAT'ed network - it will instead return the external address of the NAT gateway. ipconfig displays the ip address(es) of the interfaces on the current machine. You need to use the socket.socket.getsockname method: py import socket py s = socket.socket() py s.connect((google.com, 80)) py s.getsockname() ('192.168.1.1', 57581) py The local ethernet card is 192.168.1.1, the local port for the socket is 57581. Note that the presence of multiple interface cards makes the question ambiguous. mike -- Mike Meyer [EMAIL PROTECTED] http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
using variables with modules
Hi, I am trying to move away from Windows only scripting to Python. I've written a quick script that will pull the product version from the client registry. I can get the IP addresses from a file into a list and then pull each element in the list using the for loop. I am setting each element to a varuable ClientIP. When I try to use that variable in _winreg values it is not substituting the element from the list. If I type the list value straight into the _winreg command it works fine. The IPaddresses in the list are surrounded by quotes. So 1. can I use variables with modules? (I have assumed that I can!) 2. does putting quotes around the IPaddress in the list create a problem (my list is something like [192.168.0.1,192.168.0.2] I've also tried not having the list elements in quotes and using %s substitution in the _winreg command. Any help would be much appreciated, Cheers, MW. #Query ProductName in windows Registry import _winreg import sys readfile = open(c:\scripts\ip.txt, 'r') IPList = readfile.readlines() for ClientIP in IPList: print ClientIP key = _winreg.ConnectRegistry(ClientIP, _winreg.HKEY_LOCAL_MACHINE) hkey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, SOFTWARE\Microsoft\Windows NT\CurrentVersion) OSver=_winreg.QueryValueEx( hkey, ProductName) print OSver print Exiting Script sys.exit() -- http://mail.python.org/mailman/listinfo/python-list
Re: Strange behaviour of __cmp__
[EMAIL PROTECTED] wrote: See the following... class X(list): def __cmp__(self,anX): print comparing from,id(self) return cmp(self.v,anX.v) x1=X() x2=X() x1.v=-1 x2.v=100 x1x2 False x1x2 False I expected x1x2 or x1x2 were False and True respectively. list.__lt__ and list.__gt__ are being used in preference to X.__cmp__. Override these methods. -- Robert Kern [EMAIL PROTECTED] In the fields of hell where the grass grows high Are the graves of dreams allowed to die. -- Richard Harter -- http://mail.python.org/mailman/listinfo/python-list
Re: Adding new methods to new-style classes dynamically
John Machin wrote: A.foo 123 Oh, I've been a little dumb to forget about it :) Thanks. Max. -- http://mail.python.org/mailman/listinfo/python-list
Re: using variables with modules
The only problem I can see, is trailing whitespace from the ip.txt file. Perhaps ClientIP.strip() will help? -- http://mail.python.org/mailman/listinfo/python-list
Re: using variables with modules
I tested your code and made a few changes: import _winreg import sys readfile = open(C:\scripts\ip.txt, 'r') IPList = readfile.readlines() for ClientIP in IPList: ClientIP = ClientIP.strip() ClientIP = r'\\' + ClientIP try: key = _winreg.ConnectRegistry(ClientIP, _winreg.HKEY_LOCAL_MACHINE) except EnvironmentError: sys.exit(EnvironmentError occured) hkey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, SOFTWARE\Microsoft\Windows NT\CurrentVersion) OSver=_winreg.QueryValueEx( hkey, ProductName) print OSver print Exiting Script sys.exit() It gives the following output on my XP box when running it against a ip.txt with two IP's, the firste being the box it self, the second a non-domain 2003-server in the network: (u'Microsoft Windows XP', 1) EnvironmentError occured -- http://mail.python.org/mailman/listinfo/python-list
Re: postgresql plpython bug
Jonathan Ellis wrote: First, you don't give enough context to see where your python code generates a timestamp, but in any case it's more of a limitation than a bug that plpython doesn't try to autoconvert certain datatypes. (Are you even returning a datetime class, or a string?) I gave (almost) all the required information because my function doesn't generates any timestamp. I did not make any work with the timestamp field, it was only sent back with return 'MODIFY' Finally I found the source of the bug. It's not in plypython but it is in plperl. I call a plperl stored procedure in my plpython stored procedure. I won't do it anymore. Below is the sample script which produces the bug. I have to set the locale in plperl same to the server locales because buggy plperl doesn't see the database server locales (which plpsql and plpython does). I sent this issue to the general pgsql mailing list earlier. The funny thing that this plperl bug was one of the reasons of my first python adventures. create table test (id int, date timestamp); create or replace function trigger_test() returns trigger as $$ plpy.info(TD['new']) return 'MODIFY' $$ language plpythonu; create trigger test_update before update on test for each row execute procedure trigger_test(); insert into test values (1, now()); insert into test values (2, now()); update test set id = 3; create or replace function test_perl() returns boolean as $$ use locale; use POSIX qw(locale_h); setlocale(LC_COLLATE,'hu_HU'); setlocale(LC_CTYPE,'hu_HU'); setlocale(LC_NUMERIC,'hu_HU'); return True $$ language plperlu; create or replace function trigger_test() returns trigger as $$ plpy.info(TD['new']) plpy.execute('select * from test_perl()') return 'MODIFY' $$ language plpythonu; update test set id = 4; - CREATE TABLE CREATE FUNCTION CREATE TRIGGER INSERT 9138862 1 INSERT 9138863 1 INFO: ({'date': '2005-05-05 13:20:43.793551', 'id': 3},) INFO: ({'date': '2005-05-05 13:20:43.794401', 'id': 3},) UPDATE 2 CREATE FUNCTION CREATE FUNCTION INFO: ({'date': '2005-05-05 13:20:43.793551', 'id': 4},) ERROR: invalid input syntax for type timestamp: 2005-05-05 13:20:43.793551 --- Mage -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Challenge ahead [NEW] for riddle lovers
[SNIP me whining then cheering about level 13] Dan Bishop wrote: You mean there's a hint in that XML-RPC fault? No, there is a hint in level 12. Remember how you could manipulate the URL of the image of level 12 to get to the data file for that level. Now continue that manipulation and don't believe the suggestion about no more evils. *Then* pay close attention to what you find. If you get a 'Not Found' you either didn't pay attention in the previous step and have passed over the hint, or you searched in the wrong direction. Martijn Pieters signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: If you use PayPal you might consider an alternative
Tim Roberts wrote: That web zite iz juzt too cutezy. I could never truzt it, even if I hadn't learned about it through a newzgroup zpam. And a quick Google shows you to be very right: http://www.greenzapscam.com/ http://wwsn-forums.com/forum/index.php?showtopic=3496%3Ehttp://wwsn-forums.com/forum/index.php?showtopic=3496 Martijn Pieters signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Challenge ahead [NEW] for riddle lovers
Michael Spencer wrote: Dan Bishop wrote: You mean there's a hint in that XML-RPC fault? No - the hint is associated with another error message Assuming a web browser (firefox in my case) is being used. ;) I got no error message when I retrieved that URL with urllib and examined the result.. Martijn Pieters signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: annonymous functions -- how to
Jason Mobarak wrote: What's wrong with: def blah(): def _ (a, b, c): a = a + 2 print stmt 2 return a+b/c return doSomethingWith(_) It's basically anonymous, it just uses a name that you don't care about. AFAIK, it can be immediately clobbered later if need be. Otherwise, the function shouldn't be anonymous. Or even better: def blah(): def doJasonsAlgorithm(a, b, c): a = a + 2 print stmt 2 return a+b/c return doSomethingWith(doJasonsAlgorithm) That way you've got reasonably self-documenting code, and don't have to face an annoyed maintainer saying what a jerk: he didn't comment this or even give it a useful name... idiot... grumble grumble. I doubt there's a valid usecase for a anonymous function that has more than a line or two. Personally, I don't think there's a good usecase for an anonymous function longer than one line... -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: using variables with modules
thanks runes, that makes sense, time for me to go off and read some more about strip and try: Cheers, MW. -- http://mail.python.org/mailman/listinfo/python-list
[newbie] how to look up functions
Hi all, I am a python newbie. I need some help to loop up about API, or reference. If any web that Java API Document, I will try it. Is there some one like it or other ways? -- [1;30;40m[m [1;30m[37mBBS telnet://bbs.wretch.cc [30m [m[1;30m[m [1;30m[37m[30m[m [1;30m [37mpc210-59-94-118.nutn.edu.tw[30m[m -- http://mail.python.org/mailman/listinfo/python-list
Re: [newbie] how to look up functions
On 05 May 2005 06:27:14 GMT, slayer [EMAIL PROTECTED] wrote: Hi all, I am a python newbie. I need some help to loop up about API, or reference. If any web that Java API Document, I will try it. Is there some one like it or other ways? http://www.google.com/search?q=python+documentation -- Cheers, Simon B, [EMAIL PROTECTED], http://www.brunningonline.net/simon/blog/ -- http://mail.python.org/mailman/listinfo/python-list
Re: problem in the compiler ?
So , I will try to explain ! I´m trying to modify a code that doesn´t belong to me. I thought that there was a bug in the compilation of Pmw.RadioSelect, but there wans't. I hadn't noticed that the code invoked the button of radioselect in another part of it. Now I simply took off the part of the code which invoked the button and the program is working as I expected. Thanks for your help. Anyway, the code was this : - self.myButton = Pmw.RadioSelect(frame, selectmode = MULTIPLE, command = self.Function) self.myButton.add('C1') self.myButton.pack() ... self.myButton.invoke('C1') - - Original Message - From: Delaney, Timothy C (Timothy) [EMAIL PROTECTED] To: Glauco Silva [EMAIL PROTECTED]; python-list@python.org Sent: Wednesday, May 04, 2005 8:20 PM Subject: RE: problem in the compiler ? Glauco Silva wrote: I´m sorry, I feel I didn't comunicate very well . The program I am writing is a part of a big project, so it would be no use to post it here as it involves many other things and concepts. We wouldn't want the whole thing - that would be useless. What you need to do is trim it down to the smallest piece of code that causes the problem. Normally doing this reveals the actual problem, and you don't need to go to the newsgroup. But i solve my problem and don´t have bug. My code was wrong. Excellent. You should now post your solution to the newsgroup. Tim Delaney -- No virus found in this incoming message. Checked by AVG Anti-Virus. Version: 7.0.308 / Virus Database: 266.11.3 - Release Date: 3/5/2005 -- No virus found in this outgoing message. Checked by AVG Anti-Virus. Version: 7.0.308 / Virus Database: 266.11.5 - Release Date: 4/5/2005 -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Challenge ahead [NEW] for riddle lovers
Och! Thanks for the hint! I actually guessed the answer of who to phone earlier in the day, but didn't have the capitolization correct... Damn! Great riddles! -Jim On 5/5/05, Martijn Pieters [EMAIL PROTECTED] wrote: [SNIP me whining then cheering about level 13] Dan Bishop wrote: You mean there's a hint in that XML-RPC fault? No, there is a hint in level 12. Remember how you could manipulate the URL of the image of level 12 to get to the data file for that level. Now continue that manipulation and don't believe the suggestion about no more evils. *Then* pay close attention to what you find. If you get a 'Not Found' you either didn't pay attention in the previous step and have passed over the hint, or you searched in the wrong direction. Martijn Pieters -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Sockets
On Thu, 05 May 2005 17:11:08 +0800, Dan [EMAIL PROTECTED] wrote: I have a problem and I don't quite know how to implement the solution. I'll have a server application that will listen on a tcp port and make many similtaneous connections to remote clients. From time to time, I'll need to write a small amount of data on one of those sockets. A notification to write to one of the sockets will come from another program/process. I think that the best way to send the notification to this server application is via a udp message. Alternatively, I could use tcp, but I don't think I'll need the extra complexity for what I want to do. (Other suggestions welcome.) UDP is actually more complex than TCP. I recommend sticking with TCP until you have a better reason (eg, you need to communicate simultaneously with tens of thousands of clients). The server application will multiplex the connections using 'select', so much of the time it will be blocked on 'select'. My problem is how to also listen on a udp port while the process is blocked by 'select'. Should I run a separate thread? And if so can I share the socket connection across the two threads? (Thread 1 will be accepting client connections, thread 2 will we writing data to it.) Or should I simply let 'select' time out after some period? I'm a bit lost as to how to do this, I hope someone can put me on the right track. Any solution that I use should be applicable on Linux and Windows platforms. I recommend using Twisted. Here's a sample application that accepts connections, waits on messages from each client, and then transmits another message to all other clients in response to receiving one (untested code): from twisted.internet import reactor, protocol from twisted.protocols import basic # Define the protocol with which we will handle all # incoming connections class ClientMessageProtocol(protocol.LineReceiver): # When a connection is established, append this # instance to the factory's list of connected # clients, so it can send messages to this client # when necessary. def connectionMade(self): self.factory.clients.append(self) # Likewise, remove the instance when the connection # is lost. def connectionLost(self): self.factory.clients.remove(self) # Every time a whole line is received, tell the factory # about it. def lineReceiver(self, line): self.factory.lineReceived(self, line) class ClientMessageFactory(protocol.ServerFactory): # Indicate the protocol to be instantiated for each # connection to this factory. protocol = ClientMessageProtocol # At startup, make an empty clients list. def startFactory(self): self.clients = [] # Whenever a client tells us they received a line, send # a short message to every other connection client. def lineReceived(self, client, line): for cl in self.clientz: if cl is not client: cl.sendLine(%s sent me a message: %r % (client, line)) # Start the server on TCP port 54321 reactor.listenTCP(54321, ClientMessageFactory()) # Run the main event loop reactor.run() Learn more about Twisted on its website: http://www.twistedmatrix.com/ Jp -- http://mail.python.org/mailman/listinfo/python-list
Best way to convert a list into function call arguments?
I'm a newcomer to python - what is the best way to convert a list into a function call agruments? For example: list = (2005, 5, 5) date = datetime.date( list ) fails with: TypeError: function takes exactly 3 arguments (1 given) I assumed that since Python allows multiple assignments per statement, such as a, b, c = list the date call above should work... So, what is the best way to call date? This works, but looks clunky: date = datetime.date( list[0], list[1], list[2 ) Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: Best way to convert a list into function call arguments?
Your question is answered in the tutorial: http://docs.python.org/tut/node6.html#SECTION00674 4.7.4 Unpacking Argument Lists The reverse situation occurs when the arguments are already in a list or tuple but need to be unpacked for a function call requiring separate positional arguments. For instance, the built-in range() function expects separate start and stop arguments. If they are not available separately, write the function call with the *-operator to unpack the arguments out of a list or tuple: range(3, 6) # normal call with separate arguments [3, 4, 5] args = [3, 6] range(*args)# call with arguments unpacked from a list [3, 4, 5] Jeff pgpaezewLDmEG.pgp Description: PGP signature -- http://mail.python.org/mailman/listinfo/python-list
Re: OOPS concept
Chapter 5, Python in Nutshell: concise explanations of everythin' you need to know about inheritance, instantiation, method resolution, namespaces, class/instance methods, getting under the hood with special methods, whatever. I couldn't code without it: http://www.oreilly.com/catalog/pythonian/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Challenge ahead [NEW] for riddle lovers
James Carroll wrote: Och! Thanks for the hint! I actually guessed the answer of who to phone earlier in the day, but didn't have the capitolization correct... Damn! Great riddles! I found the answer with a brute-force search (using /usr/share/dict/words). -- http://mail.python.org/mailman/listinfo/python-list
Re: ERP CRM in Python
Wolfgang Keller wrote: pinky wrote: download, doc, forum ; http://tinyerp.org Why not downloadable and printable PDF documentation instead of online-HTML. Because 1. we need interaction with contributors in our doc. 2. we write docs in the wiki: http://tinyerp.org/wiki We are writing a script to render a PDF from our doc. (using openreport.org) HTML is _extremely_ inconvenient, both for offline use and for printing. Why printing? Because reading siginficant amounts of text on-screen is simply impossible, as is reading an on-screen manual while actually trying out the software (- screenspace). yes, but we need html doc for our contextual help in Tiny ERP. Why not mailing lists instead of online-forums. There is some mailing lists; http://tinyerp.org/lists.php ... but nobody uses it. The former was made for efficient human-to-human communication, the latter not. I agree. Fabien -- http://mail.python.org/mailman/listinfo/python-list
SWIG and Python incompatibilities?
Hi all, Has anyone experienced issues incompatible versions of the above? On solaris, we are experiencing suspect crashes memory leaks? How do I determine which versions are proven to be compatible/incompatible etc? Thanks for helping. Alan -- http://mail.python.org/mailman/listinfo/python-list
a cx_Oracle ORA-01036 problem
I'm using Python 2.4, cx_Oracle-4.1 on Linux with Oracle instant client 10.1.0.3. This is the sql string: SQL = insert into D.D_NOTIFY values (:CARDREF, :BANKKEY, :OK1, :OK2 \ :DEBTEUR, :DEBTDEN, to_date(:INVOICE_DATE,'DD.MM.YY'), to_date(:PAYMENT_DEADLINE,'DD.MM.YY'), :POINTS) And I'm trying to execute it as: c = db.cursor() c.execute(SQL, CARDREF=id, BANKKEY=dc_kluc, OK1=okd, OK2=okc, DEBTEUR=iznos_eur, DEBTDEN=iznos_mkd, INVOICE_DATE=datum_g, PAYMENT_DEADLINE=datum_d, POINTS=bodovi) And I get an ORA-01036 exception. I also have tried args = dict(CARDREF=id, BANKKEY=dc_kluc, OK1=okd, OK2=okc, DEBTEUR=iznos_eur, DEBTDEN=iznos_mkd, INVOICE_DATE=datum_g, PAYMENT_DEADLINE=datum_d, POINTS=bodovi) c = db.cursor() c.execute(SQL, **args) Same thing. Everything works If I use python string substituion, like this sql: SQL = insert into D.D_NOTIFY values (%s,'%s','%s','%s','%s','%s', \ to_date('%s','DD.MM.YY'),to_date('%s','DD.MM.YY'),'%s') % fields Any ideas? -- damjan -- http://mail.python.org/mailman/listinfo/python-list
Re: a cx_Oracle ORA-01036 problem
Damjan [EMAIL PROTECTED] schrieb im Newsbeitrag news:[EMAIL PROTECTED] | I'm using Python 2.4, cx_Oracle-4.1 on Linux with Oracle instant client | 10.1.0.3. This is the sql string: | | SQL = insert into D.D_NOTIFY values (:CARDREF, :BANKKEY, :OK1, :OK2 \ |:DEBTEUR, :DEBTDEN, to_date(:INVOICE_DATE,'DD.MM.YY'), |to_date(:PAYMENT_DEADLINE,'DD.MM.YY'), :POINTS) | | And I'm trying to execute it as: |c = db.cursor() |c.execute(SQL, CARDREF=id, BANKKEY=dc_kluc, OK1=okd, OK2=okc, | DEBTEUR=iznos_eur, DEBTDEN=iznos_mkd, INVOICE_DATE=datum_g, | PAYMENT_DEADLINE=datum_d, POINTS=bodovi) | And I get an ORA-01036 exception. | | I also have tried |args = dict(CARDREF=id, BANKKEY=dc_kluc, OK1=okd, OK2=okc, | DEBTEUR=iznos_eur, DEBTDEN=iznos_mkd, INVOICE_DATE=datum_g, | PAYMENT_DEADLINE=datum_d, POINTS=bodovi) |c = db.cursor() |c.execute(SQL, **args) Shouldn't that be c.execute(SQL, args) (no **-unpacking of the dictionary)? -- Vincent Wehren | Same thing. | | Everything works If I use python string substituion, like this sql: | SQL = insert into D.D_NOTIFY values (%s,'%s','%s','%s','%s','%s', \ |to_date('%s','DD.MM.YY'),to_date('%s','DD.MM.YY'),'%s') % fields | | Any ideas? | | | -- | damjan -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython custom list drawing?
Ivan Voras wrote: Does wxPython (actually, the wx toolkit) support setting up ListCtrls or similar to allow custom element drawing? Something like generating an 'OnPaint()' event in which I could paint whatever I like in a listbox element. (example from some other toolkits) wx.VListBox allows you to render whatever you want for each item. You could also do something similar with a wx.Grid Will McGugan -- http://www.willmcgugan.com .join( [ {'*':'@','^':'.'}.get(c,None) or chr(97+(ord(c)-84)%26) for c in jvyy*jvyyzpthtna^pbz ] ) -- http://mail.python.org/mailman/listinfo/python-list
Re: SWIG and Python incompatibilities?
On 5 May 2005 07:19:34 -0700, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Hi all, Has anyone experienced issues incompatible versions of the above? On solaris, we are experiencing suspect crashes memory leaks? How do I determine which versions are proven to be compatible/incompatible etc? We've used Swig 1.3.21 with a couple version of Python now (2.3.3, 2.3.4, 2.4, and now 2.4.1) without any problems. You might want to take a look at the code that Swig generates to see if that's really where your problems are coming from. Good luck. -- Steve Juranich Tucson, AZ USA -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie.......Python and Networking
Thanks phil, I think I'll start off with your chat prog (UDP-- 50 lines code ) and then try for routing and firewall scripts for linux, yepp that would be really tough but why not give it a try, i am going to have my vacations for like 13 days so will be preparing for my CCNA and also learning python in that duration. You have been most helpful through ur well thought and scaled reply xeron -- http://mail.python.org/mailman/listinfo/python-list
Re: annonymous functions -- how to
Peter Hansen wrote: Jason Mobarak wrote: What's wrong with: def blah(): def _ (a, b, c): a = a + 2 print stmt 2 return a+b/c return doSomethingWith(_) It's basically anonymous, it just uses a name that you don't care about. AFAIK, it can be immediately clobbered later if need be. Otherwise, the function shouldn't be anonymous. Or even better: Python doesn't have anonymous functions. See http://boo.codehaus.org/Closures and the closures examples here: http://svn.boo.codehaus.org/trunk/tests/testcases/integration/ -- http://mail.python.org/mailman/listinfo/python-list
Re: a cx_Oracle ORA-01036 problem
vincent wehren wrote: |c = db.cursor() |c.execute(SQL, **args) Shouldn't that be c.execute(SQL, args) (no **-unpacking of the dictionary)? Actually I tried that too, I still get the same error. -- damjan -- http://mail.python.org/mailman/listinfo/python-list
Re: How to write this regular expression?
Peter Hansen wrote: could ildg wrote: I need a regular expression to check if a string matches it. Why do you think you need a regular expression? If another approach that involved no regular expressions worked much better, would you reject it for some reason? -Peter A regular expression will work fine for his problem. Just match the digits separated by underscores using a regular expression, then afterward check if the values are valid. -- http://mail.python.org/mailman/listinfo/python-list
Hard times with packages and instances
Hi people, I wonder why the isinstance() function is sensitive about the import path i.e. the result depends not only on the class and the instance but also on how a class is imported? Example: MyPackage/ Top-level package __init__.py Initialize package __me__.py Module used for setting Python-path A.py Use objects of ForeignPackage and subpackages ForeignPackage/ Don't touch! __init__.py Initialize package B.pyDefines class B1 MySubPackage/ Subpackage __init__.py Initialize subpackage C.pyDefines instance checker for B1 instances Provide some implementations: _ # MyPackage.__init__.py import __me__ __me__.setmypath() # MyPackage.__me__.py def setmypath(): import __me__ import inspect import sys absfile = inspect.getabsfile(__me__) abspath = /.join(absfile.split(/)[:-1]+absfile.split(\\)[:-1]) sys.path.append(abspath) # MyPackage.A.py from MySubPackage.C import* from ForeignPackage.B import* b1 = B1() checkInstance(b1) #print b1.__class__ # MyPackage.ForeignPackage.__init__.py # left empty # MyPackage.ForeignPackage.B.py class B1(object): def __init__(self):pass # MyPackage.MySubPackage.C.py import MyPackage import ForeignPackage.B as B #import MyPackage.ForeignPackage.B as B def checkInstance(inst): if isinstance(inst,B.B1): print class is %s%inst.__class__ else: raise TypeError,Instance of unknown class '%s' found%inst.__class__ No run A.py : A will call checkInstance with a B1 instance and prints class is class 'MySubPackage.B.B1' as expected. But if one comments in the line import MyPackage.ForeignPackage.B as B in module C.py and calls A.py one gets: Traceback (most recent call last): ... TypeError: Instance of unknown class 'class 'ForeignPackage.B.B1'' found The class which was expected by the checkInstance() function is class 'MyPackage.ForeignPackage.B.B1' I'm curios if someone could explain me the difference between this two class objects? Regards, Kay -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie.......Python and Networking
xeron wrote: Thanks phil, I think I'll start off with your chat prog (UDP-- 50 lines code ) and then try for routing and firewall scripts for linux, yepp that would be really tough but why not give it a try, i am going to have my vacations for like 13 days so will be preparing for my CCNA and also learning python in that duration. You have been most helpful through ur well thought and scaled reply xeron I could send you the chat program they wrote if it would help. It has 2 threads, listener and sender. Might spoil your fun. However it is very primitive and asynchronous and needs work. Oh heck, here it is. DO NOT PEEK BEYOND THIS POINT IF YOU WISH TO SOLVE YOURSELF. # chat1.py # remote unknown, firewall allow UDP 12101 import os from threading import * from socket import * HOST = '' BUFSIZE = 1024 ListenPort = 12101 ListenAddr = (HOST,ListenPort) listenersocket = socket(AF_INET,SOCK_DGRAM) listenersocket.bind(ListenAddr) sendsocket = socket(AF_INET,SOCK_DGRAM) sendsocket = socket(AF_INET,SOCK_DGRAM) def listener(): while 1: msg,addr = listenersocket.recvfrom(BUFSIZE) print '',msg if msg == 'die-now': break def sender(): print; print print 'Type away. When you are thru with your' print ' message, hit enter an extra time' print ' to let the other guy know its his turn.' print 'To exit, enter exit' print; print while 1: msg = raw_input() if msg == 'exit': sendsocket.sendto( 'die-now', ('localhost',ListenPort) ) break sendsocket.sendto( msg, (sendtoip,ListenPort) ) # Main program start here print sendtoip = raw_input('Enter IP address of other computer: ') sendtoip = sendtoip.strip() # Define and start 2 threads listnr = Thread(target=listener) sendr = Thread(target=sender) listnr.start() sendr.start() listnr.join() sendr.join() -- http://mail.python.org/mailman/listinfo/python-list
Re: SWIG and Python incompatibilities?
Thanks Steve! appreciate the response. -- http://mail.python.org/mailman/listinfo/python-list
Does the Python/C interface support Queue objects?
I'm a new user of the Python C interface. I would like to know if it is possible to put items on a standard python Queue object in C, and pop them from Python. Does the Python/C interface support Queue objects? A little background. I made a C dll that sets up a thread for collecting data from an NI data aquisition card. The thread builds a list and passes the list to to python via a callback, then python puts them in the Queue. I would prefer to put the data in the Queue from the C thread for efficiency, and then monitor the Queue from python. -- http://mail.python.org/mailman/listinfo/python-list
Re: dictionary comparison
On 5 May 2005 08:19:31 -0700, rickle [EMAIL PROTECTED] wrote: I'm trying to compare sun patch levels on a server to those of what sun is recommending. For those that aren't familiar with sun patch numbering here is a quick run down. A patch number shows up like this: 113680-03 ^^ ^^ patch# revision What I want to do is make a list. I want to show what server x has versus what sun recommends, and if the patch exists, but the revision is different, I want to show that difference. Here are some sample patches that sun recommends: 117000-05 116272-03 116276-01 116278-01 116378-02 116455-01 116602-01 116606-01 Here are some sample patches that server x has: 117000-01 116272-02 116272-01 116602-02 So there are some that are the same, some that sun recommends that server x doesn't have, and some where the patch is the same but the revision is different. I've thrown the data into dictionaries, but I just can't seem to figure out how I should actually compare the data and present it. Here's what I have so far (the split is in place because there is actually a lot more data in the file, so I split it out so I just get the patch number and revision). So I end up with (for example) 116272-01, then split so field[0] is 116272 and field[1] is 01. def sun(): sun = open('sun-patchlist', 'r') for s in sun: sun_fields = s.split(None, 7) for sun_field in sun_fields: sun_field = sun_field.strip() sun_patch = {} sun_patch['number'] = sun_fields[0] sun_patch['rev'] = sun_fields[1] print sun_patch['number'], sun_patch['rev'] sun.close() def serverx(): serverx = open('serverx-patchlist', 'r') for p in serverx: serverx_fields = p.split(None, 7) for serverx_field in serverx_fields: serverx_field = serverx_field.strip() serverx_patch = {} serverx_patch['number'] = serverx_fields[0] serverx_patch['rev'] = serverx_fields[1] print serverx_patch['number'], serverx_patch['rev'] serverx.close() The first thing you should notice about this code is that you copied a good amount of code between functions; this should be a huge warning bell that something can be abstracted out into a function. In this case, it's the parsing of the patch files. Also, you should see that you're creating a new dictionary every iteration through the loop, and furthermore, you're not returning it at the end of your function. Thus, it's destroyed when the function exits and it goes out of scope. snip Anyway, since you at least made an effort, here's some totally untested code that should (I think) do something close to what you're looking for: def parse_patch_file(f): patches = {} for line in f: patch, rev = line.strip().split('-') patches[patch] = rev return patches def diff_patches(sun, serverx): for patch in sun: if not serverx.has_key(patch): print Sun recommends patch %s % patch for patch in serverx: if not sun.has_key(patch): print Serverx has unnecessary patch %s % patch def diff_revs(sun, serverx): for patch, rev in sun.iteritems(): if serverx.has_key(patch) and rev != serverx[patch]: print Sun recommends rev %d of patch %s; serverx has rev %d\ % (rev, patch, serverx[patch]) if __name__ == '__main__': sun = parse_patch_file(open('sun-patchlist')) serverx = parse_patch_file(open('serverx-patchlist')) diff_patches(sun, serverx) diff_revs(sun, serverx) Hope this helps. Peace Bill Mill bill.mill at gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: annonymous functions -- how to
Peter Hansen wrote: I doubt there's a valid usecase for a anonymous function that has more than a line or two. Personally, I don't think there's a good usecase for an anonymous function longer than one line... The case that I keep running into regards event-driven programming. I need to do a series of operations that are tied together asynchronously via callback functions, but I still want the actions to read in-order. With anonymous functions (and I mean the ones that you can use within expressions, Bengt ;) ), I could write something like the following: def add_thingy(): with_next_thingy_id(def(thingy_id): print 'got thingy id:', thingy_id with_next_doodad_id(def(doodad_id): pring 'got doodad id:', doodad_id with_new_thingy_doodad(thingy_id, doodad_id, def(thingy_doodad): print 'thingy doodad created, froobling...' frooble(thingy_doodad) print 'froobling complete' ) ) ) In this case, having to name these callback functions is tiring and awkward, and (IMHO) disrupts the flow of my function: def add_thingy(): def next_thingy_id_func(thingy_id): print 'got thingy id:', thingy_id def next_doodad_id_func(doodad_id): print 'got doodad id:', doodad_id def new_thingy_doodad_func(thingy_doodad): print 'thingy doodad created, froobling...' frooble(thingy_doodad) print 'froobling complete' with_new_thingy_doodad(thingy_id, doodad_id, new_thingy_doodad_func) with_next_doodad_id(next_doodad_id_func) with_next_thingy_id(next_thingy_id_func) There is no reason why these callbacks would necessarily be one-liners or ten-liners. I suppose this problem could be solved by defining all the functions at the top-level (or by using bound methods of an object), but to me this is harder to maintain and doesn't read as well. Not life or death, but there's at least one use case that I would at least consider valid. Your definition of valid may differ, of course. =) Dave -- http://mail.python.org/mailman/listinfo/python-list
Re: python and glut
Mike Meyer wrote: max(01)* [EMAIL PROTECTED] writes: $ python GLE.py freeglut (GLE.py): OpenGL GLX extension not supported by display ':0.0' what's up? what's missing? The GLX extension to your X server. i use a standard debian installation. I don't know which X debian uses, and it may have changed over time, mine uses XFree86, Version 4.3.0.1 (from the man page) so you'll want to specify the name of the distribution. woody. thanks max -- http://mail.python.org/mailman/listinfo/python-list
Re: Adding new methods to new-style classes dynamically
On Thu, May 05, 2005 at 01:35:09AM -0700, Max Derkachev wrote: Good day to all. Some time ago I'd been playing with a framework which uses dynamic class creation havily. Say, I could do: snip #well, try this with the new-style class class A(object): pass # the new-style __dict__ is a dictproxy object A.__dict__[meth_name] = lambda self: type(self) Traceback (most recent call last): File interactive input, line 1, in ? TypeError: object does not support item assignment Is there other way to add/change methods to new-style classes dynamically? import new dir(new) ['__builtins__', '__doc__', '__file__', '__name__', 'classobj', 'code', 'function', 'instance', 'instancemethod', 'module'] def foo(self): ... print FOO! A.foo = new.instancemethod(foo, None, A) # func, object, class A.foo unbound method A.foo a = A() a.foo bound method A.foo of __main__.A object at 0xb7e0b4cc a.foo() FOO! -jackdied -- http://mail.python.org/mailman/listinfo/python-list
Re: python and glut
Lonnie Princehouse wrote: See if you can run `glxgears`, and read the output of `glxinfo`. $ glxgears Xlib: extension GLX missing on display :0.0. Error: couldn't get an RGB, Double-buffered visual $ glxinfo name of display: :0.0 Xlib: extension GLX missing on display :0.0. Xlib: extension GLX missing on display :0.0. Xlib: extension GLX missing on display :0.0. Error: couldn't find RGB GLX visual visual x bf lv rg d st colorbuffer ax dp st accumbuffer ms cav id dep cl sp sz l ci b ro r g b a bf th cl r g b a ns b eat -- Xlib: extension GLX missing on display :0.0. Xlib: extension GLX missing on display :0.0. 0x21 16 tc 1 0 0 c . . 0 0 0 0 0 0 0 0 0 0 0 0 0 None now what? bye max -- http://mail.python.org/mailman/listinfo/python-list
Re: dictionary comparison
rickle wrote: I'm trying to compare sun patch levels on a server to those of what sun is recommending. For those that aren't familiar with sun patch numbering here is a quick run down. A patch number shows up like this: 113680-03 ^^ ^^ patch# revision What I want to do is make a list. I want to show what server x has versus what sun recommends, and if the patch exists, but the revision is different, I want to show that difference. Here are some sample patches that sun recommends: 117000-05 116272-03 116276-01 116278-01 116378-02 116455-01 116602-01 116606-01 Here are some sample patches that server x has: 117000-01 116272-02 116272-01 116602-02 So there are some that are the same, some that sun recommends that server x doesn't have, and some where the patch is the same but the revision is different. I've thrown the data into dictionaries, but I just can't seem to figure out how I should actually compare the data and present it. Here's what I have so far (the split is in place because there is actually a lot more data in the file, so I split it out so I just get the patch number and revision). So I end up with (for example) 116272-01, then split so field[0] is 116272 and field[1] is 01. def sun(): sun = open('sun-patchlist', 'r') for s in sun: sun_fields = s.split(None, 7) for sun_field in sun_fields: sun_field = sun_field.strip() sun_patch = {} sun_patch['number'] = sun_fields[0] sun_patch['rev'] = sun_fields[1] print sun_patch['number'], sun_patch['rev'] sun.close() def serverx(): serverx = open('serverx-patchlist', 'r') for p in serverx: serverx_fields = p.split(None, 7) for serverx_field in serverx_fields: serverx_field = serverx_field.strip() serverx_patch = {} serverx_patch['number'] = serverx_fields[0] serverx_patch['rev'] = serverx_fields[1] print serverx_patch['number'], serverx_patch['rev'] serverx.close() if __name__=='__main__': sun() serverx() Right now I'm just printing the data, just to be sure that each dictionary contains the correct data, which it does. But now I need the comparison and I just can't seem to figure it out. I could probably write this in perl or a shell script, but I'm trying really hard to force myself to learn Python so I want this to be a python script, created with only built-in modules. Any help would be greatly appreciated, Rick Well, it seems that what youre asking is more of a generic programming question than anything specific to Python - if you can think of how you'd solve this in Perl, for example, then a Python solution along the same lines would work just as well. I'm not sure if there was some specific issue with Python that was confusing you - if so, perhaps you could state it more explicitly. To address the problem itself, there are a few things about your approach in the above code that I find puzzling. First of all, the sun() and servex() functions are identical, except for the name of the file they open. This kind of code duplication is bad practice, in Python, Perl, or any other language (even Shell scripting perhaps, although I wouldn't really know) - you should definitely use a single function that takes a filename as an argument instead. Second, you are creating a new dictionary inside every iteration of the for loop, one for every patch in the file; each dictionary you create contains one patch number and one revision number. This data is printed, and thereafter ignored (and thus will be consumed by Python's Garbage Collector.) Hence youre not actually storing it for later use. I don't know whether this was because you were unsure how to proceed to the comparing the two datasets; however I think what you probably wanted was to have a single dictionary, that keeps track of all the patches in the file. You need to define this outside the for loop; and, if you want to use it outside the body of the function, you'll need to return it. Also, rather than have a dictionary of two values, keyed by strings, I'd suggest a dictionary mapping patch numbers to their corresponding revision numbers is what you want. Once you've got two dictionaries - one for the list for the servers patches, and one for Sun's recommended patches - you can compare the two sets of data by going through the Sun's patches, checking if the server has that patch, and if so, caluclating the difference in revision numbers. So heres a rough idea of how I'd suggest modifying what you've got to get the intended result: def patchlevels(filename): patchfile = open(filename, 'r') patch_dict = {} for line in patchfile: fields = line.split(None, 7) for field in fields:
Re: annonymous functions -- how to
On Thu, 05 May 2005 07:45:33 -0400, Peter Hansen [EMAIL PROTECTED] wrote: Jason Mobarak wrote: What's wrong with: def blah(): def _ (a, b, c): a = a + 2 print stmt 2 return a+b/c return doSomethingWith(_) It's basically anonymous, it just uses a name that you don't care about. AFAIK, it can be immediately clobbered later if need be. Otherwise, the function shouldn't be anonymous. Or even better: def blah(): def doJasonsAlgorithm(a, b, c): a = a + 2 print stmt 2 return a+b/c return doSomethingWith(doJasonsAlgorithm) That way you've got reasonably self-documenting code, and don't have to face an annoyed maintainer saying what a jerk: he didn't comment this or even give it a useful name... idiot... grumble grumble. I doubt there's a valid usecase for a anonymous function that has more than a line or two. Personally, I don't think there's a good usecase for an anonymous function longer than one line... Yes, but only the BDFL can outlaw things on that kind of basis ;-) My post was just to play with anonymous a little, not to motivate more examples of strange call layering and dynamic execution of defs that don't change etc. ;-) BTW, I view a def as a kind of assignment statement with the target restricted to a local bare name. I.e., def foo(): pass # def restricted assignment target():pass So why have this form of assignment? And why restrict it to a bare name, even if you want to keep the def for mnemonic convention to use as usual? I.e., why not loosen def to allow e.g. def MyClass.method(self): pass or @staticmethod def MyClass.square(x): return x*x or def fdict['sqr'](x): return x*x Well, I can see a reason not to do the last that way. It would be much clearer using an anonymous def, e.g., fdict['sqr'] = def(x): return x*x And then you can say lambda is fine for that, except for the limitation that the body be just an expression. Then you might ask, why not bend that a little? E.g., fdict['sqrt'] = def(x): if x 0: raise ValueError, 'x must be non-negative, not %r' %x return math.sqrt(x) And then, why not allow an anonymous defs as expressions anywhere expressions can go? (indentation problems are actually easy to overcome). Anyway, in general, I'd rather be persuaded than forced ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list
Re: python and glut
Lonnie Princehouse wrote: See if you can run `glxgears`, and read the output of `glxinfo`. If neither of those work, you will probably have better luck on a debian or XFree86/xorg forum than on c.l.py your hints were helpful anyway. thanks! ok, i uncommented the line: Load glx in my /etc/X11/XF86Config file. now glxgears seems to work... except for the following message: Xlib: extension XFree86-DRI missing on display :0.0. can you give some more help? (sorry again for being offtopic) max -- http://mail.python.org/mailman/listinfo/python-list
Re: dictionary comparison
Bill and Jordan, thank you both kindly. I'm not too well versed in functions in python and that's exactly what I needed. I could see I was doing something wrong in my original attempt, but I didn't know how to correct it. It's working like a charm now, thank you both very much. -Rick -- http://mail.python.org/mailman/listinfo/python-list
Re: dictionary comparison
On Thursday 05 May 2005 10:20 am, so sayeth rickle: Bill and Jordan, thank you both kindly. I'm not too well versed in functions in python and that's exactly what I needed. I could see I was doing something wrong in my original attempt, but I didn't know how to correct it. It's working like a charm now, thank you both very much. -Rick I thought I'd throw this in to show some things in python that make such comparisons very easy to write and also to recommend to use the patch as key and version as value in the dict.: Note that the meat of the code is really about 4 lines because of (module) sets and list comprehension. Everything else is window dressing. James === # /usr/bin/env python from sets import Set # pretending these stripped from file recc_ary = [117000-05, 116272-03, 116276-01, 116278-01, 116378-02, 116455-01, 116602-01, 116606-01] serv_ary = [117000-01, 116272-02, 116272-01, 116602-02] # use patch as value and version as key recc_dct = dict([x.split(-) for x in recc_ary]) serv_dct = dict([x.split(-) for x in serv_ary]) # use Set to see if patches overlap overlap = Set(recc_dct.keys()).intersection(serv_dct.keys()) # find differences (change comparison operator to ,,=,=, etc.) diffs = [patch for patch in overlap if recc_dct[patch] != serv_dct[patch]] # print a pretty report for patch in diffs: print reccomended patch for %s (%s) is not server patch (%s) % \ (patch, recc_dct[patch], serv_dct[patch]) -- 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
How to detect a double's significant digits
Hi all... How can I find out the number of significant digits (to the right of the decimal place, that is) in a double? At least, I *think* that's what I'm asking for. For instance: 0.103 -- 3 0.0103 -- 4 0.00103 -- 5 0.000103 -- 6 0.103 -- 7 Thanks in advance! --Steve ([EMAIL PROTECTED]) -- http://mail.python.org/mailman/listinfo/python-list
Re: Does the Python/C interface support Queue objects?
[EMAIL PROTECTED] wrote: A little background. I made a C dll that sets up a thread for collecting data from an NI data aquisition card. The thread builds a list and passes the list to to python via a callback, then python puts them in the Queue. I would prefer to put the data in the Queue from the C thread for efficiency, and then monitor the Queue from python. the Queue type is implemented in Python, so you won't gain much by skipping the callback. but if you insist, you can use the abstract API to manipulate the queue object: http://docs.python.org/api/object.html res = PyObject_CallMethod(queue, put, O, object); ... check error status ... Py_DECREF(res); /F -- http://mail.python.org/mailman/listinfo/python-list
Re: How to detect a double's significant digits
Significant digits are an accounting concept. As such, it is up to the accountant to keep track of these as only she knows the precision of her measurements. Koan for the day: What are the significant digits of 0.1? Hint: `0.1` James On Thursday 05 May 2005 10:37 am, so sayeth mrstephengross: Hi all... How can I find out the number of significant digits (to the right of the decimal place, that is) in a double? At least, I *think* that's what I'm asking for. For instance: 0.103 -- 3 0.0103 -- 4 0.00103 -- 5 0.000103 -- 6 0.103 -- 7 Thanks in advance! --Steve ([EMAIL PROTECTED]) -- James Stroud, Ph.D. 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
Europython update
This is a news update about the Europython 2005 conference, to be held in Göteborg, Sweden 27-29 June - Due to some technical prolems with the registration website we have decided to extend the registration of talks until 8 May. We already have an impressive array of talks, but we do have room for some more. We are especially interested in talks focusing on the Python language and talks on Python usage in Science. - To encourage companies to bring their whole staff and their customers to Europython, we have created a corporate discount. If you bring 5 people or more from a single organisation, you get a 20% discount on the regular and early-bird regular fee. - A list of all the accepted talks will be published 11 May 2005 on the Europython website. - Early bird registrations end 15 May. Registration for the low cost accomodation close to the conference venue ends on the same day. For all conference details, go to: http://www.europython.org See you in Göteborg. EuroPython Team About EuroPython: Europython is an annual conference for the Python and Zope communities. It circulates between different sites in Europe. Having started in Charleroi, Belgium, it is now in Göteborg, Sweden and will move to CERN in Swizerland next year. Europython is a community conference run by volunteers. -- -- http://mail.python.org/mailman/listinfo/python-list
[ANN] Voidspace Guestbook 1.4.2
Oops, embarrasing bugix release time. Guestbook 1.4.1 worked fine (wonderfully even) with Python 2.4, but not with Python 2.3. This release fixes that, and also another Python 2.2 compatibility problem (yes I'm testing now...). Homepage : http://www.voidspace.org.uk/python/guestbook.html Example : http://www.voidspace.org.uk/cgi-bin/voidspace/guestbook2.py Quick Download : http://www.voidspace.org.uk/cgi-bin/voidspace/downman.py?file=guestbook.zip I might even have spelt my domain name right this time... Best Regards, Fuzzyman http://www.voidspace.org.uk/python -- http://mail.python.org/mailman/listinfo/python-list
Re: How to detect a double's significant digits
So how can I get the kind of information I want then? For example: 0.103 -- 3 0.0103 -- 4 0.00103 -- 5 0.000103 -- 6 0.103 -- 7 Any ideas? --Steve -- http://mail.python.org/mailman/listinfo/python-list
Re: How to detect a double's significant digits
fl = 1.0002 x = str(fl) pos = x.find('.') print len( x[pos+1:] ) 4 mrstephengross wrote: Hi all... How can I find out the number of significant digits (to the right of the decimal place, that is) in a double? At least, I *think* that's what I'm asking for. For instance: 0.103 -- 3 0.0103 -- 4 0.00103 -- 5 0.000103 -- 6 0.103 -- 7 Thanks in advance! --Steve ([EMAIL PROTECTED]) -- http://mail.python.org/mailman/listinfo/python-list
Re: min max of a list
[EMAIL PROTECTED] wrote: Thanks for that. My version of python does'nt find groupby. I am using python 2.3.2. Is there a way I could do it with out using groupby itertools.groupby is in Python 2.4. The docs[1] give a Python equivalent, so if for some reason you can't upgrade to the current version of Python, you can just copy the groupby code from there. STeVe [1]http://docs.python.org/lib/itertools-functions.html#l2h-1379 -- http://mail.python.org/mailman/listinfo/python-list
Re: How to detect a double's significant digits
mrstephengross wrote: So how can I get the kind of information I want then? For example: 0.103 -- 3 0.0103 -- 4 0.00103 -- 5 0.000103 -- 6 0.103 -- 7 Beware that this is probably only relevant if you have your numbers as strings, not as floats: py 0.103 0.10299 But, assuming you have your numbers as strings, I would suggest looking at str.split() and len(). I'd give you an example, but this sounds kinda like a homework assignment. STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: How to detect a double's significant digits
mrstephengross wrote: First of all, str() is not a function. Yes it is. float f = 1.004; ostringstream s; s f; cout s.str(); This doesn't look like Python to me. Are you sure you're on the right newsgroup? STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: How to detect a double's significant digits
But, assuming you have your numbers as strings, I would suggest looking at str.split() and len(). Well, the numbers are in fact stored as numbers, so string processing won't work. I'd give you an example, but this sounds kinda like a homework assignment. The task may sound like it comes from class, but I can assure you that I am indeed a professional developer. I'm doing some rather intricate text processing / rendering stuff these days, and C++ is unfortunately none too handy for that sort of thing. Unfortunately, I have to use it for the task. Thanks, --Steve -- http://mail.python.org/mailman/listinfo/python-list
Re: How to detect a double's significant digits
mrstephengross wrote: Well, the numbers are in fact stored as numbers, so string processing won't work. What kind of numbers? Python floats? STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: How to detect a double's significant digits
mrstephengross wrote: But, assuming you have your numbers as strings, I would suggest looking at str.split() and len(). Well, the numbers are in fact stored as numbers, so string processing won't work. How about: py def digits(f): ... return len(str(f).split('.')[1].rstrip('0')) ... py for f in [0.103, 0.1030, 0.0103, 0.010300]: ... print f, digits(f) ... 0.103 3 0.103 3 0.0103 4 0.0103 4 I believe the rstrip is unnecessary because I think str() will never produce additional following zeros, but you can guarantee it by calling rstrip if you want. Note that, for example, 0.103 and 0.1030 are identical as far as Python is concerned, so I hope you're not hoping to show a difference between these two... STeVe -- http://mail.python.org/mailman/listinfo/python-list
phyton memory management
Hi all, I do have a problem with python and it is that it raise an outofmemory (i comment lines in Py.java to avoid system.exit, to debug), i try to debug this issue with jprobe and realize that i get the exception even although the java heap is not in the limit, i can notice that python needa memory pick to parse the command line. The program is a command line that receive a string line that python parse and call some java classes ti execute the appropiate command, any idea? Thansk, ==Carlos García Phone : +34 91 714 8796Lucent Technologies e-mail : [EMAIL PROTECTED]Avenida de Bruselas , 8 - 28108 Alcobendas (Madrid)== -- http://mail.python.org/mailman/listinfo/python-list
Re: How to detect a double's significant digits
On 5 May 2005 10:37:00 -0700, mrstephengross [EMAIL PROTECTED] wrote: Hi all... How can I find out the number of significant digits (to the right of the decimal place, that is) in a double? At least, I *think* that's what I'm asking for. For instance: 0.103 -- 3 0.0103 -- 4 0.00103 -- 5 0.000103 -- 6 0.103 -- 7 Thanks in advance! --Steve ([EMAIL PROTECTED]) I would say that each of these examples has three signficant figures. Each of them can be expressed as: 1.03e+n For any integer n. The fact that you've only shown the cases where n \in {-1, -2, -3, -4, -5 . . } doesn't change the generality of the answer. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to detect a double's significant digits
On 2005-05-05, mrstephengross [EMAIL PROTECTED] wrote: But, assuming you have your numbers as strings, I would suggest looking at str.split() and len(). Well, the numbers are in fact stored as numbers, Then your question is in fact meaningless. The related question that can be answered is where is the least significant '1' bit in the IEEE representation. If that's useful information, the struct module will help you find it. so string processing won't work. That's the only way to answer the question you asked. I'd give you an example, but this sounds kinda like a homework assignment. The task may sound like it comes from class, but I can assure you that I am indeed a professional developer. I'm doing some rather intricate text processing / rendering stuff these days, and C++ is unfortunately none too handy for that sort of thing. Unfortunately, I have to use it for the task. -- Grant Edwards grante Yow! Hmmm... A hash-singer at and a cross-eyed guy were visi.comSLEEPING on a deserted island, when... -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Challenge ahead [NEW] for riddle lovers
any help on level 4 would be appreciated. i've looked at the hints, but isn't obvious -- http://mail.python.org/mailman/listinfo/python-list
Re: How to detect a double's significant digits
This doesn't look like Python to me. Are you sure you're on the right newsgroup? Er, ok, I'm an idiot. This was all supposed to be on comp.lang.c++, but obviously I posted on the wrong one. Sorry for all the hassle. In python, this stuff is a heck of a lot easier. --Steve -- http://mail.python.org/mailman/listinfo/python-list
Re: How to detect a double's significant digits
Bollocks, works here. That looks like Java!!! Aaaihh! mrstephengross wrote: Ok, that won't work. First of all, str() is not a function. If I want to convert the float into a string, the conversion function will have to use some kind of numeric precision, which will screw things up. Consider this: float f = 1.004; ostringstream s; s f; cout s.str(); The above code may produce 1.004, or 1.0040, or 1.00400, depending on the stream's precision setting. I need a way to detect the number of digits to the right of decimal point *prior* to doing any kind of string conversion. --Steve -- http://mail.python.org/mailman/listinfo/python-list
Re: How to detect a double's significant digits
mrstephengross wrote: This was all supposed to be on comp.lang.c++, but You may still want to read the following thread on Python-Dev: http://mail.python.org/pipermail/python-dev/2004-March/043703.html A link mentioned by Andrew Koenig may be helpful: http://www.netlib.org/fp/ fileg_fmt.c by David Gay for ANSI C or C++ source for function g_fmt(char *, double): , with help from dtoa, g_fmt(buf, x) sets buf to the shortest , decimal string that correctly rounds to x and returns buf. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: So many things that need to be decided....
Mage [EMAIL PROTECTED] writes: - identing with tabs Indenting with tabs is pretty much frowned upon in Python, as Guido relates in PEP 8: http://www.python.org/peps/pep-0008.html I guess it doesn't matter much if you are the only person who will ever touch your code, and you never, ever, accidentally mix spaces and tabs... Nick -- # sigmask (lambda deprecation version) 20041028 || feed this to a python print ''.join([chr(ord(x)-1) for x in 'Ojdl!Wbshjti!=ojdlAwbshjti/psh?']) -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Challenge ahead [NEW] for riddle lovers
willitfw wrote: any help on level 4 would be appreciated. i've looked at the hints, but isn't obvious It isn't meant to be too obvious.. If you're expecting obvious solutions, you won't like the rest of the challenge. ;) What have you tried? Have you studied the source of the page, tried the link, seen what you get back from that link and then adjusted the URL according to what you got back? From there on out, just follow the chain, the linked list. Martijn Pieters signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: How to detect a double's significant digits
mrstephengross wrote: But, assuming you have your numbers as strings, I would suggest looking at str.split() and len(). Well, the numbers are in fact stored as numbers, so string processing won't work. if they're not strings, your question is meaningless. as others have pointed out, the exact internal representation for 0.103 is more like 0.10299433786257441170164383947849273681640625 which has a lot more than 3 digits... I'd give you an example, but this sounds kinda like a homework assignment. The task may sound like it comes from class, but I can assure you that I am indeed a professional developer. well professional or not, you clearly need to refresh your floating point skills. I suggest reading the following documents before proceeding: http://docs.python.org/tut/node16.html http://www.lahey.com/float.htm /F -- http://mail.python.org/mailman/listinfo/python-list
Re: min max of a list
what if we do something like this. Assume the values list is the content of a histogram. Then we see that values = [ 0, 72, 0, 4, 9, 2, 0, 0, 42, 26, 0, 282, 23, 0, 101, 0, 0, 0, 0, 0] 1 is repeated 72 times, 3 - 4 times and so on. That is the index would be the value repeated as many times as in the list. Now If we find the max and look for the adjcent index. FOr example take 282 : Index of 282 -- 11 now check for value of index 10 and 12 .If value(10) value(9) then there is a dip as value(9) and value(11) are greater than value(10). that could be the lower bound of that range. then if value(11) and value(13) for value(12). if value(11) value(10) there is a dip. SO the bounds of [10,12] - [0,282,23] rather than [10, 13] values: [0, 282, 23, 0] ( in your case). How would this work. Is there someway I could do this faster. -- http://mail.python.org/mailman/listinfo/python-list
Re: dictionary comparison
On 5 May 2005 08:19:31 -0700, rickle [EMAIL PROTECTED] wrote: I'm trying to compare sun patch levels on a server to those of what sun is recommending. For those that aren't familiar with sun patch numbering here is a quick run down. A patch number shows up like this: 113680-03 ^^ ^^ patch# revision What I want to do is make a list. I want to show what server x has versus what sun recommends, and if the patch exists, but the revision is different, I want to show that difference. Here are some sample patches that sun recommends: 117000-05 116272-03 116276-01 116278-01 116378-02 116455-01 116602-01 116606-01 Here are some sample patches that server x has: 117000-01 116272-02 116272-01 116602-02 So there are some that are the same, some that sun recommends that server x doesn't have, and some where the patch is the same but the revision is different. I've thrown the data into dictionaries, but I just can't seem to figure out how I should actually compare the data and present it. Here's what I have so far (the split is in place because there is actually a lot more data in the file, so I split it out so I just get the patch number and revision). So I end up with (for example) 116272-01, then split so field[0] is 116272 and field[1] is 01. def sun(): sun = open('sun-patchlist', 'r') for s in sun: sun_fields = s.split(None, 7) for sun_field in sun_fields: sun_field = sun_field.strip() sun_patch = {} sun_patch['number'] = sun_fields[0] sun_patch['rev'] = sun_fields[1] print sun_patch['number'], sun_patch['rev'] sun.close() def serverx(): serverx = open('serverx-patchlist', 'r') for p in serverx: serverx_fields = p.split(None, 7) for serverx_field in serverx_fields: serverx_field = serverx_field.strip() serverx_patch = {} serverx_patch['number'] = serverx_fields[0] serverx_patch['rev'] = serverx_fields[1] print serverx_patch['number'], serverx_patch['rev'] serverx.close() if __name__=='__main__': sun() serverx() Right now I'm just printing the data, just to be sure that each dictionary contains the correct data, which it does. But now I need the comparison and I just can't seem to figure it out. I could probably write this in perl or a shell script, but I'm trying really hard to force myself to learn Python so I want this to be a python script, created with only built-in modules. Any help would be greatly appreciated, In place of sun_rec.splitlines() and x_has.splitlines() you can substitute open('sun-patchlist') adn open('serverx-patchlist') respectively, and you can wrap it all in some rountine for your convenience etc. But this shows recommended revs that are either there, missing, and/or have unrecommended revs present. I added some test data to illustrate. You might want to make the input a little more forgiving about e.g. blank lines etc or raise exceptions for what's not allowed or expected. sunpatches.py -- #Here are some sample patches that sun recommends: sun_rec = \ 117000-05 116272-03 116276-01 116278-01 116378-02 116455-01 116602-01 116606-01 testok-01 testok-02 testok-03 test_0-01 test_0-02 test_0-03 test_2-01 test_2-02 test_2-03 test23-02 test23-03 #Here are some sample patches that server x has: x_has = \ 117000-01 116272-02 116272-01 116602-02 testok-01 testok-02 testok-03 test_2-01 test_2-02 test23-01 test23-02 test23-03 def mkdict(lineseq): dct = {} for line in lineseq: patch, rev = line.split('-') dct.setdefault(patch, set()).add(rev) return dct dct_x_has = mkdict(x_has.splitlines()) # or e.g., mkdict(open('sunrecfile.txt')) dct_sun_rec = mkdict(sun_rec.splitlines()) for sunpatch, sunrevs in sorted(dct_sun_rec.items()): xrevs = dct_x_has.get(sunpatch, set()) print 'patch %s: recommended revs %s, missing %s, actual other %s'%( sunpatch, map(str,sunrevsxrevs) or '(none)', map(str,sunrevs-xrevs) or '(none)', map(str,xrevs-sunrevs) or '(none)') -- Result: [12:51] C:\pywk\clppy24 sunpatches.py patch 116272: recommended revs (none), missing ['03'], actual other ['02', '01'] patch 116276: recommended revs (none), missing ['01'], actual other (none) patch 116278: recommended revs (none), missing ['01'], actual other (none) patch 116378: recommended revs (none), missing ['02'], actual other (none) patch 116455: recommended revs (none), missing ['01'], actual other (none) patch 116602: recommended revs (none), missing ['01'], actual other ['02'] patch 116606: recommended revs (none), missing ['01'], actual other (none) patch 117000: recommended revs (none), missing ['05'],
Re: python and glut
Welcome to the exciting world of trying to make graphics work on Linux =) DRI is direct rendering. The Module section of your XF8Config should have: Load glx Load dri Load GLCore That probably won't solve things. Google for some combination of (debian + xfree86 + your video card), and also Google the error messages you get (e.g. XFree86-DRI missing on display ) DRI not working could also be a permissions issue; check to see if it works as root. Once your XFree86 is set up properly, the Python OpenGL bindings should work just fine. -- http://mail.python.org/mailman/listinfo/python-list
UnicodeDecodeError
Hi Fredrik Sorry that I confused u Thomas Thomas wrote:there's no way the tuple creation will generate a UnicodeDecodeErrorall by itself. are you sure the error occurs on that line?u r right, the error is not generated in tuple creation . it generated where join the strings at the line body = CRLF.join(L) what i was trying to saywas how the various tuples behave..if i use file = ('file', filename, data) #it gives me unicode error in this case I am using binary data.. file = ('file', filename, 'data'*100)but the same filename works fine if i pass text data file = ('file', 'test.pdf', data) so if hardcode the file name /use filename=filename.encode("ascii") things work with binary data as well.. I was wondering why.. thanks Thomasimport httplib, mimetypesimport os;def get_content_type(filename): return mimetypes.guess_type(filename)[0] or 'application/octet-stream'filepath= 'c:/Documents and Settings/Administrator/Desktop/tmp/test.pdf';f = open(filepath, "rb")data = "">f.close()(filedir, filename) = os.path.split(filepath)filename=unicode(filename);#file = ('file', filename, data) #This won't work will give a UnicodeDecodeError: 'ascii' codec can't decode byte 0xc7 in position 10: ordinal not in range(128)file = ('file', filename, 'data'*100) #this will work fine#file = ('file', 'test.pdf', data) #This also works finefiles = [file]CRLF = '\r\n'L = []for (key, filename, value) in files: L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename)) L.append(value)body = CRLF.join(L) Do you Yahoo!? Yahoo! Mail - Find what you need with new enhanced search. Learn more.-- http://mail.python.org/mailman/listinfo/python-list
Re: dictionary comparison
On Thu, 5 May 2005 10:37:23 -0700, James Stroud [EMAIL PROTECTED] wrote: [...] We had the same impulse ;-) (see my other post in this thread) # use patch as value and version as key ??? seems the other way around (as it should be?) recc_dct = dict([x.split(-) for x in recc_ary]) serv_dct = dict([x.split(-) for x in serv_ary]) But what about multiple revs for the same patch? Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list
Re: FTP/TLS connection using python
Does anyone know how I can get m2crypto installed on a windows box w/o paying for the installer? I think thats dumb to charge for the windows version and the unix version is free...o well --Barry -- http://mail.python.org/mailman/listinfo/python-list
Re: UnicodeDecodeError
thomas ct wrote: what i was trying to say was how the various tuples behave..if i use file = ('file', filename, data) #it gives me unicode error in this case I am using binary data.. file = ('file', filename, 'data'*100) but the same filename works fine if i pass text data file = ('file', 'test.pdf', data) so if hardcode the file name /use filename=filename.encode(ascii) things work with binary data as well.. I was wondering why.. if you mix a Unicode string with an 80-bit string, Python will try to convert the 8-bit string to a Unicode string, which doesn't work if the string contains characters outside the ASCII set. you have to either encode the Unicode string into an 8-bit string, or decode the non-ASCII string into a Unicode string. /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Challenge ahead [NEW] for riddle lovers
yes, I have done that. i'll keep working on it. thanks -- http://mail.python.org/mailman/listinfo/python-list
Encryption with Python?
I want to save some sensitive data (passwords, PIN numbers, etc.) to disk in a secure manner in one of my programs. What is the easiest/best way to accomplish strong file encryption in Python? Any modern block cipher will do: AES, Blowfish, etc. I'm not looking for public key stuff; I just want to provide a pass-phrase. I found a few modules out there, but they seem to be all but abandoned. Most seem to have died several years ago. The most promising package is A.M. Kuchling's Python Cryptography Toolkit (http://www.amk.ca/python/code/crypto.html). Is this the defacto Python encryption solution? What does everyone else use? Any other suggestions? The SSLCrypto package (http://www.freenet.org.nz/python/SSLCrypto/) may be a good alternative too, but I am not sure if it is actively maintained. Thanks, Blake -- http://mail.python.org/mailman/listinfo/python-list
Re: How to write this regular expression?
D H [EMAIL PROTECTED] wrote: Why do you think you need a regular expression? If another approach that involved no regular expressions worked much better, would you reject it for some reason? A regular expression will work fine for his problem. Just match the digits separated by underscores using a regular expression, then afterward check if the values are valid. you forgot to mention Boo here, Doug. nice IronPython announcement, btw. the Boo developers must be so proud of you. /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Encryption with Python?
Bill Gates us MD5. Hah! Sorry. :-) Blake T. Garretson wrote: I want to save some sensitive data (passwords, PIN numbers, etc.) to disk in a secure manner in one of my programs. What is the easiest/best way to accomplish strong file encryption in Python? Any modern block cipher will do: AES, Blowfish, etc. I'm not looking for public key stuff; I just want to provide a pass-phrase. I found a few modules out there, but they seem to be all but abandoned. Most seem to have died several years ago. The most promising package is A.M. Kuchling's Python Cryptography Toolkit (http://www.amk.ca/python/code/crypto.html). Is this the defacto Python encryption solution? What does everyone else use? Any other suggestions? The SSLCrypto package (http://www.freenet.org.nz/python/SSLCrypto/) may be a good alternative too, but I am not sure if it is actively maintained. Thanks, Blake -- http://mail.python.org/mailman/listinfo/python-list
Re: How to detect a double's significant digits
On Thu, 05 May 2005 18:42:17 +, Charles Krug wrote: On 5 May 2005 10:37:00 -0700, mrstephengross [EMAIL PROTECTED] wrote: Hi all... How can I find out the number of significant digits (to the right of the decimal place, that is) in a double? At least, I *think* that's what I'm asking for. For instance: 0.103 -- 3 0.0103 -- 4 0.00103 -- 5 0.000103 -- 6 0.103 -- 7 Thanks in advance! --Steve ([EMAIL PROTECTED]) I would say that each of these examples has three signficant figures. Each of them can be expressed as: 1.03e+n For any integer n. You beat me to it. Step one for mrstephengross is to *rigorously* define what he means by significant digits, then go from there. Since I think he mentioned something about predicting how much space it will take to print out, my suggestion is to run through whatever printing routines there are and get a string out, the measure the string, as anything else will likely be wrong. If that's not possible with the formatting library, you've already lost; you'll have to completely correctly re-implement the formatting library, and not only is that a major PITA, you almost never get it bug-for-bug right... -- http://mail.python.org/mailman/listinfo/python-list
Re: How to detect a double's significant digits
Jeremy Bowers wrote: Step one for mrstephengross is to *rigorously* define what he means by significant digits, then go from there. Since I think he mentioned something about predicting how much space it will take to print out, my suggestion is to run through whatever printing routines there are and get a string out, the measure the string, as anything else will likely be wrong. If that's not possible with the formatting library, you've already lost; you'll have to completely correctly re-implement the formatting library, and not only is that a major PITA, you almost never get it bug-for-bug right... Especially since all of his examples have the same number of significant digits (3), as the term is usually meant. Zeroes to the right are significant, not zeroes to the left. -- Erik Max Francis [EMAIL PROTECTED] http://www.alcyone.com/max/ San Jose, CA, USA 37 20 N 121 53 W AIM erikmaxfrancis What is it that shapes a species? -- Louis Wu -- http://mail.python.org/mailman/listinfo/python-list
Re: Encryption with Python?
Blake T. Garretson [EMAIL PROTECTED] writes: I want to save some sensitive data (passwords, PIN numbers, etc.) to disk in a secure manner in one of my programs. What is the easiest/best way to accomplish strong file encryption in Python? Any modern block cipher will do: AES, Blowfish, etc. I'm not looking for public key stuff; I just want to provide a pass-phrase. http://www.nightsong.com/phr/crypto/p3.py It uses SHA1 in OFB mode and is fairly fast for a pure Python function. I found a few modules out there, but they seem to be all but abandoned. Most seem to have died several years ago. The most promising package is A.M. Kuchling's Python Cryptography Toolkit (http://www.amk.ca/python/code/crypto.html). Nice toolkit, more flexible and powerful than p3.py, but also more complicated. -- http://mail.python.org/mailman/listinfo/python-list
Re: Encryption with Python?
Blake T. Garretson wrote: I found a few modules out there, but they seem to be all but abandoned. Most seem to have died several years ago. a lack of recent releases can also mean that they just work... Is this the defacto Python encryption solution? What does everyone else use? Any other suggestions? http://sandbox.rulemaker.net/ngps/m2/ is actively maintained, as far as I can tell. you might also be able to find some useful stuff inside: http://trevp.net/tlslite/ (see the utils package for a pure-python AES implementation) /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Hard times with packages and instances
Kay Schluehr wrote: I wonder why the isinstance() function is sensitive about the import path i.e. the result depends not only on the class and the instance but also on how a class is imported? isinstance uses class object identity. if you manage to import the same thing multiple times, you'll have multiple class objects representing the same source code, and is- instance won't work properly. Example: MyPackage/ Top-level package __init__.py Initialize package __me__.py Module used for setting Python-path A.py Use objects of ForeignPackage and subpackages ForeignPackage/ Don't touch! __init__.py Initialize package B.pyDefines class B1 MySubPackage/ Subpackage __init__.py Initialize subpackage C.pyDefines instance checker for B1 instances in my newsreader, it looks like the C.py module is defined some- where inbetween MyPackage and MyPackage/ForeignPackage. what file system are you using? ;-) (I don't have the energy to decipher your convoluted import and path-manipulation code; but my intuition tells me that if you flatten the hierarchy, put MyPackage and ForeignPackage at the same level, and stop messing with the path inside the __init__ files, your problems will just disappear). /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Py2Exe security
I think that encrypt with public/private key will be a solution in your case. I don't know if python has a module to do this kind of encrypt. -- http://mail.python.org/mailman/listinfo/python-list
Re: New Python regex Doc (was: Python documentation moronicities)
I have now also started to rewrite the re-syntax page. At first i thought that page needs not to be rewritten, since its about regex and not really involved with Python. But after another look, that page is as incompetent as every other page of Python documentation. The rewritten page is here: http://xahlee.org/perl-python/python_re-write/lib/re-syntax.html It's not complete, but is a start. The organization is largely taken care of, except the last few paragraphs. The bottom half on capturing and extension syntax i haven't started working on. In particular, they need examples. The repetitions section also needs to be examed. here are few notes on this whole rewriting ordeal. --- In the doc, examples are often given in Python command line interface format, e.g. def f(n): ... return n+1 ... f(1) 2 instead of: def f(n): return n+1 print f(1) # returns 2 the clean format should be used because it does not require familiarity with Python command line, it is more readable, and the code can be copied and run readily. A significant portion of Python doc's readers, if not majority, didn't come to Python as beginning programers, and or one way or another never used or cared about the Python command line interface. Suppose a non-Python programer is casually shown a page of Python doc. She will get much more from the clean example than the version cluttered with Python Command line interface irrelevancies. Suppose now we have a experienced professional Python programer. Upon reading the Python doc, she will also find examples in plain code much more readable and familiar, than the version plastered with Python Command line interface irrelevancies. The only place where the Python command line look-and-feel is appropriate is in the Python tutorial, and arguably only in the beginning sections. - Extra point: If the Python command line interface is actually a robust application, like so-called IDE e.g. Mathematica front-end, then things are very different. In reality, the Python command line interface is a fucking toy whose max use is as a simplest calculator and double as a chanting novelty for standard coding morons. In practice it isn't even suitable as a trial'n'error pad for real-world programing. Extra point: do not use the fucking stupid meaningless jargon interpreter. 90% of its use in the doc should be deleted. They should be replaced with software, program, command line interface, or language or others. (I dare say that 50% of all uses of the word interpreter in computer language contexts are inane. Fathering large amounts of misunderstanding and confusion.) - history of Python are littered all over the doc. e.g. Incompatibility note: in the original Python 1.5 release, maxsplit was ignored. This has been fixed in later releases. 99% of programers really don't need to give a flying fuck about the history of a language. Inevitably software including languages change over time, however conservative one tries to be. So, move all these changes into a New and Incompatible changes page at some appendix of the lang spec. This way, people who are maintaining older code, can find their info and in one coherent place. While, the general programers are not forced to wade thru the details of fuckups or whatnot of the past in every few paragraphs. (few exceptions can be made, when the change is a major fuckup that all practicing Python coders really must be informed regardless whether they maintain old code.) -- do not take a attitude like you have to stick to some artificial format or order or correctness in the doc. Remember, the doc's prime goal is to communicate to programers how a language functions, not how it is implemented or how technically or computer scientifically speaking. In writing a language documentation, there is a question of how to organize it. This is a issue of design, and it takes thinking. When a doc writer is faced with such a challenge, the easiest route is a no-brainer by following the way the language is implemented. For example, the doc will start with data types supported by the language. This no-brainer stupidity is unfortunately how most language docs are organized by, and the Python doc is one of the worst. One can see this phenomenon in the official doc of Python's RE module. For example, it begin with Regex Syntax, then it follows with Module contents, then Regex Objects, then Match Objects. And in each page, the functions or methods are arranged in a alphabetical order. This is typical of the no-brainers organization following how the module is implemented or certain computer scientific logic. It has remote connection to how the module is used to perform a task. In general, language docs should be organize by the tasks it is supposed to accomplish, then by each module or function's functionalities. For example, the RE module doc, organize it by the purposes of the module. To begin, we explain in the outset that this module is