content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: Flush the console screen with special unicode class workaround for windows console I"m trying to make a simple text progress bar in windows console and also display utf8 characters. The problem isn't that the unicode characters won't display, they will. It's that in order to make the unicode characters display I used a class to tell sys.stdout what to do. This has interfered with the normal flush() function. How can I get this flush() funcionality back in the console and still use this unicode class? #coding=<utf8> import sys, os #make windows console unicode friendly if sys.platform == "win32": os.popen('chcp 65001') class UniStream(object): __slots__= "fileno", "softspace", def __init__(self, fileobject): self.fileno= fileobject.fileno() self.softspace= False def write(self, text): if isinstance(text, unicode): os.write(self.fileno, text.encode("utf_8")) else: os.write(self.fileno, text) def flush(self): self.flush() sys.stdout = UniStream(sys.stdout) sys.stderr = UniStream(sys.stderr) def progress(num): sys.stdout.write("\r"+str(num)+"% τοις εκατό...") sys.stdout.flush() for i in xrange(2000): progress(i) x = raw_input('done') A: Maybe you should use the more primitive method of using backspace to remove previous number? Or do something like: def progress(num): sys.stdout.write("\r"+20*" "+"\r"+str(num)+"% τοις εκατό...") to overwrite with spaces after return and do second return. I do not see any flashing when I do this, it only works for me when running the code from command window, not double clicking. #<coding=<utf8> import sys, os, time clear, percent ='', -1 def progress(num, maxvalue): global clear, percent p = 100 * num / maxvalue +1 if p != percent: percent = p for c in clear: sys.stdout.write(chr(8)) clear = str(p)+"% τοις εκατό..." sys.stdout.write(clear) #make windows console unicode friendly if sys.platform == "win32": os.popen('chcp 65001') class UniStream(object): __slots__= "fileno", "softspace", def __init__(self, fileobject): self.fileno= fileobject.fileno() self.softspace= False def write(self, text): if isinstance(text, unicode): os.write(self.fileno, text.encode("utf_8")) else: os.write(self.fileno, text) sys.stdout = UniStream(sys.stdout) sys.stderr = UniStream(sys.stderr) maxval=2000 for i in xrange(maxval): progress(i,maxval) time.sleep(0.02) raw_input('done')
Flush the console screen with special unicode class workaround for windows console
I"m trying to make a simple text progress bar in windows console and also display utf8 characters. The problem isn't that the unicode characters won't display, they will. It's that in order to make the unicode characters display I used a class to tell sys.stdout what to do. This has interfered with the normal flush() function. How can I get this flush() funcionality back in the console and still use this unicode class? #coding=<utf8> import sys, os #make windows console unicode friendly if sys.platform == "win32": os.popen('chcp 65001') class UniStream(object): __slots__= "fileno", "softspace", def __init__(self, fileobject): self.fileno= fileobject.fileno() self.softspace= False def write(self, text): if isinstance(text, unicode): os.write(self.fileno, text.encode("utf_8")) else: os.write(self.fileno, text) def flush(self): self.flush() sys.stdout = UniStream(sys.stdout) sys.stderr = UniStream(sys.stderr) def progress(num): sys.stdout.write("\r"+str(num)+"% τοις εκατό...") sys.stdout.flush() for i in xrange(2000): progress(i) x = raw_input('done')
[ "Maybe you should use the more primitive method of using backspace to remove previous number?\nOr do something like:\ndef progress(num): \n sys.stdout.write(\"\\r\"+20*\" \"+\"\\r\"+str(num)+\"% τοις εκατό...\") \n\nto overwrite with spaces after return and do second return.\nI do not see any flashing when I ...
[ 1 ]
[]
[]
[ "console", "python", "utf_8" ]
stackoverflow_0003582309_console_python_utf_8.txt
Q: Safe expression parser in Python How can I allow users to execute mathematical expressions in a safe way? Do I need to write a full parser? Is there something like ast.literal_eval(), but for expressions? A: The examples provided with Pyparsing include several expression parsers: https://github.com/pyparsing/pyparsing/blob/master/examples/fourFn.py is a conventional arithmetic infix notation parser/evaluator implementation using pyparsing. (Despite its name, this actually does 5-function arithmetic, plus several trig functions.) https://github.com/pyparsing/pyparsing/blob/master/examples/simpleBool.py is a boolean infix notation parser/evaluator, using a pyparsing helper method operatorPrecedence, which simplifies the definition of infix operator notations. https://github.com/pyparsing/pyparsing/blob/master/examples/simpleArith.py and https://github.com/pyparsing/pyparsing/blob/master/examples/eval_arith.py recast fourFn.py using operatorPrecedence. The first just parses and returns a parse tree; the second adds evaluation logic. If you want a more pre-packaged solution, look at plusminus, a pyparsing-based extensible arithmetic parsing package. A: What sort of expressions do you want? Variable assignment? Function evaluation? SymPy aims to become a full-fledged Python CAS. A: Few weeks ago I did similar thing, but for logical expressions (or, and, not, comparisons, parentheses etc.). I did this using Ply parser. I have created simple lexer and parser. Parser generated AST tree that was later use to perform calculations. Doing this in that way allow you to fully control what user enter, because only expressions that are compatible with grammar will be parsed. A: Yes. Even if there were an equivalent of ast.literal_eval() for expressions, a Python expression can be lots of things other than just a pure mathematical expression, for example an arbitrary function call. It wouldn't surprise me if there's already a good mathematical expression parser/evaluator available out there in some open-source module, but if not, it's pretty easy to write one of your own.
Safe expression parser in Python
How can I allow users to execute mathematical expressions in a safe way? Do I need to write a full parser? Is there something like ast.literal_eval(), but for expressions?
[ "The examples provided with Pyparsing include several expression parsers:\n\nhttps://github.com/pyparsing/pyparsing/blob/master/examples/fourFn.py is a conventional arithmetic infix notation parser/evaluator implementation using pyparsing. (Despite its name, this actually does 5-function arithmetic, plus several tr...
[ 10, 3, 1, 0 ]
[ "maths functions will consist of numeric and punctuation characters, possible 'E' or 'e' if you allow scientific notation for rational numbers, and the only (other) legal use of alpha characters will be if you allow/provide specific maths functions (e.g. stddev). So, should be trivial to run along the string for a...
[ -2 ]
[ "parsing", "python" ]
stackoverflow_0003582403_parsing_python.txt
Q: Twisted and starpy error (python) I'm using this: from twisted.web.client import getPage df = getPage(url) # there is some url I'm getting the following error. Please can anyone guide me on this ERROR:twsited:Unhandled error in Deferred: ERROR:twsited:Unhandled Error Traceback (most recent call last): File "/usr/local/lib/python2.6/dist-packages/starpy/manager.py", line 123, in lineReceived self.dispatchIncoming() # does dispatch and clears cache File "/usr/local/lib/python2.6/dist-packages/starpy/manager.py", line 200, in dispatchIncoming callback( message ) File "/usr/lib/python2.6/dist-packages/twisted/internet/defer.py", line 243, in callback self._startRunCallbacks(result) File "/usr/lib/python2.6/dist-packages/twisted/internet/defer.py", line 312, in _startRunCallbacks self._runCallbacks() --- <exception caught here> --- File "/usr/lib/python2.6/dist-packages/twisted/internet/defer.py", line 328, in _runCallbacks self.result = callback(self.result, *args, **kw) File "/usr/local/lib/python2.6/dist-packages/starpy/manager.py", line 298, in errorUnlessResponse raise error.AMICommandFailure( message ) starpy.error.AMICommandFailure: {'message': 'Channel not specified', 'response': 'Error', 'actionid': 'askme-158811948-5'} I'm not sure this error is due to getPage() method because even when i've commented this it still give me the same error. Can anyone help. I can't figure out the reason for the error and where it is generated A: The code posted is not complete. The error is not due to getPage. From the stack trace clues, this uses AMIProtocol (line receiver) . I guess some where you have to specify your protocol channel in AMIProtocol setVar(self, channel, variable, value) in star.py. This is not a twisted issue.
Twisted and starpy error (python)
I'm using this: from twisted.web.client import getPage df = getPage(url) # there is some url I'm getting the following error. Please can anyone guide me on this ERROR:twsited:Unhandled error in Deferred: ERROR:twsited:Unhandled Error Traceback (most recent call last): File "/usr/local/lib/python2.6/dist-packages/starpy/manager.py", line 123, in lineReceived self.dispatchIncoming() # does dispatch and clears cache File "/usr/local/lib/python2.6/dist-packages/starpy/manager.py", line 200, in dispatchIncoming callback( message ) File "/usr/lib/python2.6/dist-packages/twisted/internet/defer.py", line 243, in callback self._startRunCallbacks(result) File "/usr/lib/python2.6/dist-packages/twisted/internet/defer.py", line 312, in _startRunCallbacks self._runCallbacks() --- <exception caught here> --- File "/usr/lib/python2.6/dist-packages/twisted/internet/defer.py", line 328, in _runCallbacks self.result = callback(self.result, *args, **kw) File "/usr/local/lib/python2.6/dist-packages/starpy/manager.py", line 298, in errorUnlessResponse raise error.AMICommandFailure( message ) starpy.error.AMICommandFailure: {'message': 'Channel not specified', 'response': 'Error', 'actionid': 'askme-158811948-5'} I'm not sure this error is due to getPage() method because even when i've commented this it still give me the same error. Can anyone help. I can't figure out the reason for the error and where it is generated
[ "The code posted is not complete. The error is not due to getPage.\nFrom the stack trace clues, this uses AMIProtocol (line receiver) .\nI guess some where you have to specify your protocol channel in AMIProtocol \nsetVar(self, channel, variable, value) in star.py.\nThis is not a twisted issue.\n" ]
[ 0 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0003566344_python_twisted.txt
Q: Checking ogg-Files using Python on OSX and Linux I am writing a python module which checks several media and document formats whether the files correct or somehow corrupted/wrong formatted. It returns an error message or - if the file is correct - some information about the file (e.g. framerate, channels, ...) Now I am looking for a python module which I can use to check ogg-Files. There is no need to play the file, it should simply return an Exception if the file seems not to be a correct ogg-File. It should run on OSX and Linux. At the moment I am tending to python-ogg. But I think it will be some work to get it running on OSX 10.6 and perhaps there is an easier solution when there is no need to play the files. Best regards! A: Have you looked at Hachoir? It 'extracts metadata from multimedia files', including Ogg Vorbis. The different file format parsers give differing levels of detail, and I haven't tried the Vorbis one, but it might be what you are looking for. Here's an example of metatdata extraction from an AVI file: $ hachoir-metadata pacte_des_gnous.avi Common: - Duration: 4 min 25 sec - Comment: Has audio/video index (248.9 KB) - MIME type: video/x-msvideo - Endian: Little endian Video stream: - Image width: 600 - Image height: 480 - Bits/pixel: 24 - Compression: DivX v4 (fourcc:"divx") - Frame rate: 30.0 Audio stream: - Channel: stereo - Sample rate: 22.1 KHz - Compression: MPEG Layer 3
Checking ogg-Files using Python on OSX and Linux
I am writing a python module which checks several media and document formats whether the files correct or somehow corrupted/wrong formatted. It returns an error message or - if the file is correct - some information about the file (e.g. framerate, channels, ...) Now I am looking for a python module which I can use to check ogg-Files. There is no need to play the file, it should simply return an Exception if the file seems not to be a correct ogg-File. It should run on OSX and Linux. At the moment I am tending to python-ogg. But I think it will be some work to get it running on OSX 10.6 and perhaps there is an easier solution when there is no need to play the files. Best regards!
[ "Have you looked at Hachoir? It 'extracts metadata from multimedia files', including Ogg Vorbis.\nThe different file format parsers give differing levels of detail, and I haven't tried the Vorbis one, but it might be what you are looking for. Here's an example of metatdata extraction from an AVI file:\n$ hachoir-me...
[ 2 ]
[]
[]
[ "audio", "python" ]
stackoverflow_0003582737_audio_python.txt
Q: MacPorts for Python on Leopard I haven't found any concrete language on the terminal commands for installing python 3.1 on Leopard using MacPorts. I already have 2.5.1 on Leopard by way of Apple. I don't want to mess with this version & I think having the newer version of Python running from my opt/local file would be better. Also SQL3 comes packed with the standard Python version on Leopard. Do I need to download SQL3 again via MacPorts in order for it to work with Python 3.1? thanks. A: I haven't found any concrete language on the terminal commands for installing python 3.1 on Leopard using MacPorts. sudo port install python31 will install Python 3.1 (into /opt/local). In general, port install <portname> will install a port. You can find ports using port search <string> or search online. I already have 2.5.1 on Leopard by way of Apple. I don't want to mess with this version & I think having the newer version of Python running from my opt/local file would be better. MacPorts will install everything under /opt/local, and won't touch your Apple-supplied installs. Do I need to download SQL3 again via MacPorts in order for it to work with Python 3.1? MacPorts will install the dependencies you need. python31 depends on sqlite3, so SQLite 3 will automatically be downloaded and installed (under /opt/local -- Apple's version won't be touched). A: Here's an alternative way to install all Python flavors wherever you want: $ cd <wherever> $ svn http://svn.plone.org/svn/collective/buildout/python $ cd python $ python2.6 bootstrap.py $ bin/buildout It uses the system shipped Python to bootstrap the process. You'll also need Subversion installed. Make sure to edit the buildout.cfg file to add/remove versions you don't need. It also installs PIL, readline, setuptools, virtualenv and a few more goodies, it's worth a try.
MacPorts for Python on Leopard
I haven't found any concrete language on the terminal commands for installing python 3.1 on Leopard using MacPorts. I already have 2.5.1 on Leopard by way of Apple. I don't want to mess with this version & I think having the newer version of Python running from my opt/local file would be better. Also SQL3 comes packed with the standard Python version on Leopard. Do I need to download SQL3 again via MacPorts in order for it to work with Python 3.1? thanks.
[ "\nI haven't found any concrete language on the terminal commands for installing python 3.1 on Leopard using MacPorts.\n\nsudo port install python31 will install Python 3.1 (into /opt/local). In general, port install <portname> will install a port. You can find ports using port search <string> or search online.\n\n...
[ 2, 0 ]
[]
[]
[ "django", "macports", "osx_leopard", "python" ]
stackoverflow_0002600125_django_macports_osx_leopard_python.txt
Q: Python: Error --> setting an array element with a sequence The data-element is a float-number and no sequence (I think). But I get the error "setting an array element with a sequence". folder = r"C:\Dokumente und Einstellungen\ssc" contents=os.listdir(folder) ar = zeros((81,81,256),int) filenumber = 0 for d in contents: if str(".bin") in d: filename = os.path.join("C:\\Dokumente und Einstellungen\\ssc\\" + d) print filename c_file = open(filename,"rb") for k in range(8): #81 for m in range(2): #256 data = unpack('d',c_file.read(8))[0] print data ar[filename,k,m] = data filenumber += 1 A: Do you mean ar[filenumber,k,m] = data? I don't think you can index it with filename.
Python: Error --> setting an array element with a sequence
The data-element is a float-number and no sequence (I think). But I get the error "setting an array element with a sequence". folder = r"C:\Dokumente und Einstellungen\ssc" contents=os.listdir(folder) ar = zeros((81,81,256),int) filenumber = 0 for d in contents: if str(".bin") in d: filename = os.path.join("C:\\Dokumente und Einstellungen\\ssc\\" + d) print filename c_file = open(filename,"rb") for k in range(8): #81 for m in range(2): #256 data = unpack('d',c_file.read(8))[0] print data ar[filename,k,m] = data filenumber += 1
[ "Do you mean ar[filenumber,k,m] = data? I don't think you can index it with filename.\n" ]
[ 1 ]
[]
[]
[ "arrays", "multidimensional_array", "numpy", "python" ]
stackoverflow_0003582948_arrays_multidimensional_array_numpy_python.txt
Q: Delete all files/directories except two specific directories So, there seems to be a few questions asking about removing files/directories matching certain cases, but I'm looking for the exact opposite: Delete EVERYTHING in a folder that DOESN'T match my provided examples. For example, here is an example directory tree: . |-- coke | |-- diet | |-- regular | `-- vanilla |-- icecream | |-- chocolate | |-- cookiedough | |-- cupcake | | |-- file1.txt | | |-- file2.txt | | |-- file3.txt | | |-- file4.txt | | `-- file5.txt | `-- vanilla |-- lol.txt |-- mtndew | |-- classic | |-- codered | |-- livewire | | |-- file1.txt | | |-- file2.txt | | |-- file3.txt | | |-- file4.txt | | `-- file5.txt | `-- throwback `-- pepsi |-- blue |-- classic |-- diet `-- throwback I want to delete everything but the files in test/icecream/cupcake/ and test/mtndew/livewire/. Everything else can go, including the directory structure. So, how can I achieve this? Languages I wouldn't mind this being in: bash or python. A: This command will leave only the desired files in their original directories: find test \( ! -path "test/mtndew/livewire/*" ! -path "test/icecream/cupcake/*" \) -delete No need for cpio. It works on Ubuntu, Debian 5, and Mac OS X. On Linux, it will report that it cannot delete non-empty directories, which is exactly the desired result. On Mac OS X, it will quietly do the right thing. A: find's -prune comes to mind, but it's a pain to get it to work for specific paths (icecream/cupcake/) rather than specific directories (cupcake/). Personally, I'd just use cpio and hard-link (to avoid having to copy them) the files in the directories you want to keep to a new tree and then remove the old one: find test -path 'test/icecream/cupcake/*' -o -path 'test/mtndew/livewire/*' | cpio -padluv test-keep rm -rf test That'll also keep your existing directory structure for the directories you intend to keep. A: Everything "except" is why we have if-statements; and why os.walk's list of directories is a mutable list. for path, dirs, files in os.walk( 'root' ): if 'coke' in dirs: dirs.remove('coke') dirs.remove('pepsi') A: You could do something based on Python's os.walk function: import os for root, dirs, files in os.walk(top, topdown=False): for name in files: os.remove(os.path.join(root, name)) for name in dirs: os.rmdir(os.path.join(root, name)) ...just add something to ignore the paths you're interested in. A: Move the stuff you want to keep elsewhere, then delete what's left. A: find /path/to/test/ -depth -mindepth 1 \ ! -path "/path/to/test/icecream/cupcake/*" \ ! -path "/path/to/test/icecream/cupcake" \ ! -path "/path/to/test/icecream" \ ! -path "/path/to/test/mtndew/livewire/*" \ ! -path "/path/to/test/mtndew/livewire" \ ! -path "/path/to/test/mtndew" -delete -print It's a bit tedious to write all the paths to preserve but thi is the only way to use find alone. A: use find. Your command will look something like: find $directory \( -prune 'some pattern' \) -delete A: A oneliner to solve the problem: find . |grep -v "test/icecream/cupcake/"| grep -v "test/mtndew/livewire/"|xargs rm -r Removed since it does not work this might get you into trouble if have file names with space in them, and it might keep more files then you want if there are other trees that match the patterns. A somewhat better solution: find . |sed "s/.*/rm '&'/"|grep -v "rm './test/icecream/cupcake/"| grep -v "rm './test/mtndew/livewire/"|sh Not actually tested, if it breaks you get to keep both parts. Edit: As Dennis points its not only two parts that it breaks into :-) corrected the typos in the second example and removed the first A: It works for me with find using two steps: first delete the files allowed, then their empty directories! find -x -E ~/Desktop/test -not \( -type d -regex '.*/(cupcake|livewire)/*.*' -prune \) -print0 | xargs -0 ls -1 -dG # delete the files first # Mac OS X 10.4 find -x -E ~/Desktop/test -not \( -type d -regex '.*/(cupcake|livewire)/*.*' -prune \) -type f -exec /bin/rm -fv '{}' \; # Mac OS X 10.5 find -x -E ~/Desktop/test -not \( -type d -regex '.*/(cupcake|livewire)/*.*' -prune \) -type f -exec /bin/rm -fv '{}' + # delete empty directories find -x ~/Desktop/test -type d -empty -delete A: Like others I have used os.walk and os.path.join to build the list of files to delete, with fnmatch.fnmatch to select files that must be included or excluded: #-------------------------------# # make list of files to display # #-------------------------------# displayList = [] for imageDir in args : for root,dirs,files in os.walk(imageDir) : for filename in files : pathname = os.path.join( root, filename ) if fnmatch.fnmatch( pathname, options.includePattern ) : displayList.append( pathname ) #----# now filter out excluded patterns #----# try : if len(options.excludePattern) > 0 : for pattern in options.excludePattern : displayList = [pathname for pathname in displayList if not fnmatch.fnmatch( pathname, pattern ) ] except ( AttributeError, TypeError ) : pass If fnmatch isn't enough, you can use the re module to test patterns. Here I have built the file list before I do anything with it, but you could process the files as they are generated. The try/except block...is there in case my options class instance doesn't have an exclude pattern, or if it causes an exception in fnmatch because it is the wrong type. A limitation of this method is that it first includes files matching a pattern, then excludes. If you need more flexibility than this (include matching pattern a, but not pattern b unless pattern c...) well, then the fragment above isn't up to it. In fact, working through this exercise, you start to see why the find command syntax is the way it is. Seems clunky, but in fact it is exactly the way to do this. But if you generate a list, you can filter it according to whatever inclusion/exclusion rules you need. One nice thing about generating a list is you can check it before you go ahead with the deletion. This is sort of a '--dryrun' option. You can do this interactively in the python interpreter, print the list to see how it looks, apply the next filter, see if it has removed too much or too little and so on.
Delete all files/directories except two specific directories
So, there seems to be a few questions asking about removing files/directories matching certain cases, but I'm looking for the exact opposite: Delete EVERYTHING in a folder that DOESN'T match my provided examples. For example, here is an example directory tree: . |-- coke | |-- diet | |-- regular | `-- vanilla |-- icecream | |-- chocolate | |-- cookiedough | |-- cupcake | | |-- file1.txt | | |-- file2.txt | | |-- file3.txt | | |-- file4.txt | | `-- file5.txt | `-- vanilla |-- lol.txt |-- mtndew | |-- classic | |-- codered | |-- livewire | | |-- file1.txt | | |-- file2.txt | | |-- file3.txt | | |-- file4.txt | | `-- file5.txt | `-- throwback `-- pepsi |-- blue |-- classic |-- diet `-- throwback I want to delete everything but the files in test/icecream/cupcake/ and test/mtndew/livewire/. Everything else can go, including the directory structure. So, how can I achieve this? Languages I wouldn't mind this being in: bash or python.
[ "This command will leave only the desired files in their original directories:\nfind test \\( ! -path \"test/mtndew/livewire/*\" ! -path \"test/icecream/cupcake/*\" \\) -delete\n\nNo need for cpio. It works on Ubuntu, Debian 5, and Mac OS X.\nOn Linux, it will report that it cannot delete non-empty directories, whi...
[ 6, 4, 3, 2, 2, 2, 0, 0, 0, 0 ]
[]
[]
[ "bash", "linux", "python" ]
stackoverflow_0000862388_bash_linux_python.txt
Q: How to add items to wx.ScrolledPanel? I want to add dynamically captured images in hierarchical structure (one after one). I want to add them to wx.ScrolledPanel ScrolledPanel definition - updated self.hbox = wx.BoxSizer(wx.HORIZONTAL) #self.sizer.Add(self.hbox) self.scroll = scrolled.ScrolledPanel(self, id = -1, pos = wx.DefaultPosition, size = (500, 400), style= wx.SUNKEN_BORDER , name = "Scroll") self.scroll.SetupScrolling(10,10,10,10) #self.scroll.SetSizer(self.hbox) self.sizer.Add(self.scroll) #add to scroll images = wx.StaticBitmap(self, id=-1, pos=wx.DefaultPosition, size=(200,150), style= wx.SUNKEN_BORDER) images.SetBitmap(bmp) self.hbox.Add(images, 1, wx.BOTTOM | wx.EXPAND | wx.ALL, 3) self.scroll.SetSizer(self.hbox) self.scroll.SetAutoLayout(1) self.scroll.SetupScrolling() self.SetSizerAndFit(self.sizer) self.Refresh() self.Layout() Python 2.6, windows 32bit After update - I see scrollpanel and I add images to sizer. But sizer is not displaying in scrollPanel. A: Here is a crude but runnable example of what you want, there is a slight glitch in it thought that I haven't figured out the cause of yet! (You just need to put a thumbnail size jpg called "image.jpg" in the same directory as the script) import wx import wx.lib.scrolledpanel as scrolled class ImageDlg(wx.Dialog): def __init__(self, parent, title): wx.Dialog.__init__(self, parent=parent,title=title, size=wx.DefaultSize) self.scrollPnl = scrolled.ScrolledPanel(self, -1, size=(200, 200), style = wx.TAB_TRAVERSAL|wx.SUNKEN_BORDER) self.addBtn = wx.Button(self, id=wx.ID_ADD) self.Bind(wx.EVT_BUTTON, self.on_add, self.addBtn) self.mainSizer = wx.BoxSizer(wx.VERTICAL) self.scrollPnlSizer = wx.BoxSizer(wx.VERTICAL) img = wx.Image("image.jpg", wx.BITMAP_TYPE_ANY) staticBitmap = wx.StaticBitmap(self.scrollPnl, wx.ID_ANY, wx.BitmapFromImage(img)) self.scrollPnlSizer.Add(staticBitmap, 1, wx.EXPAND | wx.ALL, 3) self.mainSizer.Add(self.addBtn) self.mainSizer.Add(self.scrollPnl) self.SetSizerAndFit(self.mainSizer) def on_add(self, event): img = wx.Image("image.jpg", wx.BITMAP_TYPE_ANY) staticBitmap = wx.StaticBitmap(self.scrollPnl, wx.ID_ANY, wx.BitmapFromImage(img)) self.scrollPnlSizer.Add(staticBitmap, 1, wx.EXPAND | wx.ALL, 3) self.scrollPnl.SetSizer(self.scrollPnlSizer) self.scrollPnl.SetAutoLayout(1) self.scrollPnl.SetupScrolling() self.Refresh() self.Layout() class TestPanel(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent=parent) openDlg_btn = wx.Button(self, label="Open Dialog") self.Bind(wx.EVT_BUTTON, self.onBtn) mainSizer = wx.BoxSizer(wx.HORIZONTAL) mainSizer.Add(openDlg_btn, 0, wx.ALL, 10) self.SetSizerAndFit(mainSizer) self.Centre() def onBtn(self, event): dlg = ImageDlg(self, title='Image Dialog') dlg.SetSize((300,300)) dlg.CenterOnScreen() dlg.ShowModal() dlg.Destroy() class TestFrame(wx.Frame): def __init__(self, parent): wx.Frame.__init__(self, parent) TestPanel(self) if __name__ == "__main__": app = wx.PySimpleApp() frame = TestFrame(None) frame.Show() app.MainLoop()
How to add items to wx.ScrolledPanel?
I want to add dynamically captured images in hierarchical structure (one after one). I want to add them to wx.ScrolledPanel ScrolledPanel definition - updated self.hbox = wx.BoxSizer(wx.HORIZONTAL) #self.sizer.Add(self.hbox) self.scroll = scrolled.ScrolledPanel(self, id = -1, pos = wx.DefaultPosition, size = (500, 400), style= wx.SUNKEN_BORDER , name = "Scroll") self.scroll.SetupScrolling(10,10,10,10) #self.scroll.SetSizer(self.hbox) self.sizer.Add(self.scroll) #add to scroll images = wx.StaticBitmap(self, id=-1, pos=wx.DefaultPosition, size=(200,150), style= wx.SUNKEN_BORDER) images.SetBitmap(bmp) self.hbox.Add(images, 1, wx.BOTTOM | wx.EXPAND | wx.ALL, 3) self.scroll.SetSizer(self.hbox) self.scroll.SetAutoLayout(1) self.scroll.SetupScrolling() self.SetSizerAndFit(self.sizer) self.Refresh() self.Layout() Python 2.6, windows 32bit After update - I see scrollpanel and I add images to sizer. But sizer is not displaying in scrollPanel.
[ "Here is a crude but runnable example of what you want, there is a slight glitch in it thought that I haven't figured out the cause of yet! (You just need to put a thumbnail size jpg called \"image.jpg\" in the same directory as the script)\nimport wx\nimport wx.lib.scrolledpanel as scrolled\n\nclass ImageDlg(wx.D...
[ 1 ]
[]
[]
[ "python", "scroll", "wxpython" ]
stackoverflow_0003582696_python_scroll_wxpython.txt
Q: How do I install python gtkmozembed package or is there a replacement of python GtkMozEmbed in windows? self.widget = gtkmozembed.MozEmbed() self.widget.set_size_request(x + 18, y) I can't find a binary installer of gtkmozembed, is there an equivalent that can do the above ? A: You should specify what OS/platform you're on. Binary installers are OS-specific. Also you should specify more accurately what you're trying to do. The code is pretty much out of context and it can be hard to see what you're trying to do. I'm assuming you're trying to have an embedded browser widget in your Python app. Gtkmozembed for Python is part of PyGTK (pygtk.org) - you'll need to install PyGTK to use gtkmozembed. I couldn't find any binary installers, but at the bottom of pygtk.org/downloads.html, there are links to instructions for building the binary installer on different platforms. Also this link could be helpful (assuming you're on Windows): http://faq.pygtk.org/index.py?file=faq21.001.htp&req=show Other than gtkmozembed there exists pywebkitgtk and wx.HtmlWindow (wxWidgets) but I must admit I couldn't find much information on those.
How do I install python gtkmozembed package or is there a replacement of python GtkMozEmbed in windows?
self.widget = gtkmozembed.MozEmbed() self.widget.set_size_request(x + 18, y) I can't find a binary installer of gtkmozembed, is there an equivalent that can do the above ?
[ "You should specify what OS/platform you're on. Binary installers are OS-specific.\nAlso you should specify more accurately what you're trying to do. The code is pretty much out of context and it can be hard to see what you're trying to do.\nI'm assuming you're trying to have an embedded browser widget in your Pyth...
[ 0 ]
[]
[]
[ "package", "python" ]
stackoverflow_0002635577_package_python.txt
Q: KeyError when trying to save model instance. Django KeyError when trying to save model instance. It has to react on post_save signal than save instance... Code: from django.db.models.signals import post_save class PlaylistEntry(models.Model): playlist=models.ForeignKey(Playlist) media=models.ForeignKey(Media) order=models.PositiveIntegerField(default=9000000, editable=False) added=models.DateTimeField(default=datetime.datetime.now(),editable=False ) def playlist_entry_changed(sender, instance, **kwargs): entrys=PlaylistEntry.objects.filter(playlist=instance.playlist).order_by('order') entrys[0].save() post_save.connect(playlist_entry_changed, PlaylistEntry) Error: Exception Type: KeyError at /admin/playlist/playlistentry/add/ Exception Value: 38539456 A: From your comments what you're trying to do is update ordering. Rather than use a signal, override the save method. def save(self, *args, **kwargs): # Only do this if it's the first time we're saving. if not self.id: entries = PlaylistEntry.objects.order_by('-order') try: self.order = entries[0].order + 1 except IndexError: # we don't have any PlaylistEntries yet, so we just start @ 0 self.order = 0 super(PlaylistEntry, self).save(*args, **kwargs) Also, why are default your order to 9 million... shouldn't you start with 0? A: For implementig an ordering you can also have a look at this snippet!
KeyError when trying to save model instance. Django
KeyError when trying to save model instance. It has to react on post_save signal than save instance... Code: from django.db.models.signals import post_save class PlaylistEntry(models.Model): playlist=models.ForeignKey(Playlist) media=models.ForeignKey(Media) order=models.PositiveIntegerField(default=9000000, editable=False) added=models.DateTimeField(default=datetime.datetime.now(),editable=False ) def playlist_entry_changed(sender, instance, **kwargs): entrys=PlaylistEntry.objects.filter(playlist=instance.playlist).order_by('order') entrys[0].save() post_save.connect(playlist_entry_changed, PlaylistEntry) Error: Exception Type: KeyError at /admin/playlist/playlistentry/add/ Exception Value: 38539456
[ "From your comments what you're trying to do is update ordering. Rather than use a signal, override the save method. \ndef save(self, *args, **kwargs):\n # Only do this if it's the first time we're saving.\n if not self.id:\n entries = PlaylistEntry.objects.order_by('-order')\n try:\n ...
[ 1, 0 ]
[]
[]
[ "django", "python", "signals" ]
stackoverflow_0003577470_django_python_signals.txt
Q: Test for email charsets with python I want to import emails from an mbox format into a Django app. All database tables are Unicode. My problem: sometimes the wrong charset is given, sometimes none at all. What is the best way to deal with these encoding issues? So far, I merely nest exceptions to try the two most common charsets I receive mails in (utf-8 and iso-8859-1): if (not message.is_multipart()): message_charset = message.get_content_charset() msg.message = message_charset + unicode(message.get_payload(decode=False), message_charset) else: for part in message.walk(): if part.get_content_type() == "text/plain": message_charset = part.get_content_charset() try: msg.message = message_charset + unicode(part.get_payload(decode=False), message_charset) except(UnicodeDecodeError): try: msg.message = message_charset + unicode(part.get_payload(decode=False), "utf-8") except(UnicodeDecodeError): msg.message = message_charset + unicode(part.get_payload(decode=False), "iso-8859-1") Is there a better, more robust way? Thanks! A: You could ask the excellent chardet library to guess the encoding. "Character encoding auto-detection in Python 2 and 3. As smart as your browser. Open source." A: I'm sorry but your strategy is WRONG. Firstly, there are encodings that were deliberately designed to fly under the 7-bit ASCII radar so that they could be used in early email systems. The Chinese HZ encoding is little used these days but Japanese email seems to use ISO-2022-JP quite frequently. Both of those would be wrongly interpreted as ASCII if you tried that first; your current strategy would wrongly interpret them as UTF-8. It would also interpret restricted (all chars < U+0080) UTF-16 text as UTF-8. Secondly, ISO-8859-1 maps each of all 256 possible bytes to a Unicode character. random_garbage.decode('iso-8859-1') will never raise an exception. In other words, anything that fails the UTF-8 test will be interpreted as 'ISO-8859-1' by your strategy. Do what the man said: use chardet right from the start. It knows in what order the tests should be done.
Test for email charsets with python
I want to import emails from an mbox format into a Django app. All database tables are Unicode. My problem: sometimes the wrong charset is given, sometimes none at all. What is the best way to deal with these encoding issues? So far, I merely nest exceptions to try the two most common charsets I receive mails in (utf-8 and iso-8859-1): if (not message.is_multipart()): message_charset = message.get_content_charset() msg.message = message_charset + unicode(message.get_payload(decode=False), message_charset) else: for part in message.walk(): if part.get_content_type() == "text/plain": message_charset = part.get_content_charset() try: msg.message = message_charset + unicode(part.get_payload(decode=False), message_charset) except(UnicodeDecodeError): try: msg.message = message_charset + unicode(part.get_payload(decode=False), "utf-8") except(UnicodeDecodeError): msg.message = message_charset + unicode(part.get_payload(decode=False), "iso-8859-1") Is there a better, more robust way? Thanks!
[ "You could ask the excellent chardet library to guess the encoding.\n\"Character encoding auto-detection in Python 2 and 3. As smart as your browser. Open source.\"\n", "I'm sorry but your strategy is WRONG.\nFirstly, there are encodings that were deliberately designed to fly under the 7-bit ASCII radar so that t...
[ 1, 0 ]
[]
[]
[ "email", "python", "unicode" ]
stackoverflow_0003532641_email_python_unicode.txt
Q: How to model a m2m relation where the related table can be a city, a region (state) or a country In Django I have theses models: class Artist(models.Model): name = models.CharField(max_length=128) born_place = models.ForeignKey(???) dead_place = models.ForeignKey(???) live_places = models.ManyToManyField(???) work_places = models.ManyToManyField(???) class Country(models.Model): iso = models.CharField(max_length=2, primary_key=True) name = models.CharField(max_length=50) class Region(models.Model): iso = models.CharField(max_length=2, blank=True) name = models.CharField(max_length=150) country = models.ForeignKey('Country') class City(models.Model): name = models.CharField(max_length=150) region = models.ForeignKey('Region') All the places (born_place, dead_place, live_places, work_places) can be a City or a Region or a Country. And a City should necessarily have a Region, and a Region should necessarily have a Country. How can I achieve that? A: All the places (born_place, dead_place, live_places, work_places) can be a City or a Region or a Country. What you need in this case is a generic foreign key. In Django this can be achieved through the handy contenttypes framework. From the documentation: There are three parts to setting up a GenericForeignKey: Give your model a ForeignKey to ContentType. Give your model a field that can store a primary-key value from the models you'll be relating to. (For most models, this means an IntegerField or PositiveIntegerField.) This field must be of the same type as the primary key of the models that will be involved in the generic relation. For example, if you use IntegerField, you won't be able to form a generic relation with a model that uses a CharField as a primary key. Give your model a GenericForeignKey, and pass it the names of the two fields described above. If these fields are named "content_type" and "object_id", you can omit this -- those are the default field names GenericForeignKey will look for. A: well.. yea maybe you could use generic relations. But i think that you could solve you some problems by thinking outside the box. i'd say that you could create a Territory model instead of Country,Region and City; and then use a recursive relationship class Territory(models.Model): iso = models.CharField(max_length=2, blank=True) name = models.CharField(max_length=150) parent = models.ForeignKey('self') this will create a hierarchy structure for your territory, so now you could use as many divisions as you like (for exemple, Continents, Planets,Community) and you wont have to change your models. As for the Artist, you could do something like: class Artist(models.Model): name = models.CharField(max_length=128) born_place = models.ForeignKey(Territory) dead_place = models.ForeignKey(Territory) live_places = models.ManyToManyField(Territory) work_places = models.ManyToManyField(Territory) so now... the born_place can be a City, a Region, a Planet... anything you want! i guess that was your question. I'm no expert in django, this is just a generic way to solve this kind of problems in O.O.P. A: You can also use model inheritance class Territory(models.Model): name = models.CharField(max_length=150) class Country(Territory): iso = models.CharField(max_length=2, primary_key=True) class Region(Territory): iso = models.CharField(max_length=2, blank=True) country = models.ForeignKey('Country') class City(Territory): region = models.ForeignKey('Region') class Artist(models.Model): name = models.CharField(max_length=128) born_place = models.ForeignKey(Territory) dead_place = models.ForeignKey(Territory) live_places = models.ManyToManyField(Territory) work_places = models.ManyToManyField(Territory) Best regards! A: Take a look at Django's Generic Relations here and here, which will let you key to various types of object, rather than only a specific one.
How to model a m2m relation where the related table can be a city, a region (state) or a country
In Django I have theses models: class Artist(models.Model): name = models.CharField(max_length=128) born_place = models.ForeignKey(???) dead_place = models.ForeignKey(???) live_places = models.ManyToManyField(???) work_places = models.ManyToManyField(???) class Country(models.Model): iso = models.CharField(max_length=2, primary_key=True) name = models.CharField(max_length=50) class Region(models.Model): iso = models.CharField(max_length=2, blank=True) name = models.CharField(max_length=150) country = models.ForeignKey('Country') class City(models.Model): name = models.CharField(max_length=150) region = models.ForeignKey('Region') All the places (born_place, dead_place, live_places, work_places) can be a City or a Region or a Country. And a City should necessarily have a Region, and a Region should necessarily have a Country. How can I achieve that?
[ "\nAll the places (born_place, dead_place, live_places, work_places) can be a City or a Region or a Country.\n\nWhat you need in this case is a generic foreign key. In Django this can be achieved through the handy contenttypes framework.\nFrom the documentation:\n\nThere are three parts to setting up a GenericForei...
[ 1, 1, 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003580849_django_python.txt
Q: How do I apply a patch from gist to the Django source? I want to try out a patch on gist that modifies the source code of Django: gist: 550436 How do I do it? I have never used git so a step by step instruction would be greatly appreciated. A: You can use patch to apply diffs. Make sure you're in your django source directory (or wherever you want to apply the patch), and run something like patch -p1 < downloaded-patch.diff. You may want to experiment with the -p argument if it fails; -p tells patch to strip some of the directory prefix for each file in the diff (look at the first line in the diff).
How do I apply a patch from gist to the Django source?
I want to try out a patch on gist that modifies the source code of Django: gist: 550436 How do I do it? I have never used git so a step by step instruction would be greatly appreciated.
[ "You can use patch to apply diffs. Make sure you're in your django source directory (or wherever you want to apply the patch), and run something like patch -p1 < downloaded-patch.diff.\nYou may want to experiment with the -p argument if it fails; -p tells patch to strip some of the directory prefix for each file in...
[ 7 ]
[]
[]
[ "git", "github", "patch", "python" ]
stackoverflow_0003582849_git_github_patch_python.txt
Q: Overriding __new__ and __init__ in Python Possible Duplicate: Python's use of __new__ and __init__ ? The way I understand it, __init__ is different from a constructor in Java, because __init__ only initializes an object that has already been constructed implicitly (because __init__ is called after __new__). However, everything that I have ever needed to define has used this latter property of a 'constructor' in Java. What would be a case in which a programmer would want to override __new__? EDIT: For the record, I ask partly because I'm wondering what would be the advantage/disadvantage to overriding new vs. using a separate classmethod in the accepted answer to this question: Moving Beyond Factories in Python A: __new__ actually happens before an object exists. It's a static method of the type. Uses of __new__ are when you want to control the creation of new objects, e.g. a singleton. If your __new__ always returns the same instance of an object, it's a singleton. You can't do that with __init__. Generally, in "python as Guido intended it to be" you shouldn't use __new__ more than once a month :) A: __new__ is for creating new object instance, __init__ is for initializing it. I think if you design an immutable type, you have to initialize it in __new__, see namedtuple for example (also Python's use of __new__ and __init__?).
Overriding __new__ and __init__ in Python
Possible Duplicate: Python's use of __new__ and __init__ ? The way I understand it, __init__ is different from a constructor in Java, because __init__ only initializes an object that has already been constructed implicitly (because __init__ is called after __new__). However, everything that I have ever needed to define has used this latter property of a 'constructor' in Java. What would be a case in which a programmer would want to override __new__? EDIT: For the record, I ask partly because I'm wondering what would be the advantage/disadvantage to overriding new vs. using a separate classmethod in the accepted answer to this question: Moving Beyond Factories in Python
[ "__new__ actually happens before an object exists. It's a static method of the type. Uses of __new__ are when you want to control the creation of new objects, e.g. a singleton. If your __new__ always returns the same instance of an object, it's a singleton. You can't do that with __init__.\nGenerally, in \"python a...
[ 13, 3 ]
[]
[]
[ "python" ]
stackoverflow_0003584042_python.txt
Q: error while trying to connect with a cisco 2600 router through python in windows The code i have given is import telnetlib HOST="X" user ="X" password="X" en_password="x" tn=telnetlib.Telnet(HOST) Traceback (most recent call last): File "<pyshell#15>", line 1, in <module> tn=telnetlib.Telnet(HOST) File "C:\Python27\lib\telnetlib.py", line 209, in __init__ self.open(host, port, timeout) File "C:\Python27\lib\telnetlib.py", line 225, in open self.sock = socket.create_connection((host, port), timeout) File "C:\Python27\lib\socket.py", line 567, in create_connection raise error, msg error: [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond This is the error that i am getting while i am trying to connect to the 2600 router . How to remove this error , and connect to the router through a python script? A: It's a connection timeout - if you're not having a other networking issues then it's simply that the router is not accepting connections on the default telnet port. Are you sure you can connect via port 23? Can you use a telnet client to connect?
error while trying to connect with a cisco 2600 router through python in windows
The code i have given is import telnetlib HOST="X" user ="X" password="X" en_password="x" tn=telnetlib.Telnet(HOST) Traceback (most recent call last): File "<pyshell#15>", line 1, in <module> tn=telnetlib.Telnet(HOST) File "C:\Python27\lib\telnetlib.py", line 209, in __init__ self.open(host, port, timeout) File "C:\Python27\lib\telnetlib.py", line 225, in open self.sock = socket.create_connection((host, port), timeout) File "C:\Python27\lib\socket.py", line 567, in create_connection raise error, msg error: [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond This is the error that i am getting while i am trying to connect to the 2600 router . How to remove this error , and connect to the router through a python script?
[ "It's a connection timeout - if you're not having a other networking issues then it's simply that the router is not accepting connections on the default telnet port. Are you sure you can connect via port 23? Can you use a telnet client to connect?\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0003582970_python.txt
Q: How do you create a video file upload form with Django? I want a user to be able to upload a video from their computer or record it right from their webcam, then fill out other information with a form. I'm writing this app with Django. A: Recording directly from the web cam is not as simple as uploading an existing video file. You may need to look into one of the many video streaming protocols and handle that via a server such as red5. This approach would require the use of Flash or something similar. A: The Django documentation should be able to help you handle file uploads: http://docs.djangoproject.com/en/dev/topics/http/file-uploads/ A: Additionaly have a look at jquery uploadify. It's pretty useful for large file uploads because it display the progress of the download.
How do you create a video file upload form with Django?
I want a user to be able to upload a video from their computer or record it right from their webcam, then fill out other information with a form. I'm writing this app with Django.
[ "Recording directly from the web cam is not as simple as uploading an existing video file. You may need to look into one of the many video streaming protocols and handle that via a server such as red5. This approach would require the use of Flash or something similar.\n", "The Django documentation should be abl...
[ 1, 0, 0 ]
[]
[]
[ "django", "file_upload", "forms", "python", "video" ]
stackoverflow_0003580778_django_file_upload_forms_python_video.txt
Q: Need performance on postGIS with GeoDjango This is the first time I'm using GeoDjango with postGIS. After installation and some tests with everything running fine I am concerned about query performance when table rows will grow. I'm saving in a geometry point longitudes and latitudes that I get from Google geocoding (WGS84, or SRID 4326). My problem is that distance operations are very common in my application. I often need to get near spots from a landmark. Geometry maths are very complex, so even if I have an spatial index, it will probably take too long in the future having more than 1000 spots in a nearby area. So is there any way to project this geometry type to do distance operations faster? does anyone know a Django library that can render a Google map containing some of these points? Any advices on how to speed up spatial queries on GeoDjango? A: If you can fit your working area into a map projection, that will always be faster, as there are fewer math calls necessary for things like distance calculations. However, if you have truly global data, suck it up: use geography. If you only have continental USA data, use something like EPSG:2163 http://spatialreference.org/ref/epsg/2163/ The more constrained your working area, the more accurate results you can get in a map projection. See the state plane projections for highly constrained, accurate projections for regional areas in the USA. Or UTM projections for larger sub-national regions. A: I'm researching on this topic. As far as I have found, coordinates that you get from geopy library are in SRID 4326 format, so you can store them in a geometry field type without problems. This would be an example of a GeoDjango model using geometry: class Landmark(models.Model): point = models.PointField(spatial_index = True, srid = 4326, geography = True) objects = models.GeoManager() By the way, be very careful to pass longitude / latitude to the PointField, in that exact order. geopy returns latitude / longitude coordinates, so you will need to reverse them. For transforming points in one coordinate system to another we can use GEOS with GeoDjango. In the example I will transform a point in 4326 to the famous Google projection 900913: from django.contrib.gis.geos import Point punto = Point(40,-3) punto.set_srid(900913) punto.transform(4326) punto.wkt Out[5]: 'POINT (0.0003593261136478 -0.0000269494585230)' This way we can store coordinates in projection systems, which will have better performance maths. For showing points in a Google map in the admin site interface. We can use this great article. I have decided to go on with geography types, and I will convert them in the future, in case I need to improve performance. A: Generally, GeoDjango will create and use spatial indexes on geometry columns where appropriate. For an application dealing primarily with distances between points, the Geography type (introduced in PostGIS 1.5, and supported by GeoDjango) may be a good fit. GeoDjango says it gives "much better performance on WGS84 distance queries" [link].
Need performance on postGIS with GeoDjango
This is the first time I'm using GeoDjango with postGIS. After installation and some tests with everything running fine I am concerned about query performance when table rows will grow. I'm saving in a geometry point longitudes and latitudes that I get from Google geocoding (WGS84, or SRID 4326). My problem is that distance operations are very common in my application. I often need to get near spots from a landmark. Geometry maths are very complex, so even if I have an spatial index, it will probably take too long in the future having more than 1000 spots in a nearby area. So is there any way to project this geometry type to do distance operations faster? does anyone know a Django library that can render a Google map containing some of these points? Any advices on how to speed up spatial queries on GeoDjango?
[ "If you can fit your working area into a map projection, that will always be faster, as there are fewer math calls necessary for things like distance calculations. However, if you have truly global data, suck it up: use geography. If you only have continental USA data, use something like EPSG:2163 http://spatialref...
[ 3, 3, 0 ]
[]
[]
[ "django", "geodjango", "postgis", "python" ]
stackoverflow_0003547699_django_geodjango_postgis_python.txt
Q: How to properly add quotes to a string using python? I want to add a set of (double) quotes to a python string if they are missing but the string can also contain quotes. The purpose of this is to quote all command that are not already quoted because Windows API requires you to quote the entire command line when you execute a process using _popen(). Here are some strings that should be quoted: <empty string> type "type" /? "type" "/?" type "a a" b type "" b Here are some that should not be quoted: "type" ""type" /?" Please take the time to test all examples; it is not too easy to detect if the string needs the quotes or not. A: Your problem is inconsistent. Consider the two cases ""a" b" "a" "b" The former is interpreted as a pre-quoted string with 'nested quotes', but the latter is interpreted as separately-quoted strings. Here are some examples that highlight the issue. " "a" "b" " " "a" b" "a ""b" How should they be treated? A: I think this is a difficult question to specify in a precise way, but perhaps this strategy will approximate your goal. The basic idea is to create a copy of the original string, removing the internally quoted items. An internally quoted item is defined here so that it must contains at least one non-whitespace character. After the internally quoted items have been removed, you then check whether the entire string needs surrounding quotes or not. import re tests = [ # Test data in original question. ( '', '""' ), ( 'a', '"a"' ), ( '"a"', '"a"' ), # No change. ( '""a" b"', '""a" b"' ), # No change. ( '"a" b', '""a" b"' ), ( '"a" "b"', '""a" "b""' ), ( 'a "b" c', '"a "b" c"' ), # Test data in latest edits. ( 'type', '"type"' ), # Quote these. ( '"type" /?', '""type" /?"' ), ( '"type" "/?"', '""type" "/?""' ), ( 'type "a a" b', '"type "a a" b"' ), ( 'type "" b', '"type "" b"' ), ( '"type"', '"type"' ), # Don't quote. ( '""type" /?"', '""type" /?"' ), # Some more tests. ( '"a b" "c d"', '""a b" "c d""' ), ( '" a " foo " b "', '"" a " foo " b ""' ), ] Q = '"' re_quoted_items = re.compile(r'" \s* [^"\s] [^"]* \"', re.VERBOSE) for orig, expected in tests: # The orig string w/o the internally quoted items. woqi = re_quoted_items.sub('', orig) if len(orig) == 0: orig_quoted = Q + orig + Q elif len(woqi) > 0 and not (woqi[0] == Q and woqi[-1] == Q): orig_quoted = Q + orig + Q else: orig_quoted = orig print orig_quoted == expected A: I wrote a simple state machine to track if we are in a word or not. If the quote depth is ever zero in the string, then we need quotes: def quotify(s): if s == "": return '""' depth = 0 in_word = False needs_quotes = False for c in s: if c == '"': if in_word: depth -= 1 else: depth += 1 else: if depth == 0: needs_quotes = True break in_word = not c.isspace() if needs_quotes: return '"' + s + '"' else: return s assert quotify('') == '""' assert quotify('''type''') == '''"type"''' assert quotify('''"type" /?''') == '''""type" /?"''' assert quotify('''"type" "/?"''') == '''""type" "/?""''' assert quotify('''type "a a" b''') == '''"type "a a" b"''' assert quotify('''type "" b''') == '''"type "" b"''' assert quotify('''"type"''') == '''"type"''' assert quotify('''""type" /?"''') == '''""type" /?"'''
How to properly add quotes to a string using python?
I want to add a set of (double) quotes to a python string if they are missing but the string can also contain quotes. The purpose of this is to quote all command that are not already quoted because Windows API requires you to quote the entire command line when you execute a process using _popen(). Here are some strings that should be quoted: <empty string> type "type" /? "type" "/?" type "a a" b type "" b Here are some that should not be quoted: "type" ""type" /?" Please take the time to test all examples; it is not too easy to detect if the string needs the quotes or not.
[ "Your problem is inconsistent.\nConsider the two cases\n\n\"\"a\" b\"\n\"a\" \"b\"\n\nThe former is interpreted as a pre-quoted string with 'nested quotes', but the latter is interpreted as separately-quoted strings. Here are some examples that highlight the issue.\n\n\" \"a\" \"b\" \"\n\" \"a\" b\"\n\"a \"\"b\"\n\...
[ 8, 4, 3 ]
[ "You have three cases:\n\nString is less than two characters long: add quotes\nString has quotes at s[0] and at s[1]: don't add quotes\nAdd quotes\n\nAnd by \"add quotes\" I mean simply construct '\"'+string+'\"' and return it.\nTranslate to if-statements, and you're done.\n" ]
[ -1 ]
[ "python", "string" ]
stackoverflow_0003584005_python_string.txt
Q: Create a python function at runtime to match a variable number of dictionary entries I'm making a program to calculate latency from a tcpdump/pcap file and I want to be able to specify rules on the command line to correlate packets -- i.e. find the time taken between sending a packet matching rule A to receiving a packet matching rule B (concrete example would be a FIX NewOrderSingle being sent and a corresponding FIX ExecutionReport being received). This is an example of the fields in the packet (before they've been converted into dictionary form) -- I'm testing the numerical version of the field (in parentheses) rather than the English version: BeginString (8): FIX.4.2 BodyLength (9): 132 MsgType (35): D (ORDER SINGLE) SenderCompID (49): XXXX TargetCompID (56): EXCHANGE MsgSeqNum (34): 1409104 SendingTime (52): 20100723-12:49:52.296 Side (54): 1 (BUY) Symbol (55): A002 ClOrdID (11): BUY704552 OrderQty (38): 1000 OrdType (40): 2 (LIMIT) Price (44): 130002 TimeInForce (59): 3 (IMMEDIATE OR CANCEL) QuoteID (117): A002 RelatdSym (46): A002 CheckSum (10): 219 [correct] Currently I have the arguments coming off the command line into a nested list: [[35, 'D'], [55, 'A002']] (where the first element of each sublist is the field number and second is the value) I've tried iterating over this list of rules to accumulate a lambda expression: for field, value in args.send["fields_filter"]: if matchers["send"] == None: matchers["send"] = lambda fix : field in fix and fix[field] == value else: matchers["send"] = lambda fix : field in fix and fix[field] == value and matchers["send"](fix) When I run the program though, I get the output: RuntimeError: maximum recursion depth exceeded in cmp Lambdas are late-binding? So does this apply to all identifiers in the expression or just those passed in as arguments? It seems the former is true What's the best way to achieve this functionality? I feel like I'm going about this the wrong way currently. Maybe this is a bad use of lambda expressions, but I don't know a better alternative for this. A: Don't use lambdas. They are late binding. Perhaps you want a partial from functools, but even that seems too complex. Your data coming in has field names, numbers and values, right? Your command-line parameters use field numbers and values, right? You want a dictionary keyed by field number. In that case, you don't need any complex lookups. You just want something like this. def match( packet_dict, criteria_list ): t = [ packet_dict[f] == v for f,v in criteria_list ] return any( t ) Something like that should handle everything for you.
Create a python function at runtime to match a variable number of dictionary entries
I'm making a program to calculate latency from a tcpdump/pcap file and I want to be able to specify rules on the command line to correlate packets -- i.e. find the time taken between sending a packet matching rule A to receiving a packet matching rule B (concrete example would be a FIX NewOrderSingle being sent and a corresponding FIX ExecutionReport being received). This is an example of the fields in the packet (before they've been converted into dictionary form) -- I'm testing the numerical version of the field (in parentheses) rather than the English version: BeginString (8): FIX.4.2 BodyLength (9): 132 MsgType (35): D (ORDER SINGLE) SenderCompID (49): XXXX TargetCompID (56): EXCHANGE MsgSeqNum (34): 1409104 SendingTime (52): 20100723-12:49:52.296 Side (54): 1 (BUY) Symbol (55): A002 ClOrdID (11): BUY704552 OrderQty (38): 1000 OrdType (40): 2 (LIMIT) Price (44): 130002 TimeInForce (59): 3 (IMMEDIATE OR CANCEL) QuoteID (117): A002 RelatdSym (46): A002 CheckSum (10): 219 [correct] Currently I have the arguments coming off the command line into a nested list: [[35, 'D'], [55, 'A002']] (where the first element of each sublist is the field number and second is the value) I've tried iterating over this list of rules to accumulate a lambda expression: for field, value in args.send["fields_filter"]: if matchers["send"] == None: matchers["send"] = lambda fix : field in fix and fix[field] == value else: matchers["send"] = lambda fix : field in fix and fix[field] == value and matchers["send"](fix) When I run the program though, I get the output: RuntimeError: maximum recursion depth exceeded in cmp Lambdas are late-binding? So does this apply to all identifiers in the expression or just those passed in as arguments? It seems the former is true What's the best way to achieve this functionality? I feel like I'm going about this the wrong way currently. Maybe this is a bad use of lambda expressions, but I don't know a better alternative for this.
[ "Don't use lambdas. They are late binding. Perhaps you want a partial from functools, but even that seems too complex.\nYour data coming in has field names, numbers and values, right? \nYour command-line parameters use field numbers and values, right?\nYou want a dictionary keyed by field number. In that case, ...
[ 2 ]
[]
[]
[ "dynamic", "lambda", "matching", "python" ]
stackoverflow_0003585225_dynamic_lambda_matching_python.txt
Q: How to use less than and equal to in an assert statement in python When I run the following: growthRates = [3, 4, 5, 0, 3] for each in growthRates: print each assert growthRates >= 0, 'Growth Rate is not between 0 and 100' assert growthRates <= 100, 'Growth Rate is not between 0 and 100' I get: 3 Traceback (most recent call last): File "ps4.py", line 132, in <module> testNestEggVariable() File "ps4.py", line 126, in testNestEggVariable savingsRecord = nestEggVariable(salary, save, growthRates) File "ps4.py", line 106, in nestEggVariable assert growthRates <= 100, 'Growth Rate is not between 0 and 100' AssertionError: Growth Rate is not between 0 and 100 Why is that? A: Do: assert each >= 0, 'Growth Rate is not between 0 and 100' not: assert growthRates >= 0, 'Growth Rate is not between 0 and 100' A: assert 0 <= each <= 100, 'Growth Rate %i is not between 0 and 100.' % each Your asserts do not fail of course then, but now the growthRates > 100 because growthRates is list and 0 is integer and 'list'>'integer'. A: assert (each >= 0) not assert (growthRates >= 0) :-) A: You can also use: growthRates = [0, 10, 100, -1] assert all(0<=each<=100 for each in growthRates), 'growthRate is not between 0 and 100' Traceback (most recent call last): File "any.py", line 2, in <module> assert all([0<=each<=100 for each in growthRates]), 'growthRate is not between 0 and 100' AssertionError: growthRate is not between 0 and 100 A: Test for each instead of the list growthRates. You could also use: growthRates = [3, 4, 5, 0, 3] testRange = range(0,100) for each in growthRates: print each assert each in testRange, 'Growth Rate is not between 0 and 100'
How to use less than and equal to in an assert statement in python
When I run the following: growthRates = [3, 4, 5, 0, 3] for each in growthRates: print each assert growthRates >= 0, 'Growth Rate is not between 0 and 100' assert growthRates <= 100, 'Growth Rate is not between 0 and 100' I get: 3 Traceback (most recent call last): File "ps4.py", line 132, in <module> testNestEggVariable() File "ps4.py", line 126, in testNestEggVariable savingsRecord = nestEggVariable(salary, save, growthRates) File "ps4.py", line 106, in nestEggVariable assert growthRates <= 100, 'Growth Rate is not between 0 and 100' AssertionError: Growth Rate is not between 0 and 100 Why is that?
[ "Do:\nassert each >= 0, 'Growth Rate is not between 0 and 100'\n\nnot:\nassert growthRates >= 0, 'Growth Rate is not between 0 and 100'\n\n", "assert 0 <= each <= 100, 'Growth Rate %i is not between 0 and 100.' % each\n\nYour asserts do not fail of course then, but now the growthRates > 100 because growthRates is...
[ 15, 6, 4, 2, 0 ]
[]
[]
[ "assert", "comparison", "python" ]
stackoverflow_0003585443_assert_comparison_python.txt
Q: Python decorators and class inheritance I'm trying to use decorators in order to manage the way users may or may not access resources within a web application (running on Google App Engine). Please note that I'm not allowing users to log in with their Google accounts, so setting specific access rights to specific routes within app.yaml is not an option. I used the following resources : - Bruce Eckel's guide to decorators - SO : get-class-in-python-decorator2 - SO : python-decorators-and-inheritance - SO : get-class-in-python-decorator However I'm still a bit confused... Here's my code ! In the following example, current_user is a @property method which belong to the RequestHandler class. It returns a User(db.model) object stored in the datastore, with a level IntProperty(). class FoobarController(RequestHandler): # Access decorator def requiredLevel(required_level): def wrap(func): def f(self, *args): if self.current_user.level >= required_level: func(self, *args) else: raise Exception('Insufficient level to access this resource') return f return wrap @requiredLevel(100) def get(self, someparameters): #do stuff here... @requiredLevel(200) def post(self): #do something else here... However, my application uses different controllers for different kind of resources. In order to use the @requiredLevel decorator within all subclasses, I need to move it to the parent class (RequestHandler) : class RequestHandler(webapp.RequestHandler): #Access decorator def requiredLevel(required_level): #See code above My idea is to access the decorator in all controller subclasses using the following code : class FoobarController(RequestHandler): @RequestHandler.requiredLevel(100) def get(self): #do stuff here... I think I just reached the limit of my knowledge about decorators and class inheritance :). Any thoughts ? A: Your original code, with two small tweaks, should also work. A class-based approach seems rather heavy-weight for such a simple decorator: class RequestHandler(webapp.RequestHandler): # The decorator is now a class method. @classmethod # Note the 'klass' argument, similar to 'self' on an instance method def requiredLevel(klass, required_level): def wrap(func): def f(self, *args): if self.current_user.level >= required_level: func(self, *args) else: raise Exception('Insufficient level to access this resource') return f return wrap class FoobarController(RequestHandler): @RequestHandler.requiredLevel(100) def get(self, someparameters): #do stuff here... @RequestHandler.requiredLevel(200) def post(self): #do something else here... Alternately, you could use a @staticmethod instead: class RequestHandler(webapp.RequestHandler): # The decorator is now a static method. @staticmethod # No default argument required... def requiredLevel(required_level): The reason the original code didn't work is that requiredLevel was assumed to be an instance method, which isn't going to be available at class-declaration time (when you were decorating the other methods), nor will it be available from the class object (putting the decorator on your RequestHandler base class is an excellent idea, and the resulting decorator call is nicely self-documenting). You might be interested to read the documentation about @classmethod and @staticmethod. Also, a little bit of boilerplate I like to put in my decorators: @staticmethod def requiredLevel(required_level): def wrap(func): def f(self, *args): if self.current_user.level >= required_level: func(self, *args) else: raise Exception('Insufficient level to access this resource') # This will maintain the function name and documentation of the wrapped function. # Very helpful when debugging or checking the docs from the python shell: wrap.__doc__ = f.__doc__ wrap.__name__ = f.__name__ return f return wrap A: After digging through StackOverflow, and carefully reading Bruce Eckel's guide to decorators, I think I found a possible solution. It involves implementing the decorator as a class in the Parent class : class RequestHandler(webapp.RequestHandler): # Decorator class : class requiredLevel(object): def __init__(self, required_level): self.required_level = required_level def __call__(self, f): def wrapped_f(*f_args): if f_args[0].current_user.level >= self.required_level: return f(*f_args) else: raise Exception('User has insufficient level to access this resource') return wrapped_f This does the work ! Using f_args[0] seems a bit dirty to me, I'll edit this answer if I find something prettier. Then you can decorate methods in subclasses the following way : FooController(RequestHandler): @RequestHandler.requiredLevel(100) def get(self, id): # Do something here @RequestHandler.requiredLevel(250) def post(self) # Do some stuff here BarController(RequestHandler): @RequestHandler.requiredLevel(500) def get(self, id): # Do something here Feel free to comment or propose an enhancement.
Python decorators and class inheritance
I'm trying to use decorators in order to manage the way users may or may not access resources within a web application (running on Google App Engine). Please note that I'm not allowing users to log in with their Google accounts, so setting specific access rights to specific routes within app.yaml is not an option. I used the following resources : - Bruce Eckel's guide to decorators - SO : get-class-in-python-decorator2 - SO : python-decorators-and-inheritance - SO : get-class-in-python-decorator However I'm still a bit confused... Here's my code ! In the following example, current_user is a @property method which belong to the RequestHandler class. It returns a User(db.model) object stored in the datastore, with a level IntProperty(). class FoobarController(RequestHandler): # Access decorator def requiredLevel(required_level): def wrap(func): def f(self, *args): if self.current_user.level >= required_level: func(self, *args) else: raise Exception('Insufficient level to access this resource') return f return wrap @requiredLevel(100) def get(self, someparameters): #do stuff here... @requiredLevel(200) def post(self): #do something else here... However, my application uses different controllers for different kind of resources. In order to use the @requiredLevel decorator within all subclasses, I need to move it to the parent class (RequestHandler) : class RequestHandler(webapp.RequestHandler): #Access decorator def requiredLevel(required_level): #See code above My idea is to access the decorator in all controller subclasses using the following code : class FoobarController(RequestHandler): @RequestHandler.requiredLevel(100) def get(self): #do stuff here... I think I just reached the limit of my knowledge about decorators and class inheritance :). Any thoughts ?
[ "Your original code, with two small tweaks, should also work. A class-based approach seems rather heavy-weight for such a simple decorator:\nclass RequestHandler(webapp.RequestHandler):\n\n # The decorator is now a class method.\n @classmethod # Note the 'klass' argument, similar to 'self' on an instance ...
[ 4, 1 ]
[]
[]
[ "decorator", "python", "subclassing", "web_applications" ]
stackoverflow_0003378949_decorator_python_subclassing_web_applications.txt
Q: How to Get a Certain Number of Elements from a Django Database I have a simple class: class BlogPost(models.Model): title = models.CharField(max_length=150) ... timestamp = models.DateTimeField() How can I get the last five items from the database? I tried to do this: posts = BlogPost.objects.<any code> A: You need to invest some time in Reading The Friggin' Manual. Django is one of the best documented open source projects on the planet. Her's the specific thing you want to read, Limiting QuerySets, but you really need to read the whole page (and a few others) if you are going to do anything meaningful with Django. A: BlogPost.objects.order_by('-timestamp')[:5] A: You use the array-slicing syntax to index into your queryset, and you use the reverse() function to reverse the queryset before indexing, e.g., myQuerySet.reverse()[:5]. See the docs for more details. A: I think that ordering by id it's faster than sorting by any other field.
How to Get a Certain Number of Elements from a Django Database
I have a simple class: class BlogPost(models.Model): title = models.CharField(max_length=150) ... timestamp = models.DateTimeField() How can I get the last five items from the database? I tried to do this: posts = BlogPost.objects.<any code>
[ "You need to invest some time in Reading The Friggin' Manual. Django is one of the best documented open source projects on the planet.\nHer's the specific thing you want to read, Limiting QuerySets, but you really need to read the whole page (and a few others) if you are going to do anything meaningful with Django....
[ 7, 1, 0, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0003585919_django_django_models_python.txt
Q: gtk idle_add not running? I have a two-thread application: GUI, and some background work. I'm trying to send requests to the main thread to do GUI updates (move a progress bar), but it doesn't seem to work. I've boiled it down to a really minimal example: import pygtk pygtk.require('2.0') import glib import gtk import threading import sys import time def idle(): sys.stderr.write('Hello from another world.\n') sys.stderr.flush() gtk.main_quit() def another_thread(): time.sleep(1) glib.idle_add(idle) thread = threading.Thread(target=another_thread) thread.start() gtk.main() This should, I thought, print something to standard error from the main/GUI thread, but nothing happens. And it doesn't quit, either, so gtk.main_quit isn't being called. Also, adding more output to stderr acts weirdly. If I change the thread's function to: sys.stderr.write('----\n') sys.stderr.write('----\n') sys.stderr.flush() sys.stderr.write('After.\n') sys.stderr.flush() I see 1, sometimes 2 lines out output. It looks like some kind of race condition with the main thread entering gtk.main, but I don't know why this would be. A: You need to init glib's thread support before using glib in a multi-threaded environment. Just call: glib.threads_init() Before calling into glib functions. A: Why not use glib.timeout_add_seconds(1, idle) and return False from idle() instead of starting a thread and then sleeping 1 second? Starting an idle function from another thread is quite redundant, since idle functions already run in another thread. EDIT: By "starting an idle function from another thread is redundant", I meant that you don't have to start an idle function in order to mess with the GUI and update the progress bar. It is a myth that you can't mess with the GUI in other threads. Let me restate here what is needed to do GTK calls from other threads: Call glib.threads_init() or gobject.threads_init(), whichever you have, as discussed in vanza's answer. Call gtk.gdk.threads_init(). I am pretty sure you are right in your answer, this only has to be called before gtk.main(). The C docs suggest calling it before gtk_init(), but that's called at import time in PyGTK if I'm not mistaken. Bracket your call to gtk.main() between gtk.gdk.threads_enter() and gtk.gdk.threads_leave(). Bracket any calls to GTK functions from: threads other than the main thread idle functions timeouts basically any callback other than signal handlers between gtk.gdk.threads_enter() and gtk.gdk.threads_leave(). Note that instead of surrounding your calls with enter/leave pairs, you can also use with gtk.gdk.lock: and do your calls within that with-block. Here are some resources which also explain the matter: http://www.yolinux.com/TUTORIALS/GDK_Threads.html http://blogs.operationaldynamics.com/andrew/software/gnome-desktop/gtk-thread-awareness.html A: The following makes the above work for me: A call to gtk.gdk.threads_init() before doing anything else: before starting threads, before entering gtk.main(). I think in reality, this only needs to be called before entering gtk.main(), but it is easy enough to call it while everything is single threaded and simple. In the idle callback (idle, in the example), a call to gtk.gdk.threads_enter() before GTK stuff (easy to do just at the top of the function), and a call to gtk.gdk.threads_leave(), before the end of the function. gtk.gdk.threads_init() seems to also tell PyGTK not hold the GIL when it goes to sleep - I think I was missing some output from the aux. thread in the example just because the sleeping main thread (sleeping in gtk.main()) was still holding the GIL. gtk.gdk.threads_init(), as far as I can tell, instills good mojo into PyGTK and GTK+. Because of this, gtk.gdk.threads_init() is needed even if you launch a thread that doesn't touch GTK+, doesn't do anything with glib, gobject, etc., just does basic computation.
gtk idle_add not running?
I have a two-thread application: GUI, and some background work. I'm trying to send requests to the main thread to do GUI updates (move a progress bar), but it doesn't seem to work. I've boiled it down to a really minimal example: import pygtk pygtk.require('2.0') import glib import gtk import threading import sys import time def idle(): sys.stderr.write('Hello from another world.\n') sys.stderr.flush() gtk.main_quit() def another_thread(): time.sleep(1) glib.idle_add(idle) thread = threading.Thread(target=another_thread) thread.start() gtk.main() This should, I thought, print something to standard error from the main/GUI thread, but nothing happens. And it doesn't quit, either, so gtk.main_quit isn't being called. Also, adding more output to stderr acts weirdly. If I change the thread's function to: sys.stderr.write('----\n') sys.stderr.write('----\n') sys.stderr.flush() sys.stderr.write('After.\n') sys.stderr.flush() I see 1, sometimes 2 lines out output. It looks like some kind of race condition with the main thread entering gtk.main, but I don't know why this would be.
[ "You need to init glib's thread support before using glib in a multi-threaded environment. Just call:\nglib.threads_init()\n\nBefore calling into glib functions.\n", "Why not use glib.timeout_add_seconds(1, idle) and return False from idle() instead of starting a thread and then sleeping 1 second? Starting an idl...
[ 4, 3, 0 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0003579221_gtk_pygtk_python.txt
Q: Can I make a program reading from a piped stdin AND keyboard? Can I write a python program that read from a piped stdin and keyboard? What I mean? I want to be able to use it in this way: tail -f LOGFILE | myscript.py see the log lines appearing in the screen and type commands with the keyboard? This sounds like 2 stdin and that confuse me. Is it possible or is it conceptually wrong? Thanks! A: Possible solution would be to grab the users current tty and attach a file stream to the corresponding /dev/tty entry. This may allow you to grab the keyboard input while using stdin as your piped log file. A: Make your script take a file argument, then use bash's ability to create an anonymous fifo: myscript.py <( tail -f LOGFILE ) bash translates this to (roughly): mkfifo /tmp/UNIQUEFILENAME tail -f LOGFILE > /tmp/UNIQUEFILENAME & myscript.py /tmp/UNIQUEFILENAME Have only the commands come through stdin. <() and >(), especially when combined with tee, can be used anytime you want to create a "branch" in an either side of an arbitrary bash pipeline. A: This might be hackable, but it is conceptually wrong seems weird to me. stdin is a single input stream. Issuing the command ... | program.py changes stdin to be the stdout of whatever came before the pipe. But accepting keyboard input means reading the original stdin -- you can't have your cake and eat it too! A hack would merge those two streams into one, but that's not a good way of doing it; it doesn't separate the data correctly. If your program really should accept keyboard input as well as piped data (are you sure that it should? that seems like an awfully counterintuitive thing to want!), the right way to do it is to spawn separate threads to handle each of the input streams.
Can I make a program reading from a piped stdin AND keyboard?
Can I write a python program that read from a piped stdin and keyboard? What I mean? I want to be able to use it in this way: tail -f LOGFILE | myscript.py see the log lines appearing in the screen and type commands with the keyboard? This sounds like 2 stdin and that confuse me. Is it possible or is it conceptually wrong? Thanks!
[ "Possible solution would be to grab the users current tty and attach a file stream to the corresponding /dev/tty entry.\nThis may allow you to grab the keyboard input while using stdin as your piped log file.\n", "Make your script take a file argument, then use bash's ability to create an anonymous fifo:\nmyscrip...
[ 4, 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003584857_python.txt
Q: How can I get 'urlpatterns = __import__()' to work like a normal import statement? I'm trying to create an import statement that's pluggable with other projects. This statement is located in urls.py So this works: from forum.urls import urlpatterns # Base Class: <type 'list'> But this doesn't work: from settings import ROOT_URLCONF as project_urls urlpatterns = __import__(project_urls) # Base Class: <type 'module'> How can I get the latter to work? A: So you want to have import statements that are relative to earlier imports? Definitely something I tried at one point. I had some very long import statements that had a common root, so I tried to factor it out. I could not get it to work with straight import statements, but maybe I didn't try hard enough. Keep in mind that the import statement behavior by default is going to create a module object. It will then bind it into sys.modules, and then bind it in your current module's namespace with the name from the import statement. See http://docs.python.org/tutorial/modules.html. A module object has a namespace. If a module is not a package, it's namespace comes from evaluating the contents of the .py file of the module. However, if it is a package then the namespace comes from the __init__.py module in the package. The other modules in the package are not imported automatically and are not available in the package's namespace. You have to import them separately. The from...import statement will load the module into sys.modules. Then it will pull the object out of that module to which you referred in the import. Finally it binds that object into your current module's namespace with the name from the import statement. Basically you are copying a binding from one namespace to another. To be honest I find that it usually obfuscates the source of the name when you use it later (so I don't do it much). To the point: Your use of __import__ is one way around the limits of the import statement. See the python documentation. However, if you use a from..import statement don't try to reuse the resulting name in __import__ unless that is pointing to a module object (which it probably isn't). Imports need a dot-delimited sequence of module names only. As well, keep in mind that just putting the explicit import may be a cleaner way to indicate where an object came from. A: urlpatterns = __import__(project_urls).whateversubmodule.urlpatterns
How can I get 'urlpatterns = __import__()' to work like a normal import statement?
I'm trying to create an import statement that's pluggable with other projects. This statement is located in urls.py So this works: from forum.urls import urlpatterns # Base Class: <type 'list'> But this doesn't work: from settings import ROOT_URLCONF as project_urls urlpatterns = __import__(project_urls) # Base Class: <type 'module'> How can I get the latter to work?
[ "So you want to have import statements that are relative to earlier imports? \nDefinitely something I tried at one point. I had some very long import statements that had a common root, so I tried to factor it out. I could not get it to work with straight import statements, but maybe I didn't try hard enough.\nKe...
[ 1, 0 ]
[]
[]
[ "python", "python_import", "python_module" ]
stackoverflow_0003586152_python_python_import_python_module.txt
Q: Why my program freezing while I am listening socket So, here is some code: obj.HOST = "" obj.PORT = int(port.get()) # it's 100% correct PORT number obj.srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) obj.srv.bind((obj.HOST, obj.PORT)) obj.srv.listen(1) obj.sock, obj.addr = obj.srv.accept() class Client(threading.Thread): def __init__(self,from_): if from_.ip.get() == '': obj.HOST = 'localhost' # I am starting both programs from 1 computer, so it's 'localhost' else: obj.HOST = from_.ip.get() obj.PORT = int(from_.port.get()) # it's 100% correct PORT number (the same as previous) obj.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) obj.sock.connect((obj.HOST, obj.PORT)) threading.Thread.__init__(self) def run(self): command = obj.sock.recv(1024) print command if command == 'confirm': print 'confirm' elif command == 'start': print 'start' client = Client(cl) # cl is class, where I get port. It's works 100% correct client.start() I start the same program on my computer. One is host, second is client. Question 1: while I'm waiting to connect, my server script is freezing. How it repair? After connection both programs work correctly, but when server send some information(string), client script freezing. Question 2: so how it can be repaired? A: Not sure what the obj is. But you are not sending anything from the server to client. on the server side, you could do some thing like this : conn, addr = srv.accept() print 'Connected by', addr conn.send("confirm") conn.close() This will accept a single connection, send some data "confirm", close connection and exit. Same with client side: def run(self): command = self.sock.recv(1024) print command print "Recieved : ", command self.sock.close() This will connect to server, receive some data, print and close connection. recv is a blocking call and will block till it receives some data from the server. This might be the cause of your freeze up.
Why my program freezing while I am listening socket
So, here is some code: obj.HOST = "" obj.PORT = int(port.get()) # it's 100% correct PORT number obj.srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) obj.srv.bind((obj.HOST, obj.PORT)) obj.srv.listen(1) obj.sock, obj.addr = obj.srv.accept() class Client(threading.Thread): def __init__(self,from_): if from_.ip.get() == '': obj.HOST = 'localhost' # I am starting both programs from 1 computer, so it's 'localhost' else: obj.HOST = from_.ip.get() obj.PORT = int(from_.port.get()) # it's 100% correct PORT number (the same as previous) obj.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) obj.sock.connect((obj.HOST, obj.PORT)) threading.Thread.__init__(self) def run(self): command = obj.sock.recv(1024) print command if command == 'confirm': print 'confirm' elif command == 'start': print 'start' client = Client(cl) # cl is class, where I get port. It's works 100% correct client.start() I start the same program on my computer. One is host, second is client. Question 1: while I'm waiting to connect, my server script is freezing. How it repair? After connection both programs work correctly, but when server send some information(string), client script freezing. Question 2: so how it can be repaired?
[ "Not sure what the obj is.\nBut you are not sending anything from the server to client. \non the server side, you could do some thing like this :\nconn, addr = srv.accept()\nprint 'Connected by', addr\nconn.send(\"confirm\")\nconn.close()\n\nThis will accept a single connection, send some data \"confirm\", close co...
[ 0 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0003586452_python_sockets.txt
Q: Merits of Bash Script v. Python Script for Shell-Command-Heavy Utility I need to write a script to do the following: Monitor a queuing system, which is accessible by shell commands. Create directories from templates using a mix of inline text editing, cp/mv, command line scripts, and compiled c++ programs. Check for error conditions. Write files on error conditions. Note: 2D arrays would be mildly useful to my program, but I'm currently making due with several 1D arrays (due to the limitations of Bash script's arrays). Those tasks all seems somewhat "shell heavy" in so much as it can easily be implemented with a bunch of shell commands, so I thought Bash scripting would be a natural way to go. My results thus far have been good, but before I begin refactoring and finalizing my code, I was wondering whether it'd be better to port it to Python. I've read in numerous places that Python is "superior" to bash. I've done a bit of Python scripting and as far as I can tell, that's because it has more built in libraries and has support for object-oriented programming. However, all the scripts I've seen using shell commands, such as this one: http://magazine.redhat.com/2008/02/07/python-for-bash-scripters-a-well-kept-secret/ Implement obnoxious syntax, like having to define commands as variables, like so: #You could add another bash command here #HOLDING_SPOT="""fake_command""" #Determines Home Directory Usage in Gigs HOMEDIR_USAGE = """ du -sh $HOME | cut -f1 """ #Determines IP Address IPADDR = """ /sbin/ifconfig -a | awk '/(cast)/ { print $2 }' | cut -d':' -f2 | head -1 """ ...and requiring wrapper functions and other fun. Am I just being silly or does that seem less intuitive? Is there a speed advantage for use with Python that would outweigh the simplicity advantage of Bash when it comes to shell script commands? Or is the syntax of bash (no 2D arrays, brace/parentheses intricacies) reason to jump to Python? A: If you can't find a reason to switch it's probably because there's no reason. I started to switch python because some of my scripts require some templating process that was easier to do in other than shell script. There were also another scripts which required configuration file parsing or parameter parsing that make me learn a bit more of python, and finally another ones which deal with trac (coded in python) who made me switch to python. But if you could outline your scripts in bash fast and cleanly without require another tool, remain in bash, it is a great tool. A: Bash is good right at the actual interface with the system, because it's so easy to run external programs, and for processing data that comes in streams. Python is good at work with less surface area, involving more looping, logic, data structures, and so on. Horses for courses. It's hard to advise you which to use, or how to use both, without knowing details of your problem. But from the sound of it, this is something i'd do entirely in shell script. I'd find a way of doing it without arrays, though; the key is to stop thinking in C++ and start thinking in bash. A: It really depends on what you are trying to do, but here are some general differences. Shells, including bash, want to treat all variables as strings and to access variable values through simple textual substitution. Sometimes this is convenient; sometimes not so much. In shell scripts you tend to manipulate data by piping it through various utilities. Sometimes this is convenient; sometimes not so much. Python has very good string manipulation, so if you are doing a lot of text file munging it can be faster (both to write and to run) to do it in Python rather than figuring out what sed or awk incantation you want. That's another thing -- many of the tools you will use in shell scripts have so many options that they are essentially mini-languages of their own, some of which are terse to the point of being obtuse. Python can be much more readable than shell scripts that invoke a lot of these mini-languages since it is consistent syntactically. Some projects lend themselves to an object-oriented approach, which Python supports handily, while bash... not so much. Python also supports some functional techniques, which are handy for some projects, while bash... you get the picture. In short, a shell's scripting language is intended to be glue for tying together various single-function utilities, with some conveniences to make that easier, while Python is a robust programming language in which you can build complete GUI or Web applications if you like. I personally also find the overall syntax of Python much nicer than a shell scripting language; my programs tend to do what I want without a lot of fiddling, and when they don't it's usually because of a logic error rather than an error translating what I want into the language. To me, Python is nearly unique in this regard, although I hear Ruby programmers say similar things about their favorite language. If you are familiar with and like shell scripting, Perl might be an easier step up since it was originally intended to replace shell scripts (and sed/awk).
Merits of Bash Script v. Python Script for Shell-Command-Heavy Utility
I need to write a script to do the following: Monitor a queuing system, which is accessible by shell commands. Create directories from templates using a mix of inline text editing, cp/mv, command line scripts, and compiled c++ programs. Check for error conditions. Write files on error conditions. Note: 2D arrays would be mildly useful to my program, but I'm currently making due with several 1D arrays (due to the limitations of Bash script's arrays). Those tasks all seems somewhat "shell heavy" in so much as it can easily be implemented with a bunch of shell commands, so I thought Bash scripting would be a natural way to go. My results thus far have been good, but before I begin refactoring and finalizing my code, I was wondering whether it'd be better to port it to Python. I've read in numerous places that Python is "superior" to bash. I've done a bit of Python scripting and as far as I can tell, that's because it has more built in libraries and has support for object-oriented programming. However, all the scripts I've seen using shell commands, such as this one: http://magazine.redhat.com/2008/02/07/python-for-bash-scripters-a-well-kept-secret/ Implement obnoxious syntax, like having to define commands as variables, like so: #You could add another bash command here #HOLDING_SPOT="""fake_command""" #Determines Home Directory Usage in Gigs HOMEDIR_USAGE = """ du -sh $HOME | cut -f1 """ #Determines IP Address IPADDR = """ /sbin/ifconfig -a | awk '/(cast)/ { print $2 }' | cut -d':' -f2 | head -1 """ ...and requiring wrapper functions and other fun. Am I just being silly or does that seem less intuitive? Is there a speed advantage for use with Python that would outweigh the simplicity advantage of Bash when it comes to shell script commands? Or is the syntax of bash (no 2D arrays, brace/parentheses intricacies) reason to jump to Python?
[ "If you can't find a reason to switch it's probably because there's no reason.\nI started to switch python because some of my scripts require some templating process that was easier to do in other than shell script. \nThere were also another scripts which required configuration file parsing or parameter parsing th...
[ 7, 3, 3 ]
[]
[]
[ "bash", "performance", "python", "refactoring", "shell" ]
stackoverflow_0003585912_bash_performance_python_refactoring_shell.txt
Q: How to manage several python subprojects with setuptools? I'm wondering about the correct/easiest/most pythonic way of dealing with subprojects that you want have using the same base package. We currently have a file structure like this: trunk\ proj1\setup.py company_name\__init__.py + proj1's code proj2\setup.py company_name\__init__.py + proj2's code We want to keep the namespace company_name common to all our projects (maybe this itself is unpythonic?) but when proj1 and proj2 are installed in develop mode, the first one installed gets broken. It looks like import company_name... gets confused on which company_name package to look in and it grabs the first/last/random one. How would this normally be handled in a larger python project? Is it possible to resolve this with a setup.py in the trunk that builds some sort of mega-egg? I haven't found any relevant info on google or stack, so any information even just links are greatly appreciated! edit: I just tried adding a setup.py in the root folder with ... namespace_packages = ['company_name'], package_dir = {'company_name' : ['proj1/company_name', 'proj2/company_name']} ... with appropriate pkg_resources.declare_namespace(__name__) in the __init_.py files, but ./setup.py bdist_egg just gives: error in company_name setup command: Distribution contains no modules or packages for namespace package 'company_name' A: While I can't vouch for the pythonity of my solution, I did finally get the different applications running together alright. I was on the right track with the namespace packages, but instead of trying to have one super-project in the trunk, I added the namespace_packages line in the setup.py of each individual project. This led to the behaving properly when installed together, sharing the company_name namespace as intended. Anyone who wants to chime in on wether this is a reasonable python solution, I'm still interested to hear if this is "the way it's done". It feels right, but that could be because it mimics the java style I'm more used to.
How to manage several python subprojects with setuptools?
I'm wondering about the correct/easiest/most pythonic way of dealing with subprojects that you want have using the same base package. We currently have a file structure like this: trunk\ proj1\setup.py company_name\__init__.py + proj1's code proj2\setup.py company_name\__init__.py + proj2's code We want to keep the namespace company_name common to all our projects (maybe this itself is unpythonic?) but when proj1 and proj2 are installed in develop mode, the first one installed gets broken. It looks like import company_name... gets confused on which company_name package to look in and it grabs the first/last/random one. How would this normally be handled in a larger python project? Is it possible to resolve this with a setup.py in the trunk that builds some sort of mega-egg? I haven't found any relevant info on google or stack, so any information even just links are greatly appreciated! edit: I just tried adding a setup.py in the root folder with ... namespace_packages = ['company_name'], package_dir = {'company_name' : ['proj1/company_name', 'proj2/company_name']} ... with appropriate pkg_resources.declare_namespace(__name__) in the __init_.py files, but ./setup.py bdist_egg just gives: error in company_name setup command: Distribution contains no modules or packages for namespace package 'company_name'
[ "While I can't vouch for the pythonity of my solution, I did finally get the different applications running together alright. I was on the right track with the namespace packages, but instead of trying to have one super-project in the trunk, I added the namespace_packages line in the setup.py of each individual pro...
[ 7 ]
[]
[]
[ "name_conflict", "namespace_package", "package", "python", "setuptools" ]
stackoverflow_0003574799_name_conflict_namespace_package_package_python_setuptools.txt
Q: DEADLOCK_WRAP error when using Berkeley Db in python (bsddb) I am using a berkdb to store a huge list of key-value pairs but for some reason when i try to access some of the data later i get this error: try: key = 'scrape011201-590652' contenttext = contentdict[key] except: print the error <type 'exceptions.KeyError'> 'scrape011201-590652' in contenttext = contentdict[key]\n', ' File "/usr/lib64/python2.5/bsddb/__init__.py", line 223, in __getitem__\n return _DeadlockWrap(lambda: self.db[key]) # self.db[key]\n', 'File "/usr/lib64/python2.5/bsddb/dbutils.py", line 62, in DeadlockWrap\n return function(*_args, **_kwargs)\n', ' File "/usr/lib64/python2.5/bsddb/__init__.py", line 223, in <lambda>\n return _DeadlockWrap(lambda: self.db[key]) # self.db[key]\n'] I am not sure what DeadlockWrap is but there isnt any other program or process accessing the berkdb or writing to it (as far as i know,) so not sure how we could get a deadlock, if its referring to that. Is it possible that I am trying to access the data to rapidly? I have this function call in a loop, so something like for i in hugelist: #try to get a value from the berkdb #do something with it I am running this with multiple datasets and this error only occurs with one of them, the largest one, not the others. A: I'm pretty certain the DeadlockWrap stuff is not relevant here. It's simply a way to automagically provide retries with a back-off strategy. In other words, if the database manipulation fails, it waits a little bit then tries again, a number of times before finally failing. You seem to be getting a KeyError from your dictionary get operation which is more likely to be due to the fact that the key you're using doesn't actually exist in the database. Try your code with something like: try: key = 'scrape011201-590652' if not contentdict.has_key(key): print "Urk!, No record for %s"%(key) contenttext = contentdict[key] except: print the error This should show you if the record doesn't exist in the table (by outputting the Urk! message). As to what you do in that case, it depends on your architecture. You would probably want to return either None or an empty string. You may also want to do exactly what you're doing now (raising an exception). A: contenttext = contentdict[key] if contentdict.has_key(key) else None
DEADLOCK_WRAP error when using Berkeley Db in python (bsddb)
I am using a berkdb to store a huge list of key-value pairs but for some reason when i try to access some of the data later i get this error: try: key = 'scrape011201-590652' contenttext = contentdict[key] except: print the error <type 'exceptions.KeyError'> 'scrape011201-590652' in contenttext = contentdict[key]\n', ' File "/usr/lib64/python2.5/bsddb/__init__.py", line 223, in __getitem__\n return _DeadlockWrap(lambda: self.db[key]) # self.db[key]\n', 'File "/usr/lib64/python2.5/bsddb/dbutils.py", line 62, in DeadlockWrap\n return function(*_args, **_kwargs)\n', ' File "/usr/lib64/python2.5/bsddb/__init__.py", line 223, in <lambda>\n return _DeadlockWrap(lambda: self.db[key]) # self.db[key]\n'] I am not sure what DeadlockWrap is but there isnt any other program or process accessing the berkdb or writing to it (as far as i know,) so not sure how we could get a deadlock, if its referring to that. Is it possible that I am trying to access the data to rapidly? I have this function call in a loop, so something like for i in hugelist: #try to get a value from the berkdb #do something with it I am running this with multiple datasets and this error only occurs with one of them, the largest one, not the others.
[ "I'm pretty certain the DeadlockWrap stuff is not relevant here. It's simply a way to automagically provide retries with a back-off strategy. In other words, if the database manipulation fails, it waits a little bit then tries again, a number of times before finally failing.\nYou seem to be getting a KeyError from ...
[ 4, 0 ]
[]
[]
[ "berkeley_db", "bsddb", "python" ]
stackoverflow_0002569227_berkeley_db_bsddb_python.txt
Q: Pythonic Object Instantiation question I have a Sleep class (object) and within that class a sleepInSeconds() method. Is there any difference between doing this: wait = Sleep() wait.sleepInSeconds(10) And doing this: wait = Sleep().sleepInSeconds(10) or Sleep().sleepInSeconds(10) Which is more correct (or 'Pythonic'), what kinds of problems could I run into with one or the other? Is there some overarching principal from OO programming that should have led me to this answer? A: If sleepInSeconds is a static method (seen from a functional point of view) you are misusing the sleep class as a namespace. Sounds a bit like a java background. You could perhaps better make sleepInSeconds a function in the module namespace (not in a class) as python has very good namespace support. If you still want to have it in a class, and the method does not use instance variables (fron self) then you could annotate that method as static (@staticmethod) and you should then use the class name, and not the instance, yo make explicit that it is a static method which does not change your instance's state. So both you options seem somehow not pythonic to me. If sleepInSeconds does change the instance state then I'd go for wait.sleepInSeconds(10) as you probably need the changed state somewhere. A: wait = sleep() wait.sleepInSeconds(10) and wait = sleep().sleepInSeconds(10) Have entirely different outcome. In this first case wait reference to a sleep instance. In the second case wait reference to the return value of sleepInSeconds. You need to figure out what you are trying to get. Either case is Pythonic. They question is what are you expecting wait to be. A: All three are functionally correct. The main difference is what you intend to do after this bit of code. wait = sleep() wait.sleepInSeconds(10) The above code will leave you a sleep object hanging around afterwards, under the name wait. If you intend to use this object more or later, you probably want this. wait = sleep().sleepInSeconds(10) The above will put the return value of sleepInSeconds() to wait. In some cases, this may be None. It could be an integer, too. Note, you can have sleepInSeconds() return self, in which case it is functionally equivalent to the first block. sleep().sleepInSeconds(10) The above will just sleep for 10 seconds. There will be no sleep object left over. Use this if you never want to use the object again. In my opinion, the most Pythonic are the first and last one. Use the first one if you want to keep the object around, and the second one if you don't need the object later. A: Unless you want to reuse your instance of sleep, keeping it around is a waste (allocating wait). Don't jam too much stuff on one line. The truer Pythonic style is to just use the libraries :P import time time.sleep(seconds)
Pythonic Object Instantiation question
I have a Sleep class (object) and within that class a sleepInSeconds() method. Is there any difference between doing this: wait = Sleep() wait.sleepInSeconds(10) And doing this: wait = Sleep().sleepInSeconds(10) or Sleep().sleepInSeconds(10) Which is more correct (or 'Pythonic'), what kinds of problems could I run into with one or the other? Is there some overarching principal from OO programming that should have led me to this answer?
[ "If sleepInSeconds is a static method (seen from a functional point of view) you are misusing the sleep class as a namespace. Sounds a bit like a java background.\nYou could perhaps better make sleepInSeconds a function in the module namespace (not in a class) as python has very good namespace support.\nIf you stil...
[ 4, 4, 3, 3 ]
[]
[]
[ "object", "python" ]
stackoverflow_0003587137_object_python.txt
Q: Python - Dynamic Nested List So I'm trying to generate a nested list in Python based on a width and a height. This is what I have so far: width = 4 height = 5 row = [None]*width map = [row]*height Now, this obviously isn't quite right. When printed it looks fine: [[None, None, None, None], [None, None, None, None], [None, None, None, None], [None, None, None, None], [None, None, None, None]] But attempting to assign a value to a position like so: map[2][3] = 'foo' I get: [[None, None, None, 'foo'], [None, None, None, 'foo'], [None, None, None, 'foo'], [None, None, None, 'foo'], [None, None, None, 'foo']] Clearly this happens because each sublist is really just referencing the same object, row, so changing one, changes them all. So this is closest I've got! How can I dynamically generate a nested list? Thanks! A: When you do [row]*height you end up with the same list object in each row. The row array reference is repeated in each row which means each row is actually pointing to the same list object. Hence modifying one row actually modifies all rows. Take a look at what happens when you print the id() for each row. They're all the same! >>> grid = [[None] * width] * height >>> [id(row) for row in grid] [148014860, 148014860, 148014860, 148014860, 148014860] You can get python to generate separate-but-identical lists for each row by using a list comprehension. When you use [rowexpr for i in xrange(height)] then rowexpr will be evaluated once per row. The trick then is to use an expression that will result in a unique list each time it is evaluated. This'll make more sense if you see it in action: >>> grid = [[None] * width for i in xrange(height)] >>> grid[2][3] = 'foo' >>> grid [[None, None, None, None], [None, None, None, None], [None, None, None, 'foo'], [None, None, None, None], [None, None, None, None]] Each time [None] * width is evaluated it generates a new list. >>> [id(row) for row in grid] [148016172, 148015212, 148016236, 148016108, 148016332] A: I use something like this: w = 5 h = 5 map = [] for i in range(h): row = [] for j in range(w): row.append(None) map.append(row) print map map[2][3] = 'foo' print map
Python - Dynamic Nested List
So I'm trying to generate a nested list in Python based on a width and a height. This is what I have so far: width = 4 height = 5 row = [None]*width map = [row]*height Now, this obviously isn't quite right. When printed it looks fine: [[None, None, None, None], [None, None, None, None], [None, None, None, None], [None, None, None, None], [None, None, None, None]] But attempting to assign a value to a position like so: map[2][3] = 'foo' I get: [[None, None, None, 'foo'], [None, None, None, 'foo'], [None, None, None, 'foo'], [None, None, None, 'foo'], [None, None, None, 'foo']] Clearly this happens because each sublist is really just referencing the same object, row, so changing one, changes them all. So this is closest I've got! How can I dynamically generate a nested list? Thanks!
[ "When you do [row]*height you end up with the same list object in each row. The row array reference is repeated in each row which means each row is actually pointing to the same list object. Hence modifying one row actually modifies all rows.\nTake a look at what happens when you print the id() for each row. They'r...
[ 12, 1 ]
[]
[]
[ "list", "nested", "python" ]
stackoverflow_0003587215_list_nested_python.txt
Q: Work with JSON in Python {"required_items":[ { "filename":"abcd", "no":"3" }, { "filename":"abc", "no":"2" } ]} I am not getting the code of the JSON format in Python - I want to insert the filename and no through a loop. list_of_other_ids={} for i in xxxx: entry={} entry['filename'] = "XXXX" entry['no'] =XX list_of_other_ids.append(entry) I am doing like this... and it fails. A: # data.txt {"required_items":[ { "filename":"abcd", "no":"3" }, { "filename":"abc", "no":"2" } ]} # parser.py import json data = json.load(open('data.txt')) for file in data: print file['filename'] # This will output: # abcd # abc If you want to append new items: data.append({ 'filename': 'foo', 'nr': 1 }) json.dump(data, open('data.txt', 'w'))
Work with JSON in Python
{"required_items":[ { "filename":"abcd", "no":"3" }, { "filename":"abc", "no":"2" } ]} I am not getting the code of the JSON format in Python - I want to insert the filename and no through a loop. list_of_other_ids={} for i in xxxx: entry={} entry['filename'] = "XXXX" entry['no'] =XX list_of_other_ids.append(entry) I am doing like this... and it fails.
[ "# data.txt\n\n{\"required_items\":[\n {\n \"filename\":\"abcd\",\n \"no\":\"3\"\n },\n {\n \"filename\":\"abc\",\n \"no\":\"2\"\n }\n ]}\n\n\n# parser...
[ 5 ]
[]
[]
[ "json", "python" ]
stackoverflow_0003587023_json_python.txt
Q: Python & HTML: Make user login to use website I'm creating a website with a database search functionality, but I want to make the user login or create a account first to use the search functionality. How do I do this? And what is the easiest way to carry the login session forward. I.E. the user only has to login once to do many searches. A: Look at Web Frameworks for Python, and select one of the listed Popular Full-Stack Frameworks (Django, TurboGears, ...). Each framework provides its own session support. SO discussions, for example choosing-a-web-application-framework-in-python, can help you choose one that meets your requirements. A: If you're using Apache as your web server you can use the built-in Htaccess command line tools for user management: http://en.wikipedia.org/wiki/Htaccess Htaccess is built-in to Apache and lets you manage users for PHP pages, CGI's (including Python), HTML pages, and others. Here's a few example use-cases: Initial setup: a. copy 3 .ht* files (.htpasswords, .htgroups, .htaccess) into your document root (find templates of these files on the web). b. add "AllowOverride Authconfig" into your apache conf file Create new user ('root') when .htpasswords file does not exist: $ htpasswd -c .htpasswords root add a user named 'root': $ htpasswd /Users/username/Sites/.htpasswords root change password of user 'root': $ htpasswd /Users/username/Sites/.htpasswords root In PHP you can see who logged in via htaccess and get their password with: $pass = $_SERVER['PHP_AUTH_PW']; // from htaccess Htaccess is not super user-friendly, so feel free to update/improve my workflow
Python & HTML: Make user login to use website
I'm creating a website with a database search functionality, but I want to make the user login or create a account first to use the search functionality. How do I do this? And what is the easiest way to carry the login session forward. I.E. the user only has to login once to do many searches.
[ "Look at Web Frameworks for Python, and select one of the listed\nPopular Full-Stack Frameworks (Django, TurboGears, ...).\nEach framework provides its own session support.\nSO discussions, for example choosing-a-web-application-framework-in-python,\ncan help you choose one that meets your requirements.\n", "If y...
[ 3, 0 ]
[]
[]
[ "html", "plone", "python" ]
stackoverflow_0003442732_html_plone_python.txt
Q: Python - very confused about method and while loop I have this method: def is_active(self): if self.is_current_node(): return True cur_children = self.get_children() while cur_children is not None: for child in cur_children: if child.is_current_node(): return True raise Exception(child.display_name) cur_children = cur_children.get_children() return False I put this method together and I put the raise Exception(child.display_name) to test out and "alert()" me to which child was being hit. The exception is never raised. You'd think that was because the function returned True on the if child.is_current_node() part. Well, if I replace the if part with this: for child in cur_children: if child.is_current_node(): raise Exception(child.display_name) It doesn't raise the exception still. If I do this however: for child in cur_children: raise Exception(child.display_name) The exception is raised. I'm so confused. I'm sure this is something ridiculous but I was up till 2 and I can't think straight enough to wrap my tiny brain around this. A: If the first child in the list .is_current_node(), then the exception will never be raised in your first snippet. Everything you have for evidence is supporting the idea that either self.is_current_node() is always true, or the first scanned child .is_current_node(). Given the third code snippet, the latter seems to be the case. EDIT: removing a misunderstanding (child != self) :/ Actually, I have to ask, what is this supposed to do? It looks vaguely like recursive tree-traversal, but it's not quite there. (the cur_children = cur_children.get_children() line in particular is a bit strange) A: Some ideas: cur_children = self._children while cur_children is not None: for child in cur_children: if child.is_current_node(): return True raise Exception(child.display_name) cur_children = cur_children._children I assume that self._children contains multiple children: [A, B, C] Then, on the first loop, it will take A. Let's assume that A has these children: [AA, AB, AC]. Now, you do this: cur_children = cur_children._children. This means that now, instead of continuing with B from the inital [A, B, C], it will continue with AA, and so on. In this example, it will never reach B. Is this intended? What does your is_current_node() contains? Probably you forgot to return a value, so the result is always None, and bool(None) == False. Another idea: (recursion) def is_active(self): def check_children(children): for child in children: if child.is_current_node(): return True else: if children._children: return check_children(children._children) return False if self.is_current_node(): return True return check_children(children) A: Maybe is_current_node always returns True and is_current_tab always returns False? I think more context is needed to give you an answer. The only thing I can think of is that is_current_node changes state.
Python - very confused about method and while loop
I have this method: def is_active(self): if self.is_current_node(): return True cur_children = self.get_children() while cur_children is not None: for child in cur_children: if child.is_current_node(): return True raise Exception(child.display_name) cur_children = cur_children.get_children() return False I put this method together and I put the raise Exception(child.display_name) to test out and "alert()" me to which child was being hit. The exception is never raised. You'd think that was because the function returned True on the if child.is_current_node() part. Well, if I replace the if part with this: for child in cur_children: if child.is_current_node(): raise Exception(child.display_name) It doesn't raise the exception still. If I do this however: for child in cur_children: raise Exception(child.display_name) The exception is raised. I'm so confused. I'm sure this is something ridiculous but I was up till 2 and I can't think straight enough to wrap my tiny brain around this.
[ "If the first child in the list .is_current_node(), then the exception will never be raised in your first snippet.\nEverything you have for evidence is supporting the idea that either self.is_current_node() is always true, or the first scanned child .is_current_node(). Given the third code snippet, the latter seems...
[ 2, 1, 0 ]
[]
[]
[ "python", "while_loop" ]
stackoverflow_0003587345_python_while_loop.txt
Q: oauth & POSTing JSON Reading section 9.1 of OAuth Core 1.0, I only see a reference to performing POST requests using content-type of application/x-www-form-urlencoded. How does one go about performing POST requests with JSON data in the request body? How does handle the signing? Is it at all possible? Can this work on AppEngine? A: I have urlencoded the JSON, then unencoded on the other end in the past. I don't really know anything about AppEngine though, sorry.
oauth & POSTing JSON
Reading section 9.1 of OAuth Core 1.0, I only see a reference to performing POST requests using content-type of application/x-www-form-urlencoded. How does one go about performing POST requests with JSON data in the request body? How does handle the signing? Is it at all possible? Can this work on AppEngine?
[ "I have urlencoded the JSON, then unencoded on the other end in the past. I don't really know anything about AppEngine though, sorry.\n" ]
[ 0 ]
[]
[]
[ "google_app_engine", "json", "oauth", "python" ]
stackoverflow_0003587454_google_app_engine_json_oauth_python.txt
Q: django modeladmin list_display I'm trying to play with the Django's official tutorial. Specifically the modeladmin list_display: http://docs.djangoproject.com/en/1.2/intro/tutorial02/#customize-the-admin-change-list How can I add a column that displays the number of choices for each poll in the list? Thanks! A: You don't need to edit your model, to calculate columns for admin on the fly create a function in the ModelAdmin object that takes a second param, this will be the regular Poll model instance. Than write code just like you would in a model, you can ignore the self here since it doesn't have what you want. class PollAdmin(admin.ModelAdmin) list_display = (<other_fields>, 'choice_count') def choice_count(self, model_instance): return model_instance.choice_set.count() A: Add a custom method (say pcount) that returns the number of choices for a given Poll instance. You can then add this to the list_display attribute in your ModelAdmin subclass. class Poll(models.Model): ... def pcount(self): return self.choice_set.count() class PollAdmin(admin.ModelAdmin): list_display = (<other fields>, 'pcount', )
django modeladmin list_display
I'm trying to play with the Django's official tutorial. Specifically the modeladmin list_display: http://docs.djangoproject.com/en/1.2/intro/tutorial02/#customize-the-admin-change-list How can I add a column that displays the number of choices for each poll in the list? Thanks!
[ "You don't need to edit your model, to calculate columns for admin on the fly create a function in the ModelAdmin object that takes a second param, this will be the regular Poll model instance. Than write code just like you would in a model, you can ignore the self here since it doesn't have what you want.\nclass ...
[ 3, 1 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0003586149_django_django_admin_python.txt
Q: Foreignkeyfield - verbose name not shown in form my verbose_name of a foreignkeyfield isn't printed in my forms. (I create the modelforms via modelformset_factory model class MOrders(models.Model): amount = models.IntegerField('Bestellmenge', null=True, blank=True) order_date = models.DateField('Bestelldatum') id = models.AutoField(primary_key=True) m_product_types = models.ForeignKey(MProductTypes) class Meta: db_table = u'm_orders' verbose_name = 'Bestellung' verbose_name_plural = 'Bestellungen' unique_together = (('id','order_date','m_product_types')) def __unicode__(self): return "%s" % (self.order_date) verbose_name of m_product_types is set. B class MProductTypes(models.Model): id = models.AutoField(primary_key=True) stock = models.IntegerField('Bestand',null=True, blank=True) m_products = models.ForeignKey(MProducts, verbose_name='Produkt') m_sizes = models.ForeignKey(MSizes, verbose_name='Groesse') m_colors = models.ForeignKey(MColors, verbose_name='Farbe') class Meta: verbose_name = u'Produktart' verbose_name_plural = 'Produktarten' db_table = u'm_product_types' Am I doing something wrong? I'm using the latest Django version from trunk. A: m_product_types = models.ForeignKey(MProductTypes, verbose_name = u'Produktart', )
Foreignkeyfield - verbose name not shown in form
my verbose_name of a foreignkeyfield isn't printed in my forms. (I create the modelforms via modelformset_factory model class MOrders(models.Model): amount = models.IntegerField('Bestellmenge', null=True, blank=True) order_date = models.DateField('Bestelldatum') id = models.AutoField(primary_key=True) m_product_types = models.ForeignKey(MProductTypes) class Meta: db_table = u'm_orders' verbose_name = 'Bestellung' verbose_name_plural = 'Bestellungen' unique_together = (('id','order_date','m_product_types')) def __unicode__(self): return "%s" % (self.order_date) verbose_name of m_product_types is set. B class MProductTypes(models.Model): id = models.AutoField(primary_key=True) stock = models.IntegerField('Bestand',null=True, blank=True) m_products = models.ForeignKey(MProducts, verbose_name='Produkt') m_sizes = models.ForeignKey(MSizes, verbose_name='Groesse') m_colors = models.ForeignKey(MColors, verbose_name='Farbe') class Meta: verbose_name = u'Produktart' verbose_name_plural = 'Produktarten' db_table = u'm_product_types' Am I doing something wrong? I'm using the latest Django version from trunk.
[ "m_product_types = models.ForeignKey(MProductTypes, \n verbose_name = u'Produktart',\n )\n\n" ]
[ 15 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0003587613_django_django_models_python.txt
Q: Python error, only in the command window. Causes site to hang when loading I receive this error when files are loading and sometimes after they have stopped loading. It only happens with this site, not with my other django sites. I can't make any sense of this one. Can anyone tell me what's going wrong here? A: Your server is too slow or it doesn't responds (networking problem, not a Python problem), that's what happens. only in the command window ? A: Too large an upload? Your front end interrupted the transfer somehow? Could be anything. We'll need more details to pin point the problem. Also, does this happen on your production setup?
Python error, only in the command window. Causes site to hang when loading
I receive this error when files are loading and sometimes after they have stopped loading. It only happens with this site, not with my other django sites. I can't make any sense of this one. Can anyone tell me what's going wrong here?
[ "Your server is too slow or it doesn't responds (networking problem, not a Python problem), that's what happens.\n\nonly in the command window\n\n?\n", "Too large an upload? Your front end interrupted the transfer somehow? Could be anything. We'll need more details to pin point the problem. Also, does this happen...
[ 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003587747_django_python.txt
Q: Google App Engine: Webtest simulating logged in user and administrator from the webtest documentation I learn that: The best way to simulate authentication is if your application looks in environ['REMOTE_USER'] to see if someone is authenticated. Then you can simply set that value, like: app.get('/secret', extra_environ=dict(REMOTE_USER='bob')) I am trying to do the same thing but in a Google App engine environment. I would like to simulate a logged in user and a user that's an administrator. If possible which dictionary values do I have to set in extra_environ to accomplish this? A: Set User: os.environ['USER_EMAIL'] = 'info@example.com' Set Admin: os.environ['USER_IS_ADMIN'] = '1' This is how my whole test looks like. My example uses webtest, nose, nosegae and gaetestbed. class TestingRoutes(WebTestCase, unittest.TestCase): APPLICATION = application() def tearDown(self): os.environ['USER_EMAIL'] = '' os.environ['USER_IS_ADMIN'] = '' #AdminIndex ..... def test_adminindex_no_user(self): #No user: redirect to login form response = app.get( url_map['adminindex'] ) self.assertRedirects(response) def test_adminindex_user(self): os.environ['USER_EMAIL'] = 'info@example.com' response = app.get( url_map['adminindex'] ) self.assertForbidden(response) def test_adminindex_admin(self): os.environ['USER_EMAIL'] = 'info@example.com' os.environ['USER_IS_ADMIN'] = '1' response = app.get( url_map['adminindex'] ) self.assertOK(response) Hope it helps.
Google App Engine: Webtest simulating logged in user and administrator
from the webtest documentation I learn that: The best way to simulate authentication is if your application looks in environ['REMOTE_USER'] to see if someone is authenticated. Then you can simply set that value, like: app.get('/secret', extra_environ=dict(REMOTE_USER='bob')) I am trying to do the same thing but in a Google App engine environment. I would like to simulate a logged in user and a user that's an administrator. If possible which dictionary values do I have to set in extra_environ to accomplish this?
[ "Set User:\nos.environ['USER_EMAIL'] = 'info@example.com'\n\nSet Admin:\nos.environ['USER_IS_ADMIN'] = '1'\n\nThis is how my whole test looks like. My example uses webtest, nose, nosegae and gaetestbed. \nclass TestingRoutes(WebTestCase, unittest.TestCase):\n\n APPLICATION = application()\n\n def tearDown(sel...
[ 6 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003587022_google_app_engine_python.txt
Q: Python: Pickling highly-recursive objects without using `setrecursionlimit` I've been getting RuntimeError: maximum recursion depth exceeded when trying to pickle a highly-recursive tree object. Much like this asker here. He solved his problem by setting the recursion limit higher with sys.setrecursionlimit. But I don't want to do that: I think that's more of a workaround than a solution. Because I want to be able to pickle my trees even if they have 10,000 nodes in them. (It currently fails at around 200.) (Also, every platform's true recursion limit is different, and I would really like to avoid opening this can of worms.) Is there any way to solve this at the fundamental level? If only the pickle module would pickle using a loop instead of recursion, I wouldn't have had this problem. Maybe someone has an idea how I can cause something like this to happen, without rewriting the pickle module? Any other idea how I can solve this problem will be appreciated. A: I suppose that most people never use recursive structures of such depth. Since easiest serialization implementations are recursive, you're going to only see them. If I were you I'd not use an openly recursive data structure here. Instead I'd number every node and use a link table that efficiently translates a number to a node with that number. Every node would refer to other nodes (e.g. its children) via that table, using numbers. A simple property would make this syntactically easy. Beyond that properties, no code dealing with tree traversal would have to change. Node constructor will have to allocate a number and put itself into the link table, which is trivial, too. The link table might be just a list of nodes, where index into the list serves as the node number; Python lists seem to have efficient access by index. If speed of inserts is important, I'd preallocate a long enough list filled with None; it would not take too much space. If nodes stored their own numbers, this structure would be cheaply traversable in both directions. As you see, pickling and unpickling such a tree would be trivial at any depth. A: To make understanding easier, here's a complete example, with only one link to simplify it: class Node(object): linker = [] # one list for all Node instances def __init__(self, payload): self.payload = payload self.__next = None self.__index = len(self.linker) self.linker.append(self) # def getNext(self): if self.__next is not None: return self.linker[self.__next] # def setNext(self, another): if another is not None: self.__next = another.__index else: self.__next = None # next = property(getNext, setNext) # def __str__(self): return repr(self.payload) a = Node("One") b = Node("Two") c = Node("Three") b.next = c a.next = b # prints "One" "Two" "Three" print a, a.next, a.next.next Also note that this structure can easily contain cycles and still serialize plainly. A: Just dont use recursion. Make a stack (list / queue) with open nodes and process this. Something like this (pseudo code) stack.add(root) while not list.empty: current = stack.pop // process current for each child of current: stack.add(child) That should do it A: I think a good solution is a combination of Mene's and 9000's answers. Given that nodes have globally unique IDs (maybe somehow memory addresses can be used as such) you can do this. Granted this is a sloppy pseudo-implementation, but with a bit of abstraction if encapsulated in a tree class it could be very simple. def all_nodes(node): # walk the tree and get return all nodes as a list if node: nodes = [] for child in node.children: for sub_child in all_nodes(child): nodes.append(sub_child) return nodes return [] class Node(object): def __init__(self, children, id): self.children = children self.id = id def __getstate__(self): #when pickling translate children into IDs tmp = self.__dict__.copy() children_ids = [] for child in tmp['children']: children_ids.append(child.id) tmp['children_ids'] = children_ids return tmp lookup = dict() for node in all_nodes(rootNode): # put all nodes into a dictionary lookup[node.id] = node #then pickle the dictionary #then you can unpickle it and walk the dictionary for id, node in lookup: del node.children node.children = [] for child in node.children_ids: node.children.append(lookup[child]) #and three should now be rebuilt
Python: Pickling highly-recursive objects without using `setrecursionlimit`
I've been getting RuntimeError: maximum recursion depth exceeded when trying to pickle a highly-recursive tree object. Much like this asker here. He solved his problem by setting the recursion limit higher with sys.setrecursionlimit. But I don't want to do that: I think that's more of a workaround than a solution. Because I want to be able to pickle my trees even if they have 10,000 nodes in them. (It currently fails at around 200.) (Also, every platform's true recursion limit is different, and I would really like to avoid opening this can of worms.) Is there any way to solve this at the fundamental level? If only the pickle module would pickle using a loop instead of recursion, I wouldn't have had this problem. Maybe someone has an idea how I can cause something like this to happen, without rewriting the pickle module? Any other idea how I can solve this problem will be appreciated.
[ "I suppose that most people never use recursive structures of such depth. Since easiest serialization implementations are recursive, you're going to only see them.\nIf I were you I'd not use an openly recursive data structure here. Instead I'd number every node and use a link table that efficiently translates a num...
[ 3, 2, 1, 1 ]
[]
[]
[ "pickle", "python", "recursion" ]
stackoverflow_0002912841_pickle_python_recursion.txt
Q: Pickle vs output to a file in python I have a program that outputs some lists that I want to store to work with later. For example, suppose it outputs a list of student names and another list of their midterm scores. I can store this output in the following two ways: Standard File Output way: newFile = open('trialWrite1.py','w') newFile.write(str(firstNames)) newFile.write(str(midterm1Scores)) newFile.close() The pickle way: newFile = open('trialWrite2.txt','w') cPickle.dump(firstNames, newFile) cPickle.dump(midterm1Scores, newFile) newFile.close() Which technique is better or preferred? Is there an advantage of using one over the other? Thanks A: I think the csv module might be a good fit here, since CSV is a standard format that can be both read and written by Python (and many other languages), and it's also human-readable. Usage could be as simple as with open('trialWrite1.py','wb') as fileobj: newFile = csv.writer(fileobj) newFile.writerow(firstNames) newFile.writerow(midterm1Scores) However, it'd probably make more sense to write one student per row, including their name and score. That can be done like this: from itertools import izip with open('trialWrite1.py','wb') as fileobj: newFile = csv.writer(fileobj) for row in izip(firstNames, midterm1Scores): newFile.writerow(row) A: pickle is more generic -- it allows you to dump many different kinds of objects to a file for later use. The downside is that the interim storage is not very human-readable, and not in a standard format. Writing strings to a file, on the other hand, is a much better interface to other activities or code. But it comes at the cost of having to parse the text back into your Python object again. Both are fine for this simple (list?) data; I would use write( firstNames ) simply because there's no need to use pickle. In general, how to persist your data to the filesystem depends on the data! For instance, pickle will happily pickle functions, which you can't do by simply writing the string representations. >>> data = range <class 'range'> >>> pickle.dump( data, foo ) # stuff >>> pickle.load( open( ..., "rb" ) ) <class 'range'. A: For a completely different approach, consider that Python ships with SQLite. You could store your data in a SQL database without adding any third-party dependencies.
Pickle vs output to a file in python
I have a program that outputs some lists that I want to store to work with later. For example, suppose it outputs a list of student names and another list of their midterm scores. I can store this output in the following two ways: Standard File Output way: newFile = open('trialWrite1.py','w') newFile.write(str(firstNames)) newFile.write(str(midterm1Scores)) newFile.close() The pickle way: newFile = open('trialWrite2.txt','w') cPickle.dump(firstNames, newFile) cPickle.dump(midterm1Scores, newFile) newFile.close() Which technique is better or preferred? Is there an advantage of using one over the other? Thanks
[ "I think the csv module might be a good fit here, since CSV is a standard format that can be both read and written by Python (and many other languages), and it's also human-readable. Usage could be as simple as \nwith open('trialWrite1.py','wb') as fileobj:\n newFile = csv.writer(fileobj)\n newFile.writerow(f...
[ 6, 3, 0 ]
[]
[]
[ "file_io", "pickle", "python" ]
stackoverflow_0003588023_file_io_pickle_python.txt
Q: python: keep char only if it is within this list i have a list: a = ['a','b','c'.........'A','B','C'.........'Z'] and i have string: string1= 's#$%ERGdfhliisgdfjkskjdfW$JWLI3590823r' i want to keep ONLY those characters in string1 that exist in a what is the most effecient way to do this? perhaps instead of having a be a list, i should just make it a string? like this a='abcdefg..........ABC..Z' ?? A: This should be faster. >>> import re >>> string1 = 's#$%ERGdfhliisgdfjkskjdfW$JWLI3590823r' >>> a = ['E', 'i', 'W'] >>> r = re.compile('[^%s]+' % ''.join(a)) >>> print r.sub('', string1) EiiWW This is even faster than that. >>> all_else = ''.join( chr(i) for i in range(256) if chr(i) not in set(a) ) >>> string1.translate(None, all_else) 'EiiWW' 44 microsec vs 13 microsec on my laptop. How about that? (Edit: turned out, translate yields the best performance.) A: ''.join([s for s in string1 if s in a]) Explanation: [s for s in string1 if s in a] creates a list of all characters in string1, but only if they are also in the list a. ''.join([...]) turns it back into a string by joining it with nothing ('') in between the elements of the given list. A: List comprehension to the rescue! wanted = ''.join(letter for letter in string1 if letter in a) (Note that when passing a list comprehension to a function you can omit the brackets so that the full list isn't generated prior to being evaluated. While semantically the same as a list comprehension, this is called a generator expression.) A: If, you are going to do this with large strings, there is a faster solution using translate; see this answer. A: @katrielalex: To spell it out: import string string1= 's#$%ERGdfhliisgdfjkskjdfW$JWLI3590823r' non_letters= ''.join(chr(i) for i in range(256) if chr(i) not in string.letters) print string1.translate(None,non_letters) print 'Simpler, but possibly less correct' print string1.translate(None, string.punctuation+string.digits+string.whitespace)
python: keep char only if it is within this list
i have a list: a = ['a','b','c'.........'A','B','C'.........'Z'] and i have string: string1= 's#$%ERGdfhliisgdfjkskjdfW$JWLI3590823r' i want to keep ONLY those characters in string1 that exist in a what is the most effecient way to do this? perhaps instead of having a be a list, i should just make it a string? like this a='abcdefg..........ABC..Z' ??
[ "This should be faster.\n>>> import re\n>>> string1 = 's#$%ERGdfhliisgdfjkskjdfW$JWLI3590823r'\n>>> a = ['E', 'i', 'W']\n>>> r = re.compile('[^%s]+' % ''.join(a))\n>>> print r.sub('', string1)\nEiiWW\n\nThis is even faster than that.\n>>> all_else = ''.join( chr(i) for i in range(256) if chr(i) not in set(a) )\n>>>...
[ 7, 5, 3, 1, 0 ]
[]
[]
[ "list", "python", "string" ]
stackoverflow_0003588452_list_python_string.txt
Q: Localization of GUI built with Glade and Python (Gtk) I have made an application using Glade and Python and I would like to make several localizations. I know how to localize strings that are in the Python code, I just encapsule all the strings that are supposed to be localized with _() and than specify the translation of the string in a .po file. But how do I tell a string that is built with Glade that it should be localizable (for example labels, menu items, button labels, ...)? I am using gettext for the localization. Thank you, Tomas A: You should be able to create a *.pot file from a *.glade file using intltool-extract --type=gettext/glade foo.glade, and intltool supposedly knows what is translatable. Also, I suggest you look into GtkBuilder if you didn't do that already (you can save GtkBuilder interface files from recent Glade 3 versions, and you won't need the extra libglade anymore).
Localization of GUI built with Glade and Python (Gtk)
I have made an application using Glade and Python and I would like to make several localizations. I know how to localize strings that are in the Python code, I just encapsule all the strings that are supposed to be localized with _() and than specify the translation of the string in a .po file. But how do I tell a string that is built with Glade that it should be localizable (for example labels, menu items, button labels, ...)? I am using gettext for the localization. Thank you, Tomas
[ "You should be able to create a *.pot file from a *.glade file using intltool-extract --type=gettext/glade foo.glade, and intltool supposedly knows what is translatable.\nAlso, I suggest you look into GtkBuilder if you didn't do that already (you can save GtkBuilder interface files from recent Glade 3 versions, and...
[ 4 ]
[]
[]
[ "gettext", "glade", "pygtk", "python", "user_interface" ]
stackoverflow_0003586071_gettext_glade_pygtk_python_user_interface.txt
Q: Number of floats between two floats Say I have two Python floats a and b, is there an easy way to find out how many representable real numbers are between the two in IEEE-754 representation (or whatever representation the machine used is using)? A: AFAIK, IEEE754 floats have an interesting property. If you have float f, then (*(int*)&f + 1) under certain conditions, is the next representable floating point number. So for floats a and b *(int*)&a - *(int*)&b Will give you the amount of floating point numbers between those numbers. See http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm for more information. A: I don'tknow what you will be using this for - but, if both floats have the same exponent, it should be possible. As the exponent is kept on the high order bits, loading the float bytes (8 bytes in this case) as an integer and subtracting one from another should give the number you want. I use the struct model to pack the floats to a binary representation, and then unpack those as (C, 8 byte) long ints: >>> import struct >>> a = struct.pack("dd", 1.000000,1.000001) >>> b = struct.unpack("ll",a) >>> b[1] - b[0] 4503599627 >>> a = struct.pack("dd", 1.000000000,1.000000001) >>> b = struct.unpack("ll",a) >>> b[1] - b[0] 4503600 >>> A: For positive numbers b > a > 0, the answer is approximately: (2**52) ** (log(b,2) - log(a,2)) There are 52 bits of mantissa ( past the implied 1 ), multiplied by 2 raised to an exponent. So there are 2**52 numbers in range [1:2) as in the range [1024:2048) A: I would look at the frexp function in the math module. The example below extracts the mantissa and converts it to an integer. The difference should be the number of floats between to the two values. >>> math.frexp(1.1234567890)[0] * 2**53 5059599576307254.0 >>> math.frexp(1.12345678901)[0] * 2**53 5059599576352290.0 The following code should do it: import math import sys def delta(x,y): '''Return the number of floats between x and y.''' x = float(x) y = float(y) if x == y: return 0 elif x < y: return -delta(y,x) else: x_mant, x_exp = math.frexp(x) y_mant, y_exp = math.frexp(y) x_int = int(x_mant * 2**(sys.float_info.mant_dig + x_exp - y_exp)) y_int = int(y_mant * 2**sys.float_info.mant_dig) return x_int - y_int print(delta(1.123456789, 1.1234567889999)) 450 >>>
Number of floats between two floats
Say I have two Python floats a and b, is there an easy way to find out how many representable real numbers are between the two in IEEE-754 representation (or whatever representation the machine used is using)?
[ "AFAIK, IEEE754 floats have an interesting property. If you have float f, then\n(*(int*)&f + 1)\n\nunder certain conditions, is the next representable floating point number. So for floats a and b\n*(int*)&a - *(int*)&b\n\nWill give you the amount of floating point numbers between those numbers.\nSee http://www.cygn...
[ 13, 12, 3, 0 ]
[]
[]
[ "floating_point", "ieee_754", "python" ]
stackoverflow_0003587880_floating_point_ieee_754_python.txt
Q: python + windows: run exe as if it's unrelated to the current process I know I can use subprocess.Popen to run an executable, and potentially redirect stdin and stdout to files / using pipes to my process. Is there a way to run an executable such that the spawned process has no relation to the current Python process, however? Meaning, I want to start a process in the same way as if I would double-click on the .exe, or type in its name into Start->Run... A: On Windows, see os.startfile().
python + windows: run exe as if it's unrelated to the current process
I know I can use subprocess.Popen to run an executable, and potentially redirect stdin and stdout to files / using pipes to my process. Is there a way to run an executable such that the spawned process has no relation to the current Python process, however? Meaning, I want to start a process in the same way as if I would double-click on the .exe, or type in its name into Start->Run...
[ "On Windows, see os.startfile().\n" ]
[ 1 ]
[]
[]
[ "process", "python", "pywin32", "subprocess", "windows" ]
stackoverflow_0003550605_process_python_pywin32_subprocess_windows.txt
Q: urllib2.urlopen throws 404 exception for urls that browser opens The following url (and others like it) can be opened in a browser but causes urllib2.urlopen to throw a 404 exception: http://store.ovi.com/#/applications?categoryId=20&fragment=1&page=1 geturl() returns the same url (no redirect). The headers are copied and pasted from firebug. I tried passing in the headers as a dictionary to Request, but got the same result. wget opens the url in the console but not from the script. the code: source_url = 'http://store.ovi.com/#/applications?categoryId=20&fragment=1&page=2' try: socket.setdefaulttimeout(10) hdrs = [('Host','store.ovi.com'),('User-Agent','Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US;rv:1.9.0.13) Gecko/2009073021 Firefox/3.0.13 AppEngine-Google;(+http://code.google.com/appengine)'),('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'),('Accept-Language','en-us,en;q=0.5'),('Accept-Encoding','gzip,deflate'),('Accept-Charset','ISO-8859-1,utf-8;q=0.7,*;q=0.7'),('Keep-Alive','115'),('Connection','keep-alive'),('Cookie','JNPRSESSID=4u4devdrt7eb6e0qem3gin47i2; s_cc=true; undefined_s=First%20Visit; s_nr=1282817443274; s_sq=%5B%5BB%5D%5D; view=Grid; menu=menuOpen; OVI_DEVICE=b5130'),('Cache-Control','max-age=0')] ree = urllib2.Request(source_url) ree.addheaders = hdrs opener = urllib2.build_opener() htmlSource = opener.open(ree).read() except urllib2.HTTPError, e: print e.code print e.msg print e.headers The error output: 404 Not Found Date: Sat, 28 Aug 2010 00:36:57 GMT Server: Apache/2.2.3 (Red Hat) X-Powered-By: PHP/5.2.2 Expires: Thu, 19 Nov 1981 08:52:00 GMT Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0 Pragma: no-cache Keep-Alive: timeout=7, max=333 Connection: Keep-Alive Transfer-Encoding: chunked Content-Type: text/html; charset=UTF-8 What, if anything, am I doing incorrectly? Is this a bug? And if so, is there a workaround? Thanks! A: Given a URL like: http://store.ovi.com/#/applications?categoryId=20&fragment=1&page=2 The bit that browsers fetch is just: http://store.ovi.com/ Everything to the right of that is a ‘fragment identifier’, which is not passed to the server at all (evidently, if you try, it will get confused). Instead, the HTML returned for the / URL will include a load of JavaScript that reads the #... data at the client side and fills in the page content using a bunch of XMLHttpRequests. Webapps implemented like this are a big old pain to scrape, because you can't just take the HTML content of the main page. Instead you have to either analyse the script to find out where it gets the actual data from, or you have to hook up a real browser in order to execute all the scripts and see what document objects you're left with. They're also typically bad for accessibility and SEO. Luckily for you this site appears to be putting something in the fragment that's also a valid path. So it looks like you can get the dynamic page data from the URL: http://store.ovi.com/applications?categoryId=20&fragment=1&page=1
urllib2.urlopen throws 404 exception for urls that browser opens
The following url (and others like it) can be opened in a browser but causes urllib2.urlopen to throw a 404 exception: http://store.ovi.com/#/applications?categoryId=20&fragment=1&page=1 geturl() returns the same url (no redirect). The headers are copied and pasted from firebug. I tried passing in the headers as a dictionary to Request, but got the same result. wget opens the url in the console but not from the script. the code: source_url = 'http://store.ovi.com/#/applications?categoryId=20&fragment=1&page=2' try: socket.setdefaulttimeout(10) hdrs = [('Host','store.ovi.com'),('User-Agent','Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US;rv:1.9.0.13) Gecko/2009073021 Firefox/3.0.13 AppEngine-Google;(+http://code.google.com/appengine)'),('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'),('Accept-Language','en-us,en;q=0.5'),('Accept-Encoding','gzip,deflate'),('Accept-Charset','ISO-8859-1,utf-8;q=0.7,*;q=0.7'),('Keep-Alive','115'),('Connection','keep-alive'),('Cookie','JNPRSESSID=4u4devdrt7eb6e0qem3gin47i2; s_cc=true; undefined_s=First%20Visit; s_nr=1282817443274; s_sq=%5B%5BB%5D%5D; view=Grid; menu=menuOpen; OVI_DEVICE=b5130'),('Cache-Control','max-age=0')] ree = urllib2.Request(source_url) ree.addheaders = hdrs opener = urllib2.build_opener() htmlSource = opener.open(ree).read() except urllib2.HTTPError, e: print e.code print e.msg print e.headers The error output: 404 Not Found Date: Sat, 28 Aug 2010 00:36:57 GMT Server: Apache/2.2.3 (Red Hat) X-Powered-By: PHP/5.2.2 Expires: Thu, 19 Nov 1981 08:52:00 GMT Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0 Pragma: no-cache Keep-Alive: timeout=7, max=333 Connection: Keep-Alive Transfer-Encoding: chunked Content-Type: text/html; charset=UTF-8 What, if anything, am I doing incorrectly? Is this a bug? And if so, is there a workaround? Thanks!
[ "Given a URL like:\nhttp://store.ovi.com/#/applications?categoryId=20&fragment=1&page=2\n\nThe bit that browsers fetch is just:\nhttp://store.ovi.com/\n\nEverything to the right of that is a ‘fragment identifier’, which is not passed to the server at all (evidently, if you try, it will get confused). Instead, the H...
[ 3 ]
[]
[]
[ "debugging", "exception", "http", "python", "urllib2" ]
stackoverflow_0003589003_debugging_exception_http_python_urllib2.txt
Q: Pluggable Python program I want to make a PyQt4 program that supports plugins. Basically I want the user to be able to write QWidget subclasses in PyQt4 and add/remove them from the main application window via a GUI. How would I do that, especially the plugin mechanism? A: First, use a QFileDialog or more conveniently the static function QFileDialog.getOpenFileName to let the user pick the .py file they want to "plug into" your GUI. Next, if you want to allow importing the plugin from anywhere on the disk (as opposed to, from specific directories previously added to your sys.path, e.g. via the environment variable PYTHONPATH), you can "do it right" (a non-negligible amount of work), via the imp module in the standard Python library), or you can "cut corners" as follows (assuming filepath is the QString with the path to the file, and that you're using a filesystem/platform with natively Unicode filenames -- otherwise you'll have to add whatever .encode your platform and filesystem require)...: import sys, os def importfrom(filepath): ufp = unicode(filepath) thedir, thefile = os.path.split(ufp) if sys.path[0] != thedir: sys.path.insert(0, thedir) themodule, theext = os.path.splitext(thefile) return __import__(themodule) This isn't thread-safe because it may have a side effect on sys.path, which is why I said it's "cutting corners"... but then, making thread-safe imports (and "clean" imports from "anywhere") is really hard work (probably worth a separate question if you need to, since it really has nothing much to do with the gist of this one, or PyQt, &c). Once you do have the module object (the result from importfrom above), I suggest: from PyQt4 import QtGui import inspect def is_widget(w): return inspect.isclass(w) and issubclass(w, QtGui.QWidget) def all_widget_classes(amodule): return [v for n, v in inspect.getmembers(amodule, is_widget)] This returns a list with all the widget classes (if any) defined (at the top level) in module amodule. What you want to do next is up to you, of course. Perhaps you want to give some kind of error messages if the list is empty (or maybe also if it has more than one item? or else how do decide which widget class to use?) or else instantiate the widget class (how many times? At what coordinates? And so on -- questions only you can answer) and show the resulting widget(s) in the appropriate spot(s) on your window. A: Have a directory for the plugins, define an interface for those plugins, and walk the directory importing them. I've never done this in Python, but in C the way I did it was to define a number of functions that the plugin needed to implement. The basic key elements that are necessary is the name of the things in the plugin (so that you can display them in your UI so that the user can instantiate them) and a factory to actually create the things. I suppose in Python it'd be pretty trivial to just do those as one dict that you can return from the module. E.g. declare that all plugins must author a function called GetPluginInfo() which returns a dictionary of name:class mappings. Actually now that I think about it you could probably just import the file and look for classes that are subclasses of whatever you care about and not require any explicit API be implemented. I haven't done a lot of that but basically you'd walk the module's dir() and test to see if each thing is a subclass of QWidget (for example).
Pluggable Python program
I want to make a PyQt4 program that supports plugins. Basically I want the user to be able to write QWidget subclasses in PyQt4 and add/remove them from the main application window via a GUI. How would I do that, especially the plugin mechanism?
[ "First, use a QFileDialog or more conveniently the static function QFileDialog.getOpenFileName to let the user pick the .py file they want to \"plug into\" your GUI.\nNext, if you want to allow importing the plugin from anywhere on the disk (as opposed to, from specific directories previously added to your sys.path...
[ 6, 0 ]
[]
[]
[ "pluggable", "plugins", "pyqt4", "python", "qt" ]
stackoverflow_0003588915_pluggable_plugins_pyqt4_python_qt.txt
Q: Tkinter removing standard window in Ubuntu Is there a command similar to "wm_overrideredirect" for Ubuntu? I want My program to be displayed without the standard window. A: Ubuntu's desktop manager is Gnome, which should support wm_overrideredirect as well as any other. What's going wrong for you when you try that? Can you show (by editing your Q) some as-tiny-as-possible Python/Tkinter script that does not behave the way you want, and tell us how it does behave and how you'd like to behave? A: As noted (obliquely) in the manual: my_toplevel.master.overrideredirect(True) I tested this on Ubuntu Lucid, compiz window manager, Python 2.6.5. As the WM protocol is ancient, I don't expect the window manager to be an issue.
Tkinter removing standard window in Ubuntu
Is there a command similar to "wm_overrideredirect" for Ubuntu? I want My program to be displayed without the standard window.
[ "Ubuntu's desktop manager is Gnome, which should support wm_overrideredirect as well as any other. What's going wrong for you when you try that? Can you show (by editing your Q) some as-tiny-as-possible Python/Tkinter script that does not behave the way you want, and tell us how it does behave and how you'd like ...
[ 3, 1 ]
[]
[]
[ "python", "tkinter", "ubuntu", "window" ]
stackoverflow_0003589185_python_tkinter_ubuntu_window.txt
Q: How to show a vertical rule at the beginning of the current line? I'm looking for a way in vim to easily visualize the various indent levels of python code. It would help if there was always a vertical rule at the beginning of the current line. That way I can scan down the code to see where the current block ends. Are there any plugins out there that do this? A: You could simply emulate indentation guides. It's simpler and more effective, in my opinion. Please, take a look at my answer to the question about indentation guides. A: The first thing that comes to mind is that you could benefit from a plugin that implements code folding. Here is a tutorial with examples (scroll down to "Code folding") that recommends the use of the "Efficient python folding" plugin for vim. (source: dancingpenguinsoflight.com) A: in vim (no plugins needed): :set list will display tabs as '^I' and EOL as '$' by default. with :set lcs=tab:>> you'd set '^I' to '>' (see more on that by :help listchars). i'm not sure, but there should be another option to set the tab width. also you may set :set autoindent for python A: I think the command you're looking for is "colorcolumn", it's new to vim 7.2 or 7.3 I think. You might be able to work something up with the autocommand trigger CursorMoved autocmd CursorMovedI * set colorcolumn=match(getline("."),"\S") You will probably have to play with this, using intermediate variables and such. What this would do (if properly buried inside a function), is put a single vertical line at the starting character of the current line. This might be handy, but should probably only be put on a toggle. EDIT: This turns out to be a bit more complicated than I thought originally. Basically you have to eliminate the effect of literal tabs (if they show up in your file) autocmd CursorMoved * let &colorcolumn=matchend(substitute(getline("."),'\t',repeat(" ",&ts),'g'),"\\S") When I was first putting this together I sortof thought it was silly, but just playing around with it for a few minutes, I sortof like the effect. Note that you may or may not want a CursorMovedI version. A: You can define you own syntax items for it (or use matches). Quick and dirty solution: let colors=["red", "white", "yellow", "green", "blue"] let matchids=[] for level in range(1, len(colors)) execute "hi IndentLevel".level." ctermbg=".colors[level-1]." guibg=".colors[level-1] call add(matchids, matchadd('IndentLevel'.level, '^ '.repeat(' ', level-1).'\zs ')) endfor This will highlight five first indentation levels with different colors. To disable: while !empty(matchids) call matchdelete(remove(matchids, 0)) endwhile
How to show a vertical rule at the beginning of the current line?
I'm looking for a way in vim to easily visualize the various indent levels of python code. It would help if there was always a vertical rule at the beginning of the current line. That way I can scan down the code to see where the current block ends. Are there any plugins out there that do this?
[ "You could simply emulate indentation guides. It's simpler and more effective, in my opinion. Please, take a look at my answer to the question about indentation guides.\n", "The first thing that comes to mind is that you could benefit from a plugin that implements code folding.\nHere is a tutorial with examples...
[ 5, 1, 0, 0, 0 ]
[]
[]
[ "highlighting", "indentation", "python", "vim" ]
stackoverflow_0003588162_highlighting_indentation_python_vim.txt
Q: Django, database retrieval not working but deleting fields and adding new fields is working I have been able to get my database queries to work properly for deleting existing entries and also adding new entries to the database but I am completely stumped as to why I am unable to retrieve anything from my database. I am trying a query such as: from web1.polls.models import Poll retquery = Poll.objects.all() print retquery --prints: "[ ]" Also, if I try this, it just returns "poll object" from web1.polls.models import Poll retquery = Poll.objects.all()[0] print retquery --prints: "poll object" I have looked at everything and there are definitely entries in the database, I have tried this with a number of different models where everything else is working otherwise so I don't know what I can do at this point, any advice is greatly appreciated A: if you have provide well __unicode__ method to your model, you won't have such problem... http://www.djangoproject.com/documentation/models/str/ A: I finally figured this out, I am leaving this up since this can be really confusing for someone fairly new to Python, such as myself, as Django's docs don't make this entirely clear, I'm used to printing out an object and having it list everything in it but for some reason the type of object that is returned is not in such a format that doing this will work, so you need to take the resulting variable from the query and add the name of the field to the end in order to access it, such as: If I have a field named "question" that I want to retrieve: retquery = Poll.objects.all() print retquery.question This will work, whereas the way I was doing it before it just printed nothing making me think that the returned object was empty
Django, database retrieval not working but deleting fields and adding new fields is working
I have been able to get my database queries to work properly for deleting existing entries and also adding new entries to the database but I am completely stumped as to why I am unable to retrieve anything from my database. I am trying a query such as: from web1.polls.models import Poll retquery = Poll.objects.all() print retquery --prints: "[ ]" Also, if I try this, it just returns "poll object" from web1.polls.models import Poll retquery = Poll.objects.all()[0] print retquery --prints: "poll object" I have looked at everything and there are definitely entries in the database, I have tried this with a number of different models where everything else is working otherwise so I don't know what I can do at this point, any advice is greatly appreciated
[ "if you have provide well __unicode__ method to your model, you won't have such problem...\nhttp://www.djangoproject.com/documentation/models/str/\n\n", "I finally figured this out, I am leaving this up since this can be really confusing for someone fairly new to Python, such as myself, as Django's docs don't mak...
[ 1, 0 ]
[]
[]
[ "django", "mysql", "python" ]
stackoverflow_0003589055_django_mysql_python.txt
Q: python enumeration class for ORM purposes EDITED QUESTION I'm trying to create a class factory that can generate enumeration-like classes with the following properties: Class is initialized from the list of allowed values (i.e., it's automatically generated!). Class creates one instance of itself for each of the allowed value. Class does not allow the creation of any additional instances once the above step is complete (any attempt to do so results in an exception). Class instances provide a method that, given a value, returns a reference to the corresponding instance. Class instances have just two attributes: id and value. The attribute id auto-increments for each new instance; the attribute value is the value the instance represents. Class is iterable. I'd prefer to implement this using the accepted answer to another SO question (specifically, by utilizing class registry and defining an iter method in the metaclass from which my enumeration classes are instanced). This is all I'm looking for. Please consider the original text (below) just a background to the question. Sorry for not being clear from the start. UPDATED ANSWER I made slight modifications to the very helpful answer by aaronasterling. I thought I'd show it here so that others can benefit, and so that I receive more comments if I did something wrong :) The modifications I made are: (0) Ported to p3k (iteritems --> items, metaclass --> 'metaclass =', no need to specify object as base class) (1) Changed instance method into @classmethod (now I don't need the object to call it, just the class) (2) Instead of populating _registry in one swoop, I update it every time a new element is constructed. This means I can use its length to set id, and so I got rid of _next_id attribute. It will also work better for the extension I plan (see below). (3) Removed classname parameter from enum(). After all, that classname is going to be a local name; the global name would have to be set separately anyway. So I used a dummy 'XXX' as the local classname. I'm a bit worried about what happens when I call the function for the second time, but it seems to work. If anyone knows why, let me know. If it's a bad idea, I can of course auto-generate a new local classname at every invocation. (4) Extended this class to allow an option whereby new enum elements can be added by the user. Specifically, if instance() is called with a non-existent value, the corresponding object is created and then returned by the method. This is useful if I grab a large number of enum values from parsing a file. def enum(values): class EnumType(metaclass = IterRegistry): _registry = {} def __init__(self, value): self.value = value self.id = len(type(self)._registry) type(self)._registry[value] = self def __repr__(self): return self.value @classmethod def instance(cls, value): return cls._registry[value] cls = type('XXX', (EnumType, ), {}) for value in values: cls(value) def __new__(cls, value): if value in cls._registry: return cls._registry[value] else: if cls.frozen: raise TypeError('No more instances allowed') else: return object.__new__(cls) cls.__new__ = staticmethod(__new__) return cls ORIGINAL TEXT I am using SQLAlchemy as the object-relational mapping tool. It allows me to map classes into tables in a SQL database. I have several classes. One class (Book) is your typical class with some instance data. The others (Genre, Type, Cover, etc.) are all essentially enumeration type; e.g., Genre can only be 'scifi', 'romance', 'comic', 'science'; Cover can only be 'hard', 'soft'; and so on. There is many-to-one relationship between Book and each of the other classes. I would like to semi-automatically generate each of the enumeration-style classes. Note that SQLAlchemy requires that 'scifi' is represented as an instance of class Genre; in other words, it wouldn't work to simply define Genre.scifi = 0, Genre.romance = 1, etc. I tried to write a metaclass enum that accepts as arguments the name of the class and the list of allowed values. I was hoping that Genre = enum('Genre', ['scifi', 'romance', 'comic', 'science']) would create a class that allows these particular values, and also goes around and creates each of the objects that I need: Genre('scifi'), Genre('romance'), etc. But I am stuck. One particular problem is that I can't create Genre('scifi') until ORM is aware of this class; on the other hand, by the time ORM knows about Genre, we're no longer in the class constructor. Also, I'm not sure my approach is good to begin with. Any advice would be appreciated. A: new answer based on updates I think that this satisfies all of your specified requirements. If not, we can probably add whatever you need. def enum(classname, values): class EnumMeta(type): def __iter__(cls): return cls._instances.itervalues() class EnumType(object): __metaclass__ = EnumMeta _instances = {} _next_id = 0 def __init__(self, value): self.value = value self.id = type(self)._next_id type(self)._next_id += 1 def instance(self, value): return type(self)._instances[value] cls = type(classname, (EnumType, ), {}) instances = dict((value, cls(value)) for value in values) cls._instances = instances def __new__(cls, value): raise TypeError('No more instances allowed') cls.__new__ = staticmethod(__new__) return cls Genre = enum('Genre', ['scifi', 'comic', 'science']) for item in Genre: print item, item.value, item.id assert(item is Genre(item.value)) assert(item is item.instance(item.value)) Genre('romance') old answer In response to your comment on Noctis Skytower's answer wherein you say that you want Genre.comic = Genre('comic') (untested): class Genre(GenreBase): genres = ['comic', 'scifi', ... ] def __getattr__(self, attr): if attr in type(self).genres: self.__dict__[attr] = type(self)(attr) return self.__dict__[attr] This creates an instance of genre in response to an attempt to access it and attaches it to the instance on which it is requested. If you want it attached to the entire class, replace the line self.__dict__[attr] == type(self)(attr) with type(self).__dict__[attr] = type(self)(attr) this has all subclasses create instances of the subclass in response to requests as well. If you want subclasses to create instances of Genre, replace type(self)(attr) with Genre(attr) A: You can create new classes on-the-fly with the type builtin: type(name, bases, dict) Return a new type object. This is essentially a dynamic form of the class statement. The name string is the class name and becomes the __name__ attribute; the bases tuple itemizes the base classes and becomes the __bases__ attribute; and the dict dictionary is the namespace containing definitions for class body and becomes the __dict__ attribute. For example, the following two statements create identical type objects: >>> class X(object): ... a = 1 ... >>> X = type('X', (object,), dict(a=1)) New in version 2.2. In this case: genre_mapping = { } for genre in { 'scifi', 'romance', 'comic', 'science' }: genre_mapping[ 'genre' ] = type( genre, ( Genre, ), { } ) or in Python 2.7+: genre_mapping = { genre: type( genre, ( Genre, ), { } ) for genre in genres } If you are doing this a lot, you can abstract away the pattern. >>> def enum( cls, subs ): ... return { sub: type( sub, ( cls, ), { } ) for sub in subs } ... >>> enum( Genre, [ 'scifi', 'romance', 'comic', 'science' ] ) {'romance': <class '__main__.romance'>, 'science': <class '__main__.science'>, 'comic': <class '__main__.comic'>, 'scifi': <class '__main__.scifi'>} EDIT: Have I missed the point? (I've not used SQLAlchemy before.) Are you asking how to create new subclasses of Genre, or how to create new instances? The former seems intuitively right, but the latter is what you've asked for. It's easy: list( map( Genre, [ 'scifi', ... ] ) ) will make you a list of: [ Genre( 'scifi' ), ... ] A: Maybe this enumeration function from the Verse Quiz program could be of some use to you: Verse Quiz
python enumeration class for ORM purposes
EDITED QUESTION I'm trying to create a class factory that can generate enumeration-like classes with the following properties: Class is initialized from the list of allowed values (i.e., it's automatically generated!). Class creates one instance of itself for each of the allowed value. Class does not allow the creation of any additional instances once the above step is complete (any attempt to do so results in an exception). Class instances provide a method that, given a value, returns a reference to the corresponding instance. Class instances have just two attributes: id and value. The attribute id auto-increments for each new instance; the attribute value is the value the instance represents. Class is iterable. I'd prefer to implement this using the accepted answer to another SO question (specifically, by utilizing class registry and defining an iter method in the metaclass from which my enumeration classes are instanced). This is all I'm looking for. Please consider the original text (below) just a background to the question. Sorry for not being clear from the start. UPDATED ANSWER I made slight modifications to the very helpful answer by aaronasterling. I thought I'd show it here so that others can benefit, and so that I receive more comments if I did something wrong :) The modifications I made are: (0) Ported to p3k (iteritems --> items, metaclass --> 'metaclass =', no need to specify object as base class) (1) Changed instance method into @classmethod (now I don't need the object to call it, just the class) (2) Instead of populating _registry in one swoop, I update it every time a new element is constructed. This means I can use its length to set id, and so I got rid of _next_id attribute. It will also work better for the extension I plan (see below). (3) Removed classname parameter from enum(). After all, that classname is going to be a local name; the global name would have to be set separately anyway. So I used a dummy 'XXX' as the local classname. I'm a bit worried about what happens when I call the function for the second time, but it seems to work. If anyone knows why, let me know. If it's a bad idea, I can of course auto-generate a new local classname at every invocation. (4) Extended this class to allow an option whereby new enum elements can be added by the user. Specifically, if instance() is called with a non-existent value, the corresponding object is created and then returned by the method. This is useful if I grab a large number of enum values from parsing a file. def enum(values): class EnumType(metaclass = IterRegistry): _registry = {} def __init__(self, value): self.value = value self.id = len(type(self)._registry) type(self)._registry[value] = self def __repr__(self): return self.value @classmethod def instance(cls, value): return cls._registry[value] cls = type('XXX', (EnumType, ), {}) for value in values: cls(value) def __new__(cls, value): if value in cls._registry: return cls._registry[value] else: if cls.frozen: raise TypeError('No more instances allowed') else: return object.__new__(cls) cls.__new__ = staticmethod(__new__) return cls ORIGINAL TEXT I am using SQLAlchemy as the object-relational mapping tool. It allows me to map classes into tables in a SQL database. I have several classes. One class (Book) is your typical class with some instance data. The others (Genre, Type, Cover, etc.) are all essentially enumeration type; e.g., Genre can only be 'scifi', 'romance', 'comic', 'science'; Cover can only be 'hard', 'soft'; and so on. There is many-to-one relationship between Book and each of the other classes. I would like to semi-automatically generate each of the enumeration-style classes. Note that SQLAlchemy requires that 'scifi' is represented as an instance of class Genre; in other words, it wouldn't work to simply define Genre.scifi = 0, Genre.romance = 1, etc. I tried to write a metaclass enum that accepts as arguments the name of the class and the list of allowed values. I was hoping that Genre = enum('Genre', ['scifi', 'romance', 'comic', 'science']) would create a class that allows these particular values, and also goes around and creates each of the objects that I need: Genre('scifi'), Genre('romance'), etc. But I am stuck. One particular problem is that I can't create Genre('scifi') until ORM is aware of this class; on the other hand, by the time ORM knows about Genre, we're no longer in the class constructor. Also, I'm not sure my approach is good to begin with. Any advice would be appreciated.
[ "new answer based on updates\nI think that this satisfies all of your specified requirements. If not, we can probably add whatever you need.\ndef enum(classname, values):\n class EnumMeta(type):\n def __iter__(cls):\n return cls._instances.itervalues()\n\n class EnumType(object):\n __...
[ 3, 0, 0 ]
[]
[]
[ "enumeration", "python", "sqlalchemy" ]
stackoverflow_0003588996_enumeration_python_sqlalchemy.txt
Q: Error configuring Django to run customized comments framework I'm having an issue with setting up a Django website which uses the Django comments framework on my server. The site runs fine when run locally (using manage.py runserver) but when pushed live I'm getting the error: ImproperlyConfigured at / The COMMENTS_APP setting refers to a non-existing package. My server is an apache/mod_wsgi setup. My site contains 2 applications called weblog and weblog_comments. I've appended my site's path and it's parent directories to my django.wsgi file as per the guide located here: http://code.google.com/p/modwsgi/wiki/IntegrationWithDjango I can comment out the COMMENTS_APP line from my settings.py and the site runs fine so I know site is on the python path correctly. My custom comment model is called WeblogComment and extends the default Comment model. It only extends this to add methods to the model, it doesn't change Comment model fields thus It has proxy=True in it's Meta class. Any advice would be great. A: See if alternate WSGI script described at end of: http://blog.dscpl.com.au/2010/03/improved-wsgi-script-for-use-with.html makes a difference. If it does, would be nice if can help us work out why. Still trying to get some confirmation on why so can work out if people using Django wrong, of whether Django WSGI adapter by itself is inadequate. BTW, also just ensure that all code is readable by Apache user and that you don't have any special directories listed in your user account PYTHONPATH that aren't duplicated in WSGI script sys.path setup. A: Graham, I've got the site working now by adding the WSGIDaemonProcess and WSGIProcessGroup directives to my virtual host file as per your suggestion here: multiple django sites with apache & mod_wsgi. This seems to have worked. I probably should have mentioned I'm running another Django site as well as a Wordpress blog on the same box under different domains/virtual hosts. To be quite honest, I'm not quite sure why this is now working. Maybe you have an idea?
Error configuring Django to run customized comments framework
I'm having an issue with setting up a Django website which uses the Django comments framework on my server. The site runs fine when run locally (using manage.py runserver) but when pushed live I'm getting the error: ImproperlyConfigured at / The COMMENTS_APP setting refers to a non-existing package. My server is an apache/mod_wsgi setup. My site contains 2 applications called weblog and weblog_comments. I've appended my site's path and it's parent directories to my django.wsgi file as per the guide located here: http://code.google.com/p/modwsgi/wiki/IntegrationWithDjango I can comment out the COMMENTS_APP line from my settings.py and the site runs fine so I know site is on the python path correctly. My custom comment model is called WeblogComment and extends the default Comment model. It only extends this to add methods to the model, it doesn't change Comment model fields thus It has proxy=True in it's Meta class. Any advice would be great.
[ "See if alternate WSGI script described at end of:\nhttp://blog.dscpl.com.au/2010/03/improved-wsgi-script-for-use-with.html\nmakes a difference. If it does, would be nice if can help us work out why. Still trying to get some confirmation on why so can work out if people using Django wrong, of whether Django WSGI ad...
[ 0, 0 ]
[]
[]
[ "apache", "django", "mod_wsgi", "python" ]
stackoverflow_0003575195_apache_django_mod_wsgi_python.txt
Q: How can I add some string to a list in order to make a count word? [Python] I want to simply add some word to a list and then count how many words are in there... And check if the word isn't in the list already. How can I do it? A: A list can be used for this, but if speed is important and order doesn't matter then a set will be faster. >>> S = set(['a', 'b', 'c']) >>> S set(['a', 'c', 'b']) >>> 'b' in S True >>> S.add('d') >>> S set(['a', 'c', 'b', 'd']) >>> S.add('b') >>> S set(['a', 'c', 'b', 'd']) A: You can add a word to a list by calling alist.append("word") where alist is your list. To count how many words are in the list simply use len(alist). To check if the word isn't already in the list use if "word" not in alist: -edit to remove references to word 'list', replacing it with 'alist'
How can I add some string to a list in order to make a count word? [Python]
I want to simply add some word to a list and then count how many words are in there... And check if the word isn't in the list already. How can I do it?
[ "A list can be used for this, but if speed is important and order doesn't matter then a set will be faster.\n>>> S = set(['a', 'b', 'c'])\n>>> S\nset(['a', 'c', 'b'])\n>>> 'b' in S\nTrue\n>>> S.add('d')\n>>> S\nset(['a', 'c', 'b', 'd'])\n>>> S.add('b')\n>>> S\nset(['a', 'c', 'b', 'd'])\n\n", "You can add a word t...
[ 4, 2 ]
[]
[]
[ "list", "python", "windows" ]
stackoverflow_0003589667_list_python_windows.txt
Q: Facebook connect with django/python I've been stuck on this for a while. I can't seem to get facebook login to pop up when following the google tutorial: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script> <div id="fb-root"></div> <script src="http://connect.facebook.net/en_US/all.js"></script> <script> FB.init({appId:'137101656332358', status: true, cookie: true, xfbml: true}); FB.Event.subscribe('auth.sessionChange', function(response) { if (response.session) { // A user has logged in, and a new cookie has been save } else { // The user has logged out, and the cookie has been cleared } }); I get the following error in Firebug: Firebug cannot find _firebugConsole element true Window localhost:8000 Firebug cannot find _firebugConsole element true Window localhost:8000 Firebug cannot find _firebugConsole element true Window localhost:8000 FB is not defined [Break on this error] FB.provide('',{getLoginStatus:function...ern:FB._inCanvas?0:2});return a;}}}); I set Site URL = http://localhost:8000/ thanks! A: New Facebook API requires asynchronous load: <div id="fb-root"></div> <script> window.fbAsyncInit = function() { //[here goes your code:] FB.init({appId:'137101656332358', status: true, cookie: true, xfbml: true}); FB.Event.subscribe('auth.sessionChange', function(response) { if (response.session) { // A user has logged in, and a new cookie has been save } else { // The user has logged out, and the cookie has been cleared } }); }; (function() { var e = document.createElement('script'); e.async = true; e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js'; document.getElementById('fb-root').appendChild(e); }()); </script>
Facebook connect with django/python
I've been stuck on this for a while. I can't seem to get facebook login to pop up when following the google tutorial: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script> <div id="fb-root"></div> <script src="http://connect.facebook.net/en_US/all.js"></script> <script> FB.init({appId:'137101656332358', status: true, cookie: true, xfbml: true}); FB.Event.subscribe('auth.sessionChange', function(response) { if (response.session) { // A user has logged in, and a new cookie has been save } else { // The user has logged out, and the cookie has been cleared } }); I get the following error in Firebug: Firebug cannot find _firebugConsole element true Window localhost:8000 Firebug cannot find _firebugConsole element true Window localhost:8000 Firebug cannot find _firebugConsole element true Window localhost:8000 FB is not defined [Break on this error] FB.provide('',{getLoginStatus:function...ern:FB._inCanvas?0:2});return a;}}}); I set Site URL = http://localhost:8000/ thanks!
[ "New Facebook API requires asynchronous load:\n<div id=\"fb-root\"></div>\n<script>\n window.fbAsyncInit = function() {\n //[here goes your code:]\n FB.init({appId:'137101656332358', status: true, cookie: true, xfbml: true});\n FB.Event.subscribe('auth.sessionChange', function(response) {\n if (res...
[ 1 ]
[]
[]
[ "django", "facebook", "python" ]
stackoverflow_0003588785_django_facebook_python.txt
Q: Creating a gui around a python script using Tkinter I have an existing python script and I want to wrap it in a GUI. Since I already have tkinter installed I would like to use it if possible. At the moment my script has many places where it asks for user input using raw_input(). I would like to replace these with either a modal pop-up asking for user input or (preferably) an Entry object which responds to the enter key. A: UI toolkits usually have an event-driven model where the main loop is in the toolkit itself. This is probably different from your current synchronous, interactive model (where the program just pauses while waiting for input) The best would be to try to refactor your program and factor-out the view part (look up the model-view-control design pattern). After that, it should be easy to replace your console oriented view with an tkInter based one. (that's as specific as I can get without a concrete question)
Creating a gui around a python script using Tkinter
I have an existing python script and I want to wrap it in a GUI. Since I already have tkinter installed I would like to use it if possible. At the moment my script has many places where it asks for user input using raw_input(). I would like to replace these with either a modal pop-up asking for user input or (preferably) an Entry object which responds to the enter key.
[ "UI toolkits usually have an event-driven model where the main loop is in the toolkit itself. This is probably different from your current synchronous, interactive model (where the program just pauses while waiting for input)\nThe best would be to try to refactor your program and factor-out the view part (look up t...
[ 2 ]
[]
[]
[ "python", "tkinter", "user_input" ]
stackoverflow_0003589817_python_tkinter_user_input.txt
Q: How do I store then retrieve Python-native data structures into and from a file? I am reading an XML file and reorganizing the desired data into Python data structures (lists, tuples, etc.) For example, one of my XML parser modules produces the following data: # data_miner.py animals = ['Chicken', 'Sheep', 'Cattle', 'Horse'] population = [150, 200, 50, 30] Then I have a plotter module that roughly says, e.g.: # plotter.py from data_miner import animals, population plot(animals, population) Using this method, I have to parse the XML file every time I do a plot. I'm still testing other aspects of my program and the XML file doesn't change as frequently for now. Avoiding the parse stage would dramatically improve my testing time. This is my desired result: In between data_miner.py and plotter.py, I want a file that contains animals and population such that they can be accessed by plotter.py natively (e.g. no change in plotting code), without having to run data_miner.py every time. If possible, it shouldn't be in csv or any ASCII format, just a natively-accessible format. plotter.py should now look roughly like: # plotter.py # This line may not necessarily be a one-liner. from data_file import animals, population # But I want this portion to stay the same plot(animals, population) Analogy: This is roughly equivalent to MATLAB's save command that saves the active workspace's variables into a .mat file. I'm looking for something similar to the .mat file for Python. Recent experience: I have seen pickle and cpickle, but I'm not sure how to get it to work. If that is the right tool to use, example code would be very helpful. There may also be other tools that I don't know yet. A: The pickle module, or its faster equivalent cPickle, should serve your needs well. Specifically: # data_miner.py import pickle animals = ['Chicken', 'Sheep', 'Cattle', 'Horse'] population = [150, 200, 50, 30] with open('data_miner.pik', 'wb') as f: pickle.dump([animals, population], f, -1) and # plotter.py import pickle with open('data_miner.pik', 'rb') as f: animals, population = pickle.load(f) print animals, population Here, I've made data_miner.py quite explicit regarding what needs to be saved (always an excellent idea to be very explicit unless you have extremely specific reasons to do otherwise). Some things (such as modules and open files) cannot be pickled anyway, so a simple pickling of globals() would not work. If you absolutely must, you could make a copy of globals() while removing all objects whose types make them unsuitable for saving; or, perhaps better, religiously use a leading _ in every name you don't want to save (so import pickle as _pickle, with open ... as _f, and so forth) and exclude from the copy of globals() all names with a leading underscore == with such an approach, the pickle.load would retrieve a dict, then the variables of interest would be extracted from it by indexing. However, I would strongly recommend the simple alternative of saving a list (or dict, if you want;-) with the specific values that are actually of interest, rather than taking a "wholesale" approach. A: Pickling is good if you have Python-specific objects to save. If they're just generic data in some basic container type then JSON is fine. >>> json.dumps(['Chicken', 'Sheep', 'Cattle', 'Horse']) '["Chicken", "Sheep", "Cattle", "Horse"]' >>> json.dump(['Chicken', 'Sheep', 'Cattle', 'Horse'], sys.stdout) ; print ["Chicken", "Sheep", "Cattle", "Horse"] >>> json.loads('["Chicken", "Sheep", "Cattle", "Horse"]') [u'Chicken', u'Sheep', u'Cattle', u'Horse'] A: pickle was designed for this. Use pickle.dump to write an object to a file and pickle.load to read it back. >>> data {'animals': ['Chicken', 'Sheep', 'Cattle', 'Horse'], 'population': [150, 200, 50, 30]} >>> f = open('spam.p', 'wb') >>> pickle.dump(data, f) >>> f.close() >>> f = open('spam.p', 'rb') >>> pickle.load(f) {'animals': ['Chicken', 'Sheep', 'Cattle', 'Horse'], 'population': [150, 200, 50, 30]} A: As already suggested, pickle is usually used here. Keep in mind that not everything is serializable (i.e. files, sockets, database connections). With simple data structures you can also chose json or yaml. The latter is actually pretty readable and editable.
How do I store then retrieve Python-native data structures into and from a file?
I am reading an XML file and reorganizing the desired data into Python data structures (lists, tuples, etc.) For example, one of my XML parser modules produces the following data: # data_miner.py animals = ['Chicken', 'Sheep', 'Cattle', 'Horse'] population = [150, 200, 50, 30] Then I have a plotter module that roughly says, e.g.: # plotter.py from data_miner import animals, population plot(animals, population) Using this method, I have to parse the XML file every time I do a plot. I'm still testing other aspects of my program and the XML file doesn't change as frequently for now. Avoiding the parse stage would dramatically improve my testing time. This is my desired result: In between data_miner.py and plotter.py, I want a file that contains animals and population such that they can be accessed by plotter.py natively (e.g. no change in plotting code), without having to run data_miner.py every time. If possible, it shouldn't be in csv or any ASCII format, just a natively-accessible format. plotter.py should now look roughly like: # plotter.py # This line may not necessarily be a one-liner. from data_file import animals, population # But I want this portion to stay the same plot(animals, population) Analogy: This is roughly equivalent to MATLAB's save command that saves the active workspace's variables into a .mat file. I'm looking for something similar to the .mat file for Python. Recent experience: I have seen pickle and cpickle, but I'm not sure how to get it to work. If that is the right tool to use, example code would be very helpful. There may also be other tools that I don't know yet.
[ "The pickle module, or its faster equivalent cPickle, should serve your needs well.\nSpecifically:\n# data_miner.py\nimport pickle\n\nanimals = ['Chicken', 'Sheep', 'Cattle', 'Horse']\npopulation = [150, 200, 50, 30]\n\nwith open('data_miner.pik', 'wb') as f:\n pickle.dump([animals, population], f, -1)\n\nand\n# p...
[ 6, 2, 1, 0 ]
[]
[]
[ "file", "pickle", "python" ]
stackoverflow_0003589615_file_pickle_python.txt
Q: Display simple calendar on screen in python S60 (pyS60) I am trying to develop a simple calendar based application using pyS60. I need to display a calendar as part of the form. I have searched but I couldn't find anything useful in the e32calendar documentation. I can get a calendar on the canvas but its not interactive. But i want one which is interactive ( just like inbuilt calendar in Nokia Mobiles). I don`t need the event classes though. Am I missing something? TIA Chirag Narula A: Python module for py60 has a calendar module, which provides calendar services like reading, creating entries, setting alarms. Please look into the documentation at http://wiki.opensource.nokia.com/projects/PyS60 In Doc, Section 7.2.2 provides a way to do that : CalendarDb objects represent a live view into the database. If an entry is changed outside your Python application, the changes are visible immediately, and conversely any changes you commit into the database are visible immediately to other applications.
Display simple calendar on screen in python S60 (pyS60)
I am trying to develop a simple calendar based application using pyS60. I need to display a calendar as part of the form. I have searched but I couldn't find anything useful in the e32calendar documentation. I can get a calendar on the canvas but its not interactive. But i want one which is interactive ( just like inbuilt calendar in Nokia Mobiles). I don`t need the event classes though. Am I missing something? TIA Chirag Narula
[ "Python module for py60 has a calendar module, which provides calendar services like reading, creating entries, setting alarms.\nPlease look into the documentation at http://wiki.opensource.nokia.com/projects/PyS60\nIn Doc, Section 7.2.2 provides a way to do that : \nCalendarDb objects represent a live view into th...
[ 0 ]
[]
[]
[ "calendar", "pys60", "python", "s60" ]
stackoverflow_0003589824_calendar_pys60_python_s60.txt
Q: Cannot change content of list within list. Can anybody explain why? I have a month variable which is a list of lists of tuples. Each list represents a week and each day is a tuple of the day of the month and the week day. I wish to make my month a list of lists of month days. I tried to do it like this: for week in month: week = [day[0] for day in week] for [[(1, 1), (2, 2)], [(3, 3), (4, 4)]] I expect to get [[1, 2], [3, 4]], but the list doesn't change. To my understanding of python my code is perfectly fine, so what am I missing? Isn't week a reference to each week in the month? A: No, the variable you are iterating on is never a "reference" (as in C++'s reference). You should understand the for loop as month_iter = iter(month) try: while True: week = next(month_iter) # here begins your code week = [day[0] for day in week] # here ends your code except StopIteration: pass Clearly, the 2nd assignment won't affect the content of month. You could just write month = [[day[0] for day in week] for week in month] to replace the whole month list, or use enumerate as stated in @Ivo's answer. A: By assigning something to week, you change what the variable is bound to, not what the list contains. To do what you want to do without many changes, do: for week in month: week[:] = [day[0] for day in week] It will assign the result to a specified range inside week - in this case, the whole range, replacing all existing elements. A: Assignment in python is merely attaching a name to an object, it's not an operation on the object itself (but do not confuse this with getting/setting attributes on an object) if you have x = [1,2,3] y = x[1] Then y will simply be 2 and lose all reference to the list it came from. Changing y will not change x. To do so, index x properly. In your case, you want to iterate over the indexes of month and assign to the appropriate entry for index, week in enumerate(month): month[index] = [day[0] for day in week] A: Why not just: >>> foo = [] >>> for week in month: ... foo.append([day[0] for day in week]) ... >>> foo [[1, 2], [3, 4]] Simple to read, simple to understand, ...
Cannot change content of list within list. Can anybody explain why?
I have a month variable which is a list of lists of tuples. Each list represents a week and each day is a tuple of the day of the month and the week day. I wish to make my month a list of lists of month days. I tried to do it like this: for week in month: week = [day[0] for day in week] for [[(1, 1), (2, 2)], [(3, 3), (4, 4)]] I expect to get [[1, 2], [3, 4]], but the list doesn't change. To my understanding of python my code is perfectly fine, so what am I missing? Isn't week a reference to each week in the month?
[ "No, the variable you are iterating on is never a \"reference\" (as in C++'s reference).\nYou should understand the for loop as\nmonth_iter = iter(month)\ntry:\n while True:\n week = next(month_iter)\n # here begins your code\n week = [day[0] for day in week]\n # here ends your code\nexcept StopIterati...
[ 2, 2, 1, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0003590222_list_python.txt
Q: django annotation and filtering Hopefully this result set is explanatory enough: title text total_score already_voted ------------- ------------ ----------- ------------- BP Oil spi... Recently i... 5 0 J-Lo back ... Celebrity ... 7 1 Don't Stop... If there w... 9 0 Australian... The electi... 2 1 My models file describes article (author, text, title) and vote (caster, date, score). I can get the first three columns just fine with the following: articles = Article.objects.all().annotate(total_score=Sum('vote__score')) but calculating the 4th column, which is a boolean value describing whether the current logged in user has placed any of the votes in column 3, is a bit beyond me at the moment! Hopefully there's something that doesn't require raw sql for this one. Cheers, Dave --Trindaz on Fedang #django A: I cannot think of a way to include the boolean condition. Perhaps others can answer that better. How about thinking a bit differently? If you don't mind executing two queries you can filter your articles based on whether the currently logged in user has voted on them or not. Something like this: all_articles = Article.objects.all() articles_user_has_voted_on = all_articles.filter(vote__caster = request.user).annotate(total_score=Sum('vote__score')) other_articles = all_articles.exclude(vote__caster = request.user).annotate(total_score=Sum('vote__score')) Update After some experiments I was able to figure out how to add a boolean condition for a column in the same model (Article in this case) but not for a column in another table (Vote.caster). If Article had a caster column: Article.objects.all().extra(select = {'already_voted': "caster_id = %s" % request.user.id}) In the present state this can be applied for the Vote model: Vote.objects.all().extra(select = {'already_voted': "caster_id = %s" % request.user.id})
django annotation and filtering
Hopefully this result set is explanatory enough: title text total_score already_voted ------------- ------------ ----------- ------------- BP Oil spi... Recently i... 5 0 J-Lo back ... Celebrity ... 7 1 Don't Stop... If there w... 9 0 Australian... The electi... 2 1 My models file describes article (author, text, title) and vote (caster, date, score). I can get the first three columns just fine with the following: articles = Article.objects.all().annotate(total_score=Sum('vote__score')) but calculating the 4th column, which is a boolean value describing whether the current logged in user has placed any of the votes in column 3, is a bit beyond me at the moment! Hopefully there's something that doesn't require raw sql for this one. Cheers, Dave --Trindaz on Fedang #django
[ "I cannot think of a way to include the boolean condition. Perhaps others can answer that better.\nHow about thinking a bit differently? If you don't mind executing two queries you can filter your articles based on whether the currently logged in user has voted on them or not. Something like this:\nall_articles = ...
[ 2 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0003590416_django_django_models_python.txt
Q: Need Help Creating GAE Datastore Loader Class? Need Help Creating GAE Datastore Loader Class for uploading data using appcfg.py? Any other way to simplified this process? is there any detailed example better than here When try using bulkloader.yaml: Uploading data records. [INFO ] Logging to bulkloader-log-20100701.041515 [INFO ] Throttling transfers: [INFO ] Bandwidth: 250000 bytes/second [INFO ] HTTP connections: 8/second [INFO ] Entities inserted/fetched/modified: 20/second [INFO ] Batch Size: 10 [INFO ] Opening database: bulkloader-progress-20100701.041515.sql3 [INFO ] Connecting to livelihoodproducer.appspot.com/remote_api [INFO ] Starting import; maximum 10 entities per post [ERROR ] [Thread-1] WorkerThread: Traceback (most recent call last): File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/adaptive_thread_pool.py", line 150, in WorkOnItems status, instruction = item.PerformWork(self.__thread_pool) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/bulkloader.py", line 693, in PerformWork transfer_time = self._TransferItem(thread_pool) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/bulkloader.py", line 848, in _TransferItem self.content = self.request_manager.EncodeContent(self.rows) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/bulkloader.py", line 1269, in EncodeContent entity = loader.create_entity(values, key_name=key, parent=parent) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/bulkload/bulkloader_config.py", line 385, in create_entity return self.dict_to_entity(input_dict, self.bulkload_state) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/bulkload/bulkloader_config.py", line 133, in dict_to_entity self.__run_import_transforms(input_dict, instance, bulkload_state_copy) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/bulkload/bulkloader_config.py", line 233, in __run_import_transforms value = self.__dict_to_prop(transform, input_dict, bulkload_state) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/bulkload/bulkloader_config.py", line 188, in __dict_to_prop value = transform.import_transform(value) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/bulkload/bulkloader_parser.py", line 93, in __call__ return self.method(*args, **kwargs) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/bulkload/transform.py", line 143, in generate_foreign_key_lambda return datastore.Key.from_path(kind, value) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/api/datastore_types.py", line 387, in from_path 'received %r (a %s).' % (i + 2, id_or_name, typename(id_or_name))) BadArgumentError: Expected an integer id or string name as argument 2; received None (a NoneType). [INFO ] [Thread-3] Backing off due to errors: 1.0 seconds [INFO ] Unexpected thread death: Thread-1 [INFO ] An error occurred. Shutting down... [ERROR ] Error in Thread-1: Expected an integer id or string name as argument 2; received None (a NoneType). [INFO ] 30 entites total, 0 previously transferred [INFO ] 0 entities (733 bytes) transferred in 2.8 seconds [INFO ] Some entities not successfully transferred In the process, i've downloadeded csv data manually inserted on appspot.com. While i try to upload my own csv data, the column order should made exactly like csv downloaded from appspot.com? how about blank value? A: I've created config.yaml with bulkloader config, and also written simple helper function to process None-references. I don't know why it's not done in original helper. The helper (file helpers.py is very simple, just place it to the same directory where you placed config.yaml): from google.appengine.api import datastore def create_foreign_key(kind, key_is_id=False): def generate_foreign_key_lambda(value): if value is None: return None if key_is_id: value = int(value) return datastore.Key.from_path(kind, value) return generate_foreign_key_lambda And this is cut from my config.yaml: python_preamble: - import: helpers # this will import our helper [other imports] ... - kind: ArticleComment connector: simplexml connector_options: xpath_to_nodes: "/blog/Comments/Comment" style: element_centric property_map: - property: __key__ external_name: key export_transform: transform.key_id_or_name_as_string - property: parent_comment external_name: parent-comment export_transform: transform.key_id_or_name_as_string import_transform: helpers.create_foreign_key('ArticleComment') # ^^^^^^^ here it is # use this instead of transform.create_foreign_key A: It looks like you have reference properties with None values, such values are handled incorrectly by bulkloader's helpers.
Need Help Creating GAE Datastore Loader Class?
Need Help Creating GAE Datastore Loader Class for uploading data using appcfg.py? Any other way to simplified this process? is there any detailed example better than here When try using bulkloader.yaml: Uploading data records. [INFO ] Logging to bulkloader-log-20100701.041515 [INFO ] Throttling transfers: [INFO ] Bandwidth: 250000 bytes/second [INFO ] HTTP connections: 8/second [INFO ] Entities inserted/fetched/modified: 20/second [INFO ] Batch Size: 10 [INFO ] Opening database: bulkloader-progress-20100701.041515.sql3 [INFO ] Connecting to livelihoodproducer.appspot.com/remote_api [INFO ] Starting import; maximum 10 entities per post [ERROR ] [Thread-1] WorkerThread: Traceback (most recent call last): File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/adaptive_thread_pool.py", line 150, in WorkOnItems status, instruction = item.PerformWork(self.__thread_pool) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/bulkloader.py", line 693, in PerformWork transfer_time = self._TransferItem(thread_pool) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/bulkloader.py", line 848, in _TransferItem self.content = self.request_manager.EncodeContent(self.rows) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/bulkloader.py", line 1269, in EncodeContent entity = loader.create_entity(values, key_name=key, parent=parent) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/bulkload/bulkloader_config.py", line 385, in create_entity return self.dict_to_entity(input_dict, self.bulkload_state) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/bulkload/bulkloader_config.py", line 133, in dict_to_entity self.__run_import_transforms(input_dict, instance, bulkload_state_copy) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/bulkload/bulkloader_config.py", line 233, in __run_import_transforms value = self.__dict_to_prop(transform, input_dict, bulkload_state) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/bulkload/bulkloader_config.py", line 188, in __dict_to_prop value = transform.import_transform(value) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/bulkload/bulkloader_parser.py", line 93, in __call__ return self.method(*args, **kwargs) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/bulkload/transform.py", line 143, in generate_foreign_key_lambda return datastore.Key.from_path(kind, value) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/api/datastore_types.py", line 387, in from_path 'received %r (a %s).' % (i + 2, id_or_name, typename(id_or_name))) BadArgumentError: Expected an integer id or string name as argument 2; received None (a NoneType). [INFO ] [Thread-3] Backing off due to errors: 1.0 seconds [INFO ] Unexpected thread death: Thread-1 [INFO ] An error occurred. Shutting down... [ERROR ] Error in Thread-1: Expected an integer id or string name as argument 2; received None (a NoneType). [INFO ] 30 entites total, 0 previously transferred [INFO ] 0 entities (733 bytes) transferred in 2.8 seconds [INFO ] Some entities not successfully transferred In the process, i've downloadeded csv data manually inserted on appspot.com. While i try to upload my own csv data, the column order should made exactly like csv downloaded from appspot.com? how about blank value?
[ "I've created config.yaml with bulkloader config, and also written simple helper function to process None-references. I don't know why it's not done in original helper.\nThe helper (file helpers.py is very simple, just place it to the same directory where you placed config.yaml):\nfrom google.appengine.api import d...
[ 3, 0 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0003148352_google_app_engine_google_cloud_datastore_python.txt
Q: Django Model design I needed some help in model design. I wanted a model where a user can associate himself with numerous emails by submitting them from a form. And when the user wants to use the websites contact form, he can choose the email he wants a reply on. Will it be something like this : class Email(models.Model): author = models.ForeignKey(User) email = models.EmailField() class Contact(models.Model) author = models.ForeignKey(User) email = models.ForeignKey(Email) A: Your example means each Contact can have a single email address, and each email address can belong to multiple contacts. This is the wrong way round, i.e. you should put the ForeignKey on the Email model. This should let you store multiple email addresses for each user. class Email(models.Model): email = models.EmailField() user = models.ForeignKey(User) u = User.objects.get(pk=1) u.email_set.all() A: You want to add a user profile to your users. from django.contrib import auth class UserProfile(models.Model): """A user profile.""" user = models.OneToOneField(auth.models.User) # ... put more fields here def user_post_save(sender, instance, **kwargs): """Make sure that every new user gets a profile.""" profile, new = UserProfile.objects.get_or_create(user=instance) models.signals.post_save.connect(user_post_save, sender=auth.models.User) then you can access it with request.user.get_profile().
Django Model design
I needed some help in model design. I wanted a model where a user can associate himself with numerous emails by submitting them from a form. And when the user wants to use the websites contact form, he can choose the email he wants a reply on. Will it be something like this : class Email(models.Model): author = models.ForeignKey(User) email = models.EmailField() class Contact(models.Model) author = models.ForeignKey(User) email = models.ForeignKey(Email)
[ "Your example means each Contact can have a single email address, and each email address can belong to multiple contacts. This is the wrong way round, i.e. you should put the ForeignKey on the Email model.\nThis should let you store multiple email addresses for each user.\nclass Email(models.Model):\n email = mo...
[ 1, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0003550086_django_django_models_python.txt
Q: How can I make a while True break if certain key is pressed? [Python] My script make a while True: begin with the F4 pressed, but I want it to stop when the F2 is pressed, how can I do it? I'm trying this (using pyhook) but doesn't work... def onKeyboardEvent(event): if event.KeyID == 115: #F4 while True: selectAndCopy(468,722) getClipboard() time.sleep(2) if event.KeyID == 113: break return True A: You're not changing event within your loop, so you wouldn't expect event.KeyID to suddenly become 113 when it was 115 previously. What you might do is, on handling an F4 keypress, start a timer that does the selectAndCopy every two seconds. When you get another event with an F2 keystroke, kill the timer. It could look something like this: def onKeyboardEvent(event): if event.KeyID == 115: #F4 startTimer(doTimer, 2) if event.KeyID == 113: stopTimer() def doTimer(): selectAndCopy(468,722) getClipboard() You would have to provide or find implementations of startTimer() and stopTimer(). A: Make key event which change variable True with F4 and if the variable is still True do new timer event for example in Tkinter mylabel.after(2000, process) # process is the function to do your stuff change variable False with F2 and cancels the timer (after_cancel)
How can I make a while True break if certain key is pressed? [Python]
My script make a while True: begin with the F4 pressed, but I want it to stop when the F2 is pressed, how can I do it? I'm trying this (using pyhook) but doesn't work... def onKeyboardEvent(event): if event.KeyID == 115: #F4 while True: selectAndCopy(468,722) getClipboard() time.sleep(2) if event.KeyID == 113: break return True
[ "You're not changing event within your loop, so you wouldn't expect event.KeyID to suddenly become 113 when it was 115 previously.\nWhat you might do is, on handling an F4 keypress, start a timer that does the selectAndCopy every two seconds. When you get another event with an F2 keystroke, kill the timer.\nIt coul...
[ 1, 0 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0003589172_python_windows.txt
Q: instantiate python class from class available as string , only in memory! I'm using Reportlab to create PDFs. I'm creating two PDFs which I want to merge after I created them. Reportlab provides a way to save a pycanvas (source) (which is basically my pdf file in memory) as a python file, and calling the method doIt(filename) on that python file, will recreate the pdf file. This is great, since you can combine two PDFs on source code basis and create one merge pdf. This is done like this: from reportlab.pdfgen import canvas, pycanvas #create your canvas p = pycanvas.Canvas(buffer,pagesize=PAGESIZE) #...instantiate your pdf... # after that, close the PDF object cleanly. p.showPage() p.save() #now create the string equivalent of your canvas source_code_equiv = str(p) source_code_equiv2 = str(p) #merge the two files on str. basis #not shown how it is exactly done, to make it more easy to read the source #actually one just have to take the middle part of source_code_equiv2 and add it into source_code_equiv final_pdf = source_code_equiv_part1 + source_code_equiv2_center_part + source_code_equiv_part2 #write the source-code equivalent of the pdf open("n2.py","w").write(final_pdf) from myproject import n2 p = n2.doIt(buffer) # Get the value of the StringIO buffer and write it to the response. pdf = buffer.getvalue() buffer.close() response.write(pdf) return response This works fine, but I want to skip the step that I save the n2.py to the disk. Thus I'm looking for a way to instantiate from the final_pdf string the corresponding python class and use it directly in the source. Is this possible? It should work somehow like this.. n2 = instantiate_python_class_from_source(final_pdf) p = n2.doIt(buffer) The reason for this is mainly that there is not really a need to save the source to the disk, and secondly that it is absolutely not thread save. I could name the created file at run time, but then I do not know what to import!? If there is no way to prevent the file saving, is there a way to define the import based on the name of the file, which is defined at runtime!? One might ask why I do not create one pdf in advance, but this is not possible, since they are coming from different applications. A: This seems like a really long way around to what you want. Doesn't Reportlab have a Canvas class from which you can pull the PDF document? I don't see why generated Python source code should be involved here. But if for some reason it is necessary, then you can use StringIO to "write" the source to a string, then exec to execute it: from cStringIO import StringIO source_code = StringIO() source_code.write(final_pdf) exec(source_code) p = doIt(buffer) A: Ok, I guess you could use code module which provides standard interpreter’s interactive mode. The following would execute function doIt. import code import string coded_data = """ def doIt(): print "XXXXX" """ script = coded_data + "\ndoIt()\n" co = code.compile_command(script, "<stdin>", "exec") if co: exec co Let me know, if this helped.
instantiate python class from class available as string , only in memory!
I'm using Reportlab to create PDFs. I'm creating two PDFs which I want to merge after I created them. Reportlab provides a way to save a pycanvas (source) (which is basically my pdf file in memory) as a python file, and calling the method doIt(filename) on that python file, will recreate the pdf file. This is great, since you can combine two PDFs on source code basis and create one merge pdf. This is done like this: from reportlab.pdfgen import canvas, pycanvas #create your canvas p = pycanvas.Canvas(buffer,pagesize=PAGESIZE) #...instantiate your pdf... # after that, close the PDF object cleanly. p.showPage() p.save() #now create the string equivalent of your canvas source_code_equiv = str(p) source_code_equiv2 = str(p) #merge the two files on str. basis #not shown how it is exactly done, to make it more easy to read the source #actually one just have to take the middle part of source_code_equiv2 and add it into source_code_equiv final_pdf = source_code_equiv_part1 + source_code_equiv2_center_part + source_code_equiv_part2 #write the source-code equivalent of the pdf open("n2.py","w").write(final_pdf) from myproject import n2 p = n2.doIt(buffer) # Get the value of the StringIO buffer and write it to the response. pdf = buffer.getvalue() buffer.close() response.write(pdf) return response This works fine, but I want to skip the step that I save the n2.py to the disk. Thus I'm looking for a way to instantiate from the final_pdf string the corresponding python class and use it directly in the source. Is this possible? It should work somehow like this.. n2 = instantiate_python_class_from_source(final_pdf) p = n2.doIt(buffer) The reason for this is mainly that there is not really a need to save the source to the disk, and secondly that it is absolutely not thread save. I could name the created file at run time, but then I do not know what to import!? If there is no way to prevent the file saving, is there a way to define the import based on the name of the file, which is defined at runtime!? One might ask why I do not create one pdf in advance, but this is not possible, since they are coming from different applications.
[ "This seems like a really long way around to what you want. Doesn't Reportlab have a Canvas class from which you can pull the PDF document? I don't see why generated Python source code should be involved here.\nBut if for some reason it is necessary, then you can use StringIO to \"write\" the source to a string, ...
[ 1, 0 ]
[]
[]
[ "python", "reportlab" ]
stackoverflow_0003590166_python_reportlab.txt
Q: Parsing JavaScript argument values in python Is there a way to parse the argument values passed to a JavaScript function in python? I want to be able to automatically document JavaScript function calls in order to make sure they have the right arguments passed to them. For example, in: function mymethod(fruit, vegetable, drink) { // dummy function } function drink(drink) { this.drink = drink } var myveg = 'tomato' mymethod('grape', myveg, new drink('apple juice')) The function call would be rewritten as: mymethod( /*fruit*/ 'grape', /*vegetable*/ myveg, /*drink*/ new drink('apple juice') ) So I really want to be able to split the arguments into ["'grape'", "myveg", "new drink('apple juice')"] removing any previous auto-inserted comments in the process, preferably allowing subfunction calls as arguments. If all else fails, I'll make it so that the arguments are as a comment before the method call (which would be much easier to parse) but I thought I'd ask first as it would make mistakes look more obvious. Thank you very much in advance. A: You'll need a full JavaScript parser unless you know in advance that your JavaScript code follows some conventions you know in advance. Regular expressions are not up to the task, because they are not good for matching nested structures like parentheses. Python has many parser generator tools: Python parsing tools. I don't know if any of them have JavaScript parsers available.
Parsing JavaScript argument values in python
Is there a way to parse the argument values passed to a JavaScript function in python? I want to be able to automatically document JavaScript function calls in order to make sure they have the right arguments passed to them. For example, in: function mymethod(fruit, vegetable, drink) { // dummy function } function drink(drink) { this.drink = drink } var myveg = 'tomato' mymethod('grape', myveg, new drink('apple juice')) The function call would be rewritten as: mymethod( /*fruit*/ 'grape', /*vegetable*/ myveg, /*drink*/ new drink('apple juice') ) So I really want to be able to split the arguments into ["'grape'", "myveg", "new drink('apple juice')"] removing any previous auto-inserted comments in the process, preferably allowing subfunction calls as arguments. If all else fails, I'll make it so that the arguments are as a comment before the method call (which would be much easier to parse) but I thought I'd ask first as it would make mistakes look more obvious. Thank you very much in advance.
[ "You'll need a full JavaScript parser unless you know in advance that your JavaScript code follows some conventions you know in advance. Regular expressions are not up to the task, because they are not good for matching nested structures like parentheses.\nPython has many parser generator tools: Python parsing too...
[ 1 ]
[]
[]
[ "arguments", "javascript", "parsing", "python", "regex" ]
stackoverflow_0003590629_arguments_javascript_parsing_python_regex.txt
Q: PyGTK: adding text over widgets I'm developing a GTK app, and would like to print some messages over existing widgets rather than displaying them in the status bar, kind of like the way Mendeley does it when no document is selected: (as opposed to what is displayed in the right pane when you select a document:) Should I dynamically create a panel, label, ... with the appropriate message and destroy it when needed, or is there a simpler / better way? A: You don't need to destroy the label, even nothing forces you to do so, neither create it dynamically. You could create it when you need it or glade could do it for you. This is a minimal example but, as you notice, both labels are created only once. import gtk labels = [] def changeLabel(widget): l = p.get_children()[1] p.remove(l) nl = labels[l is l1] p.add2(nl) w = gtk.Window() w.connect('destroy', lambda w: gtk.main_quit()) p = gtk.HPaned() w.add(p) b = gtk.Button('change label') b.connect('clicked', changeLabel) p.add1(b) l1 = gtk.Label('hello world') l1.show() p.add2(l1) l2 = gtk.Label('ciao mondo') l2.show() labels = [l1, l2] which = 0 w.show_all() gtk.main()
PyGTK: adding text over widgets
I'm developing a GTK app, and would like to print some messages over existing widgets rather than displaying them in the status bar, kind of like the way Mendeley does it when no document is selected: (as opposed to what is displayed in the right pane when you select a document:) Should I dynamically create a panel, label, ... with the appropriate message and destroy it when needed, or is there a simpler / better way?
[ "You don't need to destroy the label, even nothing forces you to do so, neither create it dynamically. You could create it when you need it or glade could do it for you. This is a minimal example but, as you notice, both labels are created only once.\nimport gtk\n\nlabels = []\n\ndef changeLabel(widget):\n l = p...
[ 2 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0003590690_gtk_pygtk_python.txt
Q: py2exe: Reduce size of the library archive I just created my first py2exe executable and noticed that with the EXE, there is a ZIP file created with the size of around 1.4 MB. My question is, can I reduce the size of this or is it expected that the typical size of an EXE generated with py2exe will be ~ 4 MB (that means with all the files: python2.6dll, library.zip) A: Short answer to your size reduction question is yes. Long answer I am not going to provide here, but instead direct you to py2exe's OptimizingSize wiki page. I hope this helps ;) A: After changing those setup.py parameters i also run UPX on DLLs and executables and repack library.zip with 7-zip, works well. By the way, there is a page on the wiki about using UPX and 7-zip.
py2exe: Reduce size of the library archive
I just created my first py2exe executable and noticed that with the EXE, there is a ZIP file created with the size of around 1.4 MB. My question is, can I reduce the size of this or is it expected that the typical size of an EXE generated with py2exe will be ~ 4 MB (that means with all the files: python2.6dll, library.zip)
[ "Short answer to your size reduction question is yes. Long answer I am not going to provide here, but instead direct you to py2exe's OptimizingSize wiki page.\nI hope this helps ;)\n", "After changing those setup.py parameters i also run UPX on DLLs and executables and repack library.zip with 7-zip, works well.\...
[ 7, 3 ]
[]
[]
[ "py2exe", "python" ]
stackoverflow_0003528763_py2exe_python.txt
Q: Bind arbitrary Python objects to CherryPy sessions I'm using CherryPy to make a web-based frontend for SymPy that uses an asynchronous process library on the server side to allow for processing multiple requests at once without waiting for each one to complete. So as to allow for the frontend to function as expected, I am using one process for the entirety of each session. The client-side Javascript sends the session-id from the cookie to the server when the user submits a request, and the server-side currently uses a pair of lists, storing instances of a controller class in one and the corresponding session-id's in another, creating a new interpreter proxy and sending the input if a non-existant session-id is submitted. The only problem with this is that the proxy classes are not deleted upon the expiration of their corresponding sessions. Also, I can't see anything to retrieve the session-id for which the current request is being served. My questions about all this are: is there any way to "connect" an arbitrary object to a CherryPy session so that it gets deleted upon session expiration, is there something I am overlooking here that would greatly simplify things, and does CherryPy's multi-threading negate the problem of synchronous reading of the stdout filehandle from the child process? A: You can create your own session type, derived from CherryPy's base session. Use its clean_up method to do your cleanup. Look at cherrypy/lib/sessions.py for details and sample session implementations.
Bind arbitrary Python objects to CherryPy sessions
I'm using CherryPy to make a web-based frontend for SymPy that uses an asynchronous process library on the server side to allow for processing multiple requests at once without waiting for each one to complete. So as to allow for the frontend to function as expected, I am using one process for the entirety of each session. The client-side Javascript sends the session-id from the cookie to the server when the user submits a request, and the server-side currently uses a pair of lists, storing instances of a controller class in one and the corresponding session-id's in another, creating a new interpreter proxy and sending the input if a non-existant session-id is submitted. The only problem with this is that the proxy classes are not deleted upon the expiration of their corresponding sessions. Also, I can't see anything to retrieve the session-id for which the current request is being served. My questions about all this are: is there any way to "connect" an arbitrary object to a CherryPy session so that it gets deleted upon session expiration, is there something I am overlooking here that would greatly simplify things, and does CherryPy's multi-threading negate the problem of synchronous reading of the stdout filehandle from the child process?
[ "You can create your own session type, derived from CherryPy's base session. Use its clean_up method to do your cleanup.\nLook at cherrypy/lib/sessions.py for details and sample session implementations.\n" ]
[ 1 ]
[]
[]
[ "asynchronous", "cherrypy", "multithreading", "python", "session" ]
stackoverflow_0003591020_asynchronous_cherrypy_multithreading_python_session.txt
Q: Image bit manipulation in Python I have an application that receives a pointer to JPEG data from a camera API wrapped with ctypes, converts it to a wx.Image, and displays the images as a movie. One of required features is to set two of the components of a pixel equal to the third. E.g, my pixel in RGB format is (100,200,255), I want to set the the R and B values equal to the G, or (200,200,200). I need to do t his for every pixel in the image whilst maintaining a decent framerate. I can access the RGB values from my wx.Image by calling the Image.GetData, which returns a string containing the pixel values in the following format: RGBRGBRGB ... I have implemented the feature naively by iterating through this RGBRGBRGB string. However, this naive approach is far too slow to achieve a decent FPS because (I think): a) I am iterating through every pixel in the image. b) I am doing too much data copying. I have considered converting my RGB data to numpy, performing the operation (I assume numpy would have a faster way of doing this sort of thing), and then converting back to wx.Image. Unfortunately I cannot convert straight from the raw data to numpy as the data comes as a JPEG, not in as a RGB bitmap. So I would need to go from data->wx.Image->numpy array->wx.Image. I have also considered implementing my own python buffer which will return, for example, the G pixel value instead of the R and B values when being read. I think this would be the ideal solution, as it requires no data copying or excessive iterations, but I have no idea how to go about doing this. Will I need to write this buffer in C? Is it possible to implement buffers in pure python and still manipulate raw memory? So SO, how do you think I should go about improving my performance? Should I attempt the numpy or buffer solution, or is there an easier solution that I am missing? I am mainly looking for ideas/links to relevant documentation or examples, but if someones wants to write some code then that's fine :) Thanks A: You could try using the Python Imaging Library (PIL) - this is a library for manipulating images. You can find information about converting between a wxPython image and a PIL image here, or you can load the jpeg directly into a PIL image. Once you have converted your wx image into a PIL image I think this will do what you want (but I have not tested it): r, g, b = im.split() # split the image into separate color planes im = Image.merge("RGB", (g, g, g)) # merge them back, using the green plane for each Then convert it back to a wxPython image. This should be orders of magnitude faster than doing it in Python, since PIL is implemented in C and optimised for image processing. A: If you need really fast processing of images I suggest writing GLSL pixel shader and interface it through OpenGL and PyGame. Nothing beats processing speed of pixel shaders, because every pixel is processed in parallel by GPU on video card. If you need to test code of pixel shaders (which is written with subset of C) it is better to do that with RenderMonkey - it is decent shader development IDE ! Good luck!
Image bit manipulation in Python
I have an application that receives a pointer to JPEG data from a camera API wrapped with ctypes, converts it to a wx.Image, and displays the images as a movie. One of required features is to set two of the components of a pixel equal to the third. E.g, my pixel in RGB format is (100,200,255), I want to set the the R and B values equal to the G, or (200,200,200). I need to do t his for every pixel in the image whilst maintaining a decent framerate. I can access the RGB values from my wx.Image by calling the Image.GetData, which returns a string containing the pixel values in the following format: RGBRGBRGB ... I have implemented the feature naively by iterating through this RGBRGBRGB string. However, this naive approach is far too slow to achieve a decent FPS because (I think): a) I am iterating through every pixel in the image. b) I am doing too much data copying. I have considered converting my RGB data to numpy, performing the operation (I assume numpy would have a faster way of doing this sort of thing), and then converting back to wx.Image. Unfortunately I cannot convert straight from the raw data to numpy as the data comes as a JPEG, not in as a RGB bitmap. So I would need to go from data->wx.Image->numpy array->wx.Image. I have also considered implementing my own python buffer which will return, for example, the G pixel value instead of the R and B values when being read. I think this would be the ideal solution, as it requires no data copying or excessive iterations, but I have no idea how to go about doing this. Will I need to write this buffer in C? Is it possible to implement buffers in pure python and still manipulate raw memory? So SO, how do you think I should go about improving my performance? Should I attempt the numpy or buffer solution, or is there an easier solution that I am missing? I am mainly looking for ideas/links to relevant documentation or examples, but if someones wants to write some code then that's fine :) Thanks
[ "You could try using the Python Imaging Library (PIL) - this is a library for manipulating images.\nYou can find information about converting between a wxPython image and a PIL image here, or you can load the jpeg directly into a PIL image.\nOnce you have converted your wx image into a PIL image I think this will d...
[ 1, 1 ]
[]
[]
[ "bitmap", "ctypes", "image_processing", "python", "wxwidgets" ]
stackoverflow_0003578373_bitmap_ctypes_image_processing_python_wxwidgets.txt
Q: developing a scalabe chat system I am a java developer and am pretty comfortable with develeoping webapps in java/jsp/servlets. I want to develop a video web based chat website.people should be able to chat with each other using my website.People dont need to use any client app installed on their pc in order to chat with others. My website should be scalable.It should be able to support many hundreds of user simultaneously.I heard that there is a framework cal is beastled twisted matrix in python that best for developing such kind of servers.But learning a new language of me is not feasible as i dont have much time to get the system up and running.I have 2 months to get the application up and running. After googling i found that twisted matrix ix best for the puropose. So what should i do?Should i go ahead with java or python?Which java framework to use?If i develop it in java should i develop a web app which will run on top of app server? or shold i develop my own chat server in java? Any pointers will be helpful. A: I'm a little confused: the requirement is that users don't need any software installed on their PC? How can that be? You need something. Given two months, I think you only have two options: Flash Skype Like you said, because you have two months to get it up and running, you're best off not learning a new language. As far as Java network frameworks go, people seem to have pretty good experiences with Netty, MINA, or Grizzly, but going that low-level will probably cause you grief. There's some good stuff on SO too: API to broadcast live webcam A: Just Try Cometd, CometD is a scalable HTTP-based event routing bus that uses a Ajax Push technology pattern known as Comet. There is also a chatroom example in the sourcecode. Cometd is based on Jetty Continuation。 Using Long pooling.
developing a scalabe chat system
I am a java developer and am pretty comfortable with develeoping webapps in java/jsp/servlets. I want to develop a video web based chat website.people should be able to chat with each other using my website.People dont need to use any client app installed on their pc in order to chat with others. My website should be scalable.It should be able to support many hundreds of user simultaneously.I heard that there is a framework cal is beastled twisted matrix in python that best for developing such kind of servers.But learning a new language of me is not feasible as i dont have much time to get the system up and running.I have 2 months to get the application up and running. After googling i found that twisted matrix ix best for the puropose. So what should i do?Should i go ahead with java or python?Which java framework to use?If i develop it in java should i develop a web app which will run on top of app server? or shold i develop my own chat server in java? Any pointers will be helpful.
[ "I'm a little confused: the requirement is that users don't need any software installed on their PC? How can that be? You need something.\nGiven two months, I think you only have two options:\n\nFlash\nSkype\n\nLike you said, because you have two months to get it up and running, you're best off not learning a new...
[ 1, 1 ]
[]
[]
[ "chat", "java", "python", "twisted", "video_streaming" ]
stackoverflow_0003589780_chat_java_python_twisted_video_streaming.txt
Q: Uses of Jython while programming I recently started learning Python and came accross the term Jython. From the Google search results, I thereby concluded that it is indeed a very important term. What is the experience programming/coding using Jython? A: Jython is just an implementation of the Python interpreter that runs on the JVM (Java Virtual Machine). What is JPython? JPython is an implementation of the Python programming language which is designed to run on the Java(tm) Platform. It consists of a compiler to compile Python source code down to Java bytecodes which can run directly on a JVM, a set of support libraries which are used by the compiled Java bytecodes, and extra support to make it trivial to use Java packages from within JPython. JPython has been renamed and superseded by Jython. So coding in Jython is the basically same as coding in Python; with the advantage of having access to Java libraries. Read: Jython FAQ, Why Jython? A: It's not just about the advantage of having access to the Java libraries. It's also being able to run on Java VM's with all their support and optimizations (i.e. JIT compilation). Jython is also very usefull for scripting Java applications. IronPython is a similar approach for the .NET CLI
Uses of Jython while programming
I recently started learning Python and came accross the term Jython. From the Google search results, I thereby concluded that it is indeed a very important term. What is the experience programming/coding using Jython?
[ "Jython is just an implementation of the Python interpreter that runs on the JVM (Java Virtual Machine).\n\nWhat is JPython?\nJPython is an implementation of the\nPython programming language which is\ndesigned to run on the Java(tm)\nPlatform. It consists of a compiler to\ncompile Python source code down to\nJava b...
[ 14, 4 ]
[ "My recommendation to you: Forget about Jython and IronPython. Nobody uses them except the beginners and their developers. As for Jython, it's much slower, less robust, and less reliable than Python (aka CPython). It doesn't have the significant number of \"batteries\" that come Python; moreover, threading, process...
[ -8 ]
[ "jython", "python" ]
stackoverflow_0003591171_jython_python.txt
Q: Transaction on GAE entity property I am trying to create a vote function that increases the class URL.votes +1 when clicked. This is a two part question: How do you pull the entity key? (I think you need the key to distinguish which vote property is being modified?) How do you then write the 'a href' for the link to perform the vote? Thanks! Models: class URL(db.Model): user = db.ReferenceProperty(User) website = db.StringProperty() created = db.DateTimeProperty(auto_now=True) votes = db.IntegerProperty(default=1) class Vote(db.Model): user = db.ReferenceProperty(User) #See if voted on this site yet url = db.ReferenceProperty(URL) #To apply vote to right URL upvote = db.IntegerProperty(default=1) created = db.DateTimeProperty(auto_now=True) Controller class VoteHandler(webapp.RequestHandler): def get(self): doRender(self, 'base/index.html') def post(self): #See if logged in self.Session = Session() if not 'userkey' in self.Session: doRender( self, '/', {'error' : 'Please login to vote'}) return #Get current vote total url = db.URL.get() #pull current site. This is where I think I need the help url.votes += 1 #pull current site vote total & add 1 url.put(); logging.info('Adding a vote'+nurl) #Create a new Vote object newvote = models.Vote(user=self.Session['userkey'], url=url) newvote.put(); self.get(); self.redirect('/', { }) View a href="/vote" {{ url.votes }} votes - {{ url.website }} A: The answer includes a few things: You need to use a Query string to pass the data on for the VoteHandler a href="/vote?url_id={{url.key.id}}">{{ url.votes }} votes - {{ url.website }} - {{ url.user.account }} - {{ url.created|date:"M d, Y" }} Clicking a vote link, is a get() not a post(). Then you use model.get_by_id() class VoteHandler(webapp.RequestHandler): def get(self): #See if logged in self.Session = Session() if not 'userkey' in self.Session: doRender( self, 'base/index.html', {'error' : 'Please login to vote'}) return #Get current vote total key = self.request.get('url_id') vurl = models.URL.get_by_id(int(key)) vurl.votes += 1 #pull current site vote total & add 1 vurl.put(); logging.info('Adding a vote') #Create a new Vote object newvote = models.Vote(user=self.Session['userkey'], url=vurl) newvote.put(); self.redirect('/', { }) A: You can use url.votes.key.id in your View a href="/vote*?id={{ url.votes.key.id }}*" {{ url.votes }} votes - {{ url.website }}
Transaction on GAE entity property
I am trying to create a vote function that increases the class URL.votes +1 when clicked. This is a two part question: How do you pull the entity key? (I think you need the key to distinguish which vote property is being modified?) How do you then write the 'a href' for the link to perform the vote? Thanks! Models: class URL(db.Model): user = db.ReferenceProperty(User) website = db.StringProperty() created = db.DateTimeProperty(auto_now=True) votes = db.IntegerProperty(default=1) class Vote(db.Model): user = db.ReferenceProperty(User) #See if voted on this site yet url = db.ReferenceProperty(URL) #To apply vote to right URL upvote = db.IntegerProperty(default=1) created = db.DateTimeProperty(auto_now=True) Controller class VoteHandler(webapp.RequestHandler): def get(self): doRender(self, 'base/index.html') def post(self): #See if logged in self.Session = Session() if not 'userkey' in self.Session: doRender( self, '/', {'error' : 'Please login to vote'}) return #Get current vote total url = db.URL.get() #pull current site. This is where I think I need the help url.votes += 1 #pull current site vote total & add 1 url.put(); logging.info('Adding a vote'+nurl) #Create a new Vote object newvote = models.Vote(user=self.Session['userkey'], url=url) newvote.put(); self.get(); self.redirect('/', { }) View a href="/vote" {{ url.votes }} votes - {{ url.website }}
[ "The answer includes a few things:\n\nYou need to use a Query string to pass the data on for the VoteHandler \n\na href=\"/vote?url_id={{url.key.id}}\">{{ url.votes }} votes - {{ url.website }} - {{ url.user.account }} - {{ url.created|date:\"M d, Y\" }}\n\nClicking a vote link, is a get() not a post(). Then you us...
[ 1, 0 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0003585943_google_app_engine_google_cloud_datastore_python.txt
Q: Django - make file I/O thread safe I want to read and write python-source-files from the file system in a thread-safe way. open("n2.py","w").write(my_new_py_class) from myproject import n2 #do something with n2 I assume that this is not thread-safe, since a request2 could modify the file before request1 is loading and executing it. I would like to achieve something like that one thread is waiting till the other thread wrote, loaded, executed and closed the file. A: Why are you making your application modify its own files? This is not only incredibly evil, metaprogramming is orders of magnitude harder to understand debug. Plus, python caches modules it imports, so it's not really easy to reload that. And, last but not least, you don't have to writ the code to a file to execute it, if you really must execute dynamically generated code. To answer your question about writing files in a thread safe way, the general convention is to: Write your content to a temporary file on the same filesystem as your target file. Rename that temporary file to your target file, overwritting it in the process. This works, because rename is atomic on POSIX systems, when done on the same device. So other threads/processes will either still have the old file opened, which is now detached from the filesystem and will be deleted as soon as those threads/processes are done with it, or they will open the new file with all of its contents. You avoid having a file that is only half-written. In practice, I like to make a temporary directory with python's tempfile module, and write the file in there, then move it and remove the directory -- this way the file is being created with default umask. Last but not least, rename is not really atomic on Windows, at least with default settings, as it won't let you overwrite your old file -- you need to do two renames, and that introduces a possibility of race condition. I don't know a good solution for Windows. A: I had a similar problem. Check the Erik Karulf answer in this question: Django and dynamically generated images We also provided some code :)
Django - make file I/O thread safe
I want to read and write python-source-files from the file system in a thread-safe way. open("n2.py","w").write(my_new_py_class) from myproject import n2 #do something with n2 I assume that this is not thread-safe, since a request2 could modify the file before request1 is loading and executing it. I would like to achieve something like that one thread is waiting till the other thread wrote, loaded, executed and closed the file.
[ "Why are you making your application modify its own files? This is not only incredibly evil, metaprogramming is orders of magnitude harder to understand debug. Plus, python caches modules it imports, so it's not really easy to reload that. And, last but not least, you don't have to writ the code to a file to execut...
[ 4, 0 ]
[]
[]
[ "django", "python", "thread_safety" ]
stackoverflow_0003590510_django_python_thread_safety.txt
Q: How can I organise program, which should have non-blocking connection on Python? My question is next: I want to write a program which should connect to the same program on the other machine, and both this program should exchange some information. I can't set up non-blocking connection. How can it be? A: Take a look at the asyncore library: http://docs.python.org/library/asyncore.html And specifically, the asynchat examples: http://docs.python.org/library/asynchat.html#asynchat.async_chat It should do exactly what you need here. A: The most simple solution to have a non-blocking socket in Python is just to use the setblocking() method on the socket. Something like this: import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setblocking(0) # bind, accept or connect stuff s.recv(100) # will not block and if no data available a "socket.error" # exception will be raised You may also want to take a look at settimeout() A: If you want to pass Python objects, you can "serialize" them with the pickle module and send them through sockets, as described in other answers.
How can I organise program, which should have non-blocking connection on Python?
My question is next: I want to write a program which should connect to the same program on the other machine, and both this program should exchange some information. I can't set up non-blocking connection. How can it be?
[ "Take a look at the asyncore library: http://docs.python.org/library/asyncore.html\nAnd specifically, the asynchat examples: http://docs.python.org/library/asynchat.html#asynchat.async_chat\nIt should do exactly what you need here.\n", "The most simple solution to have a non-blocking socket in Python is just to u...
[ 1, 0, 0 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0003591505_python_sockets.txt
Q: Transforming early modern English into 20th century spelling using the NLTK I have a list of strings that are all early modern English words ending with 'th.' These include hath, appointeth, demandeth, etc. -- they are all conjugated for the third person singular. As part of a much larger project (using my computer to convert the Gutenberg etext of Gargantua and Pantagruel into something more like 20th century English, so that I'll be able to read it more easily) I want to remove the last two or three characters from all of those words and replace them with an 's,' then use a slightly modified function on the words that still weren't modernized, both included below. My main problem is that I just never manage to get my typing right in Python. I find that part of the language really confusing at this point. Here's the function that removes th's: from __future__ import division import nltk, re, pprint def ethrema(word): if word.endswith('th'): return word[:-2] + 's' Here's the function that removes extraneous e's: def ethremb(word): if word.endswith('es'): return word[:-2] + 's' hence the words 'abateth' and 'accuseth' would pass through ethrema but not through ethremb(ethrema), while the word 'abhorreth' would need to pass through both. If anyone can think of a more efficient way to do this, I'm all ears. Here's the result of my very amateurish attempt to use these functions on a tokenized list of words that need modernizing: >>> eth1 = [w.ethrema() for w in text] Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'str' object has no attribute 'ethrema' So, yeah, it's really an issue of typing. These are the first functions I've ever written in Python, and I have no idea how to apply them to actual objects. A: ethrema() is not a method of the type str, you have to use the following : eth1 = [ethrema(w) for w in text] #AND eth2 = [ethremb(w) for w in text] EDIT (to answer comment) : ethremb(ethrema(word)) wouldn't work until you made some little changes to your functions : def ethrema(word): if word.endswith('th'): return word[:-2] + 's' else return word def ethremb(word): if word.endswith('es'): return word[:-2] + 's' else return word #OR def ethrema(word): if word.endswith('th'): return word[:-2] + 's' elif word.endswith('es'): return word[:-2] + 's' else return word
Transforming early modern English into 20th century spelling using the NLTK
I have a list of strings that are all early modern English words ending with 'th.' These include hath, appointeth, demandeth, etc. -- they are all conjugated for the third person singular. As part of a much larger project (using my computer to convert the Gutenberg etext of Gargantua and Pantagruel into something more like 20th century English, so that I'll be able to read it more easily) I want to remove the last two or three characters from all of those words and replace them with an 's,' then use a slightly modified function on the words that still weren't modernized, both included below. My main problem is that I just never manage to get my typing right in Python. I find that part of the language really confusing at this point. Here's the function that removes th's: from __future__ import division import nltk, re, pprint def ethrema(word): if word.endswith('th'): return word[:-2] + 's' Here's the function that removes extraneous e's: def ethremb(word): if word.endswith('es'): return word[:-2] + 's' hence the words 'abateth' and 'accuseth' would pass through ethrema but not through ethremb(ethrema), while the word 'abhorreth' would need to pass through both. If anyone can think of a more efficient way to do this, I'm all ears. Here's the result of my very amateurish attempt to use these functions on a tokenized list of words that need modernizing: >>> eth1 = [w.ethrema() for w in text] Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'str' object has no attribute 'ethrema' So, yeah, it's really an issue of typing. These are the first functions I've ever written in Python, and I have no idea how to apply them to actual objects.
[ "ethrema() is not a method of the type str, you have to use the following :\neth1 = [ethrema(w) for w in text]\n#AND\neth2 = [ethremb(w) for w in text]\n\nEDIT (to answer comment) : \nethremb(ethrema(word)) wouldn't work until you made some little changes to your functions : \ndef ethrema(word):\n if word.endswi...
[ 6 ]
[]
[]
[ "nlp", "nltk", "python", "text" ]
stackoverflow_0003591673_nlp_nltk_python_text.txt
Q: Why are sets bigger than lists in python? Why is the size of sets in Python noticeably larger than that of lists with same elements? a = set(range(10000)) b = list(range(10000)) print('set size = ', a.__sizeof__()) print('list size = ', b.__sizeof__()) output: set size = 524488 list size = 90088 A: The set uses more memory than the list as it stores a table of hashes of all the elements so it can quickly detect duplicate entries and so on. This is why every set member must be hashable.
Why are sets bigger than lists in python?
Why is the size of sets in Python noticeably larger than that of lists with same elements? a = set(range(10000)) b = list(range(10000)) print('set size = ', a.__sizeof__()) print('list size = ', b.__sizeof__()) output: set size = 524488 list size = 90088
[ "The set uses more memory than the list as it stores a table of hashes of all the elements so it can quickly detect duplicate entries and so on. This is why every set member must be hashable.\n" ]
[ 19 ]
[]
[]
[ "list", "python", "set" ]
stackoverflow_0003591727_list_python_set.txt
Q: Paraview and Python on Mac OSX I've installed the binary distribution of paraview on OSX. When running this I can access the python interpreter from the Tools -> Python Shell. However I cannot figure out which libraries I need to add to PYTHONPATH in order to access VTK and Paraview functionality directly from Python. Of course I could just compile the source distribution myself, but this would take a lot of time. Any ideas? A: I am basing my answer on recently built Paraview 3.9.0 from the CVS. But you should be able to access ParaView directly from your regular Python if you add: <Paraview-Bld-Directory>/Utilities/VTKPythonWrapping/site-packages <Paraview-Bld-Directory>/bin to your PYTHONPATH variable. Did this same approach fail to work when you tried the binary distribution? Sorry, but I wasn't sure how to interpret your comment about it working if you build by hand.
Paraview and Python on Mac OSX
I've installed the binary distribution of paraview on OSX. When running this I can access the python interpreter from the Tools -> Python Shell. However I cannot figure out which libraries I need to add to PYTHONPATH in order to access VTK and Paraview functionality directly from Python. Of course I could just compile the source distribution myself, but this would take a lot of time. Any ideas?
[ "I am basing my answer on recently built Paraview 3.9.0 from the CVS. But you should be able to access ParaView directly from your regular Python if you add:\n<Paraview-Bld-Directory>/Utilities/VTKPythonWrapping/site-packages\n<Paraview-Bld-Directory>/bin\n\nto your PYTHONPATH variable.\nDid this same approach fa...
[ 2 ]
[]
[]
[ "macos", "paraview", "python", "vtk" ]
stackoverflow_0003317993_macos_paraview_python_vtk.txt
Q: Export mail from Gmail At one point it was possible to use scripts like libgmail and gmail.py (can't post more than one hyperlink) to export mail from Gmail accounts. Both of those seem to not work anymore — I can't even log in with them. I assume it's because there's been some changes in Gmail. Is there still any way to do this? A: Gmail supports IMAP and POP, which are common protocols for accessing email. You should be able to use use any working IMAP or POP library for Python to download your email. If you want tag/folder information, you'll need to stick to IMAP. A: As far as I know neither libgmail nor gmail.py are compatible with the current version of Gmail. I use IMAP to download mails from gmail. Python's imaplib module is quite useful for this. This answer (disclaimer: my answer) to a related question might give you some clues.
Export mail from Gmail
At one point it was possible to use scripts like libgmail and gmail.py (can't post more than one hyperlink) to export mail from Gmail accounts. Both of those seem to not work anymore — I can't even log in with them. I assume it's because there's been some changes in Gmail. Is there still any way to do this?
[ "Gmail supports IMAP and POP, which are common protocols for accessing email. You should be able to use use any working IMAP or POP library for Python to download your email. If you want tag/folder information, you'll need to stick to IMAP.\n", "As far as I know neither libgmail nor gmail.py are compatible with t...
[ 7, 1 ]
[]
[]
[ "gmail", "python" ]
stackoverflow_0003592015_gmail_python.txt
Q: Cannot select item from QListView with custom QStyledItemDelegate I want to render each row with HTML code. The rendering works but -at least for me- items cannot be selected individually. import sys from PyQt4.QtCore import * from PyQt4.QtGui import * #################################################################### def main(): app = QApplication(sys.argv) w = MyWindow() w.show() sys.exit(app.exec_()) list_data = [1,2,3,4] #################################################################### class MyWindow(QWidget): def __init__(self, *args): QWidget.__init__(self, *args) # create table lm = MyListModel(list_data, self) lv = QListView() lv.setModel(lm) lv.setItemDelegate(HTMLDelegate(self)) # layout layout = QVBoxLayout() layout.addWidget(lv) self.setLayout(layout) #################################################################### class MyListModel(QAbstractListModel): def __init__(self, datain, parent=None, *args): """ datain: a list where each item is a row """ QAbstractListModel.__init__(self, parent, *args) self.listdata = datain def rowCount(self, parent=QModelIndex()): return len(self.listdata) def data(self, index, role): if index.isValid() and role == Qt.DisplayRole: return QVariant(self.listdata[index.row()]) else: return QVariant() class HTMLDelegate(QStyledItemDelegate): def paint(self, painter, option, index): painter.save() model = index.model() record = model.listdata[index.row()] doc = QTextDocument(self) doc.setHtml("<b>%s</b>"%record) doc.setTextWidth(option.rect.width()) ctx = QAbstractTextDocumentLayout.PaintContext() painter.translate(option.rect.topLeft()); painter.setClipRect(option.rect.translated(-option.rect.topLeft())) dl = doc.documentLayout() dl.draw(painter, ctx) painter.restore() def sizeHint(self, option, index): model = index.model() record = model.listdata[index.row()] doc = QTextDocument(self) doc.setHtml("<b>%s</b>"%record) doc.setTextWidth(option.rect.width()) return QSize(doc.idealWidth(), doc.size().height()) def flags(self, index): return Qt.ItemIsEnabled | Qt.ItemIsSelectable #################################################################### if __name__ == "__main__": main() A: I believe what you should do is detect selected items in your HTMLDelegate.paint method and fill the background with "highlight" color if such items detected. I've slightly changed your paint method, pls, check if it works for you def paint(self, painter, option, index): painter.save() # highlight selected items if option.state & QtGui.QStyle.State_Selected: painter.fillRect(option.rect, option.palette.highlight()); model = index.model() record = model.listdata[index.row()] doc = QTextDocument(self) doc.setHtml("<b>%s</b>"%record) doc.setTextWidth(option.rect.width()) ctx = QAbstractTextDocumentLayout.PaintContext() painter.translate(option.rect.topLeft()); painter.setClipRect(option.rect.translated(-option.rect.topLeft())) dl = doc.documentLayout() dl.draw(painter, ctx) painter.restore() hope this helps, regards
Cannot select item from QListView with custom QStyledItemDelegate
I want to render each row with HTML code. The rendering works but -at least for me- items cannot be selected individually. import sys from PyQt4.QtCore import * from PyQt4.QtGui import * #################################################################### def main(): app = QApplication(sys.argv) w = MyWindow() w.show() sys.exit(app.exec_()) list_data = [1,2,3,4] #################################################################### class MyWindow(QWidget): def __init__(self, *args): QWidget.__init__(self, *args) # create table lm = MyListModel(list_data, self) lv = QListView() lv.setModel(lm) lv.setItemDelegate(HTMLDelegate(self)) # layout layout = QVBoxLayout() layout.addWidget(lv) self.setLayout(layout) #################################################################### class MyListModel(QAbstractListModel): def __init__(self, datain, parent=None, *args): """ datain: a list where each item is a row """ QAbstractListModel.__init__(self, parent, *args) self.listdata = datain def rowCount(self, parent=QModelIndex()): return len(self.listdata) def data(self, index, role): if index.isValid() and role == Qt.DisplayRole: return QVariant(self.listdata[index.row()]) else: return QVariant() class HTMLDelegate(QStyledItemDelegate): def paint(self, painter, option, index): painter.save() model = index.model() record = model.listdata[index.row()] doc = QTextDocument(self) doc.setHtml("<b>%s</b>"%record) doc.setTextWidth(option.rect.width()) ctx = QAbstractTextDocumentLayout.PaintContext() painter.translate(option.rect.topLeft()); painter.setClipRect(option.rect.translated(-option.rect.topLeft())) dl = doc.documentLayout() dl.draw(painter, ctx) painter.restore() def sizeHint(self, option, index): model = index.model() record = model.listdata[index.row()] doc = QTextDocument(self) doc.setHtml("<b>%s</b>"%record) doc.setTextWidth(option.rect.width()) return QSize(doc.idealWidth(), doc.size().height()) def flags(self, index): return Qt.ItemIsEnabled | Qt.ItemIsSelectable #################################################################### if __name__ == "__main__": main()
[ "I believe what you should do is detect selected items in your HTMLDelegate.paint method and fill the background with \"highlight\" color if such items detected. I've slightly changed your paint method, pls, check if it works for you\ndef paint(self, painter, option, index):\n painter.save()\n\n # highlight s...
[ 5 ]
[]
[]
[ "pyqt", "pyqt4", "python" ]
stackoverflow_0003472651_pyqt_pyqt4_python.txt
Q: Output of proc.communicate() does not format newlines in django python I have a subprocess using communicate to get the output ans saving it to my database: p = Popen([str(pre_sync), '-avu', str(src), str(dest)], stdout=PIPE) syncoutput = p.communicate() check.log = syncoutput It all works fine, but the output from communicate looks like this: ('sending incremental file list\n\nsent 89 bytes received 13 bytes 204.00 bytes/sec\ntotal size is 25 speedup is 0.25\n', None) All in a single line and with the "\n" inserted. Is there a way I can make it print each line in a new line? Thanks in advance. A: syncoutput,sync_error = p.communicate() print(syncoutput) p.communicate() returns a 2-tuple, composed of the output from stdout and stderr. When you print the 2-tuple, you see the \n characters. When you print the string (of the new syncoutput), you will get formatted text.
Output of proc.communicate() does not format newlines in django python
I have a subprocess using communicate to get the output ans saving it to my database: p = Popen([str(pre_sync), '-avu', str(src), str(dest)], stdout=PIPE) syncoutput = p.communicate() check.log = syncoutput It all works fine, but the output from communicate looks like this: ('sending incremental file list\n\nsent 89 bytes received 13 bytes 204.00 bytes/sec\ntotal size is 25 speedup is 0.25\n', None) All in a single line and with the "\n" inserted. Is there a way I can make it print each line in a new line? Thanks in advance.
[ "syncoutput,sync_error = p.communicate()\nprint(syncoutput)\n\np.communicate() returns a 2-tuple, composed of the output from stdout and stderr. When you print the 2-tuple, you see the \\n characters. When you print the string (of the new syncoutput), you will get formatted text.\n" ]
[ 4 ]
[]
[]
[ "django", "django_views", "popen", "python" ]
stackoverflow_0003592750_django_django_views_popen_python.txt
Q: Parsing HTML easily like PyQuery in Python 2.5 I am writing an app for GAE (Python 2.5) and I was wondering if there is any library like PyQuery (which runs on Python 2.6+). All I have to do is to load an HTML file and get the content of a especific tag through its ID. In PyQuery, or even Python2.6's libraries like lxml, it is very easy, but I don't know how to do that with Python 2.5. Can someone help me? ^^ Thank you guys. :) A: BeautifulSoup should be what you are looking for. A: BeautifulSoup is a common choice for HTML parsing, and is compatible with Python 2.5.
Parsing HTML easily like PyQuery in Python 2.5
I am writing an app for GAE (Python 2.5) and I was wondering if there is any library like PyQuery (which runs on Python 2.6+). All I have to do is to load an HTML file and get the content of a especific tag through its ID. In PyQuery, or even Python2.6's libraries like lxml, it is very easy, but I don't know how to do that with Python 2.5. Can someone help me? ^^ Thank you guys. :)
[ "BeautifulSoup should be what you are looking for.\n", "BeautifulSoup is a common choice for HTML parsing, and is compatible with Python 2.5.\n" ]
[ 4, 2 ]
[]
[]
[ "google_app_engine", "html", "python" ]
stackoverflow_0003592872_google_app_engine_html_python.txt
Q: How to filter a numpy.ndarray by date? I have a 2d numpy.array, where the first column contains datetime.datetime objects, and the second column integers: A = array([[2002-03-14 19:57:38, 197], [2002-03-17 16:31:33, 237], [2002-03-17 16:47:18, 238], [2002-03-17 18:29:31, 239], [2002-03-17 20:10:11, 240], [2002-03-18 16:18:08, 252], [2002-03-23 23:44:38, 327], [2002-03-24 09:52:26, 334], [2002-03-25 16:04:21, 352], [2002-03-25 18:53:48, 353]], dtype=object) What I would like to do is select all rows for a specific date, something like A[first_column.date()==datetime.date(2002,3,17)] array([[2002-03-17 16:31:33, 237], [2002-03-17 16:47:18, 238], [2002-03-17 18:29:31, 239], [2002-03-17 20:10:11, 240]], dtype=object) How can I achieve this? Thanks for your insight :) A: You could do this: from_date=datetime.datetime(2002,3,17,0,0,0) to_date=from_date+datetime.timedelta(days=1) idx=(A[:,0]>from_date) & (A[:,0]<=to_date) print(A[idx]) # array([[2002-03-17 16:31:33, 237], # [2002-03-17 16:47:18, 238], # [2002-03-17 18:29:31, 239], # [2002-03-17 20:10:11, 240]], dtype=object) A[:,0] is the first column of A. Unfortunately, comparing A[:,0] with a datetime.date object raises a TypeError. However, comparison with a datetime.datetime object works: In [63]: A[:,0]>datetime.datetime(2002,3,17,0,0,0) Out[63]: array([False, True, True, True, True, True, True, True, True, True], dtype=bool) Also, unfortunately, datetime.datetime(2002,3,17,0,0,0)<A[:,0]<=datetime.datetime(2002,3,18,0,0,0) raises a TypeError too, since this calls datetime.datetime's __lt__ method instead of the numpy array's __lt__ method. Perhaps this is a bug. Anyway, it's not hard to work-around; you can say In [69]: (A[:,0]>datetime.datetime(2002,3,17,0,0,0)) & (A[:,0]<=datetime.datetime(2002,3,18,0,0,0)) Out[69]: array([False, True, True, True, True, False, False, False, False, False], dtype=bool) Since this gives you a boolean array, you can use it as a "fancy index" to A, which yields the desired result. A: from datetime import datetime as dt, timedelta as td import numpy as np # Create 2-d numpy array d1 = dt.now() d2 = dt.now() d3 = dt.now() - td(1) d4 = dt.now() - td(1) d5 = d1 + td(1) arr = np.array([[d1, 1], [d2, 2], [d3, 3], [d4, 4], [d5, 5]]) # Here we will extract all the data for today, so get date range in datetime dtx = d1.replace(hour=0, minute=0, second=0, microsecond=0) dty = dtx + td(hours=24) # Condition cond = np.logical_and(arr[:, 0] >= dtx, arr[:, 0] < dty) # Full array print arr # Extracted array for the range print arr[cond, :]
How to filter a numpy.ndarray by date?
I have a 2d numpy.array, where the first column contains datetime.datetime objects, and the second column integers: A = array([[2002-03-14 19:57:38, 197], [2002-03-17 16:31:33, 237], [2002-03-17 16:47:18, 238], [2002-03-17 18:29:31, 239], [2002-03-17 20:10:11, 240], [2002-03-18 16:18:08, 252], [2002-03-23 23:44:38, 327], [2002-03-24 09:52:26, 334], [2002-03-25 16:04:21, 352], [2002-03-25 18:53:48, 353]], dtype=object) What I would like to do is select all rows for a specific date, something like A[first_column.date()==datetime.date(2002,3,17)] array([[2002-03-17 16:31:33, 237], [2002-03-17 16:47:18, 238], [2002-03-17 18:29:31, 239], [2002-03-17 20:10:11, 240]], dtype=object) How can I achieve this? Thanks for your insight :)
[ "You could do this:\nfrom_date=datetime.datetime(2002,3,17,0,0,0)\nto_date=from_date+datetime.timedelta(days=1)\nidx=(A[:,0]>from_date) & (A[:,0]<=to_date)\nprint(A[idx])\n# array([[2002-03-17 16:31:33, 237],\n# [2002-03-17 16:47:18, 238],\n# [2002-03-17 18:29:31, 239],\n# [2002-03-17 20:10:11,...
[ 8, 2 ]
[]
[]
[ "datetime", "numpy", "python", "scipy" ]
stackoverflow_0003592593_datetime_numpy_python_scipy.txt
Q: Reading input from remote control device on macs How could I read input from a remote control device on a mac (iMac, Mac Mini, etc.) and handle actions based on differently pressed buttons in python? I would like to map the button-press events to my custom app instead of "Front Row". What actions should I take to do that and what python libraries to use to handle the events? A: The Remote Control Wrapper 2 library is an Objective C class to handle interaction with Apple Remote Control (and, I believe, also some other such "remote-control-like" devices). To use some Objective C code from Python, see pyobjc.
Reading input from remote control device on macs
How could I read input from a remote control device on a mac (iMac, Mac Mini, etc.) and handle actions based on differently pressed buttons in python? I would like to map the button-press events to my custom app instead of "Front Row". What actions should I take to do that and what python libraries to use to handle the events?
[ "The Remote Control Wrapper 2 library is an Objective C class to handle interaction with Apple Remote Control (and, I believe, also some other such \"remote-control-like\" devices). To use some Objective C code from Python, see pyobjc.\n" ]
[ 3 ]
[]
[]
[ "macos", "python" ]
stackoverflow_0003592867_macos_python.txt
Q: Porting a threaded C program to Python As an exercise, I would like to port some of the functionality of a threaded C program (using pthreads) to Python. The C program spawns a thread to (almost) constantly iterate through certain directories, filling a data structure with their contents; these directories change crazy frequently (it's a mail queue). The main body of the program reacts to the contents of that data structure in various ways. From what I've read, Python has problems with concurrency. Am I going to be able to implement this? If so, do you have any advice? I've just recently started using Python regularly, and I'm loving it. FYI, the source code resembles this: // big struct for everything struct context_t { struct datastruct_t data; pthread_t my_thread; pthread_mutex_t my_mutex; } int thread_control; // does the dirty work void *thread_func(void *arg) { while ( thread_control == TH_RUNNABLE ) { // loop through dirs // fill up ctx->data sleep(1); } pthread_mutex_unlock ( my_mutex ); thread_control = TH_STOPPED; pthread_exit(NULL); } int start_thread(struct context_t* ctx) { // get a mutex to control access to our data pthread_mutex_trylock(&ctx->my_mutex) thread_control = TH_RUNNABLE; // start the thread pthread_create ( &ctx->my_thread, NULL, thread_func, ctx ); } int stop_thread() { thread_control = TH_STOPRQ; } int main() { struct context_t *ctx; start_thread(ctx); // do stuff } Thanks!!! A: The "problems with concurrency" with CPython are basically only ones of not being able to use multiple cores from within the same process (you need multiple processes for that) -- apart from that, the threading abilities of Python aren't all that different from C's (though it's easier to port to/from Java's early threading abilities, since that's what the threading module was [[loosely]] based on). Threads will yield control to other threads when they do I/O, or sleep (time.sleep(0) is a popular way to say "yield control if needed, else continue with this thread"), or pre-emptively after a certain number of bytecode instructions since last thread switch. For the "resource acquisition is initialization" (RAAI) which in C++ (but not in C) you obtain with an appropriate local variable, you can use try/finally, like in Java, or you can use the with statement -- with somelock:, where somelock is an instance of threading.Lock, performs an acquire, executes the statement's body, then ensures a release is performed whether that body terminates normally or by an exception -- I see you don't bother with that in your code, but that does mean that abnormal termination of the thread would leave the lock "held". A: Porting the code to python should be straight forward: python's threading module has all the usual suspects when talking about threading (threads, locks, condition variables, etc). What you've probably heard about python's threading support is the GIL (global interpreter lock). Python only allows one python bytecode operation to be executed at a time, so practically your app will be running "single threaded" (as in only one thread will be running at a time). If you google for it you'll find lots and lots of articles written. It does not mean your program doesn't need to worry about thread-safety, though: you still need to properly protect shared data structures with mutexes, for example.
Porting a threaded C program to Python
As an exercise, I would like to port some of the functionality of a threaded C program (using pthreads) to Python. The C program spawns a thread to (almost) constantly iterate through certain directories, filling a data structure with their contents; these directories change crazy frequently (it's a mail queue). The main body of the program reacts to the contents of that data structure in various ways. From what I've read, Python has problems with concurrency. Am I going to be able to implement this? If so, do you have any advice? I've just recently started using Python regularly, and I'm loving it. FYI, the source code resembles this: // big struct for everything struct context_t { struct datastruct_t data; pthread_t my_thread; pthread_mutex_t my_mutex; } int thread_control; // does the dirty work void *thread_func(void *arg) { while ( thread_control == TH_RUNNABLE ) { // loop through dirs // fill up ctx->data sleep(1); } pthread_mutex_unlock ( my_mutex ); thread_control = TH_STOPPED; pthread_exit(NULL); } int start_thread(struct context_t* ctx) { // get a mutex to control access to our data pthread_mutex_trylock(&ctx->my_mutex) thread_control = TH_RUNNABLE; // start the thread pthread_create ( &ctx->my_thread, NULL, thread_func, ctx ); } int stop_thread() { thread_control = TH_STOPRQ; } int main() { struct context_t *ctx; start_thread(ctx); // do stuff } Thanks!!!
[ "The \"problems with concurrency\" with CPython are basically only ones of not being able to use multiple cores from within the same process (you need multiple processes for that) -- apart from that, the threading abilities of Python aren't all that different from C's (though it's easier to port to/from Java's earl...
[ 3, 2 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0003593006_multithreading_python.txt
Q: Iterative printing over parallel lists to print columns in Python I have vsort and vsorta, both lists with equal numbers of items that should be right next to each other (about 250 elements per list). I want to print them as parallel columns, like so: >>> for x,y in vsort,vsorta: ... print x, y ... Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: too many values to unpack >>> Is there a way around this error? A: Try: for x, y in zip(vsort, vsorta): print x, y zip takes some number of lists and makes them into one list of tuples.
Iterative printing over parallel lists to print columns in Python
I have vsort and vsorta, both lists with equal numbers of items that should be right next to each other (about 250 elements per list). I want to print them as parallel columns, like so: >>> for x,y in vsort,vsorta: ... print x, y ... Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: too many values to unpack >>> Is there a way around this error?
[ "Try:\nfor x, y in zip(vsort, vsorta):\n print x, y\n\nzip takes some number of lists and makes them into one list of tuples.\n" ]
[ 8 ]
[]
[]
[ "collections", "list", "printing", "python" ]
stackoverflow_0003593040_collections_list_printing_python.txt
Q: Python invalid syntax lastPosition = GPS.getActualPosition() I m trying to compile a code which is about sending sms through telit module. above statement is giving an error. I couldn't understand, GPS library is in the place where it's supposed to be and I imported it. import SER import MOD import MDM import GPS syntaxError: invalid syntax http://forum.sparkfun.com/viewtopic.php?f=13&t=20038 please help!!! A: The post the OP referred to (in a comment -- not a great idea, @gheddo! edit your Q instead!), here, has exactly this code (I'm copying and pasting only the two relevant lines): def get_gps(): gpspos = GPS.getActualPosition() #Read GPS position see the problem? No indentation for the second line! Therefore, a syntax error: function bodies (and other bodies of compound statements) must be indented in Python. It was hardly necessary to send us reading that code, you know... the code's author, John Melbourne, in the very next post in this thread says, and I quote: Hi again Ryan, The forum software removed the indentation from the Python script that I listed in my earlier mail. You will need to re-indent the function bodies, if and while statements. See Flavio's original source if your not sure how. So that's exactly what you have to do -- re-indent the function bodies, if and while statements, and refer to Flavio Bernardotti's code if you need to for this purpose. Also, in the future, I would strongly recommend you read at least one post later in a thread (if reading the whole thread is too much work for you...;-)... A: Perhaps try some text editor with visible white-space? I've had pesky bugs like this until I turn on "Show Invisibles" in TextMate.
Python invalid syntax
lastPosition = GPS.getActualPosition() I m trying to compile a code which is about sending sms through telit module. above statement is giving an error. I couldn't understand, GPS library is in the place where it's supposed to be and I imported it. import SER import MOD import MDM import GPS syntaxError: invalid syntax http://forum.sparkfun.com/viewtopic.php?f=13&t=20038 please help!!!
[ "The post the OP referred to (in a comment -- not a great idea, @gheddo! edit your Q instead!), here, has exactly this code (I'm copying and pasting only the two relevant lines):\ndef get_gps():\ngpspos = GPS.getActualPosition() #Read GPS position\n\nsee the problem? No indentation for the second line! Therefore,...
[ 3, 0 ]
[]
[]
[ "python", "syntax_error" ]
stackoverflow_0003592693_python_syntax_error.txt
Q: How to make integration test for DB at google App. engine? I'am wondering, how to write integration tests, that involves DB interaction, for Google app engine? It's seems - no problem to run this test at Google, on "live" db, using GAEUnit SO Thread But, this seems bad practice to me, because it's live environment. Google has provided examples of such tests, for java, but not for python link. Do anybody know how to setup database locally, during test setup on python? A: You might also want to take a look at Fixture. It lets you easily create datasets that are loaded in a datastore stub at the beginning of every test. This answer has a specific example. A: Use NoseGAE. It sets up the development environment so you can test datastore and other APIs. Then, and this one is not required, gaetestbed provides some helpers to cleanup datastore or memcache etc between tests.
How to make integration test for DB at google App. engine?
I'am wondering, how to write integration tests, that involves DB interaction, for Google app engine? It's seems - no problem to run this test at Google, on "live" db, using GAEUnit SO Thread But, this seems bad practice to me, because it's live environment. Google has provided examples of such tests, for java, but not for python link. Do anybody know how to setup database locally, during test setup on python?
[ "You might also want to take a look at Fixture. It lets you easily create datasets that are loaded in a datastore stub at the beginning of every test. This answer has a specific example.\n", "Use NoseGAE. It sets up the development environment so you can test datastore and other APIs. Then, and this one is not re...
[ 1, 0 ]
[]
[]
[ "google_app_engine", "python", "unit_testing" ]
stackoverflow_0003592436_google_app_engine_python_unit_testing.txt
Q: Add page break to Reportlab Canvas object I need to generate a 2 pages pdf report. Pages are completely independent. tried using: mycanvas.drawString(x, y, "Printing on Page 1") mycanvas._pageNumer = 2 mycanvas.drawString(x, y, "Printing on Page 2") and: mycanvas.drawString(x, y, "Printing on Page 1") P = PageBreak() P.drawOn(mycanvas, 0, 1000) mycanvas.drawString(x, y, "Printing on Page 2") But everything is printed on the same page. How should I add a page break to this Canvas instance ? A: Just call mycanvas.showPage() once page 1 is done -- this way, the rest of the output goes to page 2. See the docs.
Add page break to Reportlab Canvas object
I need to generate a 2 pages pdf report. Pages are completely independent. tried using: mycanvas.drawString(x, y, "Printing on Page 1") mycanvas._pageNumer = 2 mycanvas.drawString(x, y, "Printing on Page 2") and: mycanvas.drawString(x, y, "Printing on Page 1") P = PageBreak() P.drawOn(mycanvas, 0, 1000) mycanvas.drawString(x, y, "Printing on Page 2") But everything is printed on the same page. How should I add a page break to this Canvas instance ?
[ "Just call mycanvas.showPage() once page 1 is done -- this way, the rest of the output goes to page 2. See the docs.\n" ]
[ 45 ]
[]
[]
[ "python", "reportlab" ]
stackoverflow_0003593193_python_reportlab.txt
Q: Removing Tags from HTML Parsed with BeautifulSoup I'm new to python and I'm using BeautifulSoup to parse a website and then extract data. I have the following code: for line in raw_data: #raw_data is the parsed html separated into smaller blocks d = {} d['name'] = line.find('div', {'class':'torrentname'}).find('a') print d['name'] <a href="/ubuntu-9-10-desktop-i386-t3144211.html"> <strong class="red">Ubuntu</strong> 9.10 desktop (i386)</a> Normally I would be able extract 'Ubuntu 9.10 desktop (i386)' by writing: d['name'] = line.find('div', {'class':'torrentname'}).find('a').string but due to the strong html tags it returns None. Is there a way to extract the strong tags and then use .string or is there a better way? I have tried using BeautifulSoup's extract() function but I couldn't get it to work. Edit: I just realized that my solution does not work if there are two sets of strong tags as the space between the words are left out. What would be a way to fix this problem? A: Use the ".text" property: d['name'] = line.find('div', {'class':'torrentname'}).find('a').text Or do a join on findAll(text=True): anchor = line.find('div', {'class':'torrentname'}).find('a') d['name'] = ''.join(anchor.findAll(text=True))
Removing Tags from HTML Parsed with BeautifulSoup
I'm new to python and I'm using BeautifulSoup to parse a website and then extract data. I have the following code: for line in raw_data: #raw_data is the parsed html separated into smaller blocks d = {} d['name'] = line.find('div', {'class':'torrentname'}).find('a') print d['name'] <a href="/ubuntu-9-10-desktop-i386-t3144211.html"> <strong class="red">Ubuntu</strong> 9.10 desktop (i386)</a> Normally I would be able extract 'Ubuntu 9.10 desktop (i386)' by writing: d['name'] = line.find('div', {'class':'torrentname'}).find('a').string but due to the strong html tags it returns None. Is there a way to extract the strong tags and then use .string or is there a better way? I have tried using BeautifulSoup's extract() function but I couldn't get it to work. Edit: I just realized that my solution does not work if there are two sets of strong tags as the space between the words are left out. What would be a way to fix this problem?
[ "Use the \".text\" property:\nd['name'] = line.find('div', {'class':'torrentname'}).find('a').text\n\nOr do a join on findAll(text=True):\nanchor = line.find('div', {'class':'torrentname'}).find('a')\nd['name'] = ''.join(anchor.findAll(text=True))\n\n" ]
[ 3 ]
[]
[]
[ "beautifulsoup", "html", "parsing", "python" ]
stackoverflow_0003585725_beautifulsoup_html_parsing_python.txt
Q: How do I yield a pre-unpacked list? I have a list that is created within an itertools.groupby operation: def yield_unpacked_list(): for key, grp in itertools.groupby(something_to_groupby, key=lambda x: x[0]): subset_of_grp = list(item[2] for item in list(grp)) yield key, subset_of_grp If, for example, subset_of_grp turns out to be [1, 2, 3, 4] and [5, 6, 7, 8]: for m in yield_unpacked_list(): print m would print out: ('first_key', [1, 2, 3, 4]) ('second_key', [5, 6, 7, 8]) Now, going back to my function definition. Obviously the following is a syntax error (the * operator): def yield_unpacked_list(): for key, grp in itertools.groupby(something_to_groupby, key=lambda x: x[0]): subset_of_grp = list(item[2] for item in list(grp)) yield key, *subset_of_grp I want the following result for the same print loop to be without the [list] brackets: ('first_key', 1, 2, 3, 4) ('second_key', 5, 6, 7, 8) Note that print is only for illustrative purposes here. I have other functions that would benefit from the simplified tuple structure. A: yield (key,) + tuple(subset_of_grp) A: def yield_unpacked_list(): for key, grp in itertools.groupby(something_to_groupby, key=lambda x: x[0]): yield (key,) + tuple(item[2] for item in grp) From the result you want for printing, it's clear that you want to yield a tuple -- no idea why you call it an "unpacked list" instead, but, anyway, there you are. I also removed a couple of calls to list that simply served no useful role at all in your code.
How do I yield a pre-unpacked list?
I have a list that is created within an itertools.groupby operation: def yield_unpacked_list(): for key, grp in itertools.groupby(something_to_groupby, key=lambda x: x[0]): subset_of_grp = list(item[2] for item in list(grp)) yield key, subset_of_grp If, for example, subset_of_grp turns out to be [1, 2, 3, 4] and [5, 6, 7, 8]: for m in yield_unpacked_list(): print m would print out: ('first_key', [1, 2, 3, 4]) ('second_key', [5, 6, 7, 8]) Now, going back to my function definition. Obviously the following is a syntax error (the * operator): def yield_unpacked_list(): for key, grp in itertools.groupby(something_to_groupby, key=lambda x: x[0]): subset_of_grp = list(item[2] for item in list(grp)) yield key, *subset_of_grp I want the following result for the same print loop to be without the [list] brackets: ('first_key', 1, 2, 3, 4) ('second_key', 5, 6, 7, 8) Note that print is only for illustrative purposes here. I have other functions that would benefit from the simplified tuple structure.
[ "yield (key,) + tuple(subset_of_grp)\n", "def yield_unpacked_list():\n for key, grp in itertools.groupby(something_to_groupby, key=lambda x: x[0]):\n yield (key,) + tuple(item[2] for item in grp)\n\nFrom the result you want for printing, it's clear that you want to yield a tuple -- no idea why you call ...
[ 5, 2 ]
[]
[]
[ "group_by", "iterable_unpacking", "python", "python_itertools", "yield" ]
stackoverflow_0003593475_group_by_iterable_unpacking_python_python_itertools_yield.txt
Q: Why doesn't sys.stdout.write('\b') backspace against newlines? Compare: for item in range(0, 5): sys.stdout.write('c') for item in range(0, 5): sys.stdout.write('\b') Works as you would imagine, but: for item in range(0, 5): sys.stdout.write('\n') for item in range(0, 5): sys.stdout.write('\b') still leaves you with five newline characters. Any ideas? A: It may seem reasonable today to expect backspace to be able to work over newline characters, on a console but that would not be backward compatible with teletypes as there is no reverse linefeed. A: This is about the behavior of console windows: backspaces only work within a line, they won't backup over newlines. A: This is absolutely nothing to do with Python. It's your console driver that handles any visual effects. Most of them will emulate an ASR33 teletype ... backspace means move the print head one space back towards the start-of-line position, if possible.
Why doesn't sys.stdout.write('\b') backspace against newlines?
Compare: for item in range(0, 5): sys.stdout.write('c') for item in range(0, 5): sys.stdout.write('\b') Works as you would imagine, but: for item in range(0, 5): sys.stdout.write('\n') for item in range(0, 5): sys.stdout.write('\b') still leaves you with five newline characters. Any ideas?
[ "It may seem reasonable today to expect backspace to be able to work over newline characters, on a console but that would not be backward compatible with teletypes as there is no reverse linefeed.\n", "This is about the behavior of console windows: backspaces only work within a line, they won't backup over newlin...
[ 17, 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003593339_python.txt
Q: Associating properties to Class objects I would like to define properties for classes, and be able to access them before I actually instantiate an object of that class. I'll give some context. My application handles a library of components. Each component is mapped to a Python class. Now I want to know what configuration a component needs, before actually instancing the class. One solution is to write something like this: class Component: @classmethod def config(cls, name, description, default=None): ''' Define one configuration switch for the class. ''' # now put this information in a class-specific dictionary class Model1(Component): @classmethod def define_configuration(cls): cls.config('n', 'number of burzs to instigate') cls.config('skip', 'skip any barzs among the burzs', default=True) # ... component_class = Model1 component_class.define_configuration() However, it seems pretty ugly. Ideally I would like to be able to write something like the following, and still be able to put the configuration switches in a class-specific dictionary to be accessed later. class Model1(Component): config('n', 'number of burz to instigate') config('skip', 'skip any barz in the data', default=True) My initial solution was to write something like: class Model1(Component): Model1.config('n', 'number of burz to instigate') Model1.config('skip', 'skip any barz in the data', default=True) however I discovered on other questions here on SO that the class name is not defined yet when the body is executed. What should I do? tl;dr: How can I get a nice syntax for defining class-specific properties (before I instance an object of that class)? Here is (for the record) the solution that was suggested (a bit elaborated). Yai! I could get exactly what I wanted. :-) from collections import namedtuple Config = namedtuple('Config', 'name desc default') def config(name, description, default=None): ComponentMeta.tmp_config_storage.append(Config(name, description, default)) class ComponentMeta(type): tmp_config_storage = [] def __init__(cls, clsname, bases, clsdict): for config in ComponentMeta.tmp_config_storage: if not 'my_config' in cls.__dict__: setattr(cls, 'my_config', []) cls.my_config.append(config) ComponentMeta.tmp_config_storage = [] class Component(object): __metaclass__ = ComponentMeta class Model1(Component): config('x1', 'for model1') config('y1', 'for model1') class Model2(Component): config('x2', 'for model2') print 'config for Model1:', Model1.my_config print 'config for Model2:', Model2.my_config A: A class name is defined once the body is executed. This happens when the file containing the class is imported. This is not the same as creation of an instance of a class. class A(object): """ doc """ config = [] def __init__(def): pass A.config.append(('n', 'number of burz to instigate')) A.config.append(('skip', 'skip any barz in the data', default=True)) # access class specific config before object instantiation x = A.config[0] # instantiating your class, post configuration access a_obj = A() Wouldn't this approach serve your purpose? The class config can be stored in a class variable which can be modified and added before you instantiate any objects of this class. Using class variables should serve your purpose. A: corrected def config(name, description, default=None): ComponentMeta.config_items.append((name, description, default)) class ComponentMeta(type): config_items = [] def __init__(cls, clsname, bases, clsdict): for options in ComponentMeta.config_items: cls.add_config(*options) ComponentMeta.config_items = [] class Component(object): __metaclass__ = ComponentMeta config_items = [] # this is only for testing. you don't need it @classmethod def add_config(cls, name, description, default=None): #also for testing cls.config_items.append((name, description, default)) class Model1(Component): config('n', 'number of burz to instigate') config('skip', 'skip any barz in the data', default=True) print Model1.config_items This works by making config an external function that adds the items to ComponentMeta.config_instances. ComponentMeta then checks this list when creating a class and calls config_item on the items. Note that this is not thread safe (although it could me made so). Also, if a subclass of ComponentMeta fails to call super or empty ComponentMeta.config_items itself, the next created class will get the config items. A: Why not something simple like, say: def makeconfigdict(cls): thedict = {} for name, value in cls.__dict__.items(): if isaconfig(value): addconfigtodict(thedict, name, value) delattr(cls, name) cls.specialdict = thedict return cls @makeconfigdict class Model1(Component): n = config('number of burz to instigate') skip = config('skip any barz in the data', default=True) ... As long as the config function returns objects that an isaconfig function can recognize, and an addconfigtodict function can properly set into the special dictionary in whatever format you want, you're in clover. If I understand your specs correctly you don't want a normal attribute like Model1.skip, right? That's why I have that delattr call in makeconfigdict (and also why I use .items() on the class's dictionary -- since the dictionary is modified during the loop, it's better to use .items(), which takes a "snapshot" list of all names and values, rather than the usual .iteritems(), which just iterates on the dictionary, thus not allowing it to be modified during the loop).
Associating properties to Class objects
I would like to define properties for classes, and be able to access them before I actually instantiate an object of that class. I'll give some context. My application handles a library of components. Each component is mapped to a Python class. Now I want to know what configuration a component needs, before actually instancing the class. One solution is to write something like this: class Component: @classmethod def config(cls, name, description, default=None): ''' Define one configuration switch for the class. ''' # now put this information in a class-specific dictionary class Model1(Component): @classmethod def define_configuration(cls): cls.config('n', 'number of burzs to instigate') cls.config('skip', 'skip any barzs among the burzs', default=True) # ... component_class = Model1 component_class.define_configuration() However, it seems pretty ugly. Ideally I would like to be able to write something like the following, and still be able to put the configuration switches in a class-specific dictionary to be accessed later. class Model1(Component): config('n', 'number of burz to instigate') config('skip', 'skip any barz in the data', default=True) My initial solution was to write something like: class Model1(Component): Model1.config('n', 'number of burz to instigate') Model1.config('skip', 'skip any barz in the data', default=True) however I discovered on other questions here on SO that the class name is not defined yet when the body is executed. What should I do? tl;dr: How can I get a nice syntax for defining class-specific properties (before I instance an object of that class)? Here is (for the record) the solution that was suggested (a bit elaborated). Yai! I could get exactly what I wanted. :-) from collections import namedtuple Config = namedtuple('Config', 'name desc default') def config(name, description, default=None): ComponentMeta.tmp_config_storage.append(Config(name, description, default)) class ComponentMeta(type): tmp_config_storage = [] def __init__(cls, clsname, bases, clsdict): for config in ComponentMeta.tmp_config_storage: if not 'my_config' in cls.__dict__: setattr(cls, 'my_config', []) cls.my_config.append(config) ComponentMeta.tmp_config_storage = [] class Component(object): __metaclass__ = ComponentMeta class Model1(Component): config('x1', 'for model1') config('y1', 'for model1') class Model2(Component): config('x2', 'for model2') print 'config for Model1:', Model1.my_config print 'config for Model2:', Model2.my_config
[ "A class name is defined once the body is executed. This happens when the file containing the class is imported. This is not the same as creation of an instance of a class.\nclass A(object):\n \"\"\" doc \"\"\"\n config = []\n def __init__(def):\n pass\nA.config.append(('n', 'number of burz to insti...
[ 1, 1, 1 ]
[]
[]
[ "class", "metaprogramming", "python" ]
stackoverflow_0003593605_class_metaprogramming_python.txt
Q: How do you grab a value from the scope from a string from module import * # adds 'BlahRenderer', 'FooRenderer', 'BarRenderer', etc. class MyClass def __init__(self, value) renderer = "%sRenderer" % value self.RendererClass = ???? I know this can be done by doing the import inside __init__ and then doing locals()[renderer] but how do I do it if the import is at the top? A: Try globals() instead of locals(). Although it may be better that your module defines a dictionary or Factory to map each value into a Renderer e.g. renderers = {'Blah': BlahRenderer, 'Foo': FooRenderer, ...}
How do you grab a value from the scope from a string
from module import * # adds 'BlahRenderer', 'FooRenderer', 'BarRenderer', etc. class MyClass def __init__(self, value) renderer = "%sRenderer" % value self.RendererClass = ???? I know this can be done by doing the import inside __init__ and then doing locals()[renderer] but how do I do it if the import is at the top?
[ "Try globals() instead of locals().\nAlthough it may be better that your module defines a dictionary or Factory to map each value into a Renderer e.g.\nrenderers = {'Blah': BlahRenderer, 'Foo': FooRenderer, ...}\n\n" ]
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0003594267_python.txt
Q: Make a video using Python+GST from a set of `YYYY-MM-DD`-dated pictures I have a directory with a set of YYYY-MM-DD-dated files in as so: pictures/ 2010-08-14.png 2010-08-17.png 2010-08-18.png How can I use Python GStreamer to turn these files into a video? The filenames must remain the same. I have a program that can turn incrementally numbered PNGs into a video, I just need to adapt it to use dated files instead. A: The easiest would be to create link/rename those file to a sequence number (that should be easily doable with a n=0 for f in $(ls * | sort); do ln -s $f $n && $n=$((n+1)) Then you should be able to do: gst-launch multifilesrc location=%d ! pngdec ! theoraenc ! oggmux ! filesink location=movie.ogg It would have more sense to use a different encoder than theora perhaps, to have all pictures as keyframe, perhaps with MJPEG? A: It's easy enough to sort the filenames by date: import datetime, os def key( filename ): return datetime.datetime.strptime( filename.rsplit( ".", 1 )[ 0 ], "%Y-%m-%d" ) foo = sorted( os.listdir( ... ), key = key ) Maybe you want to rename them? count = 0 def renamer( name ): os.rename( name, "{0}.png".format( count ) ) count += 1 map( renamer, foo ) A: Based on the Bash code elmarco posted, here's some basic Python code that will symlink the dated files to sequentially numbered ones in a temporary directory: # Untested example code. # import os tempfile shutil # Make a temporary directory: `temp`: temp = tempfile.mkdtemp() # List photos: files = os.listdir(os.path.expanduser('~/.photostory/photos/')) # Sort photos (by date): files.sort() # Symlink photos to `temp`: for i in range(len(files)): os.symlink(files[i], os.path.join(temp, str(i)+'.png') # Perform GStreamer operations on `temp`. # # Remove `temp`: shutil.rmtree(temp)
Make a video using Python+GST from a set of `YYYY-MM-DD`-dated pictures
I have a directory with a set of YYYY-MM-DD-dated files in as so: pictures/ 2010-08-14.png 2010-08-17.png 2010-08-18.png How can I use Python GStreamer to turn these files into a video? The filenames must remain the same. I have a program that can turn incrementally numbered PNGs into a video, I just need to adapt it to use dated files instead.
[ "The easiest would be to create link/rename those file to a sequence number (that should be easily doable with a n=0 for f in $(ls * | sort); do ln -s $f $n && $n=$((n+1))\nThen you should be able to do:\ngst-launch multifilesrc location=%d ! pngdec ! theoraenc ! oggmux ! filesink location=movie.ogg\n\nIt would hav...
[ 0, 0, 0 ]
[]
[]
[ "gstreamer", "python", "rfc3339", "video" ]
stackoverflow_0003520464_gstreamer_python_rfc3339_video.txt
Q: removing /n from list of words - python I have a list as below ['Jellicle', 'Cats', 'are', 'black', 'and', 'white,\nJellicle', 'Cats', 'are', 'rather', 'small;\nJellicle', 'Cats', 'are', 'merry', 'and', 'bright,\nAnd', 'pleasant', 'to', 'hear', 'when', 'they', 'caterwaul.\nJellicle', 'Cats', 'have', 'cheerful', 'faces,\nJellicle', 'Cats', 'have', 'bright', 'black', 'eyes;\nThey', 'like', 'to', 'practise', 'their', 'airs', 'and', 'graces\nAnd', 'wait', 'for', 'the', 'Jellicle', 'Moon', 'to', 'rise.\n'] How can I remove the /n so I end up with a list with each word as a seperate thing with no /n. Grammer is allowed to be left in the list. thanks A: The simplest (although not the best performing) is probably to join then split: l = ('\n'.join(l)).split('\n') In fact it looks like you created this list by splitting on space. If so, you might want to reconsider how to create this list in the first place to avoid this extra step. You can split directly to the correct result by splitting on a regular expression matching whitespace, or better, by using s.split() without any arguments. A: >>> [i for el in lst for i in el.splitlines()] ['Jellicle', 'Cats', 'are', 'black', 'and', 'white,', 'Jellicle', 'Cats', 'are', 'rather', 'small;', 'Jellicle', 'Cats', 'are', 'merry', 'and', 'bright,', 'And', 'pleasant', 'to', 'hear', 'when', 'they', 'caterwaul.', 'Jellicle', 'Cats', 'have', 'cheerful', 'faces,', 'Jellicle', 'Cats', 'have', 'bright', 'black', 'eyes;', 'They', 'like', 'to', 'practise', 'their', 'airs', 'and', 'graces', 'And', 'wait', 'for', 'the', 'Jellicle', 'Moon', 'to', 'rise.'] A: >>> l = ['Jellicle', 'Cats', 'are', 'black', 'and', 'white,\nJellicle', 'Cats', 'are', 'rather', 'small;\nJellicle', 'Cats', 'are', 'merry', 'and', 'bright,\nAnd', 'pleasant', 'to', 'hear', 'when', 'they', 'caterwaul.\nJellicle', 'Cats', 'have', 'cheerful', 'faces,\nJellicle', 'Cats', 'have', 'bright', 'black', 'eyes;\nThey', 'like', 'to', 'practise', 'their', 'airs', 'and', 'graces\nAnd', 'wait', 'for', 'the', 'Jellicle', 'Moon', 'to', 'rise.\n'] >>> [i.strip(',;') for v in l for i in v.split()]
removing /n from list of words - python
I have a list as below ['Jellicle', 'Cats', 'are', 'black', 'and', 'white,\nJellicle', 'Cats', 'are', 'rather', 'small;\nJellicle', 'Cats', 'are', 'merry', 'and', 'bright,\nAnd', 'pleasant', 'to', 'hear', 'when', 'they', 'caterwaul.\nJellicle', 'Cats', 'have', 'cheerful', 'faces,\nJellicle', 'Cats', 'have', 'bright', 'black', 'eyes;\nThey', 'like', 'to', 'practise', 'their', 'airs', 'and', 'graces\nAnd', 'wait', 'for', 'the', 'Jellicle', 'Moon', 'to', 'rise.\n'] How can I remove the /n so I end up with a list with each word as a seperate thing with no /n. Grammer is allowed to be left in the list. thanks
[ "The simplest (although not the best performing) is probably to join then split:\nl = ('\\n'.join(l)).split('\\n')\n\nIn fact it looks like you created this list by splitting on space. If so, you might want to reconsider how to create this list in the first place to avoid this extra step. You can split directly to ...
[ 2, 1, 0 ]
[]
[]
[ "list", "python", "string" ]
stackoverflow_0003594448_list_python_string.txt
Q: Google App Engine w/ Django - InboundMailHandler appears to only work once I'm writing an app for Google App Engine (with Python and Django) that needs to receive email and add some elements of the received email messages to a datastore. I am a very novice programmer. The problem is that the script I specify to handle incoming email appears to only run once (until the script is touched). Sending a test email from the local admin console to, say, 'test@downloadtogo.appspotmail.com' causes an entity to be added to the local datastore correctly. Sending a second, third, etc. test email has no effect - the entity is not added. 'Touching' handle_incoming_email.py (which I understand to mean adding or deleting a space and then saving), then sending another test email, will cause the entity to be added correctly. app.yaml: application: downloadtogo version: 1 runtime: python api_version: 1 handlers: - url: /static static_dir: static - url: /.* script: main.py - url: /_ah/mail/.+ script: handle_incoming_emaril.py login: admin inbound_services: - mail handle_incoming_email.py: from downloadtogo.models import Email import logging, email import wsgiref.handlers import exceptions from google.appengine.api import mail from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.ext.webapp.mail_handlers import InboundMailHandler class MailHandler(InboundMailHandler): def receive(self, message): email = Email() email.from_address = message.sender email.put() def main(): application = webapp.WSGIApplication([MailHandler.mapping()], debug=True) wsgiref.handlers.CGIHandler().run(application) main() models.py: from appengine_django.models import BaseModel from google.appengine.ext import db class Email(db.Model): from_address = db.StringProperty() to_address = db.StringProperty() body = db.StringProperty(multiline=True) added_on = db.DateTimeProperty(auto_now_add=True) A: Handlers are matched in order. .* matches any request, so the email handler will never match at all. Put .* last.
Google App Engine w/ Django - InboundMailHandler appears to only work once
I'm writing an app for Google App Engine (with Python and Django) that needs to receive email and add some elements of the received email messages to a datastore. I am a very novice programmer. The problem is that the script I specify to handle incoming email appears to only run once (until the script is touched). Sending a test email from the local admin console to, say, 'test@downloadtogo.appspotmail.com' causes an entity to be added to the local datastore correctly. Sending a second, third, etc. test email has no effect - the entity is not added. 'Touching' handle_incoming_email.py (which I understand to mean adding or deleting a space and then saving), then sending another test email, will cause the entity to be added correctly. app.yaml: application: downloadtogo version: 1 runtime: python api_version: 1 handlers: - url: /static static_dir: static - url: /.* script: main.py - url: /_ah/mail/.+ script: handle_incoming_emaril.py login: admin inbound_services: - mail handle_incoming_email.py: from downloadtogo.models import Email import logging, email import wsgiref.handlers import exceptions from google.appengine.api import mail from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.ext.webapp.mail_handlers import InboundMailHandler class MailHandler(InboundMailHandler): def receive(self, message): email = Email() email.from_address = message.sender email.put() def main(): application = webapp.WSGIApplication([MailHandler.mapping()], debug=True) wsgiref.handlers.CGIHandler().run(application) main() models.py: from appengine_django.models import BaseModel from google.appengine.ext import db class Email(db.Model): from_address = db.StringProperty() to_address = db.StringProperty() body = db.StringProperty(multiline=True) added_on = db.DateTimeProperty(auto_now_add=True)
[ "Handlers are matched in order. .* matches any request, so the email handler will never match at all. Put .* last.\n" ]
[ 5 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0003593902_django_google_app_engine_python.txt
Q: Keeping multiple clients showing up-to-date information in Python? I am new to network programming but old to Python. I have a simple blotter program that is to be used on multiple client computers. The blotter works two ways, it can show and update the information in the database. To avoid any blotters showing old data, how can I make all blotters re-fetch information from the database as soon as another blotter has updated some data in the database? I would rather like to avoid complexity in setting up some client-server protocol. Is it possible to create some form of client-only protocol where a simple refresh message is passed along straight to the other blotters when they need to update their information? A: You could use triggers. When an information is updated send a signal (is up to you choose how, maybe just an udp packet) to all blotters that will update their information consequentially. Postgresql could be scripted using python. A: To receive messages (e.g. the UDP package suggested by the other poster or an http request), the clients would have to run a basic server on the client machine. You could use the Python xmlrpc module for example. However, a local firewall may block the inward communication. The easiest solution, if the number of clients is moderate, will be to frequently poll the database for changes: add a column "last modification time" to your drawing table and have the clients check this field. This way the clients can find out whether they need to reload the drawing without wasting too many resources. Edit: The last modification field could either be actively updated by the client that made a change to the drawing, or automatically updated by a database trigger.
Keeping multiple clients showing up-to-date information in Python?
I am new to network programming but old to Python. I have a simple blotter program that is to be used on multiple client computers. The blotter works two ways, it can show and update the information in the database. To avoid any blotters showing old data, how can I make all blotters re-fetch information from the database as soon as another blotter has updated some data in the database? I would rather like to avoid complexity in setting up some client-server protocol. Is it possible to create some form of client-only protocol where a simple refresh message is passed along straight to the other blotters when they need to update their information?
[ "You could use triggers. When an information is updated send a signal (is up to you choose how, maybe just an udp packet) to all blotters that will update their information consequentially. Postgresql could be scripted using python.\n", "To receive messages (e.g. the UDP package suggested by the other poster or a...
[ 0, 0 ]
[]
[]
[ "network_programming", "python" ]
stackoverflow_0003594631_network_programming_python.txt
Q: How to transform a key pressed into a different one in pygtk I'm trying to make my pygtk application behave the way openoffice calc does, regarding the decimal point. This means that when receiving a KP_Decimal key (the dot in the keypad) I want my entries to show whatever the decimal point is in the current locale (dot or comma, appropriately). I've searched for a long while now, and I haven't been able to find how to do this. I can capture the key_press_event in the Gtk.Entry, and check for a KP_Decimal, and I can get the current locale setting for decimal point; but I don't know how to transform the dot to comma if needed. I want this change to be global to the app, and not specific to certain entries, so it'd be better if it could be done through something more general, like input methods. I've been reading about them as well, and I couldn't find a way to use them how I want either. A: One way you could do this is by subclassing gtk.Entry, like so: import gtk import locale class NumericEntry(gtk.Entry): __gsignals__ = { 'key_press_event': 'override' } def do_key_press_event(self, event): if event.keyval == gtk.gdk.keyval_from_name('KP_Decimal'): event.keyval = int(gtk.gdk.unicode_to_keyval(ord(locale.localeconv()['decimal_point']))) gtk.Entry.do_key_press_event(self, event) I haven't fully tested this, so there may be one or two edge cases, but it seems to work fine for me. The nice thing about using a subclass is that it's then easy to replace your existing widgets - just use NumericEntry rather than gtk.Entry whenever you need a text entry with this behaviour. Hope this helps!
How to transform a key pressed into a different one in pygtk
I'm trying to make my pygtk application behave the way openoffice calc does, regarding the decimal point. This means that when receiving a KP_Decimal key (the dot in the keypad) I want my entries to show whatever the decimal point is in the current locale (dot or comma, appropriately). I've searched for a long while now, and I haven't been able to find how to do this. I can capture the key_press_event in the Gtk.Entry, and check for a KP_Decimal, and I can get the current locale setting for decimal point; but I don't know how to transform the dot to comma if needed. I want this change to be global to the app, and not specific to certain entries, so it'd be better if it could be done through something more general, like input methods. I've been reading about them as well, and I couldn't find a way to use them how I want either.
[ "One way you could do this is by subclassing gtk.Entry, like so:\nimport gtk\nimport locale\n\nclass NumericEntry(gtk.Entry):\n __gsignals__ = {\n 'key_press_event': 'override'\n }\n def do_key_press_event(self, event):\n if event.keyval == gtk.gdk.keyval_from_name('KP_Decimal'):\n ...
[ 2 ]
[]
[]
[ "gtk", "localization", "pygtk", "python" ]
stackoverflow_0003161317_gtk_localization_pygtk_python.txt
Q: Python CSV DictReader/Writer issues I'm trying to extract a bunch of lines from a CSV file and write them into another, but I'm having some problems. import csv f = open("my_csv_file.csv", "r") r = csv.DictReader(f, delimiter=',') fieldnames = r.fieldnames target = open("united.csv", 'w') w = csv.DictWriter(united, fieldnames=fieldnames) while True: try: row = r.next() if r.line_num <= 2: #first two rows don't matter continue else: w.writerow(row) except StopIteration: break f.close() target.close() Running this, I get the following error: Traceback (most recent call last): File "unify.py", line 16, in <module> w.writerow(row) File "C:\Program Files\Python25\lib\csv.py", line 12 return self.writer.writerow(self._dict_to_list(row File "C:\Program Files\Python25\lib\csv.py", line 12 if k not in self.fieldnames: TypeError: argument of type 'NoneType' is not iterable Not entirely sure what I'm dong wrong. A: I don't know either, but since all you're doing is copying lines from one file to another why are you bothering with the csv stuff at all? Why not something like: f = open("my_csv_file.csv", "r") target = open("united.csv", 'w') f.readline() f.readline() for line in f: target.write(line) A: To clear up the confusion about the error: you get it because r.fieldnames is only set once you read from the input file for the first time using r. Hence the way you wrote it, fieldnames will always be initialized to None. You may initialize w = csv.DictWriter(united, fieldnames=fieldnames) with r.fieldnames only after you read the first line from r, which means you would have to restructure your code. This behavior is documented in the Python Standard Library documentation DictReader objects have the following public attribute: csvreader.fieldnames If not passed as a parameter when creating the object, this attribute is initialized upon first access or when the first record is read from the file. A: As for the exception, looks like this line: w = csv.DictWriter(united, fieldnames=fieldnames) should be w = csv.DictWriter(target, fieldnames=fieldnames) A: The reason you're getting the error is most likely that your original CSV file (my_csv_file.csv) doesn't have a header row. Therefore, when you construct the reader object, its fieldnames field is set to None. When you try to write a row using the writer, it first checks to make sure there are no keys in the dict that are not in its list of known fields. Since fieldnames is set to None, an attempt to dereference the key name throws an exception.
Python CSV DictReader/Writer issues
I'm trying to extract a bunch of lines from a CSV file and write them into another, but I'm having some problems. import csv f = open("my_csv_file.csv", "r") r = csv.DictReader(f, delimiter=',') fieldnames = r.fieldnames target = open("united.csv", 'w') w = csv.DictWriter(united, fieldnames=fieldnames) while True: try: row = r.next() if r.line_num <= 2: #first two rows don't matter continue else: w.writerow(row) except StopIteration: break f.close() target.close() Running this, I get the following error: Traceback (most recent call last): File "unify.py", line 16, in <module> w.writerow(row) File "C:\Program Files\Python25\lib\csv.py", line 12 return self.writer.writerow(self._dict_to_list(row File "C:\Program Files\Python25\lib\csv.py", line 12 if k not in self.fieldnames: TypeError: argument of type 'NoneType' is not iterable Not entirely sure what I'm dong wrong.
[ "I don't know either, but since all you're doing is copying lines from one file to another why are you bothering with the csv stuff at all? Why not something like:\nf = open(\"my_csv_file.csv\", \"r\")\ntarget = open(\"united.csv\", 'w')\n\nf.readline()\nf.readline()\nfor line in f:\n target.write(line)\n\n", ...
[ 14, 13, 1, 1 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0001202855_csv_python.txt
Q: Why does printer changes resolution? User, background, what? I am runing a .bat file from a php using exec on a Windwos php server, where php is run using fast-cgi (and nginx). The command line to run this script is pclose(popen("start / ". $cmd, "r")); Where $cmd is somethign like "mybatfile.bat 45 1" When I run the batch file manually it runs a python program to read a database, get hold of some data, and print a little report. And it all works 100% correctly. When it is run from the web page, the report comes out, so I know the program is run. The code logs the parameters passed. I know that the call is correct. When run from the server/web page the report appears on the same printer approx 20% larger that when run from the coammnd line. The python script uses PyQt and opens the printer in native mode. The code is self.printer = QPrinter() self.printer.setPrinterName(printer) self.printer.setPageSize(QPrinter.A5) self.printer.setOrientation(QPrinter.Portrait) self.painter = QPainter(self.printer) Does anyone know why this happens - and what can I do to correct it? O/S is windows 7 (64 bit) for developement and a Server version for production. Python 2.7 32 bit. QT version 4. Thanks Ian A: Cracked it! The user who is running the server has never logged in (naturally) so they have never changed their screen resolution from 90 dpi. I on the other hand, have changed by screen resolution because I use large fonts. So when I ran the print it printed in 120 dpi. When the server ran it, it printed in 90 dpi. Solution. After opening the printer, read the actual resolution back, and compute a scale factor. Use the scale factor for all layout and positioning - except font sizes in points which will be correct anyway.
Why does printer changes resolution? User, background, what?
I am runing a .bat file from a php using exec on a Windwos php server, where php is run using fast-cgi (and nginx). The command line to run this script is pclose(popen("start / ". $cmd, "r")); Where $cmd is somethign like "mybatfile.bat 45 1" When I run the batch file manually it runs a python program to read a database, get hold of some data, and print a little report. And it all works 100% correctly. When it is run from the web page, the report comes out, so I know the program is run. The code logs the parameters passed. I know that the call is correct. When run from the server/web page the report appears on the same printer approx 20% larger that when run from the coammnd line. The python script uses PyQt and opens the printer in native mode. The code is self.printer = QPrinter() self.printer.setPrinterName(printer) self.printer.setPageSize(QPrinter.A5) self.printer.setOrientation(QPrinter.Portrait) self.painter = QPainter(self.printer) Does anyone know why this happens - and what can I do to correct it? O/S is windows 7 (64 bit) for developement and a Server version for production. Python 2.7 32 bit. QT version 4. Thanks Ian
[ "Cracked it!\nThe user who is running the server has never logged in (naturally) so they have never changed their screen resolution from 90 dpi. \nI on the other hand, have changed by screen resolution because I use large fonts. \nSo when I ran the print it printed in 120 dpi. When the server ran it, it printed in ...
[ 0 ]
[]
[]
[ "php", "printing", "python", "resolution", "windows" ]
stackoverflow_0003592385_php_printing_python_resolution_windows.txt
Q: Python: What ways of making data available to plugins? I'm implementing a simple plugin framework for a little Python program and wonder what the different existing practices are for passing data to plugins. At this stage, I see two alternatives: pass task-specific data to plugins, don't give plugins access to any other data pass all the data to which any plugin should have access What are the pros and cons of these two approaches? Are there any other ways or best practices that I am unaware of? What do I have to take into consideration when deciding the way? Note: I am asking for examples and general advice. A: I like the way wxPython does events. Pass an event object to the plugin with what you think is the relevant data, but also provide an API for every plugin to access the full state of the application. For example, in wxMouseEvent has x and y properties. But also (like every other event object) has get GetEventObject (and every object has GetParent ....)
Python: What ways of making data available to plugins?
I'm implementing a simple plugin framework for a little Python program and wonder what the different existing practices are for passing data to plugins. At this stage, I see two alternatives: pass task-specific data to plugins, don't give plugins access to any other data pass all the data to which any plugin should have access What are the pros and cons of these two approaches? Are there any other ways or best practices that I am unaware of? What do I have to take into consideration when deciding the way? Note: I am asking for examples and general advice.
[ "I like the way wxPython does events. Pass an event object to the plugin with what you think is the relevant data, but also provide an API for every plugin to access the full state of the application.\nFor example, in wxMouseEvent has x and y properties. But also (like every other event object) has get GetEventObje...
[ 1 ]
[]
[]
[ "plugins", "python", "variables" ]
stackoverflow_0003595000_plugins_python_variables.txt