ANN: wxPython 2.6.1.0
Announcing -- The 2.6.1.0 release of wxPython is now available for download at http://wxpython.org/download.php. Anybody keeping track will probably notice that the prior release (2.6.0.1) was released just about a week ago. This short turn-around time is because I was slow getting the last release done, and the wxWidgets team was uncharacteristically early with the 2.6.1 release! This release consists of a few bug fixes made since 2.6.0.1. What is wxPython? - wxPython is a GUI toolkit for the Python programming language. It allows Python programmers to create programs with a robust, highly functional graphical user interface, simply and easily. It is implemented as a Python extension module that wraps the GUI components of the popular wxWidgets cross platform library, which is written in C++. wxPython is a cross-platform toolkit. This means that the same program will usually run on multiple platforms without modifications. Currently supported platforms are 32-bit Microsoft Windows, most Linux or other Unix-like systems using GTK or GTK2, and Mac OS X. Changes in 2.6.1.0 -- wx.ListCtrl: patch #1210352, fixes editing in generic wx.ListCtrl with wx.LC_EDIT_LABELS. Applied patch #208286, MediaCtrl DirectShow rewrite. DocView patches from Morgan Hua: bug fixes, and additional SVN commands, also added a default template that uses the text editor for any unknown file type. wxMSW: Use the system IDC_HAND cursor for wx.CURSOR_HAND and only fallback to the strange wxWidgets version if the system one is not available. wx.grid.Grid: Merge the cell size attribute the same way that other attributes are merged, e.g., if it is already set to a non-default value in the current GridCellAttr object then don't merge from the other. wx.lib.evtmgr: Fixed to use wx._core._wxPyDeadObject wx.lib.gridmovers: Don't scroll when the mouse is dragged outside of the grid, unless the mouse is kept in motion. wxMSW: Applied patch #1213290 incorrect logic in wx.TopLevelWindow.ShowFullScreen. Applied patch #1213066 correct device names for Joystick in Linux. wxGTK: Applied patch #1207162 wx.TextCtrl.SetStyle fix for overlapping calls. wx.FileConfig: fixed DeleteEntry to set the dirty flag properly so the change will get written at the next flush. -- Robin Dunn Software Craftsman http://wxPython.org Java give you jitters? Relax with wxPython! -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Re:
I am reading a only. But what if I want read write and execute that file. -- Regards, Jatinder Singh Everyone needs to be loved... especially when they do not deserve it. XX Quoting Tiago Stürmer Daitx [EMAIL PROTECTED]: That depends on what using a file means. You could check the thread executing a command ( http://mail.python.org/pipermail/python-list/2005-June/283963.html) and see if there's something related there, otherwise it would help if you could post what exactly you are trying to do (execute a file, open a file, write into a file, etc). Regards, Tiago S Daitx On 6/4/05, Jatinder Singh [EMAIL PROTECTED] wrote: Hi guys I am working in a complex directory structure. I want to use a file (not .py) which is in some other directory. I couldn't do it.but if I copy the file in the same directory then it is working fine. Can anybody guide me how and where to add the path of the file. I have tried it with sys.path but it is not for that. -- Regards, Jatinder Singh Everyone needs to be loved... especially when they do not deserve it. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: urllib2 pinger : insight as to use, cause of hang-up?
Mahesh advised: Timing it out will probably solve it. Thanks. Follow-on question regarding implementing a timeout for use by urllib2. I am guessing the simplest way to do this is via socket.setdefaulttimeout(), but I am not sure if this sets a global parameter, and if so, whether it might be reset via instantiations of urllib, urllib2, httplib, etc. I assume socket and the timeout parameter is in the global namespace and that I can just reset it at will for application to all the socket module 'users'. Is that right? (TIA) [experimenting] import urllib2plus urllib2plus.setSocketTimeOut(1) urllib2plus.urlopen('http://zomething.com') Traceback (most recent call last): File pyshell#52, line 1, in -toplevel- urllib2plus.urlopen('http://zomething.com') File C:\Python24\lib\urllib2plus.py, line 130, in urlopen return _opener.open(url, data) File C:\Python24\lib\urllib2plus.py, line 361, in open response = self._open(req, data) File C:\Python24\lib\urllib2plus.py, line 379, in _open '_open', req) File C:\Python24\lib\urllib2plus.py, line 340, in _call_chain result = func(*args) File C:\Python24\lib\urllib2plus.py, line 1024, in http_open return self.do_open(httplib.HTTPConnection, req) File C:\Python24\lib\urllib2plus.py, line 999, in do_open raise URLError(err) URLError: urlopen error timed out urllib2plus.setSocketTimeOut(10) urllib2plus.urlopen('http://zomething.com') addinfourl at 12449152 whose fp = socket._fileobject object at 0x00BE1340 import socket socket.setdefaulttimeout(0) urllib2plus.urlopen('http://zomething.com') Traceback (most recent call last): File pyshell#60, line 1, in -toplevel- urllib2plus.urlopen('http://zomething.com') File C:\Python24\lib\urllib2plus.py, line 130, in urlopen return _opener.open(url, data) File C:\Python24\lib\urllib2plus.py, line 361, in open response = self._open(req, data) File C:\Python24\lib\urllib2plus.py, line 379, in _open '_open', req) File C:\Python24\lib\urllib2plus.py, line 340, in _call_chain result = func(*args) File C:\Python24\lib\urllib2plus.py, line 1024, in http_open return self.do_open(httplib.HTTPConnection, req) File C:\Python24\lib\urllib2plus.py, line 999, in do_open raise URLError(err) URLError: urlopen error (10035, 'The socket operation could not complete without blocking') socket.setdefaulttimeout(1) urllib2plus.urlopen('http://zomething.com') addinfourl at 12449992 whose fp = socket._fileobject object at 0x00BE1420 -- http://mail.python.org/mailman/listinfo/python-list
easiest way to split a list into evenly divisble smaller lists, and assign them to variables?
Lets say I have a list containing 12, 13, 23 or however many entries. What I want is the greatest number of lists evenly divisible by a certain number, and for those lists to be assigned to variables. This leads to a few problems.. If I don't know the length of the list beforehand, I can't create the variables and hardcode them. Is it possible in python to generate free variables without stating them explicitly in the code, and if so, how would you get a reference to them? Secondly, is there an easier way to chop a list up into smaller lists? consider this code: #my_list=[1,2,3,4,5,6,7,8,9,10,11,12,13,14, # 15,16,17,18,19,20,21,22,23,24,25] #entry=0 #dictionary_of_lists = {} #while len(original_list) != 0: #new_list=[] #for x in range(4): #if len(original_list) 0: #new_list.append(files.pop(0)) #dictionary_of_lists[entry] = new_list #entry +=1 would give us {1:[1,2,3,4],2:[5,6,7,8], 3:[9,10,11,12],4:[13,14,15,16], 5:[17,18,19,20],6:[21,22,23,24],7:[25]} Is there a better way? What I'd like to do is create free variables without needing to put them in a dictionary. If not, is it possible in other languages? -thank in advance -- http://mail.python.org/mailman/listinfo/python-list
Re: Socket Speed
Hi Jeff Would you care to do that between two machines on a 100mb link ? M On 6/5/05, Jeff Epler [EMAIL PROTECTED] wrote: 300KB/s sounds dreadfully low. I simply ran python /usr/lib/python2.3/SimpleHTTPServer.py , then wget -O /dev/null http://0.0.0.0:8000/70megfile;. On the best of 4 runs (when the file was cached) wget measured 225.20MB/s. The hardware is a Pentium-M laptop with 768MB RAM runnng at 1.5GHz. The OS is Fedora Core 2, kernel 2.6.12-rc5, Python 2.3. Jeff -- http://mail.python.org/mailman/listinfo/python-list
Re: Socket Speed
Would you care to do that between two machines on a 100mb link ? On 6/5/05, Jeff Epler [EMAIL PROTECTED] wrote: 300KB/s sounds dreadfully low. I simply ran python /usr/lib/python2.3/SimpleHTTPServer.py , then wget -O /dev/null http://0.0.0.0:8000/70megfile;. On the best of 4 runs (when the file was cached) wget measured 225.20MB/s. The hardware is a Pentium-M laptop with 768MB RAM runnng at 1.5GHz. The OS is Fedora Core 2, kernel 2.6.12-rc5, Python 2.3. Jeff -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with pythonpath
Tim Roberts wrote: Observer [EMAIL PROTECTED] wrote: Hi, im a newbie both to python and this list. I hope someone can help me whith this: I have a directory structure like this: . |-- src | `-- pkg | |-- __init__.py | |-- main.py | `-- spkg1 | |-- __init__.py | `-- config.py `-- src2 `-- pkg |-- __init__.py `-- spkg2 |-- __init__.py `-- config2.py and main.py is a python script that contains this imports: from pkg.spkg1 import config from pkg.spkg2 import config2 executed in linux whith this: env PYTHONPATH=src:src2 src/pkg/main.py Traceback (most recent call last): File src/pkg/main.py, line 4, in ? from pkg.spkg2 import config2 ImportError: No module named spkg2 changing the order of the python path only inverts the problem, is there any way to solve this without changing the directory structure? Nope. When Python goes to look for a package called pkg, it starts at the beginning of PYTHONPATH and stops as soon as it finds one. You either need to use different names for the two packages (pkg1, pkg2), or use a symbolic link to link spkg2 into the src directory. If I remember, I think you need to add an __init__.py file just in your directories src src2. Moreover, you can add the path of src and src2 to the variable sys.path at the beginning of your main script (in that case, it not necessary to define PYTHONPATH) I hope I help you Mathieu -- http://mail.python.org/mailman/listinfo/python-list
Re: easiest way to split a list into evenly divisble smaller lists, and assign them to variables?
flamesrock [EMAIL PROTECTED] writes: Lets say I have a list containing 12, 13, 23 or however many entries. What I want is the greatest number of lists evenly divisible by a certain number, and for those lists to be assigned to variables. You almost certainly don't want to do that. That's something beginning programmers often think of doing, but it's almost always better to use something more general, like an array. consider this code: #my_list=[1,2,3,4,5,6,7,8,9,10,11,12,13,14, # 15,16,17,18,19,20,21,22,23,24,25] #entry=0 #dictionary_of_lists = {} #while len(original_list) != 0: Umm, what's original_list? Do you mean my_list? The rest of your code has similar errors. would give us {1:[1,2,3,4],2:[5,6,7,8], 3:[9,10,11,12],4:[13,14,15,16], 5:[17,18,19,20],6:[21,22,23,24],7:[25]} Is there a better way? What I'd like to do is create free variables without needing to put them in a dictionary. Your best bet is probably to create a list of lists: sublist_length = 4# desired length of the inner lists list_of_lists = [] for i in xrange(0, len(my_list), sublist_length): list_of_lists.append(my_list[i: i+sublist_length]) That gives list_of_lists = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], [17, 18, 19, 20], [21, 22, 23, 24], [25]] So you'd just use list_of_lists[0] to refer to the 1st sublist, etc. -- http://mail.python.org/mailman/listinfo/python-list
Re: anygui,anydb, any opinions?
Thomas Bartkus wrote: rzed [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] snip So what do you think? What's wrong with the picture? Why isn't there a greater priority to work in this direction? What's wrong with the picture? Just one teeny little item. The Python world lacks the phenomenally successful development models enjoyed by the now ancient Turbo Pascal, Delphi and gasp Visual Basic. AND If the likes of Visual Basic can have it, then it becomes really, *really* hard to convince the world that Python is a serious, professional system. You mean the wimp gui builder + db - ui pipeline model ? If yes, C doesn't have it, C++ doesn't have it (in fact most languages doesn't have it) - and the fact is that C and C++ are usually considered as much more serious and professionnal than VB and the likes. -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Re:
B and C are subdirectories of Parent Directory A. I am executing a file in Directory C which is importing a file f' in directory B. Now while running python file m getting an error of can't open f'. If I copy f' in current directory B. then It is running. I want to get rid of that and run the programme without copying the other f' files( even .txt also) in the current directory. and I have so many files in directory B,otherwise I wou;ld have wppended the path while opening the file. I don't want to do it for each file and also If i need to change directory structure then also I should change one path and able to run the Programme. Quoting Tiago Stürmer Daitx [EMAIL PROTECTED]: Well, I still quite don't get what you want to do. I mean, you do need to be more specific. Maybe you can post part of your code or explain in details what you are trying to do. Anything that would help me understand what's going on. In the mean time, check these sites... The file section in the Tutorial (there's not much to see, but hey, who knows?): http://www.python.org/doc/current/tut/node9.html#SECTION00920 The online book DiveIntoPython http://diveintopython.org/file_handling/file_objects.html Or some common questions about files (maybe you can find the answer for your troubles - not all of them, of course) =) http://www.faqts.com/knowledge_base/index.phtml/fid/552 Regards, Tiago S Daitx On 6/6/05, Jatinder Singh [EMAIL PROTECTED] wrote: I am reading a only. But what if I want read write and execute that file. -- Regards, Jatinder Singh Everyone needs to be loved... especially when they do not deserve it. XX Quoting Tiago Stürmer Daitx [EMAIL PROTECTED]: That depends on what using a file means. You could check the thread executing a command ( http://mail.python.org/pipermail/python-list/2005-June/283963.html) and see if there's something related there, otherwise it would help if you could post what exactly you are trying to do (execute a file, open a file, write into a file, etc). Regards, Tiago S Daitx On 6/4/05, Jatinder Singh [EMAIL PROTECTED] wrote: Hi guys I am working in a complex directory structure. I want to use a file (not .py) which is in some other directory. I couldn't do it.but if I copy the file in the same directory then it is working fine. Can anybody guide me how and where to add the path of the file. I have tried it with sys.path but it is not for that. -- Regards, Jatinder Singh Everyone needs to be loved... especially when they do not deserve it. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list -- Regards, Jatinder Singh Everyone needs to be loved... especially when they do not deserve it. -- http://mail.python.org/mailman/listinfo/python-list
Re: easiest way to split a list into evenly divisble smaller lists, and assign them to variables?
hmmm..that makes much more sense. thanks :) -- http://mail.python.org/mailman/listinfo/python-list
Re: If - Or statements
Ognjen Bezanov wrote: (snip) filelist = os.listdir('/mnt/cdrom/') #get a list of files from the cdrom drive OT Please put long comments on the previous line... And BTW, please avoid useless comments that just paraphrase the code /OT for thefile in filelist[:]: #for each file in the filelist Do you really need to work on a copy of the list ? if thefile.find(.) != -1: #if the file has an extenstion at all ext = thefile.split('.') #get the file extension ext[1] = ext[1].lower() #convert to lowercase you may want to read the doc of the os.path module. The os.path.splitext() function could save you a lot of work here. print ext[1] #debugging, to see the variable before passed to if statement if ext[1] == mp3 or ext[1] == mp4 or ext[1] == ogg or ext[1] == aac or ext[1] == wma: print we have a valid extension: + ext[1] #here would go the code for decoding the above pass Here's a somewhat more pythonic version: filelist = os.listdir(path) for filename in filelist: # I assume you want to remember what's the ext is ext = os.path.splitext(filename) # debug trace print filename : %s - ext : %s % (filename, ext) if ext in ['.this', '.that', '.whatnot']: print ext is %s - should process this file % ext HTH -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
how to show simulation at web
hi all, I have tried making a simulation with python. I want it to be shown at a web. It is ok when I run it. so, I decided using cgi. but, when I try it using a web browser it doesn't work. Is it problem in the header or something else ? If there are any suggestions about this problem, I will be very happy. thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: how to show simulation at web
Hallo wrote: hi all, I have tried making a simulation with python. I want it to be shown at a web. It is ok when I run it. so, I decided using cgi. but, when I try it using a web browser it doesn't work. Is it problem in the header or something else ? If there are any suggestions about this problem, I will be very happy. First, read this: http://www.catb.org/~esr/faqs/smart-questions.html Then, come back and give us some substantive information about your problem. A small example of code that you think should work, but doesn't, will help us help you. -- 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: Socket Speed
The machines with the 100mbps ethernet link are slightly different---Pentium 4, 2.8GHz, Python 2.2, RedHat 9. File size: 87490278 Best of 4 runs: 7.50 MB/s reported by wget. There was other network activity and system load at the time. Jeff pgpNVPeW3ghJL.pgp Description: PGP signature -- http://mail.python.org/mailman/listinfo/python-list
Review of 'Python Cookbook'
TechBookReport (http://www.techbookreport.com) has just published a review of the Python Cookbook. This is an extract from the full review: We're big fans of cookbooks here at TechBookReport, whether its Java, XSLT or Linux, they're a great way of pulling together lots of useful snippets of code and technique in one place. For the beginner they provide instant advice, usable code and a way into new areas. They're also a great way to find out about coding styles, idioms, common workarounds and how to get the most out of your language (or operating system, development environment or application). Given all of that then it should be no surprise that we love this second edition of the Python Cookbook. There's no doubt about it, this is an indispensable resource to have around. What's more, this latest edition has been enhanced and updated for Python 2.4, and now features more than 330 recipes across 20 chapters. Note that the recipes only cover Python 2.3 and 2.4, for older versions readers should look for the first edition of the book. As with the rest of O'Reilly's cookbooks, this one has a standard format for each recipe: state the problem, present a solution, discuss the solution and provide cross-references and pointers to further material. It's a good format, and allows each recipe to pretty much stand alone, even if there are pointers to other recipes in the 'see also' section. This makes the recipes a useful place to dip into for ideas and examples when hacking your own code. As with a real cookbook this is one that has a practical focus and belongs by your side when cooking not on some shelf gathering dust. Unlike most of the other books in the cookbook series, this one is not the product of one or two authors but very much a community effort, thanks in large part to the involvement of ActiveState. While the three editors deserve credit for the good job they've done putting it all together, it's down to the Python community for creating these recipes and providing the feedback to hone and improve them. Read the rest of the review here: http://www.techbookreport.com/tbr0163.html -- http://mail.python.org/mailman/listinfo/python-list
Re: odbc and python
Giles Brown wrote: MM wrote: Are there any other odbc packages other than the win32all and mxodbc ones? The win32all odbc.pyd can't access table structure info like SQLColumns, and mxobdc requires a commercial license which is unjustifiable for this tiny project. Any other OS alternatives for win32?. Thanks. You could potentially make the ODBC calls using ctypes a la: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303667 Not tried this myself and imagine it could be a bit tedious. Cheers, Giles This is the new version that work very well into my projects: http://unipex.it/vario/RealPyOdbc.py This can work on all the platforms where ctypes work. In the future I'll make it db-api 2.0 compliant. If you have some question, email me directly. Bye, Michele -- http://mail.python.org/mailman/listinfo/python-list
Re: Destructive Windows Script
BTW, since this is a bit off-topic anyway, how do I recover files accidentally removed? Is there a free tool that works on FAT/NTFS and ext2/ext3? Thanks, Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: Destructive Windows Script
On 05 Jun 2005 21:14:37 -0700, rumours say that Paul Rubin http://[EMAIL PROTECTED] might have written: The only way to be 100% sure the data is gone from a drive, is basically to melt the drive. However, if your data is that sensitive, you shouldn't ever write it to a hard drive in the clear anyway. A little healthy insanity never hurt anyone in the security field :) -- TZOTZIOY, I speak England very best. Be strict when sending and tolerant when receiving. (from RFC1958) I really should keep that in mind when talking with people, actually... -- http://mail.python.org/mailman/listinfo/python-list
Re: Destructive Windows Script
Michele Simionato wrote: BTW, since this is a bit off-topic anyway, how do I recover files accidentally removed? Is there a free tool that works on FAT/NTFS and ext2/ext3? On all of those filesystems at the same time? Probably not. But there are tools for each. Google, and ye shall find. -- 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: Destructive Windows Script
The problem is that Google gives me too many non-relevant hits. I just would like something like this: $ rm what-I-think-is-an-useless-file ACK! It was not that useless!! $ recover what-I-think-is-an-useless-file Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: Destructive Windows Script
Michele Simionato wrote: The problem is that Google gives me too many non-relevant hits. google(fat undelete) google(ext2 undelete) -- 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
Computer Cluster Python Software
Is there any open source Python software (preferably biopython) written which runs on a cluster. Alternatively are there interfaces written in Python to existing cluster software. -- http://mail.python.org/mailman/listinfo/python-list
Using IDLE for checking versions
Okay, so I need to find out what version of wxPython is being used on a companies computer. I figured I can do this through IDLE, but I cant find the proper commands. Any help would be appriciated. -- http://mail.python.org/mailman/listinfo/python-list
Re: Computer Cluster Python Software
6 Jun 2005 07:22:54 -0700 skrev uli: Is there any open source Python software (preferably biopython) written which runs on a cluster. Alternatively are there interfaces written in Python to existing cluster software. Can you be more specific? There are for example several MPI interfaces (pyMPI, pypar, ScientificPython.MPI). With pyMPI, you can run python interactively on a cluster if you want. But you are probably looking for something else? btw, soon there will be PyFDM (pyfdm.sf.net) which will make it possible to do FDM on a cluster (or any parallel computer) with little effort. mvh, -- Mandus - the only mandus around. -- http://mail.python.org/mailman/listinfo/python-list
Re: If - Or statements
bruno modulix wrote: Here's a somewhat more pythonic version: filelist = os.listdir(path) for filename in filelist: # I assume you want to remember what's the ext is ext = os.path.splitext(filename) Check the docs[1]. This should probably read: _, ext = os.path.splitext(filename) because splitext returns a pair of (root, ext). # debug trace print filename : %s - ext : %s % (filename, ext) if ext in ['.this', '.that', '.whatnot']: print ext is %s - should process this file % ext STeVe [1] http://docs.python.org/lib/module-os.path.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about Object Oriented + functions/global vars?
flamesrock wrote: ok, so to my knowledge, object oriented means splitting something into the simplest number of parts and going from there. That sounds like normal top down imperative (procedural) programming to me. But the question is- when is it enough? Thats a judgment call on the programmer's part. For example I have the following code: [...snip...] would the lines with '#' best be split up into a seperate function, for example: #def upload(ftp, file): [...snip...] and then doing the call 'upload(file_id)', or is it a better practice to leave things the way they were? I'm confused. Judgment call...=) Finally, is it considered 'un-object-oriented' in python to have functions inside a module that are called by objects (ie the upload function above) and/or use global variables in combination? 1. The upload function is not an object. 2. Functions are made to be called. 3. Some people think globals should be avoided if possible. I think it depends on the size of your project and how much convenience they can give you vs. how much confusion they can potentially cause. -thanks in advance Btw, object oriented programming is the splitting up of the program into things called object which are data and their related methods. Bah, its hard to explain, but its like instead of focusing on functions that manipulate a square, you instead have a square and its related methods. Also, I can't think of OOP without thinking of polymorphism. Ehh, this stuff is too hard for me to explain, it would be easier with examples (but too long for me to write)...=) -- C -- http://mail.python.org/mailman/listinfo/python-list
Re: anygui,anydb, any opinions?
bruno modulix [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Thomas Bartkus wrote: rzed [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] snip So what do you think? What's wrong with the picture? Why isn't there a greater priority to work in this direction? What's wrong with the picture? Just one teeny little item. The Python world lacks the phenomenally successful development models enjoyed by the now ancient Turbo Pascal, Delphi and gasp Visual Basic. AND If the likes of Visual Basic can have it, then it becomes really, *really* hard to convince the world that Python is a serious, professional system. You mean the wimp gui builder + db - ui pipeline model ? If yes, C doesn't have it, C++ doesn't have it (in fact most languages doesn't have it) - and the fact is that C and C++ are usually considered as much more serious and professionnal than VB and the likes. -- http://mail.python.org/mailman/listinfo/python-list
Lost in the inheritance tree...
Can anyone help with this code... I have infinite recursion but since I'm pretty new to Python (and programming in general) I can't find where I did the mistake. Thanks a lot in advance. Adam * import Tkinter class RootFrame(Tkinter.Frame): def __init__(self,parent=None,myHeight=600,myWidth=800,myBd=3,\ myRelief=Tkinter.RIDGE): Tkinter.Frame.__init__\ (self,parent,height=myHeight,width=myWidth,bd=myBd,\ relief=myRelief) self.grid() self.grid_propagate(0) self.createFrames() self.showMsg() def showMsg(self): msg=Tkinter.Label(textFrame,text=Are you thinking of an animal?) msg.grid() def createFrames(self): textFrame=TextFrame(self,300,600) textFrame.grid() textFrame.grid_propagate(0) def createButtons(self): yesButton=Tkinter.Button(self,text=Yes) yesButton.grid(row=1,sticky=Tkinter.E) noButton=Tkinter.Button(self,text=No) noButton.grid(row=1,sticky=Tkinter.W) class TextFrame(RootFrame): def __init__(self,parent,myHeight,myWidth): RootFrame.__init__(self,parent,myHeight,myWidth) rootFrame=RootFrame() rootFrame.mainloop() ___ Yahoo! Messenger - NEW crystal clear PC to PC calling worldwide with voicemail http://uk.messenger.yahoo.com -- http://mail.python.org/mailman/listinfo/python-list
Re: urllib2 pinger : insight as to use, cause of hang-up?
socket.setdefaulttimeout() is what I have used in the past and it has worked well. I think it is set in the global namespace though I could be wrong. I think it retains its value within the module it is called in. If you use it in a different module if will probably get reset though it is easy enough to test that out. -- http://mail.python.org/mailman/listinfo/python-list
Re: Computer Cluster Python Software
Hi Mandus Thanks for your reply. I am looking for an application written in python (preferably a bioinformatics application) which will be able to take advantage of parallel processing on a cluster. I guess what I am asking for is applications which have been written using pyMPI or other python MPI modules. Regards Uli -- http://mail.python.org/mailman/listinfo/python-list
Re: Using IDLE for checking versions
nvm, i found the wxPython directory with __version__.py which told me everything i need to know. -- http://mail.python.org/mailman/listinfo/python-list
Re: If - Or statements
On Sun, 05 Jun 2005 13:52:09 -0400, Roy Smith wrote: One sure sign of somebody trying to write C in Python is when they loop over a list by doing for i in range (len (myList)): doSomethingWith (myList[i]) I usually do that, and I've never coded a line of C in my life. I can't even read C :-) Of course, the main reason I use that form is that I frequently have to use older versions of Python without enumerate, and therefore have got into the practice of doing without it. Of course, if I'm just reading the items of myList, I don't bother with the index, and just use for item in myList: dosomethingwith(item) or when they laboriously check for every possible error condition before performing an operation instead of just doing it and catching the exception. This is not always a bad idea. For example, if you are modifying an object in place, and an error halfway through could leave the object in an inconsistent state, it may be better to check for error conditions first rather than try to back out of it after you've run into trouble. But still, in general I agree with your observation. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Lost in the inheritance tree...
Adam Munoz Lopez wrote: Can anyone help with this code... I have infinite recursion but since I'm pretty new to Python (and programming in general) I can't find where I did the mistake. It really does help to start removing things trying to get the minimal code which causes the problem. (untested snippage follows) * import Tkinter class RootFrame(Tkinter.Frame): def __init__(self,parent=None,myHeight=600,myWidth=800,myBd=3,\ myRelief=Tkinter.RIDGE): self.createFrames() def createFrames(self): textFrame=TextFrame(self,300,600) class TextFrame(RootFrame): def __init__(self,parent,myHeight,myWidth): RootFrame.__init__(self,parent,myHeight,myWidth) rootFrame=RootFrame() It appears you create a RootFrame, which creates a TextFrame, which initilizes as a RootFrame, thus creating a TextFrame which initilizes as a RootFrame, thus creating a TextFrame which -- http://mail.python.org/mailman/listinfo/python-list
Re: anygui,anydb, any opinions?
Previously, on Jun 6, Thomas Bartkus said: # bruno modulix [EMAIL PROTECTED] wrote in message # news:[EMAIL PROTECTED] # You mean the wimp gui builder + db - ui pipeline model ? If yes, C # doesn't have it, C++ doesn't have it (in fact most languages doesn't # have it) - and # # the fact is that C and C++ are usually considered as much # more serious and professionnal than VB and the likes. # # Yes but there is another fact that must be considered. # Systems like VB (and the likes) are much more *productive* . # # The secret of that particular success has nothing to do with the language # and everything to do with the integrated GUI / IDE available to that # particular (VB) language. That's pretty arguable. C/C++ has no shortage of integrated GUI/IDE available especially if your willing to fork out the same kind of books that you would need to for VB. # # Anything that reduces the overhead involved in producing a # consistent/attractive/idiot proof user interface makes a far more # productive environment. # # Thomas Bartkus My 2 cents, I'm much more productive with Python and QT Builder as I am with VB and those aren't nearly as intergrated as VB's GUI/IDE. A language's productivity, I believe, rests on how high or low-level the language and its libraries are. Not just that though, productivity is also very much affected by the breadth of the libraries available. Sure, GUI RAD solutions increase development in a very real way, but you can find an offering for just about every language out there these days. # # -- # http://mail.python.org/mailman/listinfo/python-list # --- James Tanis [EMAIL PROTECTED] http://pycoder.org -- http://mail.python.org/mailman/listinfo/python-list
Re: Software licenses and releasing Python programs for review
On Sun, 05 Jun 2005 03:57:29 -0400, Terry Reedy wrote: Robert Kern [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Mike Meyer wrote: I've heard people argue otherwise on this case. In particular, if you allow an employee to use your GPL'ed-but-not-distributed software, they are the end user, and have all the rights granted by the GPL. So they can distribute the software - possibly to your competitors. Employment contracts can't prohibit this, because the GPL specifically disallows distribution (allowing your employee to use the software) under licenses that restrict the rights granted by the GPL. Well, the FSF at least thinks that internal use within an organization does not constitute distribution. The fact that GPL effectively discriminates in favor of large corporations (and other organizations) and programmers employed by such (versus those contracting with such), is something I don't like about it. I'm sorry, I don't follow your reasoning here. How does the GPL discriminate in favour of large corporations? What advantage does the corporation get that I don't get? The way I see it, if my left hand and right hand both use the software, that isn't distribution. And if Acme Inc's accounting department and sales department both use the software, that shouldn't count as distribution either, in precisely the same way that there has been no transfer of ownership when Fred from Accounting takes an unused computer from Sales and starts using it himself. This seems contrary to the spirit of the thing. It certainly supports the myth that organizations are 'people'. By law, corporations (and possibly some other organisations) *are* people. Not natural people like you or I, but nevertheless people. For good or bad, this is the legal fact (or perhaps legal fiction) in most countries, and not a myth. What if a whole country claimed to be 'one organization' (as the entire Soviet Union once was, in a real sense). I doubt that was ever the case, not even in a figurative sense. But for the sake of the argument, I'll accept that (say) the country of Freedonia might claim the entire population of Freedonia to be a single organisation. Could it distribute modifications 'privately' while denying such to the rest of the world? Freedonia is a country. Unless some other country takes them on, they can do whatever they like within their borders because they make the laws. Of course, they may run foul of international law, and may suffer the consequences, which may range from angry words in the UN to trade sanctions to a blockade all the way to invasion (although probably not over some random piece of GPLed code). But this is hardly a problem unique to the GPL. What if you publish code under the BSD licence, and Freedonia rips your copyright notice out of it and tries to pass it off as their own creation? What if Microsoft licences Freedonia some software under Shared Source, and they promptly modify and distribute the source code? When nation states decide they are beyond the law, or subject only to whatever laws it is convenient for them to follow, no licence will protect you. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Lost in the inheritance tree...
Although you get infinite recursion with this code, you still get enough information on the error from the interpreter to help you debug. Running IDLE, I get a traceback of: File C:/Documents and Settings/Jordan/Desktop/more_blah.py, line 11, in __init__ self.createFrames() File C:/Documents and Settings/Jordan/Desktop/more_blah.py, line 19, in createFrames textFrame=TextFrame(self,300,600) File C:/Documents and Settings/Jordan/Desktop/more_blah.py, line 31, in __init__ RootFrame.__init__(self,parent,myHeight,myWidth) repeated indefinitely. At a glance, this tells you: * That __init__ (of the RootFrame method) calls self.createFrames() * createFrames(), in turn, calls TextFrame(self,300,600) * This leads to RootFrame.__init__ being called once more So theres youre infinite recursion. RootFrame's __init__ calls createFrames which creates a new TextFrame - meaning TextFrame.__init__ gets called, and this calls its parent's __init__ method, and so on ad infinitum. This is a pretty good demonstration of the prinicple that you should do as little as is nessecary to create an object - if possible, try to calling other methods on an object in its __init__ method. Without knowing more about youre program, and with only limited GUI building experience (and none in Python), I'd guess the most likely solution is for TextFrame to inherit from Tkinter.Frame directly - having it inheret from RootFrame doesn't really make much sense as far as I can see. TextFrame is, I would guess, intended as a component of RootFrame, not a subclass. Thats another important OO prinicple - don't overuse inheritance, often simple composition (one object having another as an attribute) is the right solution. If TextFrame really is supposed to inherit from RootFrame, try to explain why. -- http://mail.python.org/mailman/listinfo/python-list
Re: Lost in the inheritance tree... THANKS!
Thanks a lot for your quick response. I actually just found the answer by myself before reading your reply. Just printed out the code and read it. The mistake was pretty obvious then. Yes, Ill try your suggestion. I was just trying to experiment a bit with inheritance to understand how it works better. Once again thanx a lot. Its the first time I post and Im pretty impressed by the speed with which you guys replied. Adam. --- Jordan Rastrick [EMAIL PROTECTED] wrote: Although you get infinite recursion with this code, you still get enough information on the error from the interpreter to help you debug. Running IDLE, I get a traceback of: File C:/Documents and Settings/Jordan/Desktop/more_blah.py, line 11, in __init__ self.createFrames() File C:/Documents and Settings/Jordan/Desktop/more_blah.py, line 19, in createFrames textFrame=TextFrame(self,300,600) File C:/Documents and Settings/Jordan/Desktop/more_blah.py, line 31, in __init__ RootFrame.__init__(self,parent,myHeight,myWidth) repeated indefinitely. At a glance, this tells you: * That __init__ (of the RootFrame method) calls self.createFrames() * createFrames(), in turn, calls TextFrame(self,300,600) * This leads to RootFrame.__init__ being called once more So theres youre infinite recursion. RootFrame's __init__ calls createFrames which creates a new TextFrame - meaning TextFrame.__init__ gets called, and this calls its parent's __init__ method, and so on ad infinitum. This is a pretty good demonstration of the prinicple that you should do as little as is nessecary to create an object - if possible, try to calling other methods on an object in its __init__ method. Without knowing more about youre program, and with only limited GUI building experience (and none in Python), I'd guess the most likely solution is for TextFrame to inherit from Tkinter.Frame directly - having it inheret from RootFrame doesn't really make much sense as far as I can see. TextFrame is, I would guess, intended as a component of RootFrame, not a subclass. Thats another important OO prinicple - don't overuse inheritance, often simple composition (one object having another as an attribute) is the right solution. If TextFrame really is supposed to inherit from RootFrame, try to explain why. -- http://mail.python.org/mailman/listinfo/python-list ___ Yahoo! Messenger - NEW crystal clear PC to PC calling worldwide with voicemail http://uk.messenger.yahoo.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Adding a command to a Pmw.counter widget
Martin Franklin wrote: Mark Light wrote: Hi, I have a Pmw.Counter widget and I would like to add a command that is called on pressing either the up or down arrows (the command will be the same for both). I have managed to do this for the entryfield with entryfield_command = , but can't get the same to work for the arrows, could someone help me out with how to do this. Looking at the source for the PmwCounter it doesn't look like it exposes the buttons callbacks. I think the best way to do this would be to provide a validator method to the Counter's entryfield. The validator gets called whenever the entryfields value changes. Example validator methods are included in the Pmw documentation. Martin Thanks - this put me on the right track -- http://mail.python.org/mailman/listinfo/python-list
Re: Software licenses and releasing Python programs for review
Steven D'Aprano [EMAIL PROTECTED] wrote in news:[EMAIL PROTECTED]: By law, corporations (and possibly some other organisations) *are* people. Not natural people like you or I, but nevertheless people. For good or bad, this is the legal fact (or perhaps legal fiction) in most countries, and not a myth. s/myth/legal absurdity/ This is one thing that bothers me about the gpl. It essentially tries to create 'code as a legal entity'. That is, it gives rights not to the creator of some code, but to the code itself. For me, the fact that corporations are considered people by the law is ridiculous. Using a license that ends up doing the same thing with code leaves a bad taste in my mouth. max -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about Object Oriented + functions/global vars?
Well, if you want to apply object orientatation techniques to your work you would get something like this. Polymorphism is used to distinct between the ftp method. Another concept is data encapsulation, see the filedescription class . A third technique is inheritance - ftp is derived from an existing object, the get classes are derived from my ftp class. But most of all it is a different way of organizing your work, for your code I think it makes sense to split the work between an ftp class and a filedescrition class - where you can add methods to record the status of the retrieval. #!/usr/bin/env python import ftplib import os.path import sys class ftp_err(Exception): pass class ftp(ftplib.FTP): def __init__(self, address, filedescription, user = None, password = None): ftplib.FTP.__init__(self, address) self.login(user, password) self.filedescription = filedescription def list(self): return self.nlst() def cd(self, directory): self.cwd(directory) def quit(self): self.quit() class ftp_get(ftp): def get(self): cmd = 'RETR %s' % self.filedescription.name self.retrlines(cmd, open(self.filedescription.name, 'w').write) class ftp_get_binary(ftp): def get(self): cmd = 'RETR %s' % self.filedescription.name self.retrbinary(cmd, open(self.filedescription.name, 'wb').write) class filedescription(object): def set_name(self, name): self.__name = name def get_name(self): return self.__name name = property(get_name, set_name) def _get_texttype(self): ext = os.path.splitext(self.name)[1] if ext in ('.txt', '.htm', '.html'): return True else: return False def get_texttype(self): return self._get_texttype() text = property(get_texttype) def get_binarytype(self): return not self._get_texttype() binary = property(get_binarytype) f1 = filedescription() f1.name = 'download.ht' f2 = filedescription() f2.name = 'download.html' ftp_site = 'ftp.python.org' ftp_dir = 'pub/docs.python.org' for i in (f1, f2): try: f = None if i.text: f = ftp_get(ftp_site, i) elif i.binary: f = ftp_get_binary(ftp_site, i) f.cd(ftp_dir) f.get() except Exception, e: print sys.stderr, '%s: %s' % (e.__class__.__name__, e) -- http://mail.python.org/mailman/listinfo/python-list
Re: maybe a bug in python
If you have any doubts, try to remeber this when creating tuples, if a tuple is to have 0 elements, then it must be given as a=() in other words, the ( and the ) are essential if it has one element, then a comma after that element is essential a=1, or alternatively a=(1,) in other words, an end comma is essential but the parentheses are not if it has more than one element, comma between the elements is only essential a=1,2 or alternatively a=1,2, or alternatively a=(1,2) i might have made some silly mistake so wait till some one points it out (if the mistakes are there) :) flyaflya wrote: a = {1: (a)} a[1] 'a' why not ('a')? when a = {1: (((a)))} a[1] 'a' the result is 'a' too,not (((a))).but when use[a] or (a,b),the tuple is longer than 1, it's no problem. To define a tuple literal with one member, you must place a comma after the first element like this: a = {1: (a,)} I read this somewhere in the python docs, so I know its there somewhere. The comma eliminates ambiguity as to the meaning of the brackets, which without the comma are simply enclosing and precedence controlling brackets. Steve -- http://mail.python.org/mailman/listinfo/python-list
Re: Lost in the inheritance tree... THANKS!
comp.lang.python is a great newsgroup in that respect - so long as you ask a semi-intelligent question, you nearly always end up with a quick and helpful response. Good luck with learning programming, and Python (IMO its one of the best possible languages to do it in) -- http://mail.python.org/mailman/listinfo/python-list
Re: Software licenses and releasing Python programs for review
On Mon, 06 Jun 2005 16:12:18 +, max wrote: This is one thing that bothers me about the gpl. It essentially tries to create 'code as a legal entity'. That is, it gives rights not to the creator of some code, but to the code itself. Can you please show me where in the GPL it gives rights to the code itself? Because, frankly, I think you are mistaken. Of course, I might be wrong in this instance, and I always welcome corrections. For me, the fact that corporations are considered people by the law is ridiculous. Ridiculous? I don't think so. Take, for example, Acme Inc. Acme purchases a new factory. Who owns the factory? The CEO? The Chairperson of the Board of Directors? Split in equal shares between all the directors? Split between all the thousands of shareholders? Society has to decide between these methods. (Of course, society can choose to hedge its bets by creating multiple entities that use different rules, such as partnerships, trusts, public corporations, limited corporations, etc.) None of these alternatives are *wrong*, but they all have various disadvantages. The legal fiction that corporations are legally persons is a work-around for these disadvantages, and it works quite well in many circumstances. To call it ridiculous is, well, ridiculous. Ownership is a legal fiction in any case, so it is no more ridiculous to say that a collective entity such as a corporation owns property than it is to say that an individual being owns property. However, if you wanted to argue that giving corporations all the privileges of legal personhood with none of the responsibilities caused more harm than good, I would agree with you. I take it you've seen The Corporation? Using a license that ends up doing the same thing with code leaves a bad taste in my mouth. Of course you are free to use some other licence. But without evidence, I do not accept that the GPL attempts to give rights to code. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: how to get name of function from within function?
posted mailed Hey again Steven, I'm still having problems... Steven Bethard wrote: Something like this might work: py class C(object): ... def func_a(self): ... print func_a ... def func_b_impl(self): ... print func_b ... raise Exception ... def __getattr__(self, name): ... func = getattr(self, '%s_impl' % name) ... wrapped_func = self._impl_wrapper(func) ... setattr(self, name, wrapped_func) ... return wrapped_func ... def _impl_wrapper(self, func): ... def wrapper(*args, **kwargs): ... try: ... return func(*args, **kwargs) ... except: ... print entered except ... raise ... return wrapper ... py c = C() py c.func_a() func_a py c.func_b() func_b entered except Traceback (most recent call last): File interactive input, line 1, in ? File interactive input, line 15, in wrapper File interactive input, line 6, in func_b_impl Exception The idea here is that __getattr__ is called whenever the class doesn't have a particular function. The __getattr__ method then tries to find a corresponding _impl function, wraps it with appropriate try/except code, and returns the wrapped function. The problem is: c.func_b.__name__ 'wrapper' That messes up SOAPpy's RegisterFunction() method which apparently depends on the __name__ of the function to publish it as an available SOAP function. Any suggestions on how to change the name of c.func_b to 'func_b' instead of 'wrapper'? HTH, STeVe Thanks a bunch, -- C -- http://mail.python.org/mailman/listinfo/python-list
Using PAMIE to upload and download files...is it possible?
Ive been using PAMIE 1.4 to try to automate web page processes. The one thing I cannot do with it is upload files and download files. With uploading files, the file input box does not allow PAMIE to enter in a path to a file. With downloading files, I can click on the link to download the file, but thats where I get stuck at. It brings up that download window and then it brings up the where to save window. Theres no errors that I encounter when I get stuck at these spots it justs sits there not knowing what to do. If anyone has had success in both uploading or downloading or even some insight, I would greatly appreciate your help. Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Reading a CSV file into a list of dictionaries
Hi, I'm struggling here to do the following with any success: I have a comma delimited file where each line in the file is something like: PNumber,3056,Contractor,XYZ Contracting,Architect,ABC Architects,... So each line is intended to be: key1,value1,key2,value2,key3,value3... and each line is to be variable in length (although it will have to be an even number of records so that each key has a value). I want to read in this csv file and parse it into a list of dictionaries. So each record in the list is a dictionary: {PNumber:3056,Contractor:XYZ Contracting, ... } I have no problem reading in the CSV file to a list and splitting each line in the file into its comma separated values. But I can't figure out how to parse each resulting list into a dictionary. Any help on this? -- http://mail.python.org/mailman/listinfo/python-list
About size of Unicode string
Hi all! I need know the size of string object independently of its encoding. For example: len('123') == len('123'.encode('utf_8')) while the size of '123' object is different of the size of '123'.encode('utf_8') More: I need send in HTTP request a string. Then I need know the length of the string to set the header content-length independently of its encoding. Any idea? Thanks in advance Frank -- http://mail.python.org/mailman/listinfo/python-list
Re: Software licenses and releasing Python programs for review
On Sat, Jun 04, 2005 at 11:49:28PM -0700, Robert Kern wrote: Well, the FSF at least thinks that internal use within an organization does not constitute distribution. Well, the problem are contractors. It's very important (for example in Germany) for a number of legal reasons that contractors are separate from the organization. This basically makes it a case of distribution. And while the GPL FAQ claims that this is not a problem, it seems only to handle the easy case: Company X gives a standard SP to contractor C, and C returns SP2. While this is okay, the problems start when X discovers that it wants to distribute SP2 to contractor C2, because it has to do this under the GPL. Contractor C2 might by free will refrain from distributing SP2, but putting that as a requirement on paper would violate the GPL. Basically having a GPLed internal program limits what a company might do with it in the future ;) Andreas -- http://mail.python.org/mailman/listinfo/python-list
Re: Reading a CSV file into a list of dictionaries
RFQ wrote: Hi, I'm struggling here to do the following with any success: I have a comma delimited file where each line in the file is something like: PNumber,3056,Contractor,XYZ Contracting,Architect,ABC Architects,... So each line is intended to be: key1,value1,key2,value2,key3,value3... and each line is to be variable in length (although it will have to be an even number of records so that each key has a value). I want to read in this csv file and parse it into a list of dictionaries. So each record in the list is a dictionary: {PNumber:3056,Contractor:XYZ Contracting, ... } I have no problem reading in the CSV file to a list and splitting each line in the file into its comma separated values. But I can't figure out how to parse each resulting list into a dictionary. First, don't process the CSV stuff yourself. Use the csv module. In [9]:import csv In [10]:f = open('foo.csv') In [11]:cr = csv.reader(f) In [12]:for row in cr: :print dict(zip(row[::2], row[1::2])) : {'Architect': 'ABC Architects', 'PNumber': '3056', 'Contractor': 'XYZ Contracting'} {'Architect': 'ABC Architects', 'PNumber': '3056', 'Contractor': 'XYZ Contracting'} [etc.] -- 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: random module question
Can I rely on the random.py module to produce the same series of numbers for future/past versions of Python, given the same seed? The answer is a qualified Yes. While the core generator (currently the Mersenne Twister algorithm) is subject to change across versions, whenever we've updated the generator, a backward compatable version is offered (random.WichmannHill for example). So, it should always be possible to recreate a series but you may have to change the calling code to point to the correct generator. Can I rely on it across different architectures and operating systems? The current Mersenne Twister algorithm is guaranteed to produce the same results across different architectures and operating systems. That is evident from the test suite which verifies a bit-by-bit match to a target test sequence (the test is expected to pass on all C boxes with at least 53 bit floating point precision). Of course, none of the above applies to random.SystemRandom which accesses system generated entropy sources. Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list
Re: Reading a CSV file into a list of dictionaries
RFQ wrote: I have a comma delimited file where each line in the file is something like: PNumber,3056,Contractor,XYZ Contracting,Architect,ABC Architects,... So each line is intended to be: key1,value1,key2,value2,key3,value3... and each line is to be variable in length (although it will have to be an even number of records so that each key has a value). I want to read in this csv file and parse it into a list of dictionaries. So each record in the list is a dictionary: {PNumber:3056,Contractor:XYZ Contracting, ... } row ['PNumber', '3056', 'Contractor', 'XYZ Contracting', 'Architect', 'ABC'] dict(zip(row[::2], row[1::2])) {'Architect': 'ABC', 'PNumber': '3056', 'Contractor': 'XYZ Contracting'} A bit more elegant: irow = iter(row) dict(zip(irow, irow)) {'Architect': 'ABC', 'PNumber': '3056', 'Contractor': 'XYZ Contracting'} Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: About size of Unicode string
Frank Abel Cancio Bello wrote: Hi all! I need know the size of string object independently of its encoding. For example: len('123') == len('123'.encode('utf_8')) while the size of '123' object is different of the size of '123'.encode('utf_8') More: I need send in HTTP request a string. Then I need know the length of the string to set the header content-length independently of its encoding. Any idea? This is from the RFC: The Content-Length entity-header field indicates the size of the entity-body, in decimal number of OCTETs, sent to the recipient or, in the case of the HEAD method, the size of the entity-body that would have been sent had the request been a GET. Content-Length= Content-Length : 1*DIGIT An example is Content-Length: 3495 Applications SHOULD use this field to indicate the transfer-length of the message-body, unless this is prohibited by the rules in section 4.4 http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.4. Any Content-Length greater than or equal to zero is a valid value. Section 4.4 describes how to determine the length of a message-body if a Content-Length is not given. Looks to me that the Content-Length header has nothing to do with the encoding. It is a very low levet stuff. The content length is given in OCTETs and it represents the size of the body. Clearly, it has nothing to do with MIME/encoding etc. It is about the number of bits transferred in the body. Try to write your unicode strings into a StringIO and take its length Laci -- http://mail.python.org/mailman/listinfo/python-list
Re: how to get name of function from within function?
Christopher J. Bottaro wrote: Steven Bethard wrote: ... def _impl_wrapper(self, func): ... def wrapper(*args, **kwargs): ... try: ... return func(*args, **kwargs) ... except: ... print entered except ... raise ... return wrapper ... [snip] The problem is: c.func_b.__name__ 'wrapper' That messes up SOAPpy's RegisterFunction() method which apparently depends on the __name__ of the function to publish it as an available SOAP function. Hmm... Nasty. If you were using Python 2.4, you could simply write it as: def _impl_wrapper(self, func): def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except: print entered except raise wrapper.__name__ = func.__name__ return wrapper Where you fix up the wrapper's __name__ attribute. But I believe the __name__ attribute is read-only in Python 2.3... STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: Software licenses and releasing Python programs for review
Steven D'Aprano [EMAIL PROTECTED] wrote in news:[EMAIL PROTECTED]: On Mon, 06 Jun 2005 16:12:18 +, max wrote: This is one thing that bothers me about the gpl. It essentially tries to create 'code as a legal entity'. That is, it gives rights not to the creator of some code, but to the code itself. Can you please show me where in the GPL it gives rights to the code itself? Because, frankly, I think you are mistaken. Of course, I might be wrong in this instance, and I always welcome corrections. For me, the fact that corporations are considered people by the law is ridiculous. Ridiculous? I don't think so. Take, for example, Acme Inc. Acme purchases a new factory. Who owns the factory? The CEO? The Chairperson of the Board of Directors? Split in equal shares between all the directors? Split between all the thousands of shareholders? Society has to decide between these methods. (Of course, society can choose to hedge its bets by creating multiple entities that use different rules, such as partnerships, trusts, public corporations, limited corporations, etc.) None of these alternatives are *wrong*, but they all have various disadvantages. The legal fiction that corporations are legally persons is a work-around for these disadvantages, and it works quite well in many circumstances. To call it ridiculous is, well, ridiculous. Ownership is a legal fiction in any case, so it is no more ridiculous to say that a collective entity such as a corporation owns property than it is to say that an individual being owns property. However, if you wanted to argue that giving corporations all the privileges of legal personhood with none of the responsibilities caused more harm than good, I would agree with you. I take it you've seen The Corporation? I haven't seen The Corporation, but yes, I was reaching for the priviledges/responsibilities balance. Using a license that ends up doing the same thing with code leaves a bad taste in my mouth. Of course you are free to use some other licence. But without evidence, I do not accept that the GPL attempts to give rights to code. Perhaps 'attempts' is too strong a word. Maybe 'ends up giving' would help my argument more. The best example I can come up with at the moment is programmer A releases a project under the gpl. Programmer B makes a substantial contribution to the project, which pA reads through and accepts. Later, pA decides that he would like to release the project under a more liberal license. To me, whether he legally can under the gpl is a very murky subject, as pB might not agree, and pA, having looked through/thought about pB's contribution might have some trouble proving that he implemented any matching functionality without referencing pB's earlier contribution, which if he did reference it(even by memory), would presumably require him to continue using the gpl. I guess my argument is that with multiple contributors, the gpl, in comparison to say, a BSD style license, grants power to the code. If 3 people work on a gpl project, they must agree to any changes. If 3 people work on a BSD style project, they each can do whatever the hell they like with the code. So, in my opinion, the gpl ends up giving perhaps not rights, but certainly power, to the actual code base. Based on the limited coherence of this answer I probably need to think about it somemore, max -- http://mail.python.org/mailman/listinfo/python-list
Re: maybe a bug in python
venkata subramanian wrote: If you have any doubts, try to remeber this when creating tuples, if a tuple is to have 0 elements, then it must be given as a=() in other words, the ( and the ) are essential if it has one element, then a comma after that element is essential a=1, or alternatively a=(1,) in other words, an end comma is essential but the parentheses are not if it has more than one element, comma between the elements is only essential a=1,2 or alternatively a=1,2, or alternatively a=(1,2) That actually looks like a pretty good summary. I've posted it, with a few elaborations at: http://wiki.python.org/moin/TupleSyntax STeVe -- http://mail.python.org/mailman/listinfo/python-list
the python way?
Hi All, I've been lurking the list for a month and this is my first post. I am hoping this post is appropriate here, otherwise, my apologies. I'm somewhat new to Python, (I'm reading all the tutorials I can find, and have read through Andre Lessa's Developers Handbook.) I am trying to learn the Python way of thinking as well as the syntax. I popped this bit of code together for fun, based on a previous post regarding randomizing a word. This shuffles a word, then splits out the vowels and then reassembles it with the vowels interpolated between consonants. (To create plausible sounding gibberish) The code just seems kind of bulky to me. I am wondering, is this an efficient way to do things, or am I making things harder than necessary? #--begin code-- scrambles a word, but creates plausable gibberish import random def shuffled(s): scrambles word l = list(s) random.shuffle(l) return ''.join(l) def contains(alist,b): ...is letter b in list a... ret = [] for all in alist: #print all if all==b: return 1 return 0 def newZip(a1,a2): reassemble l1=len(a1) l2=len(a2) longest = [a1,a2][l1l2] shortest = [a1,a2][longest == a1] diff = max(l1,l2)-min(l1,l2) #print longest seq = len(longest) ret = for j in range(seq): if len(longest)0: ret = ret + longest.pop() if len(shortest)0: ret = ret + shortest.pop() return ret def reinterpolate(word): main function wlist = shuffled(list(word)) vlist = list('aeiouy') # ok, y isn't really a vowel, but... vees = filter(lambda x: contains(vlist,x),wlist) cons = filter(lambda x: not(contains(vlist,x)),wlist) a=list(vees) b=list(cons) return newZip(a,b) word = encyclopedia print reinterpolate(word) #---end code--- BTW: I'm just curious, is there an easier way to copy-paste code snippets from the interpreter so that it removes the '... ' and the ' ' from the examples? I'm using cntrl-H search and replace now which works, but if there is a better way, I'd like to know. thanks in advance, -J -- http://mail.python.org/mailman/listinfo/python-list
Re: idiom for constructor?
How about just doing this: class Foo(object): __slots__ = ('a','b','c','d') def __init__(self, *args): for (name, arg) in zip(self.__slots__, args): setattr(self, name, arg) --T -- http://mail.python.org/mailman/listinfo/python-list
Re: idiom for constructor?
And you probably should add: ... def __init__(self, *args): assert len(args) == len(self.__slots__) ... --T -- http://mail.python.org/mailman/listinfo/python-list
Re: Software licenses and releasing Python programs for review
max: For me, the fact that corporations are considered people by the law is ridiculous. Steven D'Aprano wrote: Ridiculous? I don't think so. Take, for example, Acme Inc. Acme purchases a new factory. Who owns the factory? The CEO? The Chairperson of the Board of Directors? Split in equal shares between all the directors? Split between all the thousands of shareholders? Society has to decide between these methods. Getting off-topic for c.l.py. Might want to move this to, for example, the talk thread for http://en.wikipedia.org/wiki/Corporate_personhood which is http://en.wikipedia.org/wiki/Talk:Corporate_personhood and read also http://en.wikipedia.org/wiki/Corporation Andrew [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: About size of Unicode string
Well I will repeat the question: Can I get how many bytes have a string object independently of its encoding? Is the len function the right way of get it? Laci look the following code: import urllib2 request = urllib2.Request(url= 'http://localhost:6000') data = 'data to send\n'.encode('utf_8') request.add_data(data) request.add_header('content-length', str(len(data))) request.add_header('content-encoding', 'UTF-8') file = urllib2.urlopen(request) Is always true that the size of the entity-body is len(data) independently of the encoding of data? -Original Message- From: Laszlo Zsolt Nagy [mailto:[EMAIL PROTECTED] Sent: Monday, June 06, 2005 1:43 PM To: Frank Abel Cancio Bello; python-list@python.org Subject: Re: About size of Unicode string Frank Abel Cancio Bello wrote: Hi all! I need know the size of string object independently of its encoding. For example: len('123') == len('123'.encode('utf_8')) while the size of '123' object is different of the size of '123'.encode('utf_8') More: I need send in HTTP request a string. Then I need know the length of the string to set the header content-length independently of its encoding. Any idea? This is from the RFC: The Content-Length entity-header field indicates the size of the entity-body, in decimal number of OCTETs, sent to the recipient or, in the case of the HEAD method, the size of the entity-body that would have been sent had the request been a GET. Content-Length= Content-Length : 1*DIGIT An example is Content-Length: 3495 Applications SHOULD use this field to indicate the transfer-length of the message-body, unless this is prohibited by the rules in section 4.4 http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.4. Any Content-Length greater than or equal to zero is a valid value. Section 4.4 describes how to determine the length of a message-body if a Content-Length is not given. Looks to me that the Content-Length header has nothing to do with the encoding. It is a very low levet stuff. The content length is given in OCTETs and it represents the size of the body. Clearly, it has nothing to do with MIME/encoding etc. It is about the number of bits transferred in the body. Try to write your unicode strings into a StringIO and take its length Laci -- http://mail.python.org/mailman/listinfo/python-list
Requirements for Software Coding Standards?
Does anyone have any knowledge of where to find details of docs like Requirements for Software Coding Standards, etc applicable for work within the US govt (preferably non-military). Thanks in advance Dr Tim Couper UK -- No virus found in this outgoing message. Checked by AVG Anti-Virus. Version: 7.0.322 / Virus Database: 267.6.2 - Release Date: 04/06/2005 attachment: winmail.dat-- http://mail.python.org/mailman/listinfo/python-list
Re: how to get name of function from within function?
posted mailed Christopher J. Bottaro wrote: The problem is: c.func_b.__name__ 'wrapper' That messes up SOAPpy's RegisterFunction() method which apparently depends on the __name__ of the function to publish it as an available SOAP function. Any suggestions on how to change the name of c.func_b to 'func_b' instead of 'wrapper'? Nevermind, I looked at the SOAPpy source, they provide a way to manually specify the SOAP method name that is published. Thanks anyways, -- C -- http://mail.python.org/mailman/listinfo/python-list
Re: the python way?
Grops wrote: The code just seems kind of bulky to me. I am wondering, is this an efficient way to do things, or am I making things harder than necessary? Harder than necessary. contains() is not needed at all, you can test for 'b in alist' directly. List comprehensions simplify reinterpolate(), and you have a lot of redundant calls to list(). Here is a shorter version: scrambles a word, but creates plausable gibberish import random def shuffled(s): scrambles word l = list(s) random.shuffle(l) return ''.join(l) def newZip(a1,a2): reassemble l1=len(a1) l2=len(a2) longest, shortest = [[a1,a2], [a2,a1]][l1l2] diff = max(l1,l2)-min(l1,l2) seq = len(longest) ret = for j in range(seq): if len(longest)0: ret += longest.pop() if len(shortest)0: ret += shortest.pop() return ret def reinterpolate(word): main function wlist = shuffled(word) vlist = 'aeiouy' # ok, y isn't really a vowel, but... vees = [ x for x in wlist if x in vlist ] cons = [ x for x in wlist if x not in vlist ] return newZip(vees,cons) word = encyclopedia print reinterpolate(word) Kent #--begin code-- scrambles a word, but creates plausable gibberish import random def shuffled(s): scrambles word l = list(s) random.shuffle(l) return ''.join(l) def contains(alist,b): ...is letter b in list a... ret = [] for all in alist: #print all if all==b: return 1 return 0 def newZip(a1,a2): reassemble l1=len(a1) l2=len(a2) longest = [a1,a2][l1l2] shortest = [a1,a2][longest == a1] diff = max(l1,l2)-min(l1,l2) #print longest seq = len(longest) ret = for j in range(seq): if len(longest)0: ret = ret + longest.pop() if len(shortest)0: ret = ret + shortest.pop() return ret def reinterpolate(word): main function wlist = shuffled(list(word)) vlist = list('aeiouy') # ok, y isn't really a vowel, but... vees = filter(lambda x: contains(vlist,x),wlist) cons = filter(lambda x: not(contains(vlist,x)),wlist) a=list(vees) b=list(cons) return newZip(a,b) word = encyclopedia print reinterpolate(word) #---end code--- -- http://mail.python.org/mailman/listinfo/python-list
Re: the python way?
Grops wrote: Hi All, I've been lurking the list for a month and this is my first post. I am hoping this post is appropriate here, otherwise, my apologies. I'm somewhat new to Python, (I'm reading all the tutorials I can find, and have read through Andre Lessa's Developers Handbook.) I am trying to learn the Python way of thinking as well as the syntax. I popped this bit of code together for fun, based on a previous post regarding randomizing a word. This shuffles a word, then splits out the vowels and then reassembles it with the vowels interpolated between consonants. (To create plausible sounding gibberish) The code just seems kind of bulky to me. I am wondering, is this an efficient way to do things, or am I making things harder than necessary? #--begin code-- scrambles a word, but creates plausable gibberish import random def shuffled(s): scrambles word l = list(s) random.shuffle(l) return ''.join(l) def contains(alist,b): ...is letter b in list a... ret = [] for all in alist: #print all if all==b: return 1 return 0 contains(alist, b) can be more easily written as b in alist def newZip(a1,a2): reassemble l1=len(a1) l2=len(a2) longest = [a1,a2][l1l2] shortest = [a1,a2][longest == a1] longest, shortest = sorted([a1, a2], key=len) diff = max(l1,l2)-min(l1,l2) #print longest seq = len(longest) ret = Don't build up strings using +. Create a list of strings, and use str.join at the end. for j in range(seq): if len(longest)0: The len() 0 is unnecessary, simply use: if longest: ret = ret + longest.pop() if len(shortest)0: if shortest: ret = ret + shortest.pop() return ret If I understand you right, you want to do the usual thing zip does, but guaraneeing that the first element is always from the longer list, and not throwing away elements. Note that map(None, ...) probably does what you want: longest, shortest = sorted([a1, a2], key=len, reverse=True) return ''.join(item for pair in map(None, longest, shortest) for item in pair if item is not None) def reinterpolate(word): main function wlist = shuffled(list(word)) vlist = list('aeiouy') # ok, y isn't really a vowel, but... no need to make vlist a list; contains should work fine on strings. vees = filter(lambda x: contains(vlist,x),wlist) vees = [c in vlist for c in wlist] cons = filter(lambda x: not(contains(vlist,x)),wlist) cons = [c not in vlist for c in wlist] a=list(vees) b=list(cons) The above are unnecessary. vees and cons are already lists. return newZip(a,b) word = encyclopedia print reinterpolate(word) So I think overall, my rewrite of your code would look something like (untested): def reinterpolate(word) wlist = list(word) random.shuffle(wlist) vlist = 'aeiouy' vees = [c for c in wlist if c in vlist] cons = [c for c in wlist if c not in vlist] longest, shortest = sorted([vees, cons], key=len) return ''.join(item for pair in map(None, longest, shortest) for item in pair if item is not None) -- http://mail.python.org/mailman/listinfo/python-list
Re: the python way?
Grops wrote: Hi All, I've been lurking the list for a month and this is my first post. I am hoping this post is appropriate here, otherwise, my apologies. I'm somewhat new to Python, (I'm reading all the tutorials I can find, and have read through Andre Lessa's Developers Handbook.) I am trying to learn the Python way of thinking as well as the syntax. I popped this bit of code together for fun, based on a previous post regarding randomizing a word. This shuffles a word, then splits out the vowels and then reassembles it with the vowels interpolated between consonants. (To create plausible sounding gibberish) To make it short, my version is: import random def reinterpolate2(word, vocals='aeiouy'): wlist = list(word) random.shuffle(wlist) vees = [c for c in wlist[::-1] if c in vocals] cons = [c for c in wlist[::-1] if c not in vocals] short, long = sorted((cons, vees), key=len) return ''.join(long[i] + short[i] for i in range(len(short))) + ''.join(long[len(short):]) The code just seems kind of bulky to me. I am wondering, is this an efficient way to do things, or am I making things harder than necessary? Some comments on your code: #--begin code-- scrambles a word, but creates plausable gibberish import random def shuffled(s): scrambles word l = list(s) random.shuffle(l) return ''.join(l) You can define this function separately, but needn't. def contains(alist,b): ...is letter b in list a... ret = [] for all in alist: #print all if all==b: return 1 return 0 That is entirely unnecessary - use b in alist :) def newZip(a1,a2): reassemble l1=len(a1) l2=len(a2) longest = [a1,a2][l1l2] shortest = [a1,a2][longest == a1] diff = max(l1,l2)-min(l1,l2) diff = abs(l2-l1) would be shorter. #print longest seq = len(longest) ret = for j in range(seq): if len(longest)0: ret = ret + longest.pop() ret += longest.pop() comes to mind. if len(shortest)0: ret = ret + shortest.pop() return ret def reinterpolate(word): main function wlist = shuffled(list(word)) shuffled() will make a list itself, so list() is superfluous here. vlist = list('aeiouy') # ok, y isn't really a vowel, but... vees = filter(lambda x: contains(vlist,x),wlist) Use a list comprehension here, like above. cons = filter(lambda x: not(contains(vlist,x)),wlist) a=list(vees) b=list(cons) return newZip(a,b) word = encyclopedia print reinterpolate(word) #---end code--- -- http://mail.python.org/mailman/listinfo/python-list
Re: Software licenses and releasing Python programs for review
On Mon, Jun 06, 2005 at 06:08:36PM -, max wrote: I guess my argument is that with multiple contributors, the gpl, in comparison to say, a BSD style license, grants power to the code. If 3 people work on a gpl project, they must agree to any changes. If 3 people work on a BSD style project, they each can do whatever the hell they like with the code. So, in my opinion, the gpl ends up giving perhaps not rights, but certainly power, to the actual code base. Well, but it's not comparable: GPL without copyright assignment just leads to community-owned projects. Every part-owner owns his part. And it makes relicensing (taking the project closed-source) very difficult. That's a design feature, not a bug ;) Andreas -- http://mail.python.org/mailman/listinfo/python-list
OT: Survey facing design patterns and communication
Hello everybody! We are a group of students at Freie Universitaet Berlin. As part of our computer science studies we are going to do a survey facing the use of design patterns in communication. Examples of design patterns are Abstract Factory, Singleton, Composite, Iterator and Listener. If you know what we are talking about, you are welcome to take part in our survey. It takes about 5 minutes to fill out the form. Just jump to: http://study.beatdepot.de If you agree, we will send you the results of our survey. Thanks in advance for your participation! And sorry for the interruption of your discussion. -- http://mail.python.org/mailman/listinfo/python-list
Re: random module question
Raymond Hettinger [EMAIL PROTECTED] writes: Can I rely on the random.py module to produce the same series of numbers for future/past versions of Python, given the same seed? The answer is a qualified Yes. While the core generator (currently the Mersenne Twister algorithm) is subject to change across versions, whenever we've updated the generator, a backward compatable version is offered (random.WichmannHill for example). Is Mersenne Twister currently available at all in Jython, for example? -- http://mail.python.org/mailman/listinfo/python-list
Re: Destructive Windows Script
Dennis Lee Bieber [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] My previous facility didn't even accept mil-spec wipes -- all disk drives leaving the facility had to go through a demagnitizer, OT but I am curious: does a metallic case act as a metallic shield, so that the case needs to be opened to do this? (Conversely, is a magnet near a disk drive a danger to it?) wiped everything, including control tracks, and played bleep with the R/W head and positioning magnets. I take this to mean the the drive is non-functional and might have well been melted, except that demagnetising is cheaper. TJR -- http://mail.python.org/mailman/listinfo/python-list
Re: the python way?
Wow... Thanks for all the tips guys... I will study the above examples. ...down to 8 lines of exquisitely readable code... Wow... Python rocks... (still aspiring to greatness myself,) cheers, -John x=[ohndes,j,wu,x[1][0]+x[0][:3]+chr(((len(x))*16))+x[2]+x[0][2:]+`round(1)`[1]+x[3][17]+x[0][0]+chr(ord(x[0][2])-1)] print eval(x[3]) -- http://mail.python.org/mailman/listinfo/python-list
Re: Software licenses and releasing Python programs for review
max wrote: Perhaps 'attempts' is too strong a word. Maybe 'ends up giving' would help my argument more. The best example I can come up with at the moment is programmer A releases a project under the gpl. Programmer B makes a substantial contribution to the project, which pA reads through and accepts. Later, pA decides that he would like to release the project under a more liberal license. To me, whether he legally can under the gpl is a very murky subject, as pB might not agree, and pA, having looked through/thought about pB's contribution might have some trouble proving that he implemented any matching functionality without referencing pB's earlier contribution, which if he did reference it(even by memory), would presumably require him to continue using the gpl. I guess my argument is that with multiple contributors, the gpl, in comparison to say, a BSD style license, grants power to the code. If 3 people work on a gpl project, they must agree to any changes. If 3 people work on a BSD style project, they each can do whatever the hell they like with the code. So, in my opinion, the gpl ends up giving perhaps not rights, but certainly power, to the actual code base. There's no power being granted to code. All of the power is in the hands of pA and pB. If pA wants a more liberal license to pB's code, then he needs to ask for one. pB can grant that permission (assuming the code is his and not actually pC's). There's nothing special about the GPL in this respect. The same situation works with the BSD license, too, although the BSD license is pretty much rock-bottom in terms of restrictions such that there's almost never a *desire* to ask for more permissions. The code has never been granted any legal powers. It's still just contributors. -- 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: Destructive Windows Script
On 2005-06-06, Terry Reedy [EMAIL PROTECTED] wrote: OT but I am curious: does a metallic case act as a metallic shield, It depends on the metal and the case thickness. Thin sheet-aluminum provides virtually no magnetic shielding. Some good thick iron plate will provide shielding. so that the case needs to be opened to do this? No. (Conversely, is a magnet near a disk drive a danger to it?) Yes, if it's strong enough. wiped everything, including control tracks, and played bleep with the R/W head and positioning magnets. I take this to mean the the drive is non-functional and might have well been melted, except that demagnetising is cheaper. Yup. -- Grant Edwards grante Yow! Why are these at athletic shoe salesmen visi.comfollowing me?? -- http://mail.python.org/mailman/listinfo/python-list
RE: About size of Unicode string
Frank Abel Cancio Bello wrote: Can I get how many bytes have a string object independently of its encoding? Is the len function the right way of get it? No. len(unicode_string) returns the number of characters in the unicode_string. Number of bytes depends on how the unicode character are represented. Different encodings will use different numbers of bytes. u = uG\N{Latin small letter A with ring above} u u'G\xe5' len(u) 2 u.encode(utf-8) 'G\xc3\xa5' len(u.encode(utf-8)) 3 u.encode(latin1) 'G\xe5' len(u.encode(latin1)) 2 u.encode(utf16) '\xfe\xff\x00G\x00\xe5' len(u.encode(utf16)) 6 Laci look the following code: import urllib2 request = urllib2.Request(url= 'http://localhost:6000') data = 'data to send\n'.encode('utf_8') request.add_data(data) request.add_header('content-length', str(len(data))) request.add_header('content-encoding', 'UTF-8') file = urllib2.urlopen(request) Is always true that the size of the entity-body is len(data) independently of the encoding of data? For this case it is true because the logical length of 'data' (which is a byte string) is equal to the number of bytes in the string, and the utf-8 encoding of a byte string with character values in the range 0-127, inclusive, is unchanged from the original string. In general, as if 'data' is a unicode strings, no. len() returns the logical length of 'data'. That number does not need to be the number of bytes used to represent 'data'. To get the bytes you must encode the object. Andrew [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
EnumKey vs EnumValue
I'm having trouble getting any responses back from the following snippet, where I am just trying to read some data from the Windows Registry. I intend to do a little bit more with this but will work on that later, but I think I can get more data back from EnumValue, I'd like to see the differences between them. I am running Python 2.3 on XP and can get a response from EnumKey, but EnumValue returns nothing at all; the key listing even returns 0 keys when it prints out the status. But EnumKey returns the right number and even prints out the keys I expect, I copied some of this from the Cookbook and can't tell what might be the problem. Thanks for any help. - M - from _winreg import * findkey = raw_input(What key do you want to look for? ) key = SOFTWARE\\+findkey machine = ConnectRegistry(None,HKEY_LOCAL_MACHINE) regpath = OpenKey(machine,key) print Looking for,key for i in range(25): try: regEndeca = EnumKey(regpath,i) print regEndeca except EnvironmentError: print There are, i,keys under,key break print That was using EnumKey. for j in range(25): try: regstr,value,type = EnumValue(regpath,j) print regstr,value,type except EnvironmentError: print There are, j,keys under,key break print That was using EnumValue. -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for Image, Audio and Internet/Web HOTWO's or tutorials
thanks. It's a huuuge list -- http://mail.python.org/mailman/listinfo/python-list
split up a list by condition?
Hi, while writing my solution for The python way?, I came across this fragment: vees = [c for c in wlist[::-1] if c in vocals] cons = [c for c in wlist[::-1] if c not in vocals] So I think: Have I overlooked a function which splits up a sequence into two, based on a condition? Such as vees, cons = split(wlist[::-1], lambda c: c in vocals) Reinhold -- http://mail.python.org/mailman/listinfo/python-list
Re: About size of Unicode string
Frank Abel Cancio Bello wrote: request.add_header('content-encoding', 'UTF-8') The Content-Encoding header is for things like gzip, not for specifying the text encoding. Use the charset parameter to the Content-Type header for that, as in Content-Type: text/plain; charset=utf-8. -- http://mail.python.org/mailman/listinfo/python-list
Re: Destructive Windows Script
Terry Reedy wrote: Dennis Lee Bieber [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] My previous facility didn't even accept mil-spec wipes -- all disk drives leaving the facility had to go through a demagnitizer, OT but I am curious: does a metallic case act as a metallic shield, so that the case needs to be opened to do this? (Conversely, is a magnet near a disk drive a danger to it?) Absolutely. Small HDD's (like laptops) are especially vulnerable to magnetic force. -- http://mail.python.org/mailman/listinfo/python-list
Re: the python way?
Reinhold Birkenfeld wrote: To make it short, my version is: import random def reinterpolate2(word, vocals='aeiouy'): wlist = list(word) random.shuffle(wlist) vees = [c for c in wlist[::-1] if c in vocals] cons = [c for c in wlist[::-1] if c not in vocals] Why the [::-1]? If it's randomly shuffled the order isn't important. short, long = sorted((cons, vees), key=len) return ''.join(long[i] + short[i] for i in range(len(short))) + ''.join(long[len(short):]) All the cool kids are using 2.4 these days. :) Another way to write this is (assuming the order of characters can be swapped) N = min(len(short), len(long)) return (''.join( [c1+c2 for (c1, c2) in zip(cons, vees)] + cons[N:] + vees[N:]) The main change here is that zip() stops when the first iterator finishes so there's no need to write the 'for i in range(len(short))' If the order is important then the older way is if len(cons) = len(vees): short, long = vees, cons else: short, long = cons, vees return (''.join( [c1+c2 for (c1, c2) in zip(short, long)] + long[len(short):]) 'Course to be one of the cool kids, another solution is to use the roundrobin() implementation found from http://www.python.org/sf/756253 from collections import deque def roundrobin(*iterables): pending = deque(iter(i) for i in iterables) while pending: task = pending.popleft() try: yield task.next() except StopIteration: continue pending.append(task) With it the last line becomes return ''.join(roundrobin(short, long)) Anyone know if/when roundrobin() will be part of the std. lib? The sf tracker implies that it won't be. Andrew [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Destructive Windows Script
Terry Reedy [EMAIL PROTECTED] writes: On *nix, one could open '/dev/rawdisk' (actual name depends on the *nix build) and write a tracks worth of garbage for as many tracks as there are. I don't how to programmaticly get the track size and number (if there is a standard way at all). Modern Unix systems assume drives don't care much about geometry, what with sector forwarding and variable track lengths and the like. Just open the raw disk device (assuming your Unix has such), and start writing data to it. Keep going until the write fails at the end of the media. 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
Re: Destructive Windows Script
Mike Meyer wrote: Terry Reedy [EMAIL PROTECTED] writes: On *nix, one could open '/dev/rawdisk' (actual name depends on the *nix build) and write a tracks worth of garbage for as many tracks as there are. I don't how to programmaticly get the track size and number (if there is a standard way at all). Modern Unix systems assume drives don't care much about geometry, what with sector forwarding and variable track lengths and the like. Just open the raw disk device (assuming your Unix has such), and start writing data to it. Keep going until the write fails at the end of the media. mike Wouldn't /dev/urandom or /dev/random on Linux systems work better? It's the kernel's built in random number generator. It'd fill the drive with random bits of data. You could loop it too... in fact, I think many of the pre-packaged *wipe* programs are mini Linux distros that do just this. dd if=/dev/random of=/dev/your_hard_drive -- http://mail.python.org/mailman/listinfo/python-list
Re: anygui,anydb, any opinions?
James Tanis [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Previously, on Jun 6, Thomas Bartkus said: # bruno modulix [EMAIL PROTECTED] wrote in message # news:[EMAIL PROTECTED] # You mean the wimp gui builder + db - ui pipeline model ? If yes, C # doesn't have it, C++ doesn't have it (in fact most languages doesn't # have it) - and # # the fact is that C and C++ are usually considered as much # more serious and professionnal than VB and the likes. # # Yes but there is another fact that must be considered. # Systems like VB (and the likes) are much more *productive* . # # The secret of that particular success has nothing to do with the language # and everything to do with the integrated GUI / IDE available to that # particular (VB) language. That's pretty arguable. C/C++ has no shortage of integrated GUI/IDE available especially if your willing to fork out the same kind of books that you would need to for VB. # # Anything that reduces the overhead involved in producing a # consistent/attractive/idiot proof user interface makes a far more # productive environment. # # Thomas Bartkus My 2 cents, I'm much more productive with Python and QT Builder as I am with VB and those aren't nearly as intergrated as VB's GUI/IDE. A language's productivity, I believe, rests on how high or low-level the language and its libraries are. Not just that though, productivity is also very much affected by the breadth of the libraries available. When scripting, Windows or Linux, I also am much more productive with Python. When automating a process for another human being, I am much more productive with a RAD tool like VB. The effort involved in creating the user front end simply overwhelms all the considerable efficiencies of Python. When I code wxPython, I find I want to use VB to create/model my user interface. Once I prototype my Windows (Frames!) using VB, I can then xlate this to wxPython code. What I couldn't do without the VB IDE was visualize and experiment with the impact of various layouts *before* I lay down code. It is simply too onerous to experiment by code manipulation and too easy to swish around visually with a mouse. When I use a GUI designer like wxGlade, I still find it awkward enough to merit prototyping with the VB IDE and then mimic the windows I create with wxGlade. Sure, GUI RAD solutions increase development in a very real way, but you can find an offering for just about every language out there these days. Yes. But the tools available for Python are still primitive compared to RAD tools like Delphi/Visual Studio. I still don't know enough wxPython to understand what the barriers are to creating a RAD visual design and construction tool similar to the Visual Studio environment. My ravings here are simply the result of a suspicion - - The suspicion is that the only barrier is the Python (and Linux!) communities grossly underestimating the value of such an undertaking. Thomas Bartkus -- http://mail.python.org/mailman/listinfo/python-list
Re: Destructive Windows Script
On 2005-06-06, rbt [EMAIL PROTECTED] wrote: Just open the raw disk device (assuming your Unix has such), and start writing data to it. Keep going until the write fails at the end of the media. Wouldn't /dev/urandom or /dev/random on Linux systems work better? Maybe. Last time I found an article on the subject (should have kept a copy), it suggested certain patterns for the initial passes, and then random data for the last passes. The data is converted into one of several RLL encodings (which encoding depends on the drive). The optimal erase patterns depended on the encoding used, so you have to use a several different patterns to cover all the bases. Googling for secure disk erase pattern rll encoding... Here's a good but somewhat old paper: http://www.cypherus.com/resources/docs/shred.htm and here's a newer one that deals more with secure deletion of individual files: http://www.usenix.org/events/sec01/full_papers/bauer/bauer_html/ and finally the US Navy's take on the issue: http://www.fas.org/irp/doddir/navy/5239_26.htm It's the kernel's built in random number generator. It'd fill the drive with random bits of data. The really random device will block when it runs out of entropy. It will probably take the kernel a _long_ time to generate a disk's worth of random data. The pseudo-random device won't block, but the results aren't quite as secure. You could loop it too... in fact, I think many of the pre-packaged *wipe* programs are mini Linux distros that do just this. dd if=/dev/random of=/dev/your_hard_drive -- Grant Edwards grante Yow! I always liked FLAG at DAY!! visi.com -- http://mail.python.org/mailman/listinfo/python-list
wxPython: GridBagSizer, EXPAND, and HtmlListBox
I'm having some trouble using an HtmlListBox with a GridBagSizer. I'm not sure how best to explain what's happening, but it seems that every time my frame gets resized, the HtmlListBox grows taller, even when the resize is only horizontal, or makes the frame smaller. I'm pretty new to GUI layout and wxPython, so hopefully I'm doing something obviously wrong. Here's a short runnable code sample showing my basic layout (I'm using python 2.3.3 and wxPython 2.6 running on windows XP pro): -Start Code- import wx class TestFrame(wx.Frame): def __init__(self): app = wx.PySimpleApp() wx.Frame.__init__(self, None, -1) p = wx.Panel(self, -1) gbs = wx.GridBagSizer(5, 5) gbs.Add(wx.Button(p, -1), (0, 0), span=(1, 2), flag=wx.EXPAND) hlb = wx.HtmlListBox(p, -1) gbs.Add(hlb, (1, 0), span=(4, 1), flag=wx.EXPAND) gbs.Add(wx.Button(p, -1), (1, 1), flag=wx.EXPAND) gbs.Add(wx.Button(p, -1), (2, 1), flag=wx.EXPAND) gbs.Add(wx.Button(p, -1), (3, 1), flag=wx.EXPAND) gbs.Add(wx.Button(p, -1), (4, 1), flag=wx.EXPAND) gbs.AddGrowableRow(2) gbs.AddGrowableCol(1) p.SetSizerAndFit(gbs) self.SetClientSize(p.GetSize()) self.Show(True) wx.EVT_SIZE(hlb, self.onSize) app.MainLoop() def onSize(self, event): print event.GetSize() if __name__ == '__main__': TestFrame() -End Code- If you run that and try to resize the window by dragging an edge, the HtmlListBox just goes crazy and keeps getting bigger (try dragging the right edge back and forth). It does the same thing if I replace the HtmlListBox with a wx.Panel or even a wx.Window, but not with a wx.ListBox, or wx.Button. The effect I'm trying to accomplish is basically what you get if you sub in a wx.ListBox, (but I need the HtmlListBox because I want to put a small image next to the strings in the list). Removing the wx.EXPAND flag on the HtmlListBox (at line 11) solves the weird resizing, except that now the HtmlListBox doesn't fill the space it needs to. Does anyone know what's going on here, or how I can get this to work? -- http://mail.python.org/mailman/listinfo/python-list
RE: About size of Unicode string
Thanks to all. Andrew's answer was an excellent explanation. Thanks Leif for you suggestion. -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Leif K-Brooks Sent: Monday, June 06, 2005 4:29 PM To: python-list@python.org Subject: Re: About size of Unicode string Frank Abel Cancio Bello wrote: request.add_header('content-encoding', 'UTF-8') The Content-Encoding header is for things like gzip, not for specifying the text encoding. Use the charset parameter to the Content-Type header for that, as in Content-Type: text/plain; charset=utf-8. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: anygui,anydb, any opinions?
Previously, on Jun 6, Thomas Bartkus said: # James Tanis [EMAIL PROTECTED] wrote in message # news:[EMAIL PROTECTED] # Previously, on Jun 6, Thomas Bartkus said: # # # bruno modulix [EMAIL PROTECTED] wrote in message # # news:[EMAIL PROTECTED] # # You mean the wimp gui builder + db - ui pipeline model ? If yes, C # # doesn't have it, C++ doesn't have it (in fact most languages doesn't # # have it) - and # # # # the fact is that C and C++ are usually considered as much # # more serious and professionnal than VB and the likes. # # # # Yes but there is another fact that must be considered. # # Systems like VB (and the likes) are much more *productive* . # # # # The secret of that particular success has nothing to do with the # language # # and everything to do with the integrated GUI / IDE available to that # # particular (VB) language. # # That's pretty arguable. C/C++ has no shortage of integrated GUI/IDE # available especially if your willing to fork out the same kind of books # that you would need to for VB. # # # # # Anything that reduces the overhead involved in producing a # # consistent/attractive/idiot proof user interface makes a far more # # productive environment. # # # # Thomas Bartkus # # My 2 cents, I'm much more productive with Python and QT Builder as I # am with VB and those aren't nearly as intergrated as VB's GUI/IDE. A # language's productivity, I believe, rests on how high or low-level the # language and its libraries are. Not just that though, productivity is # also very much affected by the breadth of the libraries available. # # When scripting, Windows or Linux, I also am much more productive with # Python. # When automating a process for another human being, I am much more productive # with a RAD tool like VB. The effort involved in creating the user front end # simply overwhelms all the considerable efficiencies of Python. # # When I code wxPython, I find I want to use VB to create/model my user # interface. Once I prototype my Windows (Frames!) using VB, I can then xlate # this to wxPython code. What I couldn't do without the VB IDE was visualize # and experiment with the impact of various layouts *before* I lay down code. # It is simply too onerous to experiment by code manipulation and too easy to # swish around visually with a mouse. # # When I use a GUI designer like wxGlade, I still find it awkward enough to # merit prototyping with the VB IDE and then mimic the windows I create with # wxGlade. # # Sure, GUI RAD solutions increase development in a very real way, but you # can find an offering for just about every language out there these days. # # Yes. But the tools available for Python are still primitive compared to RAD # tools like Delphi/Visual Studio. I still don't know enough wxPython to # understand what the barriers are to creating a RAD visual design and # construction tool similar to the Visual Studio environment. # My ravings here are simply the result of a suspicion - # # - The suspicion is that the only barrier is the Python (and Linux!) # communities grossly underestimating the value of such an undertaking. # Thomas Bartkus # Hmm, it's not that simple though. Unfortunately efforts get spread among the various projects, wxPython is only one among many. You seem set on wxPython, and its true, RAD projects based around that toolkit still seem to be in alpha/beta stages, but that does not go for all the toolkits. There are no barriers that I know of, but your comparing an application (vb) that has been 11+ years with one (wxglade) that has been around what.. maybe three years? # # # -- # http://mail.python.org/mailman/listinfo/python-list # --- James Tanis [EMAIL PROTECTED] http://pycoder.org -- http://mail.python.org/mailman/listinfo/python-list
Re: Controlling source IP address within urllib2
John, Thanks for your input. I can kind of see the light in this, but I'm having difficulty knowing where the do_open method comes from. Also, I'll need to follow redirects, so I assume then I would add a HTTPRedirectHandler instance to the urllib2.build_opener. (?) Thanks again for your help. -Dan -- http://mail.python.org/mailman/listinfo/python-list
help with sending mail in Program
Hey i'm new here and relatively new to python. I've made a few small programs and now I'm making a program for my friends that at the end has a feedback form. I want to send the feedback back to my email adress. I know I should use the SMTP module and I have figured out how to send with it, but I can't figure out how to include my variables in it, such as the questions I ask them. Can someone explain this to me? -Ivan _ On the road to retirement? Check out MSN Life Events for advice on how to get there! http://lifeevents.msn.com/category.aspx?cid=Retirement -- http://mail.python.org/mailman/listinfo/python-list
Re: Destructive Windows Script
rbt [EMAIL PROTECTED] writes: Mike Meyer wrote: Terry Reedy [EMAIL PROTECTED] writes: On *nix, one could open '/dev/rawdisk' (actual name depends on the *nix build) and write a tracks worth of garbage for as many tracks as there are. I don't how to programmaticly get the track size and number (if there is a standard way at all). Modern Unix systems assume drives don't care much about geometry, what with sector forwarding and variable track lengths and the like. Just open the raw disk device (assuming your Unix has such), and start writing data to it. Keep going until the write fails at the end of the media. mike Wouldn't /dev/urandom or /dev/random on Linux systems work better? Well, that would certainly make a good source for the data you write. It's the kernel's built in random number generator. It'd fill the drive with random bits of data. You could loop it too... in fact, I think many of the pre-packaged *wipe* programs are mini Linux distros that do just this. dd if=/dev/random of=/dev/your_hard_drive That works. You may want to set a block size for performance reasons. 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
[wxPython] How to change deafult tab traversing (radiobuttons panel)
Hello! I want change default tab traversing in my app. But i don't know how to do it :( Belowe i include simple example - i want change default tab order: radiobutton mode11 - radiobutton mode31 - button OK I can't find any option, flag, or another way. I try use wx.EVT_KEY_DOWN macro, or Bind - but without success. When i use Borland Builder C++ i must only set tabStop=False sorry for my english ! w.p. ### import wx class MyFrame(wx.Frame): def __init__(self, parent, title): wx.Frame.__init__(self, parent, -1, title) mainPanel = wx.Panel(self) mainSizer = wx.BoxSizer(wx.VERTICAL) panel1=wx.Panel(mainPanel,style=wx.TAB_TRAVERSAL|wx.SUNKEN_BORDER,size=(200,100)) mainSizer.Add(panel1,flag=wx.ALL,border=5) panel2=wx.Panel(mainPanel,style=wx.TAB_TRAVERSAL|wx.SUNKEN_BORDER,size=(200,100)) mainSizer.Add(panel2,flag=wx.ALL,border=5) # group 1 gridSiz1 = wx.FlexGridSizer(2,2) panel1.SetSizer(gridSiz1) self.rb11 = wx.RadioButton(panel1, -1, style=wx.RB_GROUP, label=mode 11) self.rb12 = wx.RadioButton(panel1, -1, label=mode 12) self.rb21 = wx.RadioButton(panel1, -1, style=wx.RB_GROUP, label=mode 21) self.rb22 = wx.RadioButton(panel1, -1, label=mode 22) gridSiz1.Add(self.rb11,flag=wx.ALL,border=3) gridSiz1.Add(self.rb12,flag=wx.ALL,border=3) gridSiz1.Add(self.rb21,flag=wx.ALL,border=3) gridSiz1.Add(self.rb22,flag=wx.ALL,border=3) # group 2 gridSiz2 = wx.FlexGridSizer(2,2) panel2.SetSizer(gridSiz2) self.rb31 = wx.RadioButton(panel2, -1, style=wx.RB_GROUP, label=mode 31) self.rb32 = wx.RadioButton(panel2, -1, label=mode 32) self.rb41 = wx.RadioButton(panel2, -1, style=wx.RB_GROUP, label=mode 41) self.rb42 = wx.RadioButton(panel2, -1, label=mode 42) gridSiz2.Add(self.rb31,flag=wx.ALL,border=3) gridSiz2.Add(self.rb32,flag=wx.ALL,border=3) gridSiz2.Add(self.rb41,flag=wx.ALL,border=3) gridSiz2.Add(self.rb42,flag=wx.ALL,border=3) okBut = wx.Button(mainPanel,label=-- OK --) mainSizer.Add(okBut,flag=wx.ALL|wx.ALIGN_CENTER,border=10) mainPanel.SetSizer(mainSizer) self.Layout() #wx.EVT_KEY_DOWN(self.rb11,self.OnRBKD) self.rb11.Bind(wx.EVT_KEY_DOWN, self.OnRBKD) def OnRBKD(self,event): print OnKey! event.Skip() class MyApp(wx.App): def OnInit(self): frame = MyFrame(None, Simple wxPython App) self.SetTopWindow(frame) frame.Show(True) return True app = MyApp(0) app.MainLoop() -- http://mail.python.org/mailman/listinfo/python-list
PyRun_String does not appear to handle EInvalidOp exceptions
Here's a snippet of code that demonstrates my problem: result = PyRun_String (import math, Py_file_input, pdict,pdict); result = PyRun_String (math.sqrt(-1), Py_file_input, pdict,pdict); result = PyRun_String (math.pow(2,1024), Py_file_input, pdict,pdict); Other types of exceptions seem to be handled properly by PyRun_String; however, EInvalidOp or EOverflow exceptions do not seem to be handled. My application is unable to recover gracefully after this exception occurs. Has anyone else run into this problem? Thanks. -- http://mail.python.org/mailman/listinfo/python-list
file permissions on windows XP (home)
I'm trying to write to an existing file under windows XP (home). The files are in 'My Music' which I think may be treated in some special way under XP. The relevant python code is as follows: os.chdir(dir) os.chmod(filename, 0744) print Okay to write = +str(os.access(filename, os.W_OK)) afile = file(filename, 'r+b') When I run this I get the following console output: Okay to write = True Traceback (most recent call last): File c:\temp\eyed3-0.6.6\src\test.py, line 28, in ? processFiles(root,files) File c:\temp\eyed3-0.6.6\src\test.py, line 24, in processFiles afile = file(filename, 'r+b') IOError: [Errno 13] Permission denied: 02 - New Year's Day.mp3 If I look at the files in explorer then the read only flag is not set. If I change to cygwin and then do an ls -l I get something like: -r--r--r-- 1 Barney None 4142103 Feb 28 1999 02 - New Year's Day.mp3 If I do a chmod 644 from bash first then the python works fine? I'm at a loss to understand what is going on. Why is python returing True from os.access? Why isn't chmod doing anything? Why is cygwin able to sort the problem out? Thanks Barney p.s. I'm using ActiveState Python 2.4 -- http://mail.python.org/mailman/listinfo/python-list
Creating file of size x
Hello all, Is there any way to create a file with a specified size? -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating file of size x
Jan Danielsson wrote: Is there any way to create a file with a specified size? What do you want to put in the file? Once you've answered that question, the solution should present itself. -- Erik Max Francis [EMAIL PROTECTED] http://www.alcyone.com/max/ San Jose, CA, USA 37 20 N 121 53 W AIM erikmaxfrancis All the people in my neighborhood turn around and get mad and sing -- Public Enemy -- http://mail.python.org/mailman/listinfo/python-list
RE: EnumKey vs EnumValue
EnumKey enumerates subkeys which are equivalent to the folders in regedit. EnumValue enumerates values only. The reason your script is not printing anything must be due to the fact that you are passing in a registry path that contains only subkeys and no values. As I mentioned before, the folders are the subkeys, but the values are the name, type, data tuple in a given key. Some loosely call the values keys, but technically, the keys are the folders and the values are the names. The names can be set to a specific data item. Hence the data column in regedit. The type is obviously the data type of the data that is associated with a given value (name). So, to summarize, keys are the folders that hold values that are set to data of a specific type. Keys are equivalent to the path, values are equivalent to the name in regedit. That value is assigned a date item of a specific type. This can get confusing because people commonly referred to the values as keys when keys are actually the folders. -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Pykid Sent: Monday, June 06, 2005 1:07 PM To: python-list@python.org Subject: EnumKey vs EnumValue I'm having trouble getting any responses back from the following snippet, where I am just trying to read some data from the Windows Registry. I intend to do a little bit more with this but will work on that later, but I think I can get more data back from EnumValue, I'd like to see the differences between them. I am running Python 2.3 on XP and can get a response from EnumKey, but EnumValue returns nothing at all; the key listing even returns 0 keys when it prints out the status. But EnumKey returns the right number and even prints out the keys I expect, I copied some of this from the Cookbook and can't tell what might be the problem. Thanks for any help. - M - from _winreg import * findkey = raw_input(What key do you want to look for? ) key = SOFTWARE\\+findkey machine = ConnectRegistry(None,HKEY_LOCAL_MACHINE) regpath = OpenKey(machine,key) print Looking for,key for i in range(25): try: regEndeca = EnumKey(regpath,i) print regEndeca except EnvironmentError: print There are, i,keys under,key break print That was using EnumKey. for j in range(25): try: regstr,value,type = EnumValue(regpath,j) print regstr,value,type except EnvironmentError: print There are, j,keys under,key break print That was using EnumValue. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating file of size x
Can you elaborate more? Just any file? Yes -- a binary file. The file will contain check blocks for another file. The problem is that the order of the received check blocks is not specified, so I need to be able seek to the block's position in the file, and then just write the block. -- Kind Regards, Jan Danielsson Nobody loves a cynic signature.asc I don't know. . .have you searched through modules? That's all I can think of. . . -Ivan _ Express yourself instantly with MSN Messenger! Download today - it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating file of size x
Erik Max Francis wrote: Is there any way to create a file with a specified size? What do you want to put in the file? Once you've answered that question, the solution should present itself. Check blocks from an FEC-encoder (Freenet, more specifically). The problem is that the design I'm working on won't guarantee what order the blocks will be returned in -- so I need to be able to seek to block n's location and write the ckeck block. Next block could be m, where m n. So, they aren't continous. -- http://mail.python.org/mailman/listinfo/python-list
poker card game revisited (code included)
Hi, i've included the code so interested people can take a look. I've tried to expand on the thread of 26/05/2005 on Checking for a full house. Code is suboptimal as I coded it rather quickly. I've added the normal classes one would expect from a cardgame: card, deck, hand etc. 1. I can detect most things except a straightflush. The problem with the code now is that it only returns 1 straight which is enough for mere straight detection but won't suffice for hand comparison and especially detecting straight flushes. For use in straight flush detection, the function would need to return all possible straights and then these would need to be checked to see if they are flushes. For instance a list [4,4,5,5,6,7,8] yields 4 different straights. A hand like [4,4,5,5,6,7,8,9] gets even worse. I can't see how i can do this using sets, i'll need to come up with another method since the suit is important. 2. Hand comparison. For this to succeed the getrank function would need to return the exact 5 cards that represent the highest hand. This could be less than 5 cards if one uses wildcards. Then you not only have the correct rank but also the highest hand so you can compare in case there are ties. 3. x wild. For games like deuces wild, what would be the best way to manage those? I tought about removing them from a hand before shipping it of to the getrank function? Any ideas? Regards, Benedict Verheyen = CODE = Attempt for a poker cardgame representation Benedict Verheyen Code additions from web (http://www.ibiblio.org/obp/thinkCSpy/) and newsgroup comp.lang.python esp. Raymond Hettinger import random class Card(object): Represents a single card 2,3,4, ... 10, 11 for Jack, 12 for Queen, 13 for King, 14 for Ace suitList = [Clubs, Diamonds, Hearts, Spades] rankList = [ narf, narf, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King, Ace] def __init__(self, suit=0, rank=0): Initialise a card @type suit: int @param suit: suit of the card (see suitList) @type rank: int @param rank: rank of the card (see rankList) self.suit = suit self.rank = rank def __str__(self): Pretty print a card return self.rankList[self.rank] + of + self.suitList[self.suit] def __cmp__(self, other): Compare 2 cards @type other: card @param other: the card to compare with # check the suits if self.suit other.suit: return 1 if self.suit other.suit: return -1 # suits are the same... check ranks if self.rank other.rank: return 1 if self.rank other.rank: return -1 # ranks are the same... it's a tie return 0 class Deck(object): Represents a deck of cards. We can have different decks of cards DECK_NORMAL = 1 # 52 cards def __init__(self,decktype=DECK_NORMAL): Makes a deck of cards @type decktype: type of deck @param decktype: what type of deck is it? (DECK_NORMAL,...) self.cards = [] for suit in range(4): for rank in range(2, 15): self.cards.append(Card(suit, rank)) def printdeck(self): Pretty print the deck for card in self.cards: print card def __str__(self): Pretty print the deck s = for i in range(len(self.cards)): s = s + *i + str(self.cards[i]) + \n return s def sort(self,rank=True,suit=False): Sort the deck def sortonrank(x,y): if x.rank y.rank: return 1 if x.rank y.rank: return -1 return 0 def sortonsuit(x,y): if x.suit y.suit: return 1 if x.suit y.suit: return -1 return 0 def sortonboth(x,y): return cmp(x,y) if ( rank == True and suit == False): self.cards.sort(sortonrank) elif ( suit == True and rank == False ): self.cards.sort(sortonsuit) else: self.cards.sort(sortonboth) # roept sort van card op def shuffle(self,nshuffle=1): Shuffle the deck of cards. This happens by swapping cards @type nshuffle: int @param nshuffle: how many times do we shuffle import random nCards = len(self.cards) # swap cards on place i and j for shuffle in range(nshuffle): print shuffle %s % shuffle for i in range(nCards): j = random.randrange(i, nCards) [self.cards[i], self.cards[j]] = [self.cards[j], self.cards[i]] def removecard(self, card): Removes a card
Re: How to change deafult tab traversing (radiobuttons panel)
I just figured this out myself, but probably not the way you're asking. There are supposed to be ways to change the tab order using tk_focusNext() and tk_focusPrevious(), but I've never used it. What I've done is simply point one widget to the next one, basically creating a linked list of tabs. I only had a couple that I wanted to change the order of, so this was pretty easy to change. I bound the widgets I wanted changed to tab and had a function that knew where to go. Here's a simple example: def tab(self, event): self.port.component('entry').focus_set() return 'break' The return 'break' is very important, because if you don't include it then the default tab functionality of window will be used which will override whatever changes you make. I had problems using the tk_focusNext() and tk_focusPrevious() commands because the two widgets that were supposed to be next to each other in order were in different windows. I kept getting errors when I tried it. And since I only had two widgets I created two different functions to handle the tabs. But if I had more than two I would have created a forwarding table based on widget names or ids using the event that is returned in the callback from the binding. Based on the event id returned I would know where to set focuse next. -- http://mail.python.org/mailman/listinfo/python-list